three.webgpu.js 2.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624
  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. 'gradientMap',
  33. 'ior',
  34. 'iridescence',
  35. 'iridescenceIOR',
  36. 'iridescenceMap',
  37. 'iridescenceThicknessMap',
  38. 'lightMap',
  39. 'lightMapIntensity',
  40. 'map',
  41. 'matcap',
  42. 'metalness',
  43. 'metalnessMap',
  44. 'normalMap',
  45. 'normalScale',
  46. 'opacity',
  47. 'roughness',
  48. 'roughnessMap',
  49. 'sheen',
  50. 'sheenColor',
  51. 'sheenColorMap',
  52. 'sheenRoughnessMap',
  53. 'shininess',
  54. 'specular',
  55. 'specularColor',
  56. 'specularColorMap',
  57. 'specularIntensity',
  58. 'specularIntensityMap',
  59. 'specularMap',
  60. 'thickness',
  61. 'transmission',
  62. 'transmissionMap'
  63. ];
  64. /**
  65. * A WeakMap to cache lights data for node materials.
  66. * Cache lights data by render ID to avoid unnecessary recalculations.
  67. *
  68. * @private
  69. * @type {WeakMap<LightsNode,Object>}
  70. */
  71. const _lightsCache = new WeakMap();
  72. /**
  73. * Holds the material data for comparison.
  74. *
  75. * @private
  76. * @type {WeakMap<Material,Object>}
  77. */
  78. const _materialCache = new WeakMap();
  79. /**
  80. * Holds the geometry data for comparison.
  81. *
  82. * @private
  83. * @type {WeakMap<BufferGeometry,Object>}
  84. */
  85. const _geometryCache = new WeakMap();
  86. /**
  87. * This class is used by {@link WebGPURenderer} as management component.
  88. * It's primary purpose is to determine whether render objects require a
  89. * refresh right before they are going to be rendered or not.
  90. */
  91. class NodeMaterialObserver {
  92. /**
  93. * Constructs a new node material observer.
  94. *
  95. * @param {NodeBuilder} builder - The node builder.
  96. */
  97. constructor( builder ) {
  98. /**
  99. * A node material can be used by more than one render object so the
  100. * monitor must maintain a list of render objects.
  101. *
  102. * @type {WeakMap<RenderObject,Object>}
  103. */
  104. this.renderObjects = new WeakMap();
  105. /**
  106. * Whether the material uses node objects or not.
  107. *
  108. * @type {boolean}
  109. */
  110. this.hasNode = this.containsNode( builder );
  111. /**
  112. * Whether the node builder's 3D object is animated or not.
  113. *
  114. * @type {boolean}
  115. */
  116. this.hasAnimation = builder.object.isSkinnedMesh === true;
  117. /**
  118. * A list of all possible material uniforms
  119. *
  120. * @type {Array<string>}
  121. */
  122. this.refreshUniforms = refreshUniforms;
  123. /**
  124. * Holds the current render ID from the node frame.
  125. *
  126. * @type {number}
  127. * @default 0
  128. */
  129. this.renderId = 0;
  130. }
  131. /**
  132. * Returns `true` if the given render object is verified for the first time of this observer.
  133. *
  134. * @param {RenderObject} renderObject - The render object.
  135. * @return {boolean} Whether the given render object is verified for the first time of this observer.
  136. */
  137. firstInitialization( renderObject ) {
  138. const hasInitialized = this.renderObjects.has( renderObject );
  139. if ( hasInitialized === false ) {
  140. this.getRenderObjectData( renderObject );
  141. return true;
  142. }
  143. return false;
  144. }
  145. /**
  146. * Returns `true` if the current rendering produces motion vectors.
  147. *
  148. * @param {Renderer} renderer - The renderer.
  149. * @return {boolean} Whether the current rendering produces motion vectors or not.
  150. */
  151. needsVelocity( renderer ) {
  152. const mrt = renderer.getMRT();
  153. return ( mrt !== null && mrt.has( 'velocity' ) );
  154. }
  155. /**
  156. * Returns monitoring data for the given render object.
  157. *
  158. * @param {RenderObject} renderObject - The render object.
  159. * @return {Object} The monitoring data.
  160. */
  161. getRenderObjectData( renderObject ) {
  162. let data = this.renderObjects.get( renderObject );
  163. if ( data === undefined ) {
  164. const { geometry, object } = renderObject;
  165. data = {
  166. geometryId: geometry.id,
  167. worldMatrix: object.matrixWorld.clone()
  168. };
  169. if ( object.center ) {
  170. data.center = object.center.clone();
  171. }
  172. if ( object.morphTargetInfluences ) {
  173. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  174. }
  175. if ( renderObject.bundle !== null ) {
  176. data.version = renderObject.bundle.version;
  177. }
  178. if ( renderObject.material.transmission > 0 ) {
  179. const { width, height } = renderObject.context;
  180. data.bufferWidth = width;
  181. data.bufferHeight = height;
  182. }
  183. data.lights = this.getLightsData( renderObject.lightsNode.getLights(), [] );
  184. this.renderObjects.set( renderObject, data );
  185. }
  186. return data;
  187. }
  188. /**
  189. * Returns an attribute data structure holding the attributes versions for
  190. * monitoring.
  191. *
  192. * @param {Object} attributes - The geometry attributes.
  193. * @return {Object} An object for monitoring the versions of attributes.
  194. */
  195. getAttributesData( attributes ) {
  196. const attributesData = {};
  197. for ( const name in attributes ) {
  198. const attribute = attributes[ name ];
  199. attributesData[ name ] = {
  200. id: attribute.id,
  201. version: attribute.version,
  202. };
  203. }
  204. return attributesData;
  205. }
  206. /**
  207. * Returns `true` if the node builder's material uses
  208. * node properties.
  209. *
  210. * @param {NodeBuilder} builder - The current node builder.
  211. * @return {boolean} Whether the node builder's material uses node properties or not.
  212. */
  213. containsNode( builder ) {
  214. const material = builder.material;
  215. for ( const property in material ) {
  216. if ( material[ property ] && material[ property ].isNode )
  217. return true;
  218. }
  219. if ( builder.context.modelViewMatrix || builder.context.modelNormalViewMatrix || builder.context.getAO || builder.context.getShadow )
  220. return true;
  221. return false;
  222. }
  223. /**
  224. * Returns a geometry data structure holding the geometry property values for
  225. * monitoring.
  226. *
  227. * @param {BufferGeometry} geometry - The geometry.
  228. * @return {Object} An object for monitoring geometry properties.
  229. */
  230. getGeometryData( geometry ) {
  231. let data = _geometryCache.get( geometry );
  232. if ( data === undefined ) {
  233. data = {
  234. _renderId: -1,
  235. _equal: false,
  236. attributes: this.getAttributesData( geometry.attributes ),
  237. indexId: geometry.index ? geometry.index.id : null,
  238. indexVersion: geometry.index ? geometry.index.version : null,
  239. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  240. };
  241. _geometryCache.set( geometry, data );
  242. }
  243. return data;
  244. }
  245. /**
  246. * Returns a material data structure holding the material property values for
  247. * monitoring.
  248. *
  249. * @param {Material} material - The material.
  250. * @return {Object} An object for monitoring material properties.
  251. */
  252. getMaterialData( material ) {
  253. let data = _materialCache.get( material );
  254. if ( data === undefined ) {
  255. data = { _renderId: -1, _equal: false };
  256. for ( const property of this.refreshUniforms ) {
  257. const value = material[ property ];
  258. if ( value === null || value === undefined ) continue;
  259. if ( typeof value === 'object' && value.clone !== undefined ) {
  260. if ( value.isTexture === true ) {
  261. data[ property ] = { id: value.id, version: 0 };
  262. } else {
  263. data[ property ] = value.clone();
  264. }
  265. } else {
  266. data[ property ] = value;
  267. }
  268. }
  269. _materialCache.set( material, data );
  270. }
  271. return data;
  272. }
  273. /**
  274. * Returns `true` if the given render object has not changed its state.
  275. *
  276. * @param {RenderObject} renderObject - The render object.
  277. * @param {Array<Light>} lightsData - The current material lights.
  278. * @param {number} renderId - The current render ID.
  279. * @return {boolean} Whether the given render object has changed its state or not.
  280. */
  281. equals( renderObject, lightsData, renderId ) {
  282. const { object, material, geometry } = renderObject;
  283. const renderObjectData = this.getRenderObjectData( renderObject );
  284. // world matrix
  285. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  286. renderObjectData.worldMatrix.copy( object.matrixWorld );
  287. return false;
  288. }
  289. // material
  290. const materialData = this.getMaterialData( renderObject.material );
  291. // check the material for the "equal" state just once per render for all render objects
  292. if ( materialData._renderId !== renderId ) {
  293. materialData._renderId = renderId;
  294. for ( const property in materialData ) {
  295. const value = materialData[ property ];
  296. const mtlValue = material[ property ];
  297. if ( property === '_renderId' ) continue;
  298. if ( property === '_equal' ) continue;
  299. if ( value.equals !== undefined ) {
  300. if ( value.equals( mtlValue ) === false ) {
  301. value.copy( mtlValue );
  302. materialData._equal = false;
  303. return false;
  304. }
  305. } else if ( mtlValue.isTexture === true ) {
  306. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  307. value.id = mtlValue.id;
  308. value.version = mtlValue.version;
  309. materialData._equal = false;
  310. return false;
  311. }
  312. } else if ( value !== mtlValue ) {
  313. materialData[ property ] = mtlValue;
  314. materialData._equal = false;
  315. return false;
  316. }
  317. }
  318. if ( materialData.transmission > 0 ) {
  319. const { width, height } = renderObject.context;
  320. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  321. renderObjectData.bufferWidth = width;
  322. renderObjectData.bufferHeight = height;
  323. materialData._equal = false;
  324. return false;
  325. }
  326. }
  327. materialData._equal = true;
  328. } else {
  329. if ( materialData._equal === false ) return false;
  330. }
  331. // geometry
  332. if ( renderObjectData.geometryId !== geometry.id ) {
  333. renderObjectData.geometryId = geometry.id;
  334. return false;
  335. }
  336. const geometryData = this.getGeometryData( renderObject.geometry );
  337. // check the geoemtry for the "equal" state just once per render for all render objects
  338. if ( geometryData._renderId !== renderId ) {
  339. geometryData._renderId = renderId;
  340. // attributes
  341. const attributes = geometry.attributes;
  342. const storedAttributes = geometryData.attributes;
  343. let currentAttributeCount = 0;
  344. let storedAttributeCount = 0;
  345. for ( const _ in attributes ) currentAttributeCount ++; // eslint-disable-line no-unused-vars
  346. for ( const name in storedAttributes ) {
  347. storedAttributeCount ++;
  348. const storedAttributeData = storedAttributes[ name ];
  349. const attribute = attributes[ name ];
  350. if ( attribute === undefined ) {
  351. // attribute was removed
  352. delete storedAttributes[ name ];
  353. geometryData._equal = false;
  354. return false;
  355. }
  356. if ( storedAttributeData.id !== attribute.id || storedAttributeData.version !== attribute.version ) {
  357. storedAttributeData.id = attribute.id;
  358. storedAttributeData.version = attribute.version;
  359. geometryData._equal = false;
  360. return false;
  361. }
  362. }
  363. if ( storedAttributeCount !== currentAttributeCount ) {
  364. geometryData.attributes = this.getAttributesData( attributes );
  365. geometryData._equal = false;
  366. return false;
  367. }
  368. // check index
  369. const index = geometry.index;
  370. const storedIndexId = geometryData.indexId;
  371. const storedIndexVersion = geometryData.indexVersion;
  372. const currentIndexId = index ? index.id : null;
  373. const currentIndexVersion = index ? index.version : null;
  374. if ( storedIndexId !== currentIndexId || storedIndexVersion !== currentIndexVersion ) {
  375. geometryData.indexId = currentIndexId;
  376. geometryData.indexVersion = currentIndexVersion;
  377. geometryData._equal = false;
  378. return false;
  379. }
  380. // check drawRange
  381. if ( geometryData.drawRange.start !== geometry.drawRange.start || geometryData.drawRange.count !== geometry.drawRange.count ) {
  382. geometryData.drawRange.start = geometry.drawRange.start;
  383. geometryData.drawRange.count = geometry.drawRange.count;
  384. geometryData._equal = false;
  385. return false;
  386. }
  387. geometryData._equal = true;
  388. } else {
  389. if ( geometryData._equal === false ) return false;
  390. }
  391. // morph targets
  392. if ( renderObjectData.morphTargetInfluences ) {
  393. let morphChanged = false;
  394. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  395. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  396. renderObjectData.morphTargetInfluences[ i ] = object.morphTargetInfluences[ i ];
  397. morphChanged = true;
  398. }
  399. }
  400. if ( morphChanged ) return false;
  401. }
  402. // lights
  403. if ( renderObjectData.lights ) {
  404. for ( let i = 0; i < lightsData.length; i ++ ) {
  405. if ( renderObjectData.lights[ i ].map !== lightsData[ i ].map ) {
  406. return false;
  407. }
  408. }
  409. }
  410. // center
  411. if ( renderObjectData.center ) {
  412. if ( renderObjectData.center.equals( object.center ) === false ) {
  413. renderObjectData.center.copy( object.center );
  414. return true;
  415. }
  416. }
  417. // bundle
  418. if ( renderObject.bundle !== null ) {
  419. renderObjectData.version = renderObject.bundle.version;
  420. }
  421. return true;
  422. }
  423. /**
  424. * Returns the lights data for the given material lights.
  425. *
  426. * @param {Array<Light>} materialLights - The material lights.
  427. * @return {Array<Object>} The lights data for the given material lights.
  428. */
  429. getLightsData( materialLights, lights ) {
  430. lights.length = 0;
  431. for ( const light of materialLights ) {
  432. if ( light.isSpotLight === true && light.map !== null ) {
  433. // only add lights that have a map
  434. lights.push( { map: light.map.version } );
  435. }
  436. }
  437. return lights;
  438. }
  439. /**
  440. * Returns the lights for the given lights node and render ID.
  441. *
  442. * @param {LightsNode} lightsNode - The lights node.
  443. * @param {number} renderId - The render ID.
  444. * @return {Array<Object>} The lights for the given lights node and render ID.
  445. */
  446. getLights( lightsNode, renderId ) {
  447. let cached = _lightsCache.get( lightsNode );
  448. if ( cached === undefined ) {
  449. cached = { renderId: -1, lightsData: [] };
  450. _lightsCache.set( lightsNode, cached );
  451. }
  452. if ( cached.renderId === renderId ) {
  453. return cached.lightsData;
  454. }
  455. cached.renderId = renderId;
  456. this.getLightsData( lightsNode.getLights(), cached.lightsData );
  457. return cached.lightsData;
  458. }
  459. /**
  460. * Checks if the given render object requires a refresh.
  461. *
  462. * @param {RenderObject} renderObject - The render object.
  463. * @param {NodeFrame} nodeFrame - The current node frame.
  464. * @return {boolean} Whether the given render object requires a refresh or not.
  465. */
  466. needsRefresh( renderObject, nodeFrame ) {
  467. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) || this.needsVelocity( nodeFrame.renderer ) )
  468. return true;
  469. const { renderId } = nodeFrame;
  470. if ( this.renderId !== renderId ) {
  471. this.renderId = renderId;
  472. return true;
  473. }
  474. const isStatic = renderObject.object.static === true;
  475. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  476. if ( isStatic || isBundle )
  477. return false;
  478. const lightsData = this.getLights( renderObject.lightsNode, renderId );
  479. const notEqual = this.equals( renderObject, lightsData, renderId ) !== true;
  480. return notEqual;
  481. }
  482. }
  483. // Pre-compiled RegExp patterns for ignored files
  484. const IGNORED_FILES = [
  485. /^StackTrace\.js$/,
  486. /^TSLCore\.js$/,
  487. /^.*Node\.js$/,
  488. /^three\.webgpu.*\.js$/
  489. ];
  490. /**
  491. * Parses the stack trace and filters out ignored files.
  492. * Returns an array with function name, file, line, and column.
  493. */
  494. function getFilteredStack( stack ) {
  495. // Pattern to extract function name, file, line, and column from different browsers
  496. // Chrome: "at functionName (file.js:1:2)" or "at file.js:1:2"
  497. // Firefox: "functionName@file.js:1:2"
  498. const regex = /(?:at\s+(.+?)\s+\()?(?:(.+?)@)?([^@\s()]+):(\d+):(\d+)/;
  499. return stack.split( '\n' )
  500. .map( line => {
  501. const match = line.match( regex );
  502. if ( ! match ) return null; // Skip if line format is invalid
  503. // Chrome: match[1], Firefox: match[2]
  504. const fn = match[ 1 ] || match[ 2 ] || '';
  505. const file = match[ 3 ].split( '?' )[ 0 ]; // Clean file name (Vite/HMR)
  506. const lineNum = parseInt( match[ 4 ], 10 );
  507. const column = parseInt( match[ 5 ], 10 );
  508. // Extract only the filename from full path
  509. const fileName = file.split( '/' ).pop();
  510. return {
  511. fn: fn,
  512. file: fileName,
  513. line: lineNum,
  514. column: column
  515. };
  516. } )
  517. .filter( frame => {
  518. // Only keep frames that are valid and not in the ignore list
  519. return frame && ! IGNORED_FILES.some( regex => regex.test( frame.file ) );
  520. } );
  521. }
  522. /**
  523. * Class representing a stack trace for debugging purposes.
  524. */
  525. class StackTrace {
  526. /**
  527. * Creates a StackTrace instance by capturing and filtering the current stack trace.
  528. *
  529. * @param {Error|string|null} stackMessage - An optional stack trace to use instead of capturing a new one.
  530. */
  531. constructor( stackMessage = null ) {
  532. /**
  533. * This flag can be used for type testing.
  534. *
  535. * @type {boolean}
  536. * @readonly
  537. * @default true
  538. */
  539. this.isStackTrace = true;
  540. /**
  541. * The stack trace.
  542. *
  543. * @type {Array<{fn: string, file: string, line: number, column: number}>}
  544. */
  545. this.stack = getFilteredStack( stackMessage ? stackMessage : new Error().stack );
  546. }
  547. /**
  548. * Returns a formatted location string of the top stack frame.
  549. *
  550. * @returns {string} The formatted stack trace message.
  551. */
  552. getLocation() {
  553. if ( this.stack.length === 0 ) {
  554. return '[Unknown location]';
  555. }
  556. const mainStack = this.stack[ 0 ];
  557. const fn = mainStack.fn;
  558. const fnName = fn ? `"${ fn }()" at ` : '';
  559. return `${fnName}"${mainStack.file}:${mainStack.line}"`; // :${mainStack.column}
  560. }
  561. /**
  562. * Returns the full error message including the stack trace.
  563. *
  564. * @param {string} message - The error message.
  565. * @returns {string} The full error message with stack trace.
  566. */
  567. getError( message ) {
  568. if ( this.stack.length === 0 ) {
  569. return message;
  570. }
  571. // Output: "Error: message\n at functionName (file.js:line:column)"
  572. const stackString = this.stack.map( frame => {
  573. const location = `${ frame.file }:${ frame.line }:${ frame.column }`;
  574. if ( frame.fn ) {
  575. return ` at ${ frame.fn } (${ location })`;
  576. }
  577. return ` at ${ location }`;
  578. } ).join( '\n' );
  579. return `${ message }\n${ stackString }`;
  580. }
  581. }
  582. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  583. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  584. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  585. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  586. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  587. function cyrb53( value, seed = 0 ) {
  588. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  589. if ( Array.isArray( value ) ) {
  590. for ( let i = 0, val; i < value.length; i ++ ) {
  591. val = value[ i ];
  592. h1 = Math.imul( h1 ^ val, 2654435761 );
  593. h2 = Math.imul( h2 ^ val, 1597334677 );
  594. }
  595. } else {
  596. for ( let i = 0, ch; i < value.length; i ++ ) {
  597. ch = value.charCodeAt( i );
  598. h1 = Math.imul( h1 ^ ch, 2654435761 );
  599. h2 = Math.imul( h2 ^ ch, 1597334677 );
  600. }
  601. }
  602. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  603. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  604. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  605. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  606. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  607. }
  608. /**
  609. * Computes a hash for the given string.
  610. *
  611. * @private
  612. * @method
  613. * @param {string} str - The string to be hashed.
  614. * @return {number} The hash.
  615. */
  616. const hashString = ( str ) => cyrb53( str );
  617. /**
  618. * Computes a hash for the given array.
  619. *
  620. * @private
  621. * @method
  622. * @param {Array<number>} array - The array to be hashed.
  623. * @return {number} The hash.
  624. */
  625. const hashArray = ( array ) => cyrb53( array );
  626. /**
  627. * Computes a hash for the given list of parameters.
  628. *
  629. * @private
  630. * @method
  631. * @param {...number} params - A list of parameters.
  632. * @return {number} The hash.
  633. */
  634. const hash$1 = ( ...params ) => cyrb53( params );
  635. const typeFromLength = /*@__PURE__*/ new Map( [
  636. [ 1, 'float' ],
  637. [ 2, 'vec2' ],
  638. [ 3, 'vec3' ],
  639. [ 4, 'vec4' ],
  640. [ 9, 'mat3' ],
  641. [ 16, 'mat4' ]
  642. ] );
  643. const dataFromObject = /*@__PURE__*/ new WeakMap();
  644. /**
  645. * Returns the data type for the given the length.
  646. *
  647. * @private
  648. * @method
  649. * @param {number} length - The length.
  650. * @return {string} The data type.
  651. */
  652. function getTypeFromLength( length ) {
  653. return typeFromLength.get( length );
  654. }
  655. /**
  656. * Returns the typed array for the given data type.
  657. *
  658. * @private
  659. * @method
  660. * @param {string} type - The data type.
  661. * @return {TypedArray} The typed array.
  662. */
  663. function getTypedArrayFromType( type ) {
  664. // Handle component type for vectors and matrices
  665. if ( /[iu]?vec\d/.test( type ) ) {
  666. // Handle int vectors
  667. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  668. // Handle uint vectors
  669. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  670. // Default to float vectors
  671. return Float32Array;
  672. }
  673. // Handle matrices (always float)
  674. if ( /mat\d/.test( type ) ) return Float32Array;
  675. // Basic types
  676. if ( /float/.test( type ) ) return Float32Array;
  677. if ( /uint/.test( type ) ) return Uint32Array;
  678. if ( /int/.test( type ) ) return Int32Array;
  679. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  680. }
  681. /**
  682. * Returns the length for the given data type.
  683. *
  684. * @private
  685. * @method
  686. * @param {string} type - The data type.
  687. * @return {number} The length.
  688. */
  689. function getLengthFromType( type ) {
  690. if ( /float|int|uint/.test( type ) ) return 1;
  691. if ( /vec2/.test( type ) ) return 2;
  692. if ( /vec3/.test( type ) ) return 3;
  693. if ( /vec4/.test( type ) ) return 4;
  694. if ( /mat2/.test( type ) ) return 4;
  695. if ( /mat3/.test( type ) ) return 9;
  696. if ( /mat4/.test( type ) ) return 16;
  697. error( `TSL: Unsupported type: ${ type }`, new StackTrace() );
  698. }
  699. /**
  700. * Returns the gpu memory length for the given data type.
  701. *
  702. * @private
  703. * @method
  704. * @param {string} type - The data type.
  705. * @return {number} The length.
  706. */
  707. function getMemoryLengthFromType( type ) {
  708. if ( /float|int|uint/.test( type ) ) return 1;
  709. if ( /vec2/.test( type ) ) return 2;
  710. if ( /vec3/.test( type ) ) return 3;
  711. if ( /vec4/.test( type ) ) return 4;
  712. if ( /mat2/.test( type ) ) return 4;
  713. if ( /mat3/.test( type ) ) return 12;
  714. if ( /mat4/.test( type ) ) return 16;
  715. error( `TSL: Unsupported type: ${ type }`, new StackTrace() );
  716. }
  717. /**
  718. * Returns the alignment requirement for the given data type.
  719. *
  720. * @private
  721. * @method
  722. * @param {string} type - The data type.
  723. * @return {number} The alignment requirement in bytes.
  724. */
  725. function getAlignmentFromType( type ) {
  726. if ( /float|int|uint/.test( type ) ) return 4;
  727. if ( /vec2/.test( type ) ) return 8;
  728. if ( /vec3/.test( type ) ) return 16;
  729. if ( /vec4/.test( type ) ) return 16;
  730. if ( /mat2/.test( type ) ) return 8;
  731. if ( /mat3/.test( type ) ) return 16;
  732. if ( /mat4/.test( type ) ) return 16;
  733. error( `TSL: Unsupported type: ${ type }`, new StackTrace() );
  734. }
  735. /**
  736. * Returns the data type for the given value.
  737. *
  738. * @private
  739. * @method
  740. * @param {any} value - The value.
  741. * @return {?string} The data type.
  742. */
  743. function getValueType( value ) {
  744. if ( value === undefined || value === null ) return null;
  745. const typeOf = typeof value;
  746. if ( value.isNode === true ) {
  747. return 'node';
  748. } else if ( typeOf === 'number' ) {
  749. return 'float';
  750. } else if ( typeOf === 'boolean' ) {
  751. return 'bool';
  752. } else if ( typeOf === 'string' ) {
  753. return 'string';
  754. } else if ( typeOf === 'function' ) {
  755. return 'shader';
  756. } else if ( value.isVector2 === true ) {
  757. return 'vec2';
  758. } else if ( value.isVector3 === true ) {
  759. return 'vec3';
  760. } else if ( value.isVector4 === true ) {
  761. return 'vec4';
  762. } else if ( value.isMatrix2 === true ) {
  763. return 'mat2';
  764. } else if ( value.isMatrix3 === true ) {
  765. return 'mat3';
  766. } else if ( value.isMatrix4 === true ) {
  767. return 'mat4';
  768. } else if ( value.isColor === true ) {
  769. return 'color';
  770. } else if ( value instanceof ArrayBuffer ) {
  771. return 'ArrayBuffer';
  772. }
  773. return null;
  774. }
  775. /**
  776. * Returns the value/object for the given data type and parameters.
  777. *
  778. * @private
  779. * @method
  780. * @param {string} type - The given type.
  781. * @param {...any} params - A parameter list.
  782. * @return {any} The value/object.
  783. */
  784. function getValueFromType( type, ...params ) {
  785. const last4 = type ? type.slice( -4 ) : undefined;
  786. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  787. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  788. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  789. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  790. }
  791. if ( type === 'color' ) {
  792. return new Color( ...params );
  793. } else if ( last4 === 'vec2' ) {
  794. return new Vector2( ...params );
  795. } else if ( last4 === 'vec3' ) {
  796. return new Vector3( ...params );
  797. } else if ( last4 === 'vec4' ) {
  798. return new Vector4( ...params );
  799. } else if ( last4 === 'mat2' ) {
  800. return new Matrix2( ...params );
  801. } else if ( last4 === 'mat3' ) {
  802. return new Matrix3( ...params );
  803. } else if ( last4 === 'mat4' ) {
  804. return new Matrix4( ...params );
  805. } else if ( type === 'bool' ) {
  806. return params[ 0 ] || false;
  807. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  808. return params[ 0 ] || 0;
  809. } else if ( type === 'string' ) {
  810. return params[ 0 ] || '';
  811. } else if ( type === 'ArrayBuffer' ) {
  812. return base64ToArrayBuffer( params[ 0 ] );
  813. }
  814. return null;
  815. }
  816. /**
  817. * Gets the object data that can be shared between different rendering steps.
  818. *
  819. * @private
  820. * @param {Object} object - The object to get the data for.
  821. * @return {Object} The object data.
  822. */
  823. function getDataFromObject( object ) {
  824. let data = dataFromObject.get( object );
  825. if ( data === undefined ) {
  826. data = {};
  827. dataFromObject.set( object, data );
  828. }
  829. return data;
  830. }
  831. /**
  832. * Converts the given array buffer to a Base64 string.
  833. *
  834. * @private
  835. * @method
  836. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  837. * @return {string} The Base64 string.
  838. */
  839. function arrayBufferToBase64( arrayBuffer ) {
  840. let chars = '';
  841. const array = new Uint8Array( arrayBuffer );
  842. for ( let i = 0; i < array.length; i ++ ) {
  843. chars += String.fromCharCode( array[ i ] );
  844. }
  845. return btoa( chars );
  846. }
  847. /**
  848. * Converts the given Base64 string to an array buffer.
  849. *
  850. * @private
  851. * @method
  852. * @param {string} base64 - The Base64 string.
  853. * @return {ArrayBuffer} The array buffer.
  854. */
  855. function base64ToArrayBuffer( base64 ) {
  856. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  857. }
  858. var NodeUtils = /*#__PURE__*/Object.freeze({
  859. __proto__: null,
  860. arrayBufferToBase64: arrayBufferToBase64,
  861. base64ToArrayBuffer: base64ToArrayBuffer,
  862. getAlignmentFromType: getAlignmentFromType,
  863. getDataFromObject: getDataFromObject,
  864. getLengthFromType: getLengthFromType,
  865. getMemoryLengthFromType: getMemoryLengthFromType,
  866. getTypeFromLength: getTypeFromLength,
  867. getTypedArrayFromType: getTypedArrayFromType,
  868. getValueFromType: getValueFromType,
  869. getValueType: getValueType,
  870. hash: hash$1,
  871. hashArray: hashArray,
  872. hashString: hashString
  873. });
  874. /**
  875. * Possible shader stages.
  876. *
  877. * @property {string} VERTEX The vertex shader stage.
  878. * @property {string} FRAGMENT The fragment shader stage.
  879. */
  880. const NodeShaderStage = {
  881. VERTEX: 'vertex',
  882. FRAGMENT: 'fragment'
  883. };
  884. /**
  885. * Update types of a node.
  886. *
  887. * @property {string} NONE The update method is not executed.
  888. * @property {string} FRAME The update method is executed per frame.
  889. * @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.
  890. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  891. */
  892. const NodeUpdateType = {
  893. NONE: 'none',
  894. FRAME: 'frame',
  895. RENDER: 'render',
  896. OBJECT: 'object'
  897. };
  898. /**
  899. * Data types of a node.
  900. *
  901. * @property {string} BOOLEAN Boolean type.
  902. * @property {string} INTEGER Integer type.
  903. * @property {string} FLOAT Float type.
  904. * @property {string} VECTOR2 Two-dimensional vector type.
  905. * @property {string} VECTOR3 Three-dimensional vector type.
  906. * @property {string} VECTOR4 Four-dimensional vector type.
  907. * @property {string} MATRIX2 2x2 matrix type.
  908. * @property {string} MATRIX3 3x3 matrix type.
  909. * @property {string} MATRIX4 4x4 matrix type.
  910. */
  911. const NodeType = {
  912. BOOLEAN: 'bool',
  913. INTEGER: 'int',
  914. FLOAT: 'float',
  915. VECTOR2: 'vec2',
  916. VECTOR3: 'vec3',
  917. VECTOR4: 'vec4',
  918. MATRIX2: 'mat2',
  919. MATRIX3: 'mat3',
  920. MATRIX4: 'mat4'
  921. };
  922. /**
  923. * Access types of a node. These are relevant for compute and storage usage.
  924. *
  925. * @property {string} READ_ONLY Read-only access
  926. * @property {string} WRITE_ONLY Write-only access.
  927. * @property {string} READ_WRITE Read and write access.
  928. */
  929. const NodeAccess = {
  930. READ_ONLY: 'readOnly',
  931. WRITE_ONLY: 'writeOnly',
  932. READ_WRITE: 'readWrite',
  933. };
  934. const defaultShaderStages = [ 'fragment', 'vertex' ];
  935. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  936. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  937. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  938. const _parentBuildStage = {
  939. analyze: 'setup',
  940. generate: 'analyze'
  941. };
  942. let _nodeId = 0;
  943. /**
  944. * Base class for all nodes.
  945. *
  946. * @augments EventDispatcher
  947. */
  948. class Node extends EventDispatcher {
  949. static get type() {
  950. return 'Node';
  951. }
  952. /**
  953. * Constructs a new node.
  954. *
  955. * @param {?string} nodeType - The node type.
  956. */
  957. constructor( nodeType = null ) {
  958. super();
  959. /**
  960. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  961. *
  962. * @type {?string}
  963. * @default null
  964. */
  965. this.nodeType = nodeType;
  966. /**
  967. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  968. *
  969. * @type {string}
  970. * @default 'none'
  971. */
  972. this.updateType = NodeUpdateType.NONE;
  973. /**
  974. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  975. *
  976. * @type {string}
  977. * @default 'none'
  978. */
  979. this.updateBeforeType = NodeUpdateType.NONE;
  980. /**
  981. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  982. *
  983. * @type {string}
  984. * @default 'none'
  985. */
  986. this.updateAfterType = NodeUpdateType.NONE;
  987. /**
  988. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  989. *
  990. * @type {number}
  991. * @readonly
  992. * @default 0
  993. */
  994. this.version = 0;
  995. /**
  996. * The name of the node.
  997. *
  998. * @type {string}
  999. * @default ''
  1000. */
  1001. this.name = '';
  1002. /**
  1003. * Whether this node is global or not. This property is relevant for the internal
  1004. * node caching system. All nodes which should be declared just once should
  1005. * set this flag to `true` (a typical example is {@link AttributeNode}).
  1006. *
  1007. * @type {boolean}
  1008. * @default false
  1009. */
  1010. this.global = false;
  1011. /**
  1012. * Create a list of parents for this node during the build process.
  1013. *
  1014. * @type {boolean}
  1015. * @default false
  1016. */
  1017. this.parents = false;
  1018. /**
  1019. * This flag can be used for type testing.
  1020. *
  1021. * @type {boolean}
  1022. * @readonly
  1023. * @default true
  1024. */
  1025. this.isNode = true;
  1026. // private
  1027. this._beforeNodes = null;
  1028. /**
  1029. * The cache key of this node.
  1030. *
  1031. * @private
  1032. * @type {?number}
  1033. * @default null
  1034. */
  1035. this._cacheKey = null;
  1036. /**
  1037. * The UUID of the node.
  1038. *
  1039. * @type {string}
  1040. * @default null
  1041. * @private
  1042. */
  1043. this._uuid = null;
  1044. /**
  1045. * The cache key's version.
  1046. *
  1047. * @private
  1048. * @type {number}
  1049. * @default 0
  1050. */
  1051. this._cacheKeyVersion = 0;
  1052. /**
  1053. * The unique ID of the node.
  1054. *
  1055. * @type {number}
  1056. * @readonly
  1057. */
  1058. this.id = _nodeId ++;
  1059. /**
  1060. * The stack trace of the node for debugging purposes.
  1061. *
  1062. * @type {?string}
  1063. * @default null
  1064. */
  1065. this.stackTrace = null;
  1066. if ( Node.captureStackTrace === true ) {
  1067. this.stackTrace = new StackTrace();
  1068. }
  1069. }
  1070. /**
  1071. * Set this property to `true` when the node should be regenerated.
  1072. *
  1073. * @type {boolean}
  1074. * @default false
  1075. * @param {boolean} value
  1076. */
  1077. set needsUpdate( value ) {
  1078. if ( value === true ) {
  1079. this.version ++;
  1080. }
  1081. }
  1082. /**
  1083. * The UUID of the node.
  1084. *
  1085. * @type {string}
  1086. * @readonly
  1087. */
  1088. get uuid() {
  1089. if ( this._uuid === null ) {
  1090. this._uuid = MathUtils.generateUUID();
  1091. }
  1092. return this._uuid;
  1093. }
  1094. /**
  1095. * The type of the class. The value is usually the constructor name.
  1096. *
  1097. * @type {string}
  1098. * @readonly
  1099. */
  1100. get type() {
  1101. return this.constructor.type;
  1102. }
  1103. /**
  1104. * Convenient method for defining {@link Node#update}.
  1105. *
  1106. * @param {Function} callback - The update method.
  1107. * @param {string} updateType - The update type.
  1108. * @return {Node} A reference to this node.
  1109. */
  1110. onUpdate( callback, updateType ) {
  1111. this.updateType = updateType;
  1112. this.update = callback.bind( this );
  1113. return this;
  1114. }
  1115. /**
  1116. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  1117. * this method automatically sets the update type to `FRAME`.
  1118. *
  1119. * @param {Function} callback - The update method.
  1120. * @return {Node} A reference to this node.
  1121. */
  1122. onFrameUpdate( callback ) {
  1123. return this.onUpdate( callback, NodeUpdateType.FRAME );
  1124. }
  1125. /**
  1126. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  1127. * this method automatically sets the update type to `RENDER`.
  1128. *
  1129. * @param {Function} callback - The update method.
  1130. * @return {Node} A reference to this node.
  1131. */
  1132. onRenderUpdate( callback ) {
  1133. return this.onUpdate( callback, NodeUpdateType.RENDER );
  1134. }
  1135. /**
  1136. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  1137. * this method automatically sets the update type to `OBJECT`.
  1138. *
  1139. * @param {Function} callback - The update method.
  1140. * @return {Node} A reference to this node.
  1141. */
  1142. onObjectUpdate( callback ) {
  1143. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  1144. }
  1145. /**
  1146. * Convenient method for defining {@link Node#updateReference}.
  1147. *
  1148. * @param {Function} callback - The update method.
  1149. * @return {Node} A reference to this node.
  1150. */
  1151. onReference( callback ) {
  1152. this.updateReference = callback.bind( this );
  1153. return this;
  1154. }
  1155. /**
  1156. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  1157. * to such objects based on a given state (e.g. the current node frame or builder).
  1158. *
  1159. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  1160. * @return {any} The updated reference.
  1161. */
  1162. updateReference( /*state*/ ) {
  1163. return this;
  1164. }
  1165. /**
  1166. * By default this method returns the value of the {@link Node#global} flag. This method
  1167. * can be overwritten in derived classes if an analytical way is required to determine the
  1168. * global cache referring to the current shader-stage.
  1169. *
  1170. * @param {NodeBuilder} builder - The current node builder.
  1171. * @return {boolean} Whether this node is global or not.
  1172. */
  1173. isGlobal( /*builder*/ ) {
  1174. return this.global;
  1175. }
  1176. /**
  1177. * Generator function that can be used to iterate over the child nodes.
  1178. *
  1179. * @generator
  1180. * @yields {Node} A child node.
  1181. */
  1182. * getChildren() {
  1183. for ( const { childNode } of this._getChildren() ) {
  1184. yield childNode;
  1185. }
  1186. }
  1187. /**
  1188. * Calling this method dispatches the `dispose` event. This event can be used
  1189. * to register event listeners for clean up tasks.
  1190. */
  1191. dispose() {
  1192. this.dispatchEvent( { type: 'dispose' } );
  1193. }
  1194. /**
  1195. * Callback for {@link Node#traverse}.
  1196. *
  1197. * @callback traverseCallback
  1198. * @param {Node} node - The current node.
  1199. */
  1200. /**
  1201. * Can be used to traverse through the node's hierarchy.
  1202. *
  1203. * @param {traverseCallback} callback - A callback that is executed per node.
  1204. */
  1205. traverse( callback ) {
  1206. callback( this );
  1207. for ( const childNode of this.getChildren() ) {
  1208. childNode.traverse( callback );
  1209. }
  1210. }
  1211. /**
  1212. * Returns the child nodes of this node.
  1213. *
  1214. * @private
  1215. * @param {Set<Node>} [ignores=new Set()] - A set of nodes to ignore during the search to avoid circular references.
  1216. * @returns {Array<Object>} An array of objects describing the child nodes.
  1217. */
  1218. _getChildren( ignores = new Set() ) {
  1219. const children = [];
  1220. // avoid circular references
  1221. ignores.add( this );
  1222. for ( const property of Object.getOwnPropertyNames( this ) ) {
  1223. const object = this[ property ];
  1224. // Ignore private properties and ignored nodes.
  1225. if ( property.startsWith( '_' ) === true || ignores.has( object ) ) continue;
  1226. if ( Array.isArray( object ) === true ) {
  1227. for ( let i = 0; i < object.length; i ++ ) {
  1228. const child = object[ i ];
  1229. if ( child && child.isNode === true ) {
  1230. children.push( { property, index: i, childNode: child } );
  1231. }
  1232. }
  1233. } else if ( object && object.isNode === true ) {
  1234. children.push( { property, childNode: object } );
  1235. } else if ( object && Object.getPrototypeOf( object ) === Object.prototype ) {
  1236. for ( const subProperty in object ) {
  1237. // Ignore private sub-properties.
  1238. if ( subProperty.startsWith( '_' ) === true ) continue;
  1239. const child = object[ subProperty ];
  1240. if ( child && child.isNode === true ) {
  1241. children.push( { property, index: subProperty, childNode: child } );
  1242. }
  1243. }
  1244. }
  1245. }
  1246. //
  1247. return children;
  1248. }
  1249. /**
  1250. * Returns the cache key for this node.
  1251. *
  1252. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  1253. * @param {Set<Node>} [ignores=null] - A set of nodes to ignore during the computation of the cache key.
  1254. * @return {number} The cache key of the node.
  1255. */
  1256. getCacheKey( force = false, ignores = null ) {
  1257. force = force || this.version !== this._cacheKeyVersion;
  1258. if ( force === true || this._cacheKey === null ) {
  1259. if ( ignores === null ) ignores = new Set();
  1260. //
  1261. const values = [];
  1262. for ( const { property, childNode } of this._getChildren( ignores ) ) {
  1263. values.push( hashString( property.slice( 0, -4 ) ), childNode.getCacheKey( force, ignores ) );
  1264. }
  1265. //
  1266. this._cacheKey = hash$1( hashArray( values ), this.customCacheKey() );
  1267. this._cacheKeyVersion = this.version;
  1268. }
  1269. return this._cacheKey;
  1270. }
  1271. /**
  1272. * Generate a custom cache key for this node.
  1273. *
  1274. * @return {number} The cache key of the node.
  1275. */
  1276. customCacheKey() {
  1277. return this.id;
  1278. }
  1279. /**
  1280. * Returns the references to this node which is by default `this`.
  1281. *
  1282. * @return {Node} A reference to this node.
  1283. */
  1284. getScope() {
  1285. return this;
  1286. }
  1287. /**
  1288. * Returns the hash of the node which is used to identify the node. By default it's
  1289. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  1290. * depending on their implementation.
  1291. *
  1292. * @param {NodeBuilder} builder - The current node builder.
  1293. * @return {string} The hash.
  1294. */
  1295. getHash( /*builder*/ ) {
  1296. return String( this.id );
  1297. }
  1298. /**
  1299. * Returns the update type of {@link Node#update}.
  1300. *
  1301. * @return {NodeUpdateType} The update type.
  1302. */
  1303. getUpdateType() {
  1304. return this.updateType;
  1305. }
  1306. /**
  1307. * Returns the update type of {@link Node#updateBefore}.
  1308. *
  1309. * @return {NodeUpdateType} The update type.
  1310. */
  1311. getUpdateBeforeType() {
  1312. return this.updateBeforeType;
  1313. }
  1314. /**
  1315. * Returns the update type of {@link Node#updateAfter}.
  1316. *
  1317. * @return {NodeUpdateType} The update type.
  1318. */
  1319. getUpdateAfterType() {
  1320. return this.updateAfterType;
  1321. }
  1322. /**
  1323. * Certain types are composed of multiple elements. For example a `vec3`
  1324. * is composed of three `float` values. This method returns the type of
  1325. * these elements.
  1326. *
  1327. * @param {NodeBuilder} builder - The current node builder.
  1328. * @return {string} The type of the node.
  1329. */
  1330. getElementType( builder ) {
  1331. const type = this.getNodeType( builder );
  1332. const elementType = builder.getElementType( type );
  1333. return elementType;
  1334. }
  1335. /**
  1336. * Returns the node member type for the given name.
  1337. *
  1338. * @param {NodeBuilder} builder - The current node builder.
  1339. * @param {string} name - The name of the member.
  1340. * @return {string} The type of the node.
  1341. */
  1342. getMemberType( /*builder, name*/ ) {
  1343. return 'void';
  1344. }
  1345. /**
  1346. * Returns the node's type.
  1347. *
  1348. * @param {NodeBuilder} builder - The current node builder.
  1349. * @param {string} [output=null] - The output of the node.
  1350. * @return {string} The type of the node.
  1351. */
  1352. getNodeType( builder, output = null ) {
  1353. const nodeData = builder.getDataFromNode( this );
  1354. let type;
  1355. if ( output !== null ) {
  1356. nodeData.typeFromOutput = nodeData.typeFromOutput || {};
  1357. type = nodeData.typeFromOutput[ output ];
  1358. if ( type === undefined ) {
  1359. type = this.generateNodeType( builder, output );
  1360. nodeData.typeFromOutput[ output ] = type;
  1361. }
  1362. } else {
  1363. type = nodeData.type;
  1364. if ( type === undefined ) {
  1365. type = this.generateNodeType( builder );
  1366. nodeData.type = type;
  1367. }
  1368. }
  1369. return type;
  1370. }
  1371. /**
  1372. * Returns the node's type.
  1373. *
  1374. * @param {NodeBuilder} builder - The current node builder.
  1375. * @param {string} [output=null] - The output of the node.
  1376. * @return {string} The type of the node.
  1377. */
  1378. generateNodeType( builder, output = null ) {
  1379. const nodeProperties = builder.getNodeProperties( this );
  1380. if ( nodeProperties.outputNode ) {
  1381. return nodeProperties.outputNode.getNodeType( builder, output );
  1382. }
  1383. return this.nodeType;
  1384. }
  1385. /**
  1386. * This method is used during the build process of a node and ensures
  1387. * equal nodes are not built multiple times but just once. For example if
  1388. * `attribute( 'uv' )` is used multiple times by the user, the build
  1389. * process makes sure to process just the first node.
  1390. *
  1391. * @param {NodeBuilder} builder - The current node builder.
  1392. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1393. */
  1394. getShared( builder ) {
  1395. const hash = this.getHash( builder );
  1396. const nodeFromHash = builder.getNodeFromHash( hash );
  1397. return nodeFromHash || this;
  1398. }
  1399. /**
  1400. * Returns the number of elements in the node array.
  1401. *
  1402. * @param {NodeBuilder} builder - The current node builder.
  1403. * @return {?number} The number of elements in the node array.
  1404. */
  1405. getArrayCount( /*builder*/ ) {
  1406. return null;
  1407. }
  1408. /**
  1409. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1410. * This method is often overwritten in derived modules to prepare the node which is used as a node's output/result.
  1411. * If an output node is prepared, then it must be returned in the `return` statement of the derived module's setup function.
  1412. *
  1413. * @param {NodeBuilder} builder - The current node builder.
  1414. * @return {?Node} The output node.
  1415. */
  1416. setup( builder ) {
  1417. const nodeProperties = builder.getNodeProperties( this );
  1418. let index = 0;
  1419. for ( const childNode of this.getChildren() ) {
  1420. nodeProperties[ 'node' + index ++ ] = childNode;
  1421. }
  1422. // return a outputNode if exists or null
  1423. return nodeProperties.outputNode || null;
  1424. }
  1425. /**
  1426. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1427. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1428. *
  1429. * @param {NodeBuilder} builder - The current node builder.
  1430. * @param {?Node} output - The target output node.
  1431. */
  1432. analyze( builder, output = null ) {
  1433. const usageCount = builder.increaseUsage( this );
  1434. if ( this.parents === true ) {
  1435. const nodeData = builder.getDataFromNode( this, 'any' );
  1436. nodeData.stages = nodeData.stages || {};
  1437. nodeData.stages[ builder.shaderStage ] = nodeData.stages[ builder.shaderStage ] || [];
  1438. nodeData.stages[ builder.shaderStage ].push( output );
  1439. }
  1440. if ( usageCount === 1 ) {
  1441. // node flow children
  1442. const nodeProperties = builder.getNodeProperties( this );
  1443. for ( const childNode of Object.values( nodeProperties ) ) {
  1444. if ( childNode && childNode.isNode === true ) {
  1445. childNode.build( builder, this );
  1446. }
  1447. }
  1448. }
  1449. }
  1450. /**
  1451. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1452. * This state builds the output node and returns the resulting shader string.
  1453. *
  1454. * @param {NodeBuilder} builder - The current node builder.
  1455. * @param {?string} [output] - Can be used to define the output type.
  1456. * @return {?string} The generated shader string.
  1457. */
  1458. generate( builder, output ) {
  1459. const { outputNode } = builder.getNodeProperties( this );
  1460. if ( outputNode && outputNode.isNode === true ) {
  1461. return outputNode.build( builder, output );
  1462. }
  1463. }
  1464. /**
  1465. * The method can be implemented to update the node's internal state before it is used to render an object.
  1466. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1467. *
  1468. * @abstract
  1469. * @param {NodeFrame} frame - A reference to the current node frame.
  1470. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1471. */
  1472. updateBefore( /*frame*/ ) {
  1473. warn( 'Abstract function.' );
  1474. }
  1475. /**
  1476. * The method can be implemented to update the node's internal state after it was used to render an object.
  1477. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1478. *
  1479. * @abstract
  1480. * @param {NodeFrame} frame - A reference to the current node frame.
  1481. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1482. */
  1483. updateAfter( /*frame*/ ) {
  1484. warn( 'Abstract function.' );
  1485. }
  1486. /**
  1487. * The method can be implemented to update the node's internal state when it is used to render an object.
  1488. * The {@link Node#updateType} property defines how often the update is executed.
  1489. *
  1490. * @abstract
  1491. * @param {NodeFrame} frame - A reference to the current node frame.
  1492. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1493. */
  1494. update( /*frame*/ ) {
  1495. warn( 'Abstract function.' );
  1496. }
  1497. before( node ) {
  1498. if ( this._beforeNodes === null ) this._beforeNodes = [];
  1499. this._beforeNodes.push( node );
  1500. return this;
  1501. }
  1502. /**
  1503. * This method performs the build of a node. The behavior and return value depend on the current build stage:
  1504. * - **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.
  1505. * - **analyze**: Analyzes the node hierarchy for optimizations in the code generation stage. Returns `null`.
  1506. * - **generate**: Generates the shader code for the node. Returns the generated shader string.
  1507. *
  1508. * @param {NodeBuilder} builder - The current node builder.
  1509. * @param {?(string|Node)} [output=null] - Can be used to define the output type.
  1510. * @return {?(Node|string)} The result of the build process, depending on the build stage.
  1511. */
  1512. build( builder, output = null ) {
  1513. const refNode = this.getShared( builder );
  1514. if ( this !== refNode ) {
  1515. return refNode.build( builder, output );
  1516. }
  1517. //
  1518. if ( this._beforeNodes !== null ) {
  1519. const currentBeforeNodes = this._beforeNodes;
  1520. this._beforeNodes = null;
  1521. for ( const beforeNode of currentBeforeNodes ) {
  1522. beforeNode.build( builder, output );
  1523. }
  1524. this._beforeNodes = currentBeforeNodes;
  1525. }
  1526. //
  1527. const nodeData = builder.getDataFromNode( this );
  1528. nodeData.buildStages = nodeData.buildStages || {};
  1529. nodeData.buildStages[ builder.buildStage ] = true;
  1530. const parentBuildStage = _parentBuildStage[ builder.buildStage ];
  1531. if ( parentBuildStage && nodeData.buildStages[ parentBuildStage ] !== true ) {
  1532. // force parent build stage (setup or analyze)
  1533. const previousBuildStage = builder.getBuildStage();
  1534. builder.setBuildStage( parentBuildStage );
  1535. this.build( builder );
  1536. builder.setBuildStage( previousBuildStage );
  1537. }
  1538. //
  1539. builder.addChain( this );
  1540. /* Build stages expected results:
  1541. - "setup" -> Node
  1542. - "analyze" -> null
  1543. - "generate" -> String
  1544. */
  1545. let result = null;
  1546. const buildStage = builder.getBuildStage();
  1547. if ( buildStage === 'setup' ) {
  1548. builder.addNode( this );
  1549. this.updateReference( builder );
  1550. const properties = builder.getNodeProperties( this );
  1551. if ( properties.initialized !== true ) {
  1552. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1553. properties.initialized = true;
  1554. properties.outputNode = this.setup( builder ) || properties.outputNode || null;
  1555. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1556. // !! no outputNode !!
  1557. //outputNode = builder.stack;
  1558. }*/
  1559. for ( const childNode of Object.values( properties ) ) {
  1560. if ( childNode && childNode.isNode === true ) {
  1561. if ( childNode.parents === true ) {
  1562. const childProperties = builder.getNodeProperties( childNode );
  1563. childProperties.parents = childProperties.parents || [];
  1564. childProperties.parents.push( this );
  1565. }
  1566. childNode.build( builder );
  1567. }
  1568. }
  1569. builder.addSequentialNode( this );
  1570. }
  1571. result = properties.outputNode;
  1572. } else if ( buildStage === 'analyze' ) {
  1573. this.analyze( builder, output );
  1574. } else if ( buildStage === 'generate' ) {
  1575. // If generate has just one argument, it means the output type is not required.
  1576. // This means that the node does not handle output conversions internally,
  1577. // so the value is stored in a cache and the builder handles the conversion
  1578. // for all requested output types.
  1579. const isGenerateOnce = this.generate.length < 2;
  1580. if ( isGenerateOnce ) {
  1581. const type = this.getNodeType( builder );
  1582. const nodeData = builder.getDataFromNode( this );
  1583. result = nodeData.snippet;
  1584. if ( result === undefined ) {
  1585. if ( nodeData.generated === undefined ) {
  1586. nodeData.generated = true;
  1587. result = this.generate( builder ) || '';
  1588. nodeData.snippet = result;
  1589. } else {
  1590. warn( 'Node: Recursion detected.', this );
  1591. result = '/* Recursion detected. */';
  1592. }
  1593. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1594. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1595. }
  1596. result = builder.format( result, type, output );
  1597. } else {
  1598. result = this.generate( builder, output ) || '';
  1599. }
  1600. if ( result === '' && output !== null && output !== 'void' && output !== 'OutputType' ) {
  1601. // if no snippet is generated, return a default value
  1602. error( `TSL: Invalid generated code, expected a "${ output }".` );
  1603. result = builder.generateConst( output );
  1604. }
  1605. }
  1606. builder.removeChain( this );
  1607. return result;
  1608. }
  1609. /**
  1610. * Returns the child nodes as a JSON object.
  1611. *
  1612. * @return {Generator<Object>} An iterable list of serialized child objects as JSON.
  1613. */
  1614. getSerializeChildren() {
  1615. return this._getChildren();
  1616. }
  1617. /**
  1618. * Serializes the node to JSON.
  1619. *
  1620. * @param {Object} json - The output JSON object.
  1621. */
  1622. serialize( json ) {
  1623. const nodeChildren = this.getSerializeChildren();
  1624. const inputNodes = {};
  1625. for ( const { property, index, childNode } of nodeChildren ) {
  1626. if ( index !== undefined ) {
  1627. if ( inputNodes[ property ] === undefined ) {
  1628. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1629. }
  1630. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1631. } else {
  1632. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1633. }
  1634. }
  1635. if ( Object.keys( inputNodes ).length > 0 ) {
  1636. json.inputNodes = inputNodes;
  1637. }
  1638. }
  1639. /**
  1640. * Deserializes the node from the given JSON.
  1641. *
  1642. * @param {Object} json - The JSON object.
  1643. */
  1644. deserialize( json ) {
  1645. if ( json.inputNodes !== undefined ) {
  1646. const nodes = json.meta.nodes;
  1647. for ( const property in json.inputNodes ) {
  1648. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1649. const inputArray = [];
  1650. for ( const uuid of json.inputNodes[ property ] ) {
  1651. inputArray.push( nodes[ uuid ] );
  1652. }
  1653. this[ property ] = inputArray;
  1654. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1655. const inputObject = {};
  1656. for ( const subProperty in json.inputNodes[ property ] ) {
  1657. const uuid = json.inputNodes[ property ][ subProperty ];
  1658. inputObject[ subProperty ] = nodes[ uuid ];
  1659. }
  1660. this[ property ] = inputObject;
  1661. } else {
  1662. const uuid = json.inputNodes[ property ];
  1663. this[ property ] = nodes[ uuid ];
  1664. }
  1665. }
  1666. }
  1667. }
  1668. /**
  1669. * Serializes the node into the three.js JSON Object/Scene format.
  1670. *
  1671. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1672. * @return {Object} The serialized node.
  1673. */
  1674. toJSON( meta ) {
  1675. const { uuid, type } = this;
  1676. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1677. if ( isRoot ) {
  1678. meta = {
  1679. textures: {},
  1680. images: {},
  1681. nodes: {}
  1682. };
  1683. }
  1684. // serialize
  1685. let data = meta.nodes[ uuid ];
  1686. if ( data === undefined ) {
  1687. data = {
  1688. uuid,
  1689. type,
  1690. meta,
  1691. metadata: {
  1692. version: 4.7,
  1693. type: 'Node',
  1694. generator: 'Node.toJSON'
  1695. }
  1696. };
  1697. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1698. this.serialize( data );
  1699. delete data.meta;
  1700. }
  1701. // TODO: Copied from Object3D.toJSON
  1702. function extractFromCache( cache ) {
  1703. const values = [];
  1704. for ( const key in cache ) {
  1705. const data = cache[ key ];
  1706. delete data.metadata;
  1707. values.push( data );
  1708. }
  1709. return values;
  1710. }
  1711. if ( isRoot ) {
  1712. const textures = extractFromCache( meta.textures );
  1713. const images = extractFromCache( meta.images );
  1714. const nodes = extractFromCache( meta.nodes );
  1715. if ( textures.length > 0 ) data.textures = textures;
  1716. if ( images.length > 0 ) data.images = images;
  1717. if ( nodes.length > 0 ) data.nodes = nodes;
  1718. }
  1719. return data;
  1720. }
  1721. }
  1722. /**
  1723. * Enables or disables the automatic capturing of stack traces for nodes.
  1724. *
  1725. * @type {boolean}
  1726. * @default false
  1727. */
  1728. Node.captureStackTrace = false;
  1729. /**
  1730. * Base class for representing element access on an array-like
  1731. * node data structures.
  1732. *
  1733. * @augments Node
  1734. */
  1735. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1736. static get type() {
  1737. return 'ArrayElementNode';
  1738. }
  1739. /**
  1740. * Constructs an array element node.
  1741. *
  1742. * @param {Node} node - The array-like node.
  1743. * @param {Node} indexNode - The index node that defines the element access.
  1744. */
  1745. constructor( node, indexNode ) {
  1746. super();
  1747. /**
  1748. * The array-like node.
  1749. *
  1750. * @type {Node}
  1751. */
  1752. this.node = node;
  1753. /**
  1754. * The index node that defines the element access.
  1755. *
  1756. * @type {Node}
  1757. */
  1758. this.indexNode = indexNode;
  1759. /**
  1760. * This flag can be used for type testing.
  1761. *
  1762. * @type {boolean}
  1763. * @readonly
  1764. * @default true
  1765. */
  1766. this.isArrayElementNode = true;
  1767. }
  1768. /**
  1769. * This method is overwritten since the node type is inferred from the array-like node.
  1770. *
  1771. * @param {NodeBuilder} builder - The current node builder.
  1772. * @return {string} The node type.
  1773. */
  1774. generateNodeType( builder ) {
  1775. return this.node.getElementType( builder );
  1776. }
  1777. /**
  1778. * This method is overwritten since the member type is inferred from the array-like node.
  1779. *
  1780. * @param {NodeBuilder} builder - The current node builder.
  1781. * @param {string} name - The member name.
  1782. * @return {string} The member type.
  1783. */
  1784. getMemberType( builder, name ) {
  1785. return this.node.getMemberType( builder, name );
  1786. }
  1787. generate( builder ) {
  1788. const indexType = this.indexNode.getNodeType( builder );
  1789. const nodeSnippet = this.node.build( builder );
  1790. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1791. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1792. }
  1793. }
  1794. /**
  1795. * This module is part of the TSL core and usually not used in app level code.
  1796. * It represents a convert operation during the shader generation process
  1797. * meaning it converts the data type of a node to a target data type.
  1798. *
  1799. * @augments Node
  1800. */
  1801. class ConvertNode extends Node {
  1802. static get type() {
  1803. return 'ConvertNode';
  1804. }
  1805. /**
  1806. * Constructs a new convert node.
  1807. *
  1808. * @param {Node} node - The node which type should be converted.
  1809. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1810. */
  1811. constructor( node, convertTo ) {
  1812. super();
  1813. /**
  1814. * The node which type should be converted.
  1815. *
  1816. * @type {Node}
  1817. */
  1818. this.node = node;
  1819. /**
  1820. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1821. *
  1822. * @type {string}
  1823. */
  1824. this.convertTo = convertTo;
  1825. }
  1826. /**
  1827. * This method is overwritten since the implementation tries to infer the best
  1828. * matching type from the {@link ConvertNode#convertTo} property.
  1829. *
  1830. * @param {NodeBuilder} builder - The current node builder.
  1831. * @return {string} The node type.
  1832. */
  1833. generateNodeType( builder ) {
  1834. const requestType = this.node.getNodeType( builder );
  1835. let convertTo = null;
  1836. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1837. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1838. convertTo = overloadingType;
  1839. }
  1840. }
  1841. return convertTo;
  1842. }
  1843. serialize( data ) {
  1844. super.serialize( data );
  1845. data.convertTo = this.convertTo;
  1846. }
  1847. deserialize( data ) {
  1848. super.deserialize( data );
  1849. this.convertTo = data.convertTo;
  1850. }
  1851. generate( builder, output ) {
  1852. const node = this.node;
  1853. const type = this.getNodeType( builder );
  1854. const snippet = node.build( builder, type );
  1855. return builder.format( snippet, type, output );
  1856. }
  1857. }
  1858. /**
  1859. * This module uses cache management to create temporary variables
  1860. * if the node is used more than once to prevent duplicate calculations.
  1861. *
  1862. * The class acts as a base class for many other nodes types.
  1863. *
  1864. * @augments Node
  1865. */
  1866. class TempNode extends Node {
  1867. static get type() {
  1868. return 'TempNode';
  1869. }
  1870. /**
  1871. * Constructs a temp node.
  1872. *
  1873. * @param {?string} nodeType - The node type.
  1874. */
  1875. constructor( nodeType = null ) {
  1876. super( nodeType );
  1877. /**
  1878. * This flag can be used for type testing.
  1879. *
  1880. * @type {boolean}
  1881. * @readonly
  1882. * @default true
  1883. */
  1884. this.isTempNode = true;
  1885. }
  1886. /**
  1887. * Whether this node is used more than once in context of other nodes.
  1888. *
  1889. * @param {NodeBuilder} builder - The node builder.
  1890. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1891. */
  1892. hasDependencies( builder ) {
  1893. return builder.getDataFromNode( this ).usageCount > 1;
  1894. }
  1895. build( builder, output ) {
  1896. const buildStage = builder.getBuildStage();
  1897. if ( buildStage === 'generate' ) {
  1898. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1899. const nodeData = builder.getDataFromNode( this );
  1900. if ( nodeData.propertyName !== undefined ) {
  1901. return builder.format( nodeData.propertyName, type, output );
  1902. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1903. const snippet = super.build( builder, type );
  1904. const nodeVar = builder.getVarFromNode( this, null, type );
  1905. const propertyName = builder.getPropertyName( nodeVar );
  1906. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1907. nodeData.snippet = snippet;
  1908. nodeData.propertyName = propertyName;
  1909. return builder.format( nodeData.propertyName, type, output );
  1910. }
  1911. }
  1912. return super.build( builder, output );
  1913. }
  1914. }
  1915. /**
  1916. * This module is part of the TSL core and usually not used in app level code.
  1917. * It represents a join operation during the shader generation process.
  1918. * For example in can compose/join two single floats into a `vec2` type.
  1919. *
  1920. * @augments TempNode
  1921. */
  1922. class JoinNode extends TempNode {
  1923. static get type() {
  1924. return 'JoinNode';
  1925. }
  1926. /**
  1927. * Constructs a new join node.
  1928. *
  1929. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1930. * @param {?string} [nodeType=null] - The node type.
  1931. */
  1932. constructor( nodes = [], nodeType = null ) {
  1933. super( nodeType );
  1934. /**
  1935. * An array of nodes that should be joined.
  1936. *
  1937. * @type {Array<Node>}
  1938. */
  1939. this.nodes = nodes;
  1940. }
  1941. /**
  1942. * This method is overwritten since the node type must be inferred from the
  1943. * joined data length if not explicitly defined.
  1944. *
  1945. * @param {NodeBuilder} builder - The current node builder.
  1946. * @return {string} The node type.
  1947. */
  1948. generateNodeType( builder ) {
  1949. if ( this.nodeType !== null ) {
  1950. return builder.getVectorType( this.nodeType );
  1951. }
  1952. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1953. }
  1954. generate( builder, output ) {
  1955. const type = this.getNodeType( builder );
  1956. const maxLength = builder.getTypeLength( type );
  1957. const nodes = this.nodes;
  1958. const primitiveType = builder.getComponentType( type );
  1959. const snippetValues = [];
  1960. let length = 0;
  1961. for ( const input of nodes ) {
  1962. if ( length >= maxLength ) {
  1963. error( `TSL: Length of parameters exceeds maximum length of function '${ type }()' type.`, this.stackTrace );
  1964. break;
  1965. }
  1966. let inputType = input.getNodeType( builder );
  1967. let inputTypeLength = builder.getTypeLength( inputType );
  1968. let inputSnippet;
  1969. if ( length + inputTypeLength > maxLength ) {
  1970. error( `TSL: Length of '${ type }()' data exceeds maximum length of output type.`, this.stackTrace );
  1971. inputTypeLength = maxLength - length;
  1972. inputType = builder.getTypeFromLength( inputTypeLength );
  1973. }
  1974. length += inputTypeLength;
  1975. inputSnippet = input.build( builder, inputType );
  1976. const inputPrimitiveType = builder.getComponentType( inputType );
  1977. if ( inputPrimitiveType !== primitiveType ) {
  1978. const targetType = builder.getTypeFromLength( inputTypeLength, primitiveType );
  1979. inputSnippet = builder.format( inputSnippet, inputType, targetType );
  1980. }
  1981. snippetValues.push( inputSnippet );
  1982. }
  1983. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1984. return builder.format( snippet, type, output );
  1985. }
  1986. }
  1987. const _stringVectorComponents = vectorComponents.join( '' );
  1988. /**
  1989. * This module is part of the TSL core and usually not used in app level code.
  1990. * `SplitNode` represents a property access operation which means it is
  1991. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1992. * For example:
  1993. * ```js
  1994. * const redValue = color.r;
  1995. * ```
  1996. *
  1997. * @augments Node
  1998. */
  1999. class SplitNode extends Node {
  2000. static get type() {
  2001. return 'SplitNode';
  2002. }
  2003. /**
  2004. * Constructs a new split node.
  2005. *
  2006. * @param {Node} node - The node that should be accessed.
  2007. * @param {string} [components='x'] - The components that should be accessed.
  2008. */
  2009. constructor( node, components = 'x' ) {
  2010. super();
  2011. /**
  2012. * The node that should be accessed.
  2013. *
  2014. * @type {Node}
  2015. */
  2016. this.node = node;
  2017. /**
  2018. * The components that should be accessed.
  2019. *
  2020. * @type {string}
  2021. */
  2022. this.components = components;
  2023. /**
  2024. * This flag can be used for type testing.
  2025. *
  2026. * @type {boolean}
  2027. * @readonly
  2028. * @default true
  2029. */
  2030. this.isSplitNode = true;
  2031. }
  2032. /**
  2033. * Returns the vector length which is computed based on the requested components.
  2034. *
  2035. * @return {number} The vector length.
  2036. */
  2037. getVectorLength() {
  2038. let vectorLength = this.components.length;
  2039. for ( const c of this.components ) {
  2040. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  2041. }
  2042. return vectorLength;
  2043. }
  2044. /**
  2045. * Returns the component type of the node's type.
  2046. *
  2047. * @param {NodeBuilder} builder - The current node builder.
  2048. * @return {string} The component type.
  2049. */
  2050. getComponentType( builder ) {
  2051. return builder.getComponentType( this.node.getNodeType( builder ) );
  2052. }
  2053. /**
  2054. * This method is overwritten since the node type is inferred from requested components.
  2055. *
  2056. * @param {NodeBuilder} builder - The current node builder.
  2057. * @return {string} The node type.
  2058. */
  2059. generateNodeType( builder ) {
  2060. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  2061. }
  2062. /**
  2063. * Returns the scope of the node.
  2064. *
  2065. * @return {Node} The scope of the node.
  2066. */
  2067. getScope() {
  2068. return this.node.getScope();
  2069. }
  2070. generate( builder, output ) {
  2071. const node = this.node;
  2072. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  2073. let snippet = null;
  2074. if ( nodeTypeLength > 1 ) {
  2075. let type = null;
  2076. const componentsLength = this.getVectorLength();
  2077. if ( componentsLength >= nodeTypeLength ) {
  2078. // needed expand the input node
  2079. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  2080. }
  2081. const nodeSnippet = node.build( builder, type );
  2082. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  2083. // unnecessary swizzle
  2084. snippet = builder.format( nodeSnippet, type, output );
  2085. } else {
  2086. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  2087. }
  2088. } else {
  2089. // ignore .components if .node returns float/integer
  2090. snippet = node.build( builder, output );
  2091. }
  2092. return snippet;
  2093. }
  2094. serialize( data ) {
  2095. super.serialize( data );
  2096. data.components = this.components;
  2097. }
  2098. deserialize( data ) {
  2099. super.deserialize( data );
  2100. this.components = data.components;
  2101. }
  2102. }
  2103. /**
  2104. * This module is part of the TSL core and usually not used in app level code.
  2105. * `SetNode` represents a set operation which means it is used to implement any
  2106. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  2107. * For example:
  2108. * ```js
  2109. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  2110. * ```
  2111. *
  2112. * @augments TempNode
  2113. */
  2114. class SetNode extends TempNode {
  2115. static get type() {
  2116. return 'SetNode';
  2117. }
  2118. /**
  2119. * Constructs a new set node.
  2120. *
  2121. * @param {Node} sourceNode - The node that should be updated.
  2122. * @param {string} components - The components that should be updated.
  2123. * @param {Node} targetNode - The value node.
  2124. */
  2125. constructor( sourceNode, components, targetNode ) {
  2126. super();
  2127. /**
  2128. * The node that should be updated.
  2129. *
  2130. * @type {Node}
  2131. */
  2132. this.sourceNode = sourceNode;
  2133. /**
  2134. * The components that should be updated.
  2135. *
  2136. * @type {string}
  2137. */
  2138. this.components = components;
  2139. /**
  2140. * The value node.
  2141. *
  2142. * @type {Node}
  2143. */
  2144. this.targetNode = targetNode;
  2145. }
  2146. /**
  2147. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  2148. *
  2149. * @param {NodeBuilder} builder - The current node builder.
  2150. * @return {string} The node type.
  2151. */
  2152. generateNodeType( builder ) {
  2153. return this.sourceNode.getNodeType( builder );
  2154. }
  2155. generate( builder ) {
  2156. const { sourceNode, components, targetNode } = this;
  2157. const sourceType = this.getNodeType( builder );
  2158. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  2159. const targetType = builder.getTypeFromLength( components.length, componentType );
  2160. const targetSnippet = targetNode.build( builder, targetType );
  2161. const sourceSnippet = sourceNode.build( builder, sourceType );
  2162. const length = builder.getTypeLength( sourceType );
  2163. const snippetValues = [];
  2164. for ( let i = 0; i < length; i ++ ) {
  2165. const component = vectorComponents[ i ];
  2166. if ( component === components[ 0 ] ) {
  2167. snippetValues.push( targetSnippet );
  2168. i += components.length - 1;
  2169. } else {
  2170. snippetValues.push( sourceSnippet + '.' + component );
  2171. }
  2172. }
  2173. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  2174. }
  2175. }
  2176. /**
  2177. * This module is part of the TSL core and usually not used in app level code.
  2178. * It represents a flip operation during the shader generation process
  2179. * meaning it flips normalized values with the following formula:
  2180. * ```
  2181. * x = 1 - x;
  2182. * ```
  2183. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  2184. * `flipSTPQ()` method invocations on node objects. For example:
  2185. * ```js
  2186. * uvNode = uvNode.flipY();
  2187. * ```
  2188. *
  2189. * @augments TempNode
  2190. */
  2191. class FlipNode extends TempNode {
  2192. static get type() {
  2193. return 'FlipNode';
  2194. }
  2195. /**
  2196. * Constructs a new flip node.
  2197. *
  2198. * @param {Node} sourceNode - The node which component(s) should be flipped.
  2199. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  2200. */
  2201. constructor( sourceNode, components ) {
  2202. super();
  2203. /**
  2204. * The node which component(s) should be flipped.
  2205. *
  2206. * @type {Node}
  2207. */
  2208. this.sourceNode = sourceNode;
  2209. /**
  2210. * The components that should be flipped e.g. `'x'` or `'xy'`.
  2211. *
  2212. * @type {string}
  2213. */
  2214. this.components = components;
  2215. }
  2216. /**
  2217. * This method is overwritten since the node type is inferred from the source node.
  2218. *
  2219. * @param {NodeBuilder} builder - The current node builder.
  2220. * @return {string} The node type.
  2221. */
  2222. generateNodeType( builder ) {
  2223. return this.sourceNode.getNodeType( builder );
  2224. }
  2225. generate( builder ) {
  2226. const { components, sourceNode } = this;
  2227. const sourceType = this.getNodeType( builder );
  2228. const sourceSnippet = sourceNode.build( builder );
  2229. const sourceCache = builder.getVarFromNode( this );
  2230. const sourceProperty = builder.getPropertyName( sourceCache );
  2231. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  2232. const length = builder.getTypeLength( sourceType );
  2233. const snippetValues = [];
  2234. let componentIndex = 0;
  2235. for ( let i = 0; i < length; i ++ ) {
  2236. const component = vectorComponents[ i ];
  2237. if ( component === components[ componentIndex ] ) {
  2238. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  2239. componentIndex ++;
  2240. } else {
  2241. snippetValues.push( sourceProperty + '.' + component );
  2242. }
  2243. }
  2244. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  2245. }
  2246. }
  2247. /**
  2248. * Base class for representing data input nodes.
  2249. *
  2250. * @augments Node
  2251. */
  2252. class InputNode extends Node {
  2253. static get type() {
  2254. return 'InputNode';
  2255. }
  2256. /**
  2257. * Constructs a new input node.
  2258. *
  2259. * @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).
  2260. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2261. */
  2262. constructor( value, nodeType = null ) {
  2263. super( nodeType );
  2264. /**
  2265. * This flag can be used for type testing.
  2266. *
  2267. * @type {boolean}
  2268. * @readonly
  2269. * @default true
  2270. */
  2271. this.isInputNode = true;
  2272. /**
  2273. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  2274. *
  2275. * @type {any}
  2276. */
  2277. this.value = value;
  2278. /**
  2279. * The precision of the value in the shader.
  2280. *
  2281. * @type {?('low'|'medium'|'high')}
  2282. * @default null
  2283. */
  2284. this.precision = null;
  2285. }
  2286. generateNodeType( /*builder*/ ) {
  2287. if ( this.nodeType === null ) {
  2288. return getValueType( this.value );
  2289. }
  2290. return this.nodeType;
  2291. }
  2292. /**
  2293. * Returns the input type of the node which is by default the node type. Derived modules
  2294. * might overwrite this method and use a fixed type or compute one analytically.
  2295. *
  2296. * A typical example for different input and node types are textures. The input type of a
  2297. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  2298. *
  2299. * @param {NodeBuilder} builder - The current node builder.
  2300. * @return {string} The input type.
  2301. */
  2302. getInputType( builder ) {
  2303. return this.getNodeType( builder );
  2304. }
  2305. /**
  2306. * Sets the precision to the given value. The method can be
  2307. * overwritten in derived classes if the final precision must be computed
  2308. * analytically.
  2309. *
  2310. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  2311. * @return {InputNode} A reference to this node.
  2312. */
  2313. setPrecision( precision ) {
  2314. this.precision = precision;
  2315. return this;
  2316. }
  2317. serialize( data ) {
  2318. super.serialize( data );
  2319. data.value = this.value;
  2320. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  2321. data.valueType = getValueType( this.value );
  2322. data.nodeType = this.nodeType;
  2323. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  2324. data.precision = this.precision;
  2325. }
  2326. deserialize( data ) {
  2327. super.deserialize( data );
  2328. this.nodeType = data.nodeType;
  2329. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  2330. this.precision = data.precision || null;
  2331. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  2332. }
  2333. generate( /*builder, output*/ ) {
  2334. warn( 'Abstract function.' );
  2335. }
  2336. }
  2337. const _regNum = /float|u?int/;
  2338. /**
  2339. * Class for representing a constant value in the shader.
  2340. *
  2341. * @augments InputNode
  2342. */
  2343. class ConstNode extends InputNode {
  2344. static get type() {
  2345. return 'ConstNode';
  2346. }
  2347. /**
  2348. * Constructs a new input node.
  2349. *
  2350. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  2351. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2352. */
  2353. constructor( value, nodeType = null ) {
  2354. super( value, nodeType );
  2355. /**
  2356. * This flag can be used for type testing.
  2357. *
  2358. * @type {boolean}
  2359. * @readonly
  2360. * @default true
  2361. */
  2362. this.isConstNode = true;
  2363. }
  2364. /**
  2365. * Generates the shader string of the value with the current node builder.
  2366. *
  2367. * @param {NodeBuilder} builder - The current node builder.
  2368. * @return {string} The generated value as a shader string.
  2369. */
  2370. generateConst( builder ) {
  2371. return builder.generateConst( this.getNodeType( builder ), this.value );
  2372. }
  2373. generate( builder, output ) {
  2374. const type = this.getNodeType( builder );
  2375. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  2376. return builder.generateConst( output, this.value );
  2377. }
  2378. return builder.format( this.generateConst( builder ), type, output );
  2379. }
  2380. }
  2381. /**
  2382. * Base class for representing member access on an object-like
  2383. * node data structures.
  2384. *
  2385. * @augments Node
  2386. */
  2387. class MemberNode extends Node {
  2388. static get type() {
  2389. return 'MemberNode';
  2390. }
  2391. /**
  2392. * Constructs a member node.
  2393. *
  2394. * @param {Node} structNode - The struct node.
  2395. * @param {string} property - The property name.
  2396. */
  2397. constructor( structNode, property ) {
  2398. super();
  2399. /**
  2400. * The struct node.
  2401. *
  2402. * @type {Node}
  2403. */
  2404. this.structNode = structNode;
  2405. /**
  2406. * The property name.
  2407. *
  2408. * @type {Node}
  2409. */
  2410. this.property = property;
  2411. /**
  2412. * This flag can be used for type testing.
  2413. *
  2414. * @type {boolean}
  2415. * @readonly
  2416. * @default true
  2417. */
  2418. this.isMemberNode = true;
  2419. }
  2420. hasMember( builder ) {
  2421. if ( this.structNode.isMemberNode ) {
  2422. if ( this.structNode.hasMember( builder ) === false ) {
  2423. return false;
  2424. }
  2425. }
  2426. return this.structNode.getMemberType( builder, this.property ) !== 'void';
  2427. }
  2428. generateNodeType( builder ) {
  2429. if ( this.hasMember( builder ) === false ) {
  2430. // default type if member does not exist
  2431. return 'float';
  2432. }
  2433. return this.structNode.getMemberType( builder, this.property );
  2434. }
  2435. getMemberType( builder, name ) {
  2436. if ( this.hasMember( builder ) === false ) {
  2437. // default type if member does not exist
  2438. return 'float';
  2439. }
  2440. const type = this.getNodeType( builder );
  2441. const struct = builder.getStructTypeNode( type );
  2442. return struct.getMemberType( builder, name );
  2443. }
  2444. generate( builder ) {
  2445. if ( this.hasMember( builder ) === false ) {
  2446. warn( `TSL: Member "${ this.property }" does not exist in struct.`, this.stackTrace );
  2447. const type = this.getNodeType( builder );
  2448. return builder.generateConst( type );
  2449. }
  2450. const propertyName = this.structNode.build( builder );
  2451. return propertyName + '.' + this.property;
  2452. }
  2453. }
  2454. let currentStack = null;
  2455. const NodeElements = new Map();
  2456. // Extend Node Class for TSL using prototype
  2457. function addMethodChaining( name, nodeElement ) {
  2458. // No require StackTrace because this is internal API
  2459. if ( NodeElements.has( name ) ) {
  2460. warn( `TSL: Redefinition of method chaining '${ name }'.` );
  2461. return;
  2462. }
  2463. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2464. NodeElements.set( name, nodeElement );
  2465. if ( name !== 'assign' ) {
  2466. // Changing Node prototype to add method chaining
  2467. Node.prototype[ name ] = function ( ...params ) {
  2468. //if ( name === 'toVarIntent' ) return this;
  2469. return this.isStackNode ? this.addToStack( nodeElement( ...params ) ) : nodeElement( this, ...params );
  2470. };
  2471. // Adding assign method chaining
  2472. Node.prototype[ name + 'Assign' ] = function ( ...params ) {
  2473. return this.isStackNode ? this.assign( params[ 0 ], nodeElement( ...params ) ) : this.assign( nodeElement( this, ...params ) );
  2474. };
  2475. }
  2476. }
  2477. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2478. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2479. Node.prototype.assign = function ( ...params ) {
  2480. if ( this.isStackNode !== true ) {
  2481. if ( currentStack !== null ) {
  2482. currentStack.assign( this, ...params );
  2483. } else {
  2484. error( 'TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().', new StackTrace() );
  2485. }
  2486. return this;
  2487. } else {
  2488. const nodeElement = NodeElements.get( 'assign' );
  2489. return this.addToStack( nodeElement( ...params ) );
  2490. }
  2491. };
  2492. Node.prototype.toVarIntent = function () {
  2493. return this;
  2494. };
  2495. Node.prototype.get = function ( value ) {
  2496. return new MemberNode( this, value );
  2497. };
  2498. // Cache prototype for TSL
  2499. const proto = {};
  2500. // Set swizzle properties for xyzw, rgba, and stpq.
  2501. function setProtoSwizzle( property, altA, altB ) {
  2502. // swizzle properties
  2503. proto[ property ] = proto[ altA ] = proto[ altB ] = {
  2504. get() {
  2505. this._cache = this._cache || {};
  2506. //
  2507. let split = this._cache[ property ];
  2508. if ( split === undefined ) {
  2509. split = new SplitNode( this, property );
  2510. this._cache[ property ] = split;
  2511. }
  2512. return split;
  2513. },
  2514. set( value ) {
  2515. this[ property ].assign( nodeObject( value ) );
  2516. }
  2517. };
  2518. // set properties ( swizzle ) and sort to xyzw sequence
  2519. const propUpper = property.toUpperCase();
  2520. const altAUpper = altA.toUpperCase();
  2521. const altBUpper = altB.toUpperCase();
  2522. // Set methods for swizzle properties
  2523. Node.prototype[ 'set' + propUpper ] = Node.prototype[ 'set' + altAUpper ] = Node.prototype[ 'set' + altBUpper ] = function ( value ) {
  2524. const swizzle = parseSwizzleAndSort( property );
  2525. return new SetNode( this, swizzle, nodeObject( value ) );
  2526. };
  2527. // Set methods for flip properties
  2528. Node.prototype[ 'flip' + propUpper ] = Node.prototype[ 'flip' + altAUpper ] = Node.prototype[ 'flip' + altBUpper ] = function () {
  2529. const swizzle = parseSwizzleAndSort( property );
  2530. return new FlipNode( this, swizzle );
  2531. };
  2532. }
  2533. const swizzleA = [ 'x', 'y', 'z', 'w' ];
  2534. const swizzleB = [ 'r', 'g', 'b', 'a' ];
  2535. const swizzleC = [ 's', 't', 'p', 'q' ];
  2536. for ( let a = 0; a < 4; a ++ ) {
  2537. let prop = swizzleA[ a ];
  2538. let altA = swizzleB[ a ];
  2539. let altB = swizzleC[ a ];
  2540. setProtoSwizzle( prop, altA, altB );
  2541. for ( let b = 0; b < 4; b ++ ) {
  2542. prop = swizzleA[ a ] + swizzleA[ b ];
  2543. altA = swizzleB[ a ] + swizzleB[ b ];
  2544. altB = swizzleC[ a ] + swizzleC[ b ];
  2545. setProtoSwizzle( prop, altA, altB );
  2546. for ( let c = 0; c < 4; c ++ ) {
  2547. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ];
  2548. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ];
  2549. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ];
  2550. setProtoSwizzle( prop, altA, altB );
  2551. for ( let d = 0; d < 4; d ++ ) {
  2552. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ] + swizzleA[ d ];
  2553. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ] + swizzleB[ d ];
  2554. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ] + swizzleC[ d ];
  2555. setProtoSwizzle( prop, altA, altB );
  2556. }
  2557. }
  2558. }
  2559. }
  2560. // Set/get static properties for array elements (0-31).
  2561. for ( let i = 0; i < 32; i ++ ) {
  2562. proto[ i ] = {
  2563. get() {
  2564. this._cache = this._cache || {};
  2565. //
  2566. let element = this._cache[ i ];
  2567. if ( element === undefined ) {
  2568. element = new ArrayElementNode( this, new ConstNode( i, 'uint' ) );
  2569. this._cache[ i ] = element;
  2570. }
  2571. return element;
  2572. },
  2573. set( value ) {
  2574. this[ i ].assign( nodeObject( value ) );
  2575. }
  2576. };
  2577. }
  2578. /*
  2579. // Set properties for width, height, and depth.
  2580. function setProtoProperty( property, target ) {
  2581. proto[ property ] = {
  2582. get() {
  2583. this._cache = this._cache || {};
  2584. //
  2585. let split = this._cache[ target ];
  2586. if ( split === undefined ) {
  2587. split = new SplitNode( this, target );
  2588. this._cache[ target ] = split;
  2589. }
  2590. return split;
  2591. },
  2592. set( value ) {
  2593. this[ target ].assign( nodeObject( value ) );
  2594. }
  2595. };
  2596. }
  2597. setProtoProperty( 'width', 'x' );
  2598. setProtoProperty( 'height', 'y' );
  2599. setProtoProperty( 'depth', 'z' );
  2600. */
  2601. Object.defineProperties( Node.prototype, proto );
  2602. // --- FINISH ---
  2603. const ShaderNodeObject = function ( obj, altType = null ) {
  2604. const type = getValueType( obj );
  2605. if ( type === 'node' ) {
  2606. return obj;
  2607. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2608. return nodeObject( getConstNode( obj, altType ) );
  2609. } else if ( type === 'shader' ) {
  2610. return obj.isFn ? obj : Fn( obj );
  2611. }
  2612. return obj;
  2613. };
  2614. const ShaderNodeObjects = function ( objects, altType = null ) {
  2615. for ( const name in objects ) {
  2616. objects[ name ] = nodeObject( objects[ name ], altType );
  2617. }
  2618. return objects;
  2619. };
  2620. const ShaderNodeArray = function ( array, altType = null ) {
  2621. const len = array.length;
  2622. for ( let i = 0; i < len; i ++ ) {
  2623. array[ i ] = nodeObject( array[ i ], altType );
  2624. }
  2625. return array;
  2626. };
  2627. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2628. function assignNode( node ) {
  2629. if ( settings !== null ) {
  2630. node = nodeObject( Object.assign( node, settings ) );
  2631. if ( settings.intent === true ) {
  2632. node = node.toVarIntent();
  2633. }
  2634. } else {
  2635. node = nodeObject( node );
  2636. }
  2637. return node;
  2638. }
  2639. let fn, name = scope, minParams, maxParams;
  2640. function verifyParamsLimit( params ) {
  2641. let tslName;
  2642. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2643. else tslName = NodeClass.type;
  2644. if ( minParams !== undefined && params.length < minParams ) {
  2645. error( `TSL: "${ tslName }" parameter length is less than minimum required.`, new StackTrace() );
  2646. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2647. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2648. error( `TSL: "${ tslName }" parameter length exceeds limit.`, new StackTrace() );
  2649. return params.slice( 0, maxParams );
  2650. }
  2651. return params;
  2652. }
  2653. if ( scope === null ) {
  2654. fn = ( ...params ) => {
  2655. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2656. };
  2657. } else if ( factor !== null ) {
  2658. factor = nodeObject( factor );
  2659. fn = ( ...params ) => {
  2660. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2661. };
  2662. } else {
  2663. fn = ( ...params ) => {
  2664. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2665. };
  2666. }
  2667. fn.setParameterLength = ( ...params ) => {
  2668. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2669. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2670. return fn;
  2671. };
  2672. fn.setName = ( value ) => {
  2673. name = value;
  2674. return fn;
  2675. };
  2676. return fn;
  2677. };
  2678. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2679. return new NodeClass( ...nodeArray( params ) );
  2680. };
  2681. class ShaderCallNodeInternal extends Node {
  2682. constructor( shaderNode, rawInputs ) {
  2683. super();
  2684. this.shaderNode = shaderNode;
  2685. this.rawInputs = rawInputs;
  2686. this.isShaderCallNodeInternal = true;
  2687. }
  2688. generateNodeType( builder ) {
  2689. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2690. }
  2691. getElementType( builder ) {
  2692. return this.getOutputNode( builder ).getElementType( builder );
  2693. }
  2694. getMemberType( builder, name ) {
  2695. return this.getOutputNode( builder ).getMemberType( builder, name );
  2696. }
  2697. call( builder ) {
  2698. const { shaderNode, rawInputs } = this;
  2699. const properties = builder.getNodeProperties( shaderNode );
  2700. const subBuild = builder.getClosestSubBuild( shaderNode.subBuilds ) || '';
  2701. const subBuildProperty = subBuild || 'default';
  2702. if ( properties[ subBuildProperty ] ) {
  2703. return properties[ subBuildProperty ];
  2704. }
  2705. //
  2706. const previousSubBuildFn = builder.subBuildFn;
  2707. const previousFnCall = builder.fnCall;
  2708. builder.subBuildFn = subBuild;
  2709. builder.fnCall = this;
  2710. let result = null;
  2711. if ( shaderNode.layout ) {
  2712. // build inputs first
  2713. if ( rawInputs ) {
  2714. // use layout inputs to ensure that no extra parameters are built
  2715. const inputs = shaderNode.layout.inputs;
  2716. if ( isArrayAsParameter( rawInputs ) ) {
  2717. const rawArrayParameters = rawInputs;
  2718. for ( let i = 0; i < inputs.length; i ++ ) {
  2719. const rawParameter = rawArrayParameters[ i ];
  2720. if ( rawParameter && rawParameter.isNode ) {
  2721. rawParameter.build( builder );
  2722. }
  2723. }
  2724. } else {
  2725. const rawObjectParameters = rawInputs[ 0 ];
  2726. for ( const param of inputs ) {
  2727. const rawParameter = rawObjectParameters[ param.name ];
  2728. if ( rawParameter && rawParameter.isNode ) {
  2729. rawParameter.build( builder );
  2730. }
  2731. }
  2732. }
  2733. }
  2734. const functionNode = builder.buildFunctionNode( shaderNode );
  2735. builder.addInclude( functionNode );
  2736. //
  2737. const inputs = rawInputs ? getLayoutParameters( rawInputs ) : null;
  2738. result = functionNode.call( inputs );
  2739. } else {
  2740. const secureNodeBuilder = new Proxy( builder, {
  2741. get: ( target, property, receiver ) => {
  2742. let value;
  2743. if ( Symbol.iterator === property ) {
  2744. value = function* () {
  2745. yield undefined;
  2746. };
  2747. } else {
  2748. value = Reflect.get( target, property, receiver );
  2749. }
  2750. return value;
  2751. }
  2752. } );
  2753. //
  2754. const inputs = rawInputs ? getProxyParameters( rawInputs ) : null;
  2755. const hasParameters = Array.isArray( rawInputs ) ? rawInputs.length > 0 : rawInputs !== null;
  2756. const jsFunc = shaderNode.jsFunc;
  2757. const outputNode = hasParameters || jsFunc.length > 1 ? jsFunc( inputs, secureNodeBuilder ) : jsFunc( secureNodeBuilder );
  2758. result = nodeObject( outputNode );
  2759. }
  2760. builder.subBuildFn = previousSubBuildFn;
  2761. builder.fnCall = previousFnCall;
  2762. if ( shaderNode.once ) {
  2763. properties[ subBuildProperty ] = result;
  2764. }
  2765. return result;
  2766. }
  2767. setupOutput( builder ) {
  2768. builder.addStack();
  2769. builder.stack.outputNode = this.call( builder );
  2770. return builder.removeStack();
  2771. }
  2772. getOutputNode( builder ) {
  2773. const properties = builder.getNodeProperties( this );
  2774. const subBuildOutput = builder.getSubBuildOutput( this );
  2775. properties[ subBuildOutput ] = properties[ subBuildOutput ] || this.setupOutput( builder );
  2776. properties[ subBuildOutput ].subBuild = builder.getClosestSubBuild( this );
  2777. return properties[ subBuildOutput ];
  2778. }
  2779. build( builder, output = null ) {
  2780. let result = null;
  2781. const buildStage = builder.getBuildStage();
  2782. const properties = builder.getNodeProperties( this );
  2783. const subBuildOutput = builder.getSubBuildOutput( this );
  2784. const outputNode = this.getOutputNode( builder );
  2785. const previousFnCall = builder.fnCall;
  2786. builder.fnCall = this;
  2787. if ( buildStage === 'setup' ) {
  2788. const subBuildInitialized = builder.getSubBuildProperty( 'initialized', this );
  2789. if ( properties[ subBuildInitialized ] !== true ) {
  2790. properties[ subBuildInitialized ] = true;
  2791. properties[ subBuildOutput ] = this.getOutputNode( builder );
  2792. properties[ subBuildOutput ].build( builder );
  2793. // If the shaderNode has subBuilds, add them to the chaining nodes
  2794. // so they can be built later in the build process.
  2795. if ( this.shaderNode.subBuilds ) {
  2796. for ( const node of builder.chaining ) {
  2797. const nodeData = builder.getDataFromNode( node, 'any' );
  2798. nodeData.subBuilds = nodeData.subBuilds || new Set();
  2799. for ( const subBuild of this.shaderNode.subBuilds ) {
  2800. nodeData.subBuilds.add( subBuild );
  2801. }
  2802. //builder.getDataFromNode( node ).subBuilds = nodeData.subBuilds;
  2803. }
  2804. }
  2805. }
  2806. result = properties[ subBuildOutput ];
  2807. } else if ( buildStage === 'analyze' ) {
  2808. outputNode.build( builder, output );
  2809. } else if ( buildStage === 'generate' ) {
  2810. result = outputNode.build( builder, output ) || '';
  2811. }
  2812. builder.fnCall = previousFnCall;
  2813. return result;
  2814. }
  2815. }
  2816. function isArrayAsParameter( params ) {
  2817. return params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2818. }
  2819. function getLayoutParameters( params ) {
  2820. let output;
  2821. nodeObjects( params );
  2822. if ( isArrayAsParameter( params ) ) {
  2823. output = [ ...params ];
  2824. } else {
  2825. output = params[ 0 ];
  2826. }
  2827. return output;
  2828. }
  2829. function getProxyParameters( params ) {
  2830. let index = 0;
  2831. nodeObjects( params );
  2832. return new Proxy( params, {
  2833. get: ( target, property, receiver ) => {
  2834. let value;
  2835. if ( property === 'length' ) {
  2836. value = params.length;
  2837. return value;
  2838. }
  2839. if ( Symbol.iterator === property ) {
  2840. value = function* () {
  2841. for ( const inputNode of params ) {
  2842. yield nodeObject( inputNode );
  2843. }
  2844. };
  2845. } else {
  2846. if ( params.length > 0 ) {
  2847. if ( Object.getPrototypeOf( params[ 0 ] ) === Object.prototype ) {
  2848. const objectTarget = params[ 0 ];
  2849. if ( objectTarget[ property ] === undefined ) {
  2850. value = objectTarget[ index ++ ];
  2851. } else {
  2852. value = Reflect.get( objectTarget, property, receiver );
  2853. }
  2854. } else if ( params[ 0 ] instanceof Node ) {
  2855. if ( params[ property ] === undefined ) {
  2856. value = params[ index ++ ];
  2857. } else {
  2858. value = Reflect.get( params, property, receiver );
  2859. }
  2860. }
  2861. } else {
  2862. value = Reflect.get( target, property, receiver );
  2863. }
  2864. value = nodeObject( value );
  2865. }
  2866. return value;
  2867. }
  2868. } );
  2869. }
  2870. class ShaderNodeInternal extends Node {
  2871. constructor( jsFunc, nodeType ) {
  2872. super( nodeType );
  2873. this.jsFunc = jsFunc;
  2874. this.layout = null;
  2875. this.global = true;
  2876. this.once = false;
  2877. }
  2878. setLayout( layout ) {
  2879. this.layout = layout;
  2880. return this;
  2881. }
  2882. getLayout() {
  2883. return this.layout;
  2884. }
  2885. call( rawInputs = null ) {
  2886. return new ShaderCallNodeInternal( this, rawInputs );
  2887. }
  2888. setup() {
  2889. return this.call();
  2890. }
  2891. }
  2892. const bools = [ false, true ];
  2893. const uints = [ 0, 1, 2, 3 ];
  2894. const ints = [ -1, -2 ];
  2895. 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 ];
  2896. const boolsCacheMap = new Map();
  2897. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2898. const uintsCacheMap = new Map();
  2899. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2900. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2901. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2902. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2903. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2904. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2905. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2906. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2907. const getConstNode = ( value, type ) => {
  2908. if ( constNodesCacheMap.has( value ) ) {
  2909. return constNodesCacheMap.get( value );
  2910. } else if ( value.isNode === true ) {
  2911. return value;
  2912. } else {
  2913. return new ConstNode( value, type );
  2914. }
  2915. };
  2916. const ConvertType = function ( type, cacheMap = null ) {
  2917. return ( ...params ) => {
  2918. for ( const param of params ) {
  2919. if ( param === undefined ) {
  2920. error( `TSL: Invalid parameter for the type "${ type }".`, new StackTrace() );
  2921. return new ConstNode( 0, type );
  2922. }
  2923. }
  2924. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => {
  2925. const paramType = typeof param;
  2926. return paramType !== 'object' && paramType !== 'function';
  2927. } ) ) ) {
  2928. params = [ getValueFromType( type, ...params ) ];
  2929. }
  2930. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2931. return nodeObjectIntent( cacheMap.get( params[ 0 ] ) );
  2932. }
  2933. if ( params.length === 1 ) {
  2934. const node = getConstNode( params[ 0 ], type );
  2935. if ( node.nodeType === type ) return nodeObjectIntent( node );
  2936. return nodeObjectIntent( new ConvertNode( node, type ) );
  2937. }
  2938. const nodes = params.map( param => getConstNode( param ) );
  2939. return nodeObjectIntent( new JoinNode( nodes, type ) );
  2940. };
  2941. };
  2942. // exports
  2943. function defined( value ) {
  2944. if ( value && value.isNode ) {
  2945. value.traverse( ( node ) => {
  2946. if ( node.isConstNode ) {
  2947. value = node.value;
  2948. }
  2949. } );
  2950. }
  2951. return Boolean( value );
  2952. }
  2953. // utils
  2954. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2955. // shader node base
  2956. function ShaderNode( jsFunc, nodeType ) {
  2957. return new ShaderNodeInternal( jsFunc, nodeType );
  2958. }
  2959. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2960. const nodeObjectIntent = ( val, altType = null ) => /* new */ nodeObject( val, altType ).toVarIntent();
  2961. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2962. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2963. const nodeProxy = ( NodeClass, scope = null, factor = null, settings = null ) => new ShaderNodeProxy( NodeClass, scope, factor, settings );
  2964. const nodeImmutable = ( NodeClass, ...params ) => new ShaderNodeImmutable( NodeClass, ...params );
  2965. const nodeProxyIntent = ( NodeClass, scope = null, factor = null, settings = {} ) => new ShaderNodeProxy( NodeClass, scope, factor, { ...settings, intent: true } );
  2966. let fnId = 0;
  2967. class FnNode extends Node {
  2968. constructor( jsFunc, layout = null ) {
  2969. super();
  2970. let nodeType = null;
  2971. if ( layout !== null ) {
  2972. if ( typeof layout === 'object' ) {
  2973. nodeType = layout.return;
  2974. } else {
  2975. if ( typeof layout === 'string' ) {
  2976. nodeType = layout;
  2977. } else {
  2978. error( 'TSL: Invalid layout type.', new StackTrace() );
  2979. }
  2980. layout = null;
  2981. }
  2982. }
  2983. this.shaderNode = new ShaderNode( jsFunc, nodeType );
  2984. if ( layout !== null ) {
  2985. this.setLayout( layout );
  2986. }
  2987. this.isFn = true;
  2988. }
  2989. setLayout( layout ) {
  2990. const nodeType = this.shaderNode.nodeType;
  2991. if ( typeof layout.inputs !== 'object' ) {
  2992. const fullLayout = {
  2993. name: 'fn' + fnId ++,
  2994. type: nodeType,
  2995. inputs: []
  2996. };
  2997. for ( const name in layout ) {
  2998. if ( name === 'return' ) continue;
  2999. fullLayout.inputs.push( {
  3000. name: name,
  3001. type: layout[ name ]
  3002. } );
  3003. }
  3004. layout = fullLayout;
  3005. }
  3006. this.shaderNode.setLayout( layout );
  3007. return this;
  3008. }
  3009. generateNodeType( builder ) {
  3010. return this.shaderNode.getNodeType( builder ) || 'float';
  3011. }
  3012. call( ...params ) {
  3013. const fnCall = this.shaderNode.call( params );
  3014. if ( this.shaderNode.nodeType === 'void' ) fnCall.toStack();
  3015. return fnCall.toVarIntent();
  3016. }
  3017. once( subBuilds = null ) {
  3018. this.shaderNode.once = true;
  3019. this.shaderNode.subBuilds = subBuilds;
  3020. return this;
  3021. }
  3022. generate( builder ) {
  3023. const type = this.getNodeType( builder );
  3024. error( 'TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".', this.stackTrace );
  3025. return builder.generateConst( type );
  3026. }
  3027. }
  3028. function Fn( jsFunc, layout = null ) {
  3029. const instance = new FnNode( jsFunc, layout );
  3030. return new Proxy( () => {}, {
  3031. apply( target, thisArg, params ) {
  3032. return instance.call( ...params );
  3033. },
  3034. get( target, prop, receiver ) {
  3035. return Reflect.get( instance, prop, receiver );
  3036. },
  3037. set( target, prop, value, receiver ) {
  3038. return Reflect.set( instance, prop, value, receiver );
  3039. }
  3040. } );
  3041. }
  3042. //
  3043. const setCurrentStack = ( stack ) => {
  3044. currentStack = stack;
  3045. };
  3046. const getCurrentStack = () => currentStack;
  3047. /**
  3048. * Represent a conditional node using if/else statements.
  3049. *
  3050. * ```js
  3051. * If( condition, function )
  3052. * .ElseIf( condition, function )
  3053. * .Else( function )
  3054. * ```
  3055. * @tsl
  3056. * @function
  3057. * @param {...any} params - The parameters for the conditional node.
  3058. * @returns {StackNode} The conditional node.
  3059. */
  3060. const If = ( ...params ) => currentStack.If( ...params );
  3061. /**
  3062. * Represent a conditional node using switch/case statements.
  3063. *
  3064. * ```js
  3065. * Switch( value )
  3066. * .Case( 1, function )
  3067. * .Case( 2, 3, 4, function )
  3068. * .Default( function )
  3069. * ```
  3070. * @tsl
  3071. * @function
  3072. * @param {...any} params - The parameters for the conditional node.
  3073. * @returns {StackNode} The conditional node.
  3074. */
  3075. const Switch = ( ...params ) => currentStack.Switch( ...params );
  3076. /**
  3077. * Add the given node to the current stack.
  3078. *
  3079. * @param {Node} node - The node to add.
  3080. * @returns {Node} The node that was added to the stack.
  3081. */
  3082. function Stack( node ) {
  3083. if ( currentStack ) currentStack.addToStack( node );
  3084. return node;
  3085. }
  3086. addMethodChaining( 'toStack', Stack );
  3087. // types
  3088. const color = new ConvertType( 'color' );
  3089. const float = new ConvertType( 'float', cacheMaps.float );
  3090. const int = new ConvertType( 'int', cacheMaps.ints );
  3091. const uint = new ConvertType( 'uint', cacheMaps.uint );
  3092. const bool = new ConvertType( 'bool', cacheMaps.bool );
  3093. const vec2 = new ConvertType( 'vec2' );
  3094. const ivec2 = new ConvertType( 'ivec2' );
  3095. const uvec2 = new ConvertType( 'uvec2' );
  3096. const bvec2 = new ConvertType( 'bvec2' );
  3097. const vec3 = new ConvertType( 'vec3' );
  3098. const ivec3 = new ConvertType( 'ivec3' );
  3099. const uvec3 = new ConvertType( 'uvec3' );
  3100. const bvec3 = new ConvertType( 'bvec3' );
  3101. const vec4 = new ConvertType( 'vec4' );
  3102. const ivec4 = new ConvertType( 'ivec4' );
  3103. const uvec4 = new ConvertType( 'uvec4' );
  3104. const bvec4 = new ConvertType( 'bvec4' );
  3105. const mat2 = new ConvertType( 'mat2' );
  3106. const mat3 = new ConvertType( 'mat3' );
  3107. const mat4 = new ConvertType( 'mat4' );
  3108. addMethodChaining( 'toColor', color );
  3109. addMethodChaining( 'toFloat', float );
  3110. addMethodChaining( 'toInt', int );
  3111. addMethodChaining( 'toUint', uint );
  3112. addMethodChaining( 'toBool', bool );
  3113. addMethodChaining( 'toVec2', vec2 );
  3114. addMethodChaining( 'toIVec2', ivec2 );
  3115. addMethodChaining( 'toUVec2', uvec2 );
  3116. addMethodChaining( 'toBVec2', bvec2 );
  3117. addMethodChaining( 'toVec3', vec3 );
  3118. addMethodChaining( 'toIVec3', ivec3 );
  3119. addMethodChaining( 'toUVec3', uvec3 );
  3120. addMethodChaining( 'toBVec3', bvec3 );
  3121. addMethodChaining( 'toVec4', vec4 );
  3122. addMethodChaining( 'toIVec4', ivec4 );
  3123. addMethodChaining( 'toUVec4', uvec4 );
  3124. addMethodChaining( 'toBVec4', bvec4 );
  3125. addMethodChaining( 'toMat2', mat2 );
  3126. addMethodChaining( 'toMat3', mat3 );
  3127. addMethodChaining( 'toMat4', mat4 );
  3128. // basic nodes
  3129. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  3130. const convert = ( node, types ) => new ConvertNode( nodeObject( node ), types );
  3131. const split = ( node, channels ) => new SplitNode( nodeObject( node ), channels );
  3132. addMethodChaining( 'element', element );
  3133. addMethodChaining( 'convert', convert );
  3134. // deprecated
  3135. /**
  3136. * @tsl
  3137. * @function
  3138. * @deprecated since r176. Use {@link Stack} instead.
  3139. *
  3140. * @param {Node} node - The node to add.
  3141. * @returns {Function}
  3142. */
  3143. const append = ( node ) => { // @deprecated, r176
  3144. warn( 'TSL: append() has been renamed to Stack().', new StackTrace() );
  3145. return Stack( node );
  3146. };
  3147. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  3148. warn( 'TSL: .append() has been renamed to .toStack().', new StackTrace() );
  3149. return Stack( node );
  3150. } );
  3151. /**
  3152. * This class represents a shader property. It can be used
  3153. * to explicitly define a property and assign a value to it.
  3154. *
  3155. * ```js
  3156. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  3157. *```
  3158. * `PropertyNode` is used by the engine to predefined common material properties
  3159. * for TSL code.
  3160. *
  3161. * @augments Node
  3162. */
  3163. class PropertyNode extends Node {
  3164. static get type() {
  3165. return 'PropertyNode';
  3166. }
  3167. /**
  3168. * Constructs a new property node.
  3169. *
  3170. * @param {string} nodeType - The type of the node.
  3171. * @param {?string} [name=null] - The name of the property in the shader.
  3172. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  3173. */
  3174. constructor( nodeType, name = null, varying = false ) {
  3175. super( nodeType );
  3176. /**
  3177. * The name of the property in the shader. If no name is defined,
  3178. * the node system auto-generates one.
  3179. *
  3180. * @type {?string}
  3181. * @default null
  3182. */
  3183. this.name = name;
  3184. /**
  3185. * Whether this property is a varying or not.
  3186. *
  3187. * @type {boolean}
  3188. * @default false
  3189. */
  3190. this.varying = varying;
  3191. /**
  3192. * This flag can be used for type testing.
  3193. *
  3194. * @type {boolean}
  3195. * @readonly
  3196. * @default true
  3197. */
  3198. this.isPropertyNode = true;
  3199. /**
  3200. * This flag is used for global cache.
  3201. *
  3202. * @type {boolean}
  3203. * @default true
  3204. */
  3205. this.global = true;
  3206. }
  3207. customCacheKey() {
  3208. return hashString( this.type + ':' + ( this.name || '' ) + ':' + ( this.varying ? '1' : '0' ) );
  3209. }
  3210. getHash( builder ) {
  3211. return this.name || super.getHash( builder );
  3212. }
  3213. generate( builder ) {
  3214. let nodeVar;
  3215. if ( this.varying === true ) {
  3216. nodeVar = builder.getVaryingFromNode( this, this.name );
  3217. nodeVar.needsInterpolation = true;
  3218. } else {
  3219. nodeVar = builder.getVarFromNode( this, this.name );
  3220. }
  3221. return builder.getPropertyName( nodeVar );
  3222. }
  3223. }
  3224. /**
  3225. * TSL function for creating a property node.
  3226. *
  3227. * @tsl
  3228. * @function
  3229. * @param {string} type - The type of the node.
  3230. * @param {?string} [name=null] - The name of the property in the shader.
  3231. * @returns {PropertyNode}
  3232. */
  3233. const property = ( type, name ) => new PropertyNode( type, name );
  3234. /**
  3235. * TSL function for creating a varying property node.
  3236. *
  3237. * @tsl
  3238. * @function
  3239. * @param {string} type - The type of the node.
  3240. * @param {?string} [name=null] - The name of the varying in the shader.
  3241. * @returns {PropertyNode}
  3242. */
  3243. const varyingProperty = ( type, name ) => new PropertyNode( type, name, true );
  3244. /**
  3245. * TSL object that represents the shader variable `DiffuseColor`.
  3246. *
  3247. * @tsl
  3248. * @type {PropertyNode<vec4>}
  3249. */
  3250. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  3251. /**
  3252. * TSL object that represents the shader variable `DiffuseContribution`.
  3253. *
  3254. * @tsl
  3255. * @type {PropertyNode<vec3>}
  3256. */
  3257. const diffuseContribution = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'DiffuseContribution' );
  3258. /**
  3259. * TSL object that represents the shader variable `EmissiveColor`.
  3260. *
  3261. * @tsl
  3262. * @type {PropertyNode<vec3>}
  3263. */
  3264. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  3265. /**
  3266. * TSL object that represents the shader variable `Roughness`.
  3267. *
  3268. * @tsl
  3269. * @type {PropertyNode<float>}
  3270. */
  3271. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  3272. /**
  3273. * TSL object that represents the shader variable `Metalness`.
  3274. *
  3275. * @tsl
  3276. * @type {PropertyNode<float>}
  3277. */
  3278. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  3279. /**
  3280. * TSL object that represents the shader variable `Clearcoat`.
  3281. *
  3282. * @tsl
  3283. * @type {PropertyNode<float>}
  3284. */
  3285. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  3286. /**
  3287. * TSL object that represents the shader variable `ClearcoatRoughness`.
  3288. *
  3289. * @tsl
  3290. * @type {PropertyNode<float>}
  3291. */
  3292. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  3293. /**
  3294. * TSL object that represents the shader variable `Sheen`.
  3295. *
  3296. * @tsl
  3297. * @type {PropertyNode<vec3>}
  3298. */
  3299. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  3300. /**
  3301. * TSL object that represents the shader variable `SheenRoughness`.
  3302. *
  3303. * @tsl
  3304. * @type {PropertyNode<float>}
  3305. */
  3306. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  3307. /**
  3308. * TSL object that represents the shader variable `Iridescence`.
  3309. *
  3310. * @tsl
  3311. * @type {PropertyNode<float>}
  3312. */
  3313. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  3314. /**
  3315. * TSL object that represents the shader variable `IridescenceIOR`.
  3316. *
  3317. * @tsl
  3318. * @type {PropertyNode<float>}
  3319. */
  3320. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  3321. /**
  3322. * TSL object that represents the shader variable `IridescenceThickness`.
  3323. *
  3324. * @tsl
  3325. * @type {PropertyNode<float>}
  3326. */
  3327. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  3328. /**
  3329. * TSL object that represents the shader variable `AlphaT`.
  3330. *
  3331. * @tsl
  3332. * @type {PropertyNode<float>}
  3333. */
  3334. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  3335. /**
  3336. * TSL object that represents the shader variable `Anisotropy`.
  3337. *
  3338. * @tsl
  3339. * @type {PropertyNode<float>}
  3340. */
  3341. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  3342. /**
  3343. * TSL object that represents the shader variable `AnisotropyT`.
  3344. *
  3345. * @tsl
  3346. * @type {PropertyNode<vec3>}
  3347. */
  3348. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  3349. /**
  3350. * TSL object that represents the shader variable `AnisotropyB`.
  3351. *
  3352. * @tsl
  3353. * @type {PropertyNode<vec3>}
  3354. */
  3355. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  3356. /**
  3357. * TSL object that represents the shader variable `SpecularColor`.
  3358. *
  3359. * @tsl
  3360. * @type {PropertyNode<color>}
  3361. */
  3362. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  3363. /**
  3364. * TSL object that represents the shader variable `SpecularColorBlended`.
  3365. *
  3366. * @tsl
  3367. * @type {PropertyNode<color>}
  3368. */
  3369. const specularColorBlended = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColorBlended' );
  3370. /**
  3371. * TSL object that represents the shader variable `SpecularF90`.
  3372. *
  3373. * @tsl
  3374. * @type {PropertyNode<float>}
  3375. */
  3376. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  3377. /**
  3378. * TSL object that represents the shader variable `Shininess`.
  3379. *
  3380. * @tsl
  3381. * @type {PropertyNode<float>}
  3382. */
  3383. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  3384. /**
  3385. * TSL object that represents the shader variable `Output`.
  3386. *
  3387. * @tsl
  3388. * @type {PropertyNode<vec4>}
  3389. */
  3390. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  3391. /**
  3392. * TSL object that represents the shader variable `dashSize`.
  3393. *
  3394. * @tsl
  3395. * @type {PropertyNode<float>}
  3396. */
  3397. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  3398. /**
  3399. * TSL object that represents the shader variable `gapSize`.
  3400. *
  3401. * @tsl
  3402. * @type {PropertyNode<float>}
  3403. */
  3404. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  3405. /**
  3406. * TSL object that represents the shader variable `pointWidth`.
  3407. *
  3408. * @tsl
  3409. * @type {PropertyNode<float>}
  3410. */
  3411. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  3412. /**
  3413. * TSL object that represents the shader variable `IOR`.
  3414. *
  3415. * @tsl
  3416. * @type {PropertyNode<float>}
  3417. */
  3418. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  3419. /**
  3420. * TSL object that represents the shader variable `Transmission`.
  3421. *
  3422. * @tsl
  3423. * @type {PropertyNode<float>}
  3424. */
  3425. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  3426. /**
  3427. * TSL object that represents the shader variable `Thickness`.
  3428. *
  3429. * @tsl
  3430. * @type {PropertyNode<float>}
  3431. */
  3432. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  3433. /**
  3434. * TSL object that represents the shader variable `AttenuationDistance`.
  3435. *
  3436. * @tsl
  3437. * @type {PropertyNode<float>}
  3438. */
  3439. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  3440. /**
  3441. * TSL object that represents the shader variable `AttenuationColor`.
  3442. *
  3443. * @tsl
  3444. * @type {PropertyNode<color>}
  3445. */
  3446. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  3447. /**
  3448. * TSL object that represents the shader variable `Dispersion`.
  3449. *
  3450. * @tsl
  3451. * @type {PropertyNode<float>}
  3452. */
  3453. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  3454. /**
  3455. * This node can be used to group single instances of {@link UniformNode}
  3456. * and manage them as a uniform buffer.
  3457. *
  3458. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  3459. * will be used when defining the {@link UniformNode#groupNode} property.
  3460. *
  3461. * - `objectGroup`: Uniform buffer per object.
  3462. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  3463. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  3464. *
  3465. * @augments Node
  3466. */
  3467. class UniformGroupNode extends Node {
  3468. static get type() {
  3469. return 'UniformGroupNode';
  3470. }
  3471. /**
  3472. * Constructs a new uniform group node.
  3473. *
  3474. * @param {string} name - The name of the uniform group node.
  3475. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  3476. * @param {number} [order=1] - Influences the internal sorting.
  3477. * @param {string|null} [updateType=null] - The update type of the uniform group node.
  3478. */
  3479. constructor( name, shared = false, order = 1, updateType = null ) {
  3480. super( 'string' );
  3481. /**
  3482. * The name of the uniform group node.
  3483. *
  3484. * @type {string}
  3485. */
  3486. this.name = name;
  3487. /**
  3488. * Whether this uniform group node is shared or not.
  3489. *
  3490. * @type {boolean}
  3491. * @default false
  3492. */
  3493. this.shared = shared;
  3494. /**
  3495. * Influences the internal sorting.
  3496. * TODO: Add details when this property should be changed.
  3497. *
  3498. * @type {number}
  3499. * @default 1
  3500. */
  3501. this.order = order;
  3502. /**
  3503. * The update type of the uniform group node.
  3504. *
  3505. * @type {string|null}
  3506. * @default null
  3507. */
  3508. this.updateType = updateType;
  3509. /**
  3510. * This flag can be used for type testing.
  3511. *
  3512. * @type {boolean}
  3513. * @readonly
  3514. * @default true
  3515. */
  3516. this.isUniformGroup = true;
  3517. }
  3518. /**
  3519. * Marks the uniform group node as needing an update.
  3520. * This will trigger the necessary updates in the rendering process.
  3521. */
  3522. update() {
  3523. this.needsUpdate = true;
  3524. }
  3525. /**
  3526. * Serializes the uniform group node to a JSON object.
  3527. *
  3528. * @param {Object} data - The object to store the serialized data.
  3529. */
  3530. serialize( data ) {
  3531. super.serialize( data );
  3532. data.name = this.name;
  3533. data.version = this.version;
  3534. data.shared = this.shared;
  3535. }
  3536. /**
  3537. * Deserializes the uniform group node from a JSON object.
  3538. *
  3539. * @param {Object} data - The object containing the serialized data.
  3540. */
  3541. deserialize( data ) {
  3542. super.deserialize( data );
  3543. this.name = data.name;
  3544. this.version = data.version;
  3545. this.shared = data.shared;
  3546. }
  3547. }
  3548. /**
  3549. * TSL function for creating a uniform group node with the given name.
  3550. *
  3551. * @tsl
  3552. * @function
  3553. * @param {string} name - The name of the uniform group node.
  3554. * @returns {UniformGroupNode}
  3555. */
  3556. const uniformGroup = ( name, order = 1, updateType = null ) => new UniformGroupNode( name, false, order, updateType );
  3557. /**
  3558. * TSL function for creating a shared uniform group node with the given name and order.
  3559. *
  3560. * @tsl
  3561. * @function
  3562. * @param {string} name - The name of the uniform group node.
  3563. * @param {number} [order=0] - Influences the internal sorting.
  3564. * @returns {UniformGroupNode}
  3565. */
  3566. const sharedUniformGroup = ( name, order = 0, updateType = null ) => new UniformGroupNode( name, true, order, updateType );
  3567. /**
  3568. * TSL object that represents a shared uniform group node which is updated once per frame.
  3569. *
  3570. * @tsl
  3571. * @type {UniformGroupNode}
  3572. */
  3573. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame', 0, NodeUpdateType.FRAME );
  3574. /**
  3575. * TSL object that represents a shared uniform group node which is updated once per render.
  3576. *
  3577. * @tsl
  3578. * @type {UniformGroupNode}
  3579. */
  3580. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render', 0, NodeUpdateType.RENDER );
  3581. /**
  3582. * TSL object that represents a uniform group node which is updated once per object.
  3583. *
  3584. * @tsl
  3585. * @type {UniformGroupNode}
  3586. */
  3587. const objectGroup = /*@__PURE__*/ uniformGroup( 'object', 1, NodeUpdateType.OBJECT );
  3588. /**
  3589. * Class for representing a uniform.
  3590. *
  3591. * @augments InputNode
  3592. */
  3593. class UniformNode extends InputNode {
  3594. static get type() {
  3595. return 'UniformNode';
  3596. }
  3597. /**
  3598. * Constructs a new uniform node.
  3599. *
  3600. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3601. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3602. */
  3603. constructor( value, nodeType = null ) {
  3604. super( value, nodeType );
  3605. /**
  3606. * This flag can be used for type testing.
  3607. *
  3608. * @type {boolean}
  3609. * @readonly
  3610. * @default true
  3611. */
  3612. this.isUniformNode = true;
  3613. /**
  3614. * The name or label of the uniform.
  3615. *
  3616. * @type {string}
  3617. * @default ''
  3618. */
  3619. this.name = '';
  3620. /**
  3621. * The uniform group of this uniform. By default, uniforms are
  3622. * managed per object but they might belong to a shared group
  3623. * which is updated per frame or render call.
  3624. *
  3625. * @type {UniformGroupNode}
  3626. */
  3627. this.groupNode = objectGroup;
  3628. }
  3629. /**
  3630. * Sets the {@link UniformNode#name} property.
  3631. *
  3632. * @param {string} name - The name of the uniform.
  3633. * @return {UniformNode} A reference to this node.
  3634. */
  3635. setName( name ) {
  3636. this.name = name;
  3637. return this;
  3638. }
  3639. /**
  3640. * Sets the {@link UniformNode#name} property.
  3641. *
  3642. * @deprecated
  3643. * @param {string} name - The name of the uniform.
  3644. * @return {UniformNode} A reference to this node.
  3645. */
  3646. label( name ) {
  3647. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.', new StackTrace() ); // @deprecated r179
  3648. return this.setName( name );
  3649. }
  3650. /**
  3651. * Sets the {@link UniformNode#groupNode} property.
  3652. *
  3653. * @param {UniformGroupNode} group - The uniform group.
  3654. * @return {UniformNode} A reference to this node.
  3655. */
  3656. setGroup( group ) {
  3657. this.groupNode = group;
  3658. return this;
  3659. }
  3660. /**
  3661. * Returns the {@link UniformNode#groupNode}.
  3662. *
  3663. * @return {UniformGroupNode} The uniform group.
  3664. */
  3665. getGroup() {
  3666. return this.groupNode;
  3667. }
  3668. /**
  3669. * By default, this method returns the result of {@link Node#getHash} but derived
  3670. * classes might overwrite this method with a different implementation.
  3671. *
  3672. * @param {NodeBuilder} builder - The current node builder.
  3673. * @return {string} The uniform hash.
  3674. */
  3675. getUniformHash( builder ) {
  3676. return this.getHash( builder );
  3677. }
  3678. onUpdate( callback, updateType ) {
  3679. callback = callback.bind( this );
  3680. return super.onUpdate( ( frame ) => {
  3681. const value = callback( frame, this );
  3682. if ( value !== undefined ) {
  3683. this.value = value;
  3684. }
  3685. }, updateType );
  3686. }
  3687. getInputType( builder ) {
  3688. let type = super.getInputType( builder );
  3689. if ( type === 'bool' ) {
  3690. type = 'uint';
  3691. }
  3692. return type;
  3693. }
  3694. generate( builder, output ) {
  3695. const type = this.getNodeType( builder );
  3696. const hash = this.getUniformHash( builder );
  3697. let sharedNode = builder.getNodeFromHash( hash );
  3698. if ( sharedNode === undefined ) {
  3699. builder.setHashNode( this, hash );
  3700. sharedNode = this;
  3701. }
  3702. const sharedNodeType = sharedNode.getInputType( builder );
  3703. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.nodeName );
  3704. const uniformName = builder.getPropertyName( nodeUniform );
  3705. if ( builder.context.nodeName !== undefined ) delete builder.context.nodeName;
  3706. //
  3707. let snippet = uniformName;
  3708. if ( type === 'bool' ) {
  3709. // cache to variable
  3710. const nodeData = builder.getDataFromNode( this );
  3711. let propertyName = nodeData.propertyName;
  3712. if ( propertyName === undefined ) {
  3713. const nodeVar = builder.getVarFromNode( this, null, 'bool' );
  3714. propertyName = builder.getPropertyName( nodeVar );
  3715. nodeData.propertyName = propertyName;
  3716. snippet = builder.format( uniformName, sharedNodeType, type );
  3717. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  3718. }
  3719. snippet = propertyName;
  3720. }
  3721. return builder.format( snippet, type, output );
  3722. }
  3723. }
  3724. /**
  3725. * TSL function for creating a uniform node.
  3726. *
  3727. * @tsl
  3728. * @function
  3729. * @param {any|string} value - The value of this uniform or your type. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3730. * @param {string} [type] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3731. * @returns {UniformNode}
  3732. */
  3733. const uniform = ( value, type ) => {
  3734. const nodeType = getConstNodeType( type || value );
  3735. if ( nodeType === value ) {
  3736. // if the value is a type but no having a value
  3737. value = getValueFromType( nodeType );
  3738. }
  3739. if ( value && value.isNode === true ) {
  3740. let v = value.value;
  3741. value.traverse( n => {
  3742. if ( n.isConstNode === true ) {
  3743. v = n.value;
  3744. }
  3745. } );
  3746. value = v;
  3747. }
  3748. return new UniformNode( value, nodeType );
  3749. };
  3750. /**
  3751. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3752. * ```js
  3753. * const colors = array( [
  3754. * vec3( 1, 0, 0 ),
  3755. * vec3( 0, 1, 0 ),
  3756. * vec3( 0, 0, 1 )
  3757. * ] );
  3758. *
  3759. * const redColor = tintColors.element( 0 );
  3760. * ```
  3761. *
  3762. * @augments TempNode
  3763. */
  3764. class ArrayNode extends TempNode {
  3765. static get type() {
  3766. return 'ArrayNode';
  3767. }
  3768. /**
  3769. * Constructs a new array node.
  3770. *
  3771. * @param {?string} nodeType - The data type of the elements.
  3772. * @param {number} count - Size of the array.
  3773. * @param {?Array<Node>} [values=null] - Array default values.
  3774. */
  3775. constructor( nodeType, count, values = null ) {
  3776. super( nodeType );
  3777. /**
  3778. * Array size.
  3779. *
  3780. * @type {number}
  3781. */
  3782. this.count = count;
  3783. /**
  3784. * Array default values.
  3785. *
  3786. * @type {?Array<Node>}
  3787. */
  3788. this.values = values;
  3789. /**
  3790. * This flag can be used for type testing.
  3791. *
  3792. * @type {boolean}
  3793. * @readonly
  3794. * @default true
  3795. */
  3796. this.isArrayNode = true;
  3797. }
  3798. /**
  3799. * Returns the number of elements in the node array.
  3800. *
  3801. * @param {NodeBuilder} builder - The current node builder.
  3802. * @return {number} The number of elements in the node array.
  3803. */
  3804. getArrayCount( /*builder*/ ) {
  3805. return this.count;
  3806. }
  3807. /**
  3808. * Returns the node's type.
  3809. *
  3810. * @param {NodeBuilder} builder - The current node builder.
  3811. * @return {string} The type of the node.
  3812. */
  3813. generateNodeType( builder ) {
  3814. if ( this.nodeType === null ) {
  3815. return this.values[ 0 ].getNodeType( builder );
  3816. }
  3817. return this.nodeType;
  3818. }
  3819. /**
  3820. * Returns the node's type.
  3821. *
  3822. * @param {NodeBuilder} builder - The current node builder.
  3823. * @return {string} The type of the node.
  3824. */
  3825. getElementType( builder ) {
  3826. return this.getNodeType( builder );
  3827. }
  3828. /**
  3829. * Returns the type of a member variable.
  3830. *
  3831. * @param {NodeBuilder} builder - The current node builder.
  3832. * @param {string} name - The name of the member variable.
  3833. * @return {string} The type of the member variable.
  3834. */
  3835. getMemberType( builder, name ) {
  3836. if ( this.nodeType === null ) {
  3837. return this.values[ 0 ].getMemberType( builder, name );
  3838. }
  3839. return super.getMemberType( builder, name );
  3840. }
  3841. /**
  3842. * This method builds the output node and returns the resulting array as a shader string.
  3843. *
  3844. * @param {NodeBuilder} builder - The current node builder.
  3845. * @return {string} The generated shader string.
  3846. */
  3847. generate( builder ) {
  3848. const type = this.getNodeType( builder );
  3849. return builder.generateArray( type, this.count, this.values );
  3850. }
  3851. }
  3852. /**
  3853. * TSL function for creating an array node.
  3854. *
  3855. * @tsl
  3856. * @function
  3857. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3858. * or an array containing the default values (e.g., [ vec3() ]).
  3859. * @param {?number} [count] - Size of the array.
  3860. * @returns {ArrayNode}
  3861. */
  3862. const array = ( ...params ) => {
  3863. let node;
  3864. if ( params.length === 1 ) {
  3865. const values = params[ 0 ];
  3866. node = new ArrayNode( null, values.length, values );
  3867. } else {
  3868. const nodeType = params[ 0 ];
  3869. const count = params[ 1 ];
  3870. node = new ArrayNode( nodeType, count );
  3871. }
  3872. return nodeObject( node );
  3873. };
  3874. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3875. /**
  3876. * These node represents an assign operation. Meaning a node is assigned
  3877. * to another node.
  3878. *
  3879. * @augments TempNode
  3880. */
  3881. class AssignNode extends TempNode {
  3882. static get type() {
  3883. return 'AssignNode';
  3884. }
  3885. /**
  3886. * Constructs a new assign node.
  3887. *
  3888. * @param {Node} targetNode - The target node.
  3889. * @param {Node} sourceNode - The source type.
  3890. */
  3891. constructor( targetNode, sourceNode ) {
  3892. super();
  3893. /**
  3894. * The target node.
  3895. *
  3896. * @type {Node}
  3897. */
  3898. this.targetNode = targetNode;
  3899. /**
  3900. * The source node.
  3901. *
  3902. * @type {Node}
  3903. */
  3904. this.sourceNode = sourceNode;
  3905. /**
  3906. * This flag can be used for type testing.
  3907. *
  3908. * @type {boolean}
  3909. * @readonly
  3910. * @default true
  3911. */
  3912. this.isAssignNode = true;
  3913. }
  3914. /**
  3915. * Whether this node is used more than once in context of other nodes. This method
  3916. * is overwritten since it always returns `false` (assigns are unique).
  3917. *
  3918. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3919. */
  3920. hasDependencies() {
  3921. return false;
  3922. }
  3923. generateNodeType( builder, output ) {
  3924. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3925. }
  3926. /**
  3927. * Whether a split is required when assigning source to target. This can happen when the component length of
  3928. * target and source data type does not match.
  3929. *
  3930. * @param {NodeBuilder} builder - The current node builder.
  3931. * @return {boolean} Whether a split is required when assigning source to target.
  3932. */
  3933. needsSplitAssign( builder ) {
  3934. const { targetNode } = this;
  3935. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3936. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3937. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3938. return assignDifferentVector;
  3939. }
  3940. return false;
  3941. }
  3942. setup( builder ) {
  3943. const { targetNode, sourceNode } = this;
  3944. const scope = targetNode.getScope();
  3945. const scopeData = builder.getDataFromNode( scope );
  3946. scopeData.assign = true;
  3947. const properties = builder.getNodeProperties( this );
  3948. properties.sourceNode = sourceNode;
  3949. properties.targetNode = targetNode.context( { assign: true } );
  3950. }
  3951. generate( builder, output ) {
  3952. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  3953. const needsSplitAssign = this.needsSplitAssign( builder );
  3954. const target = targetNode.build( builder );
  3955. const targetType = targetNode.getNodeType( builder );
  3956. const source = sourceNode.build( builder, targetType );
  3957. const sourceType = sourceNode.getNodeType( builder );
  3958. const nodeData = builder.getDataFromNode( this );
  3959. //
  3960. let snippet;
  3961. if ( nodeData.initialized === true ) {
  3962. if ( output !== 'void' ) {
  3963. snippet = target;
  3964. }
  3965. } else if ( needsSplitAssign ) {
  3966. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3967. const sourceProperty = builder.getPropertyName( sourceVar );
  3968. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3969. const splitNode = targetNode.node;
  3970. const splitTargetNode = splitNode.node.context( { assign: true } );
  3971. const targetRoot = splitTargetNode.build( builder );
  3972. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  3973. const component = splitNode.components[ i ];
  3974. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3975. }
  3976. if ( output !== 'void' ) {
  3977. snippet = target;
  3978. }
  3979. } else {
  3980. snippet = `${ target } = ${ source }`;
  3981. if ( output === 'void' || sourceType === 'void' ) {
  3982. builder.addLineFlowCode( snippet, this );
  3983. if ( output !== 'void' ) {
  3984. snippet = target;
  3985. }
  3986. }
  3987. }
  3988. nodeData.initialized = true;
  3989. return builder.format( snippet, targetType, output );
  3990. }
  3991. }
  3992. /**
  3993. * TSL function for creating an assign node.
  3994. *
  3995. * @tsl
  3996. * @function
  3997. * @param {Node} targetNode - The target node.
  3998. * @param {Node} sourceNode - The source type.
  3999. * @returns {AssignNode}
  4000. */
  4001. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  4002. addMethodChaining( 'assign', assign );
  4003. /**
  4004. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  4005. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  4006. * this logic.
  4007. *
  4008. * @augments TempNode
  4009. */
  4010. class FunctionCallNode extends TempNode {
  4011. static get type() {
  4012. return 'FunctionCallNode';
  4013. }
  4014. /**
  4015. * Constructs a new function call node.
  4016. *
  4017. * @param {?FunctionNode} functionNode - The function node.
  4018. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  4019. */
  4020. constructor( functionNode = null, parameters = {} ) {
  4021. super();
  4022. /**
  4023. * The function node.
  4024. *
  4025. * @type {?FunctionNode}
  4026. * @default null
  4027. */
  4028. this.functionNode = functionNode;
  4029. /**
  4030. * The parameters of the function call.
  4031. *
  4032. * @type {Object<string, Node>}
  4033. * @default {}
  4034. */
  4035. this.parameters = parameters;
  4036. }
  4037. /**
  4038. * Sets the parameters of the function call node.
  4039. *
  4040. * @param {Object<string, Node>} parameters - The parameters to set.
  4041. * @return {FunctionCallNode} A reference to this node.
  4042. */
  4043. setParameters( parameters ) {
  4044. this.parameters = parameters;
  4045. return this;
  4046. }
  4047. /**
  4048. * Returns the parameters of the function call node.
  4049. *
  4050. * @return {Object<string, Node>} The parameters of this node.
  4051. */
  4052. getParameters() {
  4053. return this.parameters;
  4054. }
  4055. /**
  4056. * Returns the type of this function call node.
  4057. *
  4058. * @param {NodeBuilder} builder - The current node builder.
  4059. * @returns {string} The type of this node.
  4060. */
  4061. generateNodeType( builder ) {
  4062. return this.functionNode.getNodeType( builder );
  4063. }
  4064. /**
  4065. * Returns the function node of this function call node.
  4066. *
  4067. * @param {NodeBuilder} builder - The current node builder.
  4068. * @param {string} [name] - The name of the member.
  4069. * @returns {string} The type of the member.
  4070. */
  4071. getMemberType( builder, name ) {
  4072. return this.functionNode.getMemberType( builder, name );
  4073. }
  4074. generate( builder ) {
  4075. const params = [];
  4076. const functionNode = this.functionNode;
  4077. const inputs = functionNode.getInputs( builder );
  4078. const parameters = this.parameters;
  4079. const generateInput = ( node, inputNode ) => {
  4080. const type = inputNode.type;
  4081. const pointer = type === 'pointer';
  4082. let output;
  4083. if ( pointer ) output = '&' + node.build( builder );
  4084. else output = node.build( builder, type );
  4085. return output;
  4086. };
  4087. if ( Array.isArray( parameters ) ) {
  4088. if ( parameters.length > inputs.length ) {
  4089. error( 'TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  4090. parameters.length = inputs.length;
  4091. } else if ( parameters.length < inputs.length ) {
  4092. error( 'TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  4093. while ( parameters.length < inputs.length ) {
  4094. parameters.push( float( 0 ) );
  4095. }
  4096. }
  4097. for ( let i = 0; i < parameters.length; i ++ ) {
  4098. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  4099. }
  4100. } else {
  4101. for ( const inputNode of inputs ) {
  4102. const node = parameters[ inputNode.name ];
  4103. if ( node !== undefined ) {
  4104. params.push( generateInput( node, inputNode ) );
  4105. } else {
  4106. error( `TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  4107. params.push( generateInput( float( 0 ), inputNode ) );
  4108. }
  4109. }
  4110. }
  4111. const functionName = functionNode.build( builder, 'property' );
  4112. return `${ functionName }( ${ params.join( ', ' ) } )`;
  4113. }
  4114. }
  4115. const call = ( func, ...params ) => {
  4116. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  4117. return new FunctionCallNode( nodeObject( func ), params );
  4118. };
  4119. addMethodChaining( 'call', call );
  4120. const _vectorOperators = {
  4121. '==': 'equal',
  4122. '!=': 'notEqual',
  4123. '<': 'lessThan',
  4124. '>': 'greaterThan',
  4125. '<=': 'lessThanEqual',
  4126. '>=': 'greaterThanEqual',
  4127. '%': 'mod'
  4128. };
  4129. /**
  4130. * This node represents basic mathematical and logical operations like addition,
  4131. * subtraction or comparisons (e.g. `equal()`).
  4132. *
  4133. * @augments TempNode
  4134. */
  4135. class OperatorNode extends TempNode {
  4136. static get type() {
  4137. return 'OperatorNode';
  4138. }
  4139. /**
  4140. * Constructs a new operator node.
  4141. *
  4142. * @param {string} op - The operator.
  4143. * @param {Node} aNode - The first input.
  4144. * @param {Node} bNode - The second input.
  4145. * @param {...Node} params - Additional input parameters.
  4146. */
  4147. constructor( op, aNode, bNode, ...params ) {
  4148. super();
  4149. if ( params.length > 0 ) {
  4150. let finalOp = new OperatorNode( op, aNode, bNode );
  4151. for ( let i = 0; i < params.length - 1; i ++ ) {
  4152. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  4153. }
  4154. aNode = finalOp;
  4155. bNode = params[ params.length - 1 ];
  4156. }
  4157. /**
  4158. * The operator.
  4159. *
  4160. * @type {string}
  4161. */
  4162. this.op = op;
  4163. /**
  4164. * The first input.
  4165. *
  4166. * @type {Node}
  4167. */
  4168. this.aNode = aNode;
  4169. /**
  4170. * The second input.
  4171. *
  4172. * @type {Node}
  4173. */
  4174. this.bNode = bNode;
  4175. /**
  4176. * This flag can be used for type testing.
  4177. *
  4178. * @type {boolean}
  4179. * @readonly
  4180. * @default true
  4181. */
  4182. this.isOperatorNode = true;
  4183. }
  4184. /**
  4185. * Returns the operator method name.
  4186. *
  4187. * @param {NodeBuilder} builder - The current node builder.
  4188. * @param {string} output - The output type.
  4189. * @returns {string} The operator method name.
  4190. */
  4191. getOperatorMethod( builder, output ) {
  4192. return builder.getMethod( _vectorOperators[ this.op ], output );
  4193. }
  4194. /**
  4195. * This method is overwritten since the node type is inferred from the operator
  4196. * and the input node types.
  4197. *
  4198. * @param {NodeBuilder} builder - The current node builder.
  4199. * @param {?string} [output=null] - The output type.
  4200. * @return {string} The node type.
  4201. */
  4202. generateNodeType( builder, output = null ) {
  4203. const op = this.op;
  4204. const aNode = this.aNode;
  4205. const bNode = this.bNode;
  4206. const typeA = aNode.getNodeType( builder );
  4207. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  4208. if ( typeA === 'void' || typeB === 'void' ) {
  4209. return output || 'void';
  4210. } else if ( op === '%' ) {
  4211. return typeA;
  4212. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  4213. return builder.getIntegerType( typeA );
  4214. } else if ( op === '&&' || op === '||' || op === '^^' ) {
  4215. return 'bool';
  4216. } else if ( op === '!' ) {
  4217. const typeLength = builder.getTypeLength( typeA );
  4218. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  4219. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  4220. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  4221. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  4222. } else {
  4223. // Handle matrix operations
  4224. if ( builder.isMatrix( typeA ) ) {
  4225. if ( typeB === 'float' ) {
  4226. return typeA; // matrix * scalar = matrix
  4227. } else if ( builder.isVector( typeB ) ) {
  4228. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  4229. } else if ( builder.isMatrix( typeB ) ) {
  4230. return typeA; // matrix * matrix
  4231. }
  4232. } else if ( builder.isMatrix( typeB ) ) {
  4233. if ( typeA === 'float' ) {
  4234. return typeB; // scalar * matrix = matrix
  4235. } else if ( builder.isVector( typeA ) ) {
  4236. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  4237. }
  4238. }
  4239. // Handle non-matrix cases
  4240. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  4241. // anytype x anytype: use the greater length vector
  4242. return typeB;
  4243. }
  4244. return typeA;
  4245. }
  4246. }
  4247. generate( builder, output ) {
  4248. const op = this.op;
  4249. const { aNode, bNode } = this;
  4250. const type = this.getNodeType( builder, output );
  4251. let typeA = null;
  4252. let typeB = null;
  4253. if ( type !== 'void' ) {
  4254. typeA = aNode.getNodeType( builder );
  4255. typeB = bNode ? bNode.getNodeType( builder ) : null;
  4256. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  4257. if ( builder.isVector( typeA ) ) {
  4258. typeB = typeA;
  4259. } else if ( builder.isVector( typeB ) ) {
  4260. typeA = typeB;
  4261. } else if ( typeA !== typeB ) {
  4262. typeA = typeB = 'float';
  4263. }
  4264. } else if ( op === '>>' || op === '<<' ) {
  4265. typeA = type;
  4266. typeB = builder.changeComponentType( typeB, 'uint' );
  4267. } else if ( op === '%' ) {
  4268. typeA = type;
  4269. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  4270. } else if ( builder.isMatrix( typeA ) ) {
  4271. if ( typeB === 'float' ) {
  4272. // Keep matrix type for typeA, but ensure typeB stays float
  4273. typeB = 'float';
  4274. } else if ( builder.isVector( typeB ) ) {
  4275. // matrix x vector
  4276. typeB = builder.getVectorFromMatrix( typeA );
  4277. } else if ( builder.isMatrix( typeB ) ) ; else {
  4278. typeA = typeB = type;
  4279. }
  4280. } else if ( builder.isMatrix( typeB ) ) {
  4281. if ( typeA === 'float' ) {
  4282. // Keep matrix type for typeB, but ensure typeA stays float
  4283. typeA = 'float';
  4284. } else if ( builder.isVector( typeA ) ) {
  4285. // vector x matrix
  4286. typeA = builder.getVectorFromMatrix( typeB );
  4287. } else {
  4288. typeA = typeB = type;
  4289. }
  4290. } else {
  4291. // anytype x anytype
  4292. typeA = typeB = type;
  4293. }
  4294. } else {
  4295. typeA = typeB = type;
  4296. }
  4297. const a = aNode.build( builder, typeA );
  4298. const b = bNode ? bNode.build( builder, typeB ) : null;
  4299. const fnOpSnippet = builder.getFunctionOperator( op );
  4300. if ( output !== 'void' ) {
  4301. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  4302. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  4303. if ( isGLSL ) {
  4304. if ( builder.isVector( typeA ) ) {
  4305. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  4306. } else {
  4307. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  4308. }
  4309. } else {
  4310. // WGSL
  4311. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  4312. }
  4313. } else if ( op === '%' ) {
  4314. if ( builder.isInteger( typeB ) ) {
  4315. return builder.format( `( ${ a } % ${ b } )`, type, output );
  4316. } else {
  4317. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  4318. }
  4319. } else if ( op === '!' ) {
  4320. if ( isGLSL && builder.isVector( typeA ) ) {
  4321. return builder.format( `not( ${a} )`, output );
  4322. } else {
  4323. // WGSL and scalars on GLSL
  4324. return builder.format( `( ${op} ${a} )`, typeA, output );
  4325. }
  4326. } else if ( op === '~' ) {
  4327. return builder.format( `( ${op} ${a} )`, typeA, output );
  4328. } else if ( fnOpSnippet ) {
  4329. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4330. } else {
  4331. // Handle matrix operations
  4332. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4333. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  4334. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  4335. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4336. } else {
  4337. let snippet = `( ${ a } ${ op } ${ b } )`;
  4338. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  4339. snippet = `all${ snippet }`;
  4340. }
  4341. return builder.format( snippet, type, output );
  4342. }
  4343. }
  4344. } else if ( typeA !== 'void' ) {
  4345. if ( fnOpSnippet ) {
  4346. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4347. } else {
  4348. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4349. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  4350. } else {
  4351. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4352. }
  4353. }
  4354. }
  4355. }
  4356. serialize( data ) {
  4357. super.serialize( data );
  4358. data.op = this.op;
  4359. }
  4360. deserialize( data ) {
  4361. super.deserialize( data );
  4362. this.op = data.op;
  4363. }
  4364. }
  4365. /**
  4366. * Returns the addition of two or more value.
  4367. *
  4368. * @tsl
  4369. * @function
  4370. * @param {Node} a - The first input.
  4371. * @param {Node} b - The second input.
  4372. * @param {...Node} params - Additional input parameters.
  4373. * @returns {OperatorNode}
  4374. */
  4375. const add = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  4376. /**
  4377. * Returns the subtraction of two or more value.
  4378. *
  4379. * @tsl
  4380. * @function
  4381. * @param {Node} a - The first input.
  4382. * @param {Node} b - The second input.
  4383. * @param {...Node} params - Additional input parameters.
  4384. * @returns {OperatorNode}
  4385. */
  4386. const sub = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  4387. /**
  4388. * Returns the multiplication of two or more value.
  4389. *
  4390. * @tsl
  4391. * @function
  4392. * @param {Node} a - The first input.
  4393. * @param {Node} b - The second input.
  4394. * @param {...Node} params - Additional input parameters.
  4395. * @returns {OperatorNode}
  4396. */
  4397. const mul = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  4398. /**
  4399. * Returns the division of two or more value.
  4400. *
  4401. * @tsl
  4402. * @function
  4403. * @param {Node} a - The first input.
  4404. * @param {Node} b - The second input.
  4405. * @param {...Node} params - Additional input parameters.
  4406. * @returns {OperatorNode}
  4407. */
  4408. const div = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  4409. /**
  4410. * Computes the remainder of dividing the first node by the second one.
  4411. *
  4412. * @tsl
  4413. * @function
  4414. * @param {Node} a - The first input.
  4415. * @param {Node} b - The second input.
  4416. * @returns {OperatorNode}
  4417. */
  4418. const mod = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  4419. /**
  4420. * Checks if two nodes are equal.
  4421. *
  4422. * @tsl
  4423. * @function
  4424. * @param {Node} a - The first input.
  4425. * @param {Node} b - The second input.
  4426. * @returns {OperatorNode}
  4427. */
  4428. const equal = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  4429. /**
  4430. * Checks if two nodes are not equal.
  4431. *
  4432. * @tsl
  4433. * @function
  4434. * @param {Node} a - The first input.
  4435. * @param {Node} b - The second input.
  4436. * @returns {OperatorNode}
  4437. */
  4438. const notEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  4439. /**
  4440. * Checks if the first node is less than the second.
  4441. *
  4442. * @tsl
  4443. * @function
  4444. * @param {Node} a - The first input.
  4445. * @param {Node} b - The second input.
  4446. * @returns {OperatorNode}
  4447. */
  4448. const lessThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  4449. /**
  4450. * Checks if the first node is greater than the second.
  4451. *
  4452. * @tsl
  4453. * @function
  4454. * @param {Node} a - The first input.
  4455. * @param {Node} b - The second input.
  4456. * @returns {OperatorNode}
  4457. */
  4458. const greaterThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  4459. /**
  4460. * Checks if the first node is less than or equal to the second.
  4461. *
  4462. * @tsl
  4463. * @function
  4464. * @param {Node} a - The first input.
  4465. * @param {Node} b - The second input.
  4466. * @returns {OperatorNode}
  4467. */
  4468. const lessThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  4469. /**
  4470. * Checks if the first node is greater than or equal to the second.
  4471. *
  4472. * @tsl
  4473. * @function
  4474. * @param {Node} a - The first input.
  4475. * @param {Node} b - The second input.
  4476. * @returns {OperatorNode}
  4477. */
  4478. const greaterThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  4479. /**
  4480. * Performs a logical AND operation on multiple nodes.
  4481. *
  4482. * @tsl
  4483. * @function
  4484. * @param {...Node} nodes - The input nodes to be combined using AND.
  4485. * @returns {OperatorNode}
  4486. */
  4487. const and = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  4488. /**
  4489. * Performs a logical OR operation on multiple nodes.
  4490. *
  4491. * @tsl
  4492. * @function
  4493. * @param {...Node} nodes - The input nodes to be combined using OR.
  4494. * @returns {OperatorNode}
  4495. */
  4496. const or = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  4497. /**
  4498. * Performs logical NOT on a node.
  4499. *
  4500. * @tsl
  4501. * @function
  4502. * @param {Node} value - The value.
  4503. * @returns {OperatorNode}
  4504. */
  4505. const not = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  4506. /**
  4507. * Performs logical XOR on two nodes.
  4508. *
  4509. * @tsl
  4510. * @function
  4511. * @param {Node} a - The first input.
  4512. * @param {Node} b - The second input.
  4513. * @returns {OperatorNode}
  4514. */
  4515. const xor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  4516. /**
  4517. * Performs bitwise AND on two nodes.
  4518. *
  4519. * @tsl
  4520. * @function
  4521. * @param {Node} a - The first input.
  4522. * @param {Node} b - The second input.
  4523. * @returns {OperatorNode}
  4524. */
  4525. const bitAnd = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  4526. /**
  4527. * Performs bitwise NOT on a node.
  4528. *
  4529. * @tsl
  4530. * @function
  4531. * @param {Node} a - The first input.
  4532. * @param {Node} b - The second input.
  4533. * @returns {OperatorNode}
  4534. */
  4535. const bitNot = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '~' ).setParameterLength( 1 ).setName( 'bitNot' );
  4536. /**
  4537. * Performs bitwise OR on two nodes.
  4538. *
  4539. * @tsl
  4540. * @function
  4541. * @param {Node} a - The first input.
  4542. * @param {Node} b - The second input.
  4543. * @returns {OperatorNode}
  4544. */
  4545. const bitOr = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  4546. /**
  4547. * Performs bitwise XOR on two nodes.
  4548. *
  4549. * @tsl
  4550. * @function
  4551. * @param {Node} a - The first input.
  4552. * @param {Node} b - The second input.
  4553. * @returns {OperatorNode}
  4554. */
  4555. const bitXor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  4556. /**
  4557. * Shifts a node to the left.
  4558. *
  4559. * @tsl
  4560. * @function
  4561. * @param {Node} a - The node to shift.
  4562. * @param {Node} b - The value to shift.
  4563. * @returns {OperatorNode}
  4564. */
  4565. const shiftLeft = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  4566. /**
  4567. * Shifts a node to the right.
  4568. *
  4569. * @tsl
  4570. * @function
  4571. * @param {Node} a - The node to shift.
  4572. * @param {Node} b - The value to shift.
  4573. * @returns {OperatorNode}
  4574. */
  4575. const shiftRight = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  4576. /**
  4577. * Increments a node by 1.
  4578. *
  4579. * @tsl
  4580. * @function
  4581. * @param {Node} a - The node to increment.
  4582. * @returns {OperatorNode}
  4583. */
  4584. const incrementBefore = Fn( ( [ a ] ) => {
  4585. a.addAssign( 1 );
  4586. return a;
  4587. } );
  4588. /**
  4589. * Decrements a node by 1.
  4590. *
  4591. * @tsl
  4592. * @function
  4593. * @param {Node} a - The node to decrement.
  4594. * @returns {OperatorNode}
  4595. */
  4596. const decrementBefore = Fn( ( [ a ] ) => {
  4597. a.subAssign( 1 );
  4598. return a;
  4599. } );
  4600. /**
  4601. * Increments a node by 1 and returns the previous value.
  4602. *
  4603. * @tsl
  4604. * @function
  4605. * @param {Node} a - The node to increment.
  4606. * @returns {OperatorNode}
  4607. */
  4608. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4609. const temp = int( a ).toConst();
  4610. a.addAssign( 1 );
  4611. return temp;
  4612. } );
  4613. /**
  4614. * Decrements a node by 1 and returns the previous value.
  4615. *
  4616. * @tsl
  4617. * @function
  4618. * @param {Node} a - The node to decrement.
  4619. * @returns {OperatorNode}
  4620. */
  4621. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4622. const temp = int( a ).toConst();
  4623. a.subAssign( 1 );
  4624. return temp;
  4625. } );
  4626. addMethodChaining( 'add', add );
  4627. addMethodChaining( 'sub', sub );
  4628. addMethodChaining( 'mul', mul );
  4629. addMethodChaining( 'div', div );
  4630. addMethodChaining( 'mod', mod );
  4631. addMethodChaining( 'equal', equal );
  4632. addMethodChaining( 'notEqual', notEqual );
  4633. addMethodChaining( 'lessThan', lessThan );
  4634. addMethodChaining( 'greaterThan', greaterThan );
  4635. addMethodChaining( 'lessThanEqual', lessThanEqual );
  4636. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  4637. addMethodChaining( 'and', and );
  4638. addMethodChaining( 'or', or );
  4639. addMethodChaining( 'not', not );
  4640. addMethodChaining( 'xor', xor );
  4641. addMethodChaining( 'bitAnd', bitAnd );
  4642. addMethodChaining( 'bitNot', bitNot );
  4643. addMethodChaining( 'bitOr', bitOr );
  4644. addMethodChaining( 'bitXor', bitXor );
  4645. addMethodChaining( 'shiftLeft', shiftLeft );
  4646. addMethodChaining( 'shiftRight', shiftRight );
  4647. addMethodChaining( 'incrementBefore', incrementBefore );
  4648. addMethodChaining( 'decrementBefore', decrementBefore );
  4649. addMethodChaining( 'increment', increment );
  4650. addMethodChaining( 'decrement', decrement );
  4651. /**
  4652. * This node represents a variety of mathematical methods available in shaders.
  4653. * They are divided into three categories:
  4654. *
  4655. * - Methods with one input like `sin`, `cos` or `normalize`.
  4656. * - Methods with two inputs like `dot`, `cross` or `pow`.
  4657. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  4658. *
  4659. * @augments TempNode
  4660. */
  4661. class MathNode extends TempNode {
  4662. static get type() {
  4663. return 'MathNode';
  4664. }
  4665. /**
  4666. * Constructs a new math node.
  4667. *
  4668. * @param {string} method - The method name.
  4669. * @param {Node} aNode - The first input.
  4670. * @param {?Node} [bNode=null] - The second input.
  4671. * @param {?Node} [cNode=null] - The third input.
  4672. */
  4673. constructor( method, aNode, bNode = null, cNode = null ) {
  4674. super();
  4675. // Allow the max() and min() functions to take an arbitrary number of arguments.
  4676. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  4677. let finalOp = new MathNode( method, aNode, bNode );
  4678. for ( let i = 3; i < arguments.length - 1; i ++ ) {
  4679. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4680. }
  4681. aNode = finalOp;
  4682. bNode = arguments[ arguments.length - 1 ];
  4683. cNode = null;
  4684. }
  4685. /**
  4686. * The method name.
  4687. *
  4688. * @type {string}
  4689. */
  4690. this.method = method;
  4691. /**
  4692. * The first input.
  4693. *
  4694. * @type {Node}
  4695. */
  4696. this.aNode = aNode;
  4697. /**
  4698. * The second input.
  4699. *
  4700. * @type {?Node}
  4701. * @default null
  4702. */
  4703. this.bNode = bNode;
  4704. /**
  4705. * The third input.
  4706. *
  4707. * @type {?Node}
  4708. * @default null
  4709. */
  4710. this.cNode = cNode;
  4711. /**
  4712. * This flag can be used for type testing.
  4713. *
  4714. * @type {boolean}
  4715. * @readonly
  4716. * @default true
  4717. */
  4718. this.isMathNode = true;
  4719. }
  4720. /**
  4721. * The input type is inferred from the node types of the input nodes.
  4722. *
  4723. * @param {NodeBuilder} builder - The current node builder.
  4724. * @return {string} The input type.
  4725. */
  4726. getInputType( builder ) {
  4727. const aType = this.aNode.getNodeType( builder );
  4728. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4729. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4730. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4731. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4732. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4733. if ( aLen > bLen && aLen > cLen ) {
  4734. return aType;
  4735. } else if ( bLen > cLen ) {
  4736. return bType;
  4737. } else if ( cLen > aLen ) {
  4738. return cType;
  4739. }
  4740. return aType;
  4741. }
  4742. /**
  4743. * The selected method as well as the input type determine the node type of this node.
  4744. *
  4745. * @param {NodeBuilder} builder - The current node builder.
  4746. * @return {string} The node type.
  4747. */
  4748. generateNodeType( builder ) {
  4749. const method = this.method;
  4750. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4751. return 'float';
  4752. } else if ( method === MathNode.CROSS ) {
  4753. return 'vec3';
  4754. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4755. return 'bool';
  4756. } else if ( method === MathNode.EQUALS ) {
  4757. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4758. } else {
  4759. return this.getInputType( builder );
  4760. }
  4761. }
  4762. setup( builder ) {
  4763. const { aNode, bNode, method } = this;
  4764. let outputNode = null;
  4765. if ( method === MathNode.ONE_MINUS ) {
  4766. outputNode = sub( 1.0, aNode );
  4767. } else if ( method === MathNode.RECIPROCAL ) {
  4768. outputNode = div( 1.0, aNode );
  4769. } else if ( method === MathNode.DIFFERENCE ) {
  4770. outputNode = abs( sub( aNode, bNode ) );
  4771. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4772. // dir can be either a direction vector or a normal vector
  4773. // upper-left 3x3 of matrix is assumed to be orthogonal
  4774. let tA = aNode;
  4775. let tB = bNode;
  4776. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4777. tB = vec4( vec3( tB ), 0.0 );
  4778. } else {
  4779. tA = vec4( vec3( tA ), 0.0 );
  4780. }
  4781. const mulNode = mul( tA, tB ).xyz;
  4782. outputNode = normalize( mulNode );
  4783. }
  4784. if ( outputNode !== null ) {
  4785. return outputNode;
  4786. } else {
  4787. return super.setup( builder );
  4788. }
  4789. }
  4790. generate( builder, output ) {
  4791. const properties = builder.getNodeProperties( this );
  4792. if ( properties.outputNode ) {
  4793. return super.generate( builder, output );
  4794. }
  4795. let method = this.method;
  4796. const type = this.getNodeType( builder );
  4797. const inputType = this.getInputType( builder );
  4798. const a = this.aNode;
  4799. const b = this.bNode;
  4800. const c = this.cNode;
  4801. const coordinateSystem = builder.renderer.coordinateSystem;
  4802. if ( method === MathNode.NEGATE ) {
  4803. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4804. } else {
  4805. const params = [];
  4806. if ( method === MathNode.CROSS ) {
  4807. params.push(
  4808. a.build( builder, type ),
  4809. b.build( builder, type )
  4810. );
  4811. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4812. params.push(
  4813. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4814. b.build( builder, inputType )
  4815. );
  4816. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4817. params.push(
  4818. a.build( builder, inputType ),
  4819. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4820. );
  4821. } else if ( method === MathNode.REFRACT ) {
  4822. params.push(
  4823. a.build( builder, inputType ),
  4824. b.build( builder, inputType ),
  4825. c.build( builder, 'float' )
  4826. );
  4827. } else if ( method === MathNode.MIX ) {
  4828. params.push(
  4829. a.build( builder, inputType ),
  4830. b.build( builder, inputType ),
  4831. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4832. );
  4833. } else {
  4834. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4835. method = 'atan2';
  4836. }
  4837. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4838. warn( `TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.`, this.stackTrace );
  4839. method = '/*' + method + '*/';
  4840. }
  4841. params.push( a.build( builder, inputType ) );
  4842. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4843. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4844. }
  4845. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4846. }
  4847. }
  4848. serialize( data ) {
  4849. super.serialize( data );
  4850. data.method = this.method;
  4851. }
  4852. deserialize( data ) {
  4853. super.deserialize( data );
  4854. this.method = data.method;
  4855. }
  4856. }
  4857. // 1 input
  4858. MathNode.ALL = 'all';
  4859. MathNode.ANY = 'any';
  4860. MathNode.RADIANS = 'radians';
  4861. MathNode.DEGREES = 'degrees';
  4862. MathNode.EXP = 'exp';
  4863. MathNode.EXP2 = 'exp2';
  4864. MathNode.LOG = 'log';
  4865. MathNode.LOG2 = 'log2';
  4866. MathNode.SQRT = 'sqrt';
  4867. MathNode.INVERSE_SQRT = 'inversesqrt';
  4868. MathNode.FLOOR = 'floor';
  4869. MathNode.CEIL = 'ceil';
  4870. MathNode.NORMALIZE = 'normalize';
  4871. MathNode.FRACT = 'fract';
  4872. MathNode.SIN = 'sin';
  4873. MathNode.SINH = 'sinh';
  4874. MathNode.COS = 'cos';
  4875. MathNode.COSH = 'cosh';
  4876. MathNode.TAN = 'tan';
  4877. MathNode.TANH = 'tanh';
  4878. MathNode.ASIN = 'asin';
  4879. MathNode.ASINH = 'asinh';
  4880. MathNode.ACOS = 'acos';
  4881. MathNode.ACOSH = 'acosh';
  4882. MathNode.ATAN = 'atan';
  4883. MathNode.ATANH = 'atanh';
  4884. MathNode.ABS = 'abs';
  4885. MathNode.SIGN = 'sign';
  4886. MathNode.LENGTH = 'length';
  4887. MathNode.NEGATE = 'negate';
  4888. MathNode.ONE_MINUS = 'oneMinus';
  4889. MathNode.DFDX = 'dFdx';
  4890. MathNode.DFDY = 'dFdy';
  4891. MathNode.ROUND = 'round';
  4892. MathNode.RECIPROCAL = 'reciprocal';
  4893. MathNode.TRUNC = 'trunc';
  4894. MathNode.FWIDTH = 'fwidth';
  4895. MathNode.TRANSPOSE = 'transpose';
  4896. MathNode.DETERMINANT = 'determinant';
  4897. MathNode.INVERSE = 'inverse';
  4898. // 2 inputs
  4899. MathNode.EQUALS = 'equals';
  4900. MathNode.MIN = 'min';
  4901. MathNode.MAX = 'max';
  4902. MathNode.STEP = 'step';
  4903. MathNode.REFLECT = 'reflect';
  4904. MathNode.DISTANCE = 'distance';
  4905. MathNode.DIFFERENCE = 'difference';
  4906. MathNode.DOT = 'dot';
  4907. MathNode.CROSS = 'cross';
  4908. MathNode.POW = 'pow';
  4909. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4910. // 3 inputs
  4911. MathNode.MIX = 'mix';
  4912. MathNode.CLAMP = 'clamp';
  4913. MathNode.REFRACT = 'refract';
  4914. MathNode.SMOOTHSTEP = 'smoothstep';
  4915. MathNode.FACEFORWARD = 'faceforward';
  4916. // 1 inputs
  4917. /**
  4918. * A small value used to handle floating-point precision errors.
  4919. *
  4920. * @tsl
  4921. * @type {Node<float>}
  4922. */
  4923. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4924. /**
  4925. * Represents infinity.
  4926. *
  4927. * @tsl
  4928. * @type {Node<float>}
  4929. */
  4930. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4931. /**
  4932. * Represents PI.
  4933. *
  4934. * @tsl
  4935. * @type {Node<float>}
  4936. */
  4937. const PI = /*@__PURE__*/ float( Math.PI );
  4938. /**
  4939. * Represents PI * 2. Please use the non-deprecated version `TWO_PI`.
  4940. *
  4941. * @tsl
  4942. * @deprecated
  4943. * @type {Node<float>}
  4944. */
  4945. const PI2 = /*@__PURE__*/ float( Math.PI * 2 ); // @deprecated r181
  4946. /**
  4947. * Represents PI * 2.
  4948. *
  4949. * @tsl
  4950. * @type {Node<float>}
  4951. */
  4952. const TWO_PI = /*@__PURE__*/ float( Math.PI * 2 );
  4953. /**
  4954. * Represents PI / 2.
  4955. *
  4956. * @tsl
  4957. * @type {Node<float>}
  4958. */
  4959. const HALF_PI = /*@__PURE__*/ float( Math.PI * 0.5 );
  4960. /**
  4961. * Returns `true` if all components of `x` are `true`.
  4962. *
  4963. * @tsl
  4964. * @function
  4965. * @param {Node | number} x - The parameter.
  4966. * @returns {Node<bool>}
  4967. */
  4968. const all = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4969. /**
  4970. * Returns `true` if any components of `x` are `true`.
  4971. *
  4972. * @tsl
  4973. * @function
  4974. * @param {Node | number} x - The parameter.
  4975. * @returns {Node<bool>}
  4976. */
  4977. const any = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4978. /**
  4979. * Converts a quantity in degrees to radians.
  4980. *
  4981. * @tsl
  4982. * @function
  4983. * @param {Node | number} x - The input in degrees.
  4984. * @returns {Node}
  4985. */
  4986. const radians = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4987. /**
  4988. * Convert a quantity in radians to degrees.
  4989. *
  4990. * @tsl
  4991. * @function
  4992. * @param {Node | number} x - The input in radians.
  4993. * @returns {Node}
  4994. */
  4995. const degrees = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4996. /**
  4997. * Returns the natural exponentiation of the parameter.
  4998. *
  4999. * @tsl
  5000. * @function
  5001. * @param {Node | number} x - The parameter.
  5002. * @returns {Node}
  5003. */
  5004. const exp = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP ).setParameterLength( 1 );
  5005. /**
  5006. * Returns 2 raised to the power of the parameter.
  5007. *
  5008. * @tsl
  5009. * @function
  5010. * @param {Node | number} x - The parameter.
  5011. * @returns {Node}
  5012. */
  5013. const exp2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  5014. /**
  5015. * Returns the natural logarithm of the parameter.
  5016. *
  5017. * @tsl
  5018. * @function
  5019. * @param {Node | number} x - The parameter.
  5020. * @returns {Node}
  5021. */
  5022. const log = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG ).setParameterLength( 1 );
  5023. /**
  5024. * Returns the base 2 logarithm of the parameter.
  5025. *
  5026. * @tsl
  5027. * @function
  5028. * @param {Node | number} x - The parameter.
  5029. * @returns {Node}
  5030. */
  5031. const log2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  5032. /**
  5033. * Returns the square root of the parameter.
  5034. *
  5035. * @tsl
  5036. * @function
  5037. * @param {Node | number} x - The parameter.
  5038. * @returns {Node}
  5039. */
  5040. const sqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  5041. /**
  5042. * Returns the inverse of the square root of the parameter.
  5043. *
  5044. * @tsl
  5045. * @function
  5046. * @param {Node | number} x - The parameter.
  5047. * @returns {Node}
  5048. */
  5049. const inverseSqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  5050. /**
  5051. * Finds the nearest integer less than or equal to the parameter.
  5052. *
  5053. * @tsl
  5054. * @function
  5055. * @param {Node | number} x - The parameter.
  5056. * @returns {Node}
  5057. */
  5058. const floor = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  5059. /**
  5060. * Finds the nearest integer that is greater than or equal to the parameter.
  5061. *
  5062. * @tsl
  5063. * @function
  5064. * @param {Node | number} x - The parameter.
  5065. * @returns {Node}
  5066. */
  5067. const ceil = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  5068. /**
  5069. * Calculates the unit vector in the same direction as the original vector.
  5070. *
  5071. * @tsl
  5072. * @function
  5073. * @param {Node} x - The input vector.
  5074. * @returns {Node}
  5075. */
  5076. const normalize = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  5077. /**
  5078. * Computes the fractional part of the parameter.
  5079. *
  5080. * @tsl
  5081. * @function
  5082. * @param {Node | number} x - The parameter.
  5083. * @returns {Node}
  5084. */
  5085. const fract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  5086. /**
  5087. * Returns the sine of the parameter.
  5088. *
  5089. * @tsl
  5090. * @function
  5091. * @param {Node | number} x - The parameter.
  5092. * @returns {Node}
  5093. */
  5094. const sin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIN ).setParameterLength( 1 );
  5095. /**
  5096. * Returns the hyperbolic sine of the parameter.
  5097. *
  5098. * @tsl
  5099. * @function
  5100. * @param {Node | number} x - The parameter.
  5101. * @returns {Node}
  5102. */
  5103. const sinh = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SINH ).setParameterLength( 1 );
  5104. /**
  5105. * Returns the cosine of the parameter.
  5106. *
  5107. * @tsl
  5108. * @function
  5109. * @param {Node | number} x - The parameter.
  5110. * @returns {Node}
  5111. */
  5112. const cos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COS ).setParameterLength( 1 );
  5113. /**
  5114. * Returns the hyperbolic cosine of the parameter.
  5115. *
  5116. * @tsl
  5117. * @function
  5118. * @param {Node | number} x - The parameter.
  5119. * @returns {Node}
  5120. */
  5121. const cosh = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COSH ).setParameterLength( 1 );
  5122. /**
  5123. * Returns the tangent of the parameter.
  5124. *
  5125. * @tsl
  5126. * @function
  5127. * @param {Node | number} x - The parameter.
  5128. * @returns {Node}
  5129. */
  5130. const tan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TAN ).setParameterLength( 1 );
  5131. /**
  5132. * Returns the hyperbolic tangent of the parameter.
  5133. *
  5134. * @tsl
  5135. * @function
  5136. * @param {Node | number} x - The parameter.
  5137. * @returns {Node}
  5138. */
  5139. const tanh = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TANH ).setParameterLength( 1 );
  5140. /**
  5141. * Returns the arcsine of the parameter.
  5142. *
  5143. * @tsl
  5144. * @function
  5145. * @param {Node | number} x - The parameter.
  5146. * @returns {Node}
  5147. */
  5148. const asin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  5149. /**
  5150. * Returns the inverse hyperbolic sine of the parameter.
  5151. *
  5152. * @tsl
  5153. * @function
  5154. * @param {Node | number} x - The parameter.
  5155. * @returns {Node}
  5156. */
  5157. const asinh = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASINH ).setParameterLength( 1 );
  5158. /**
  5159. * Returns the arccosine of the parameter.
  5160. *
  5161. * @tsl
  5162. * @function
  5163. * @param {Node | number} x - The parameter.
  5164. * @returns {Node}
  5165. */
  5166. const acos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  5167. /**
  5168. * Returns the inverse hyperbolic cosine of the parameter.
  5169. *
  5170. * @tsl
  5171. * @function
  5172. * @param {Node | number} x - The parameter.
  5173. * @returns {Node}
  5174. */
  5175. const acosh = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOSH ).setParameterLength( 1 );
  5176. /**
  5177. * Returns the arc-tangent of the parameter.
  5178. * If two parameters are provided, the result is `atan2(y/x)`.
  5179. *
  5180. * @tsl
  5181. * @function
  5182. * @param {Node | number} y - The y parameter.
  5183. * @param {?(Node | number)} x - The x parameter.
  5184. * @returns {Node}
  5185. */
  5186. const atan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  5187. /**
  5188. * Returns the inverse hyperbolic tangent of the parameter.
  5189. *
  5190. * @tsl
  5191. * @function
  5192. * @param {Node | number} x - The parameter.
  5193. * @returns {Node}
  5194. */
  5195. const atanh = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATANH ).setParameterLength( 1 );
  5196. /**
  5197. * Returns the absolute value of the parameter.
  5198. *
  5199. * @tsl
  5200. * @function
  5201. * @param {Node | number} x - The parameter.
  5202. * @returns {Node}
  5203. */
  5204. const abs = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ABS ).setParameterLength( 1 );
  5205. /**
  5206. * Extracts the sign of the parameter.
  5207. *
  5208. * @tsl
  5209. * @function
  5210. * @param {Node | number} x - The parameter.
  5211. * @returns {Node}
  5212. */
  5213. const sign = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  5214. /**
  5215. * Calculates the length of a vector.
  5216. *
  5217. * @tsl
  5218. * @function
  5219. * @param {Node} x - The parameter.
  5220. * @returns {Node<float>}
  5221. */
  5222. const length = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  5223. /**
  5224. * Negates the value of the parameter (-x).
  5225. *
  5226. * @tsl
  5227. * @function
  5228. * @param {Node | number} x - The parameter.
  5229. * @returns {Node}
  5230. */
  5231. const negate = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  5232. /**
  5233. * Return `1` minus the parameter.
  5234. *
  5235. * @tsl
  5236. * @function
  5237. * @param {Node | number} x - The parameter.
  5238. * @returns {Node}
  5239. */
  5240. const oneMinus = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  5241. /**
  5242. * Returns the partial derivative of the parameter with respect to x.
  5243. *
  5244. * @tsl
  5245. * @function
  5246. * @param {Node | number} x - The parameter.
  5247. * @returns {Node}
  5248. */
  5249. const dFdx = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  5250. /**
  5251. * Returns the partial derivative of the parameter with respect to y.
  5252. *
  5253. * @tsl
  5254. * @function
  5255. * @param {Node | number} x - The parameter.
  5256. * @returns {Node}
  5257. */
  5258. const dFdy = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  5259. /**
  5260. * Rounds the parameter to the nearest integer.
  5261. *
  5262. * @tsl
  5263. * @function
  5264. * @param {Node | number} x - The parameter.
  5265. * @returns {Node}
  5266. */
  5267. const round = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  5268. /**
  5269. * Returns the reciprocal of the parameter `(1/x)`.
  5270. *
  5271. * @tsl
  5272. * @function
  5273. * @param {Node | number} x - The parameter.
  5274. * @returns {Node}
  5275. */
  5276. const reciprocal = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  5277. /**
  5278. * Truncates the parameter, removing the fractional part.
  5279. *
  5280. * @tsl
  5281. * @function
  5282. * @param {Node | number} x - The parameter.
  5283. * @returns {Node}
  5284. */
  5285. const trunc = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  5286. /**
  5287. * Returns the sum of the absolute derivatives in x and y.
  5288. *
  5289. * @tsl
  5290. * @function
  5291. * @param {Node | number} x - The parameter.
  5292. * @returns {Node}
  5293. */
  5294. const fwidth = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  5295. /**
  5296. * Returns the transpose of a matrix.
  5297. *
  5298. * @tsl
  5299. * @function
  5300. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  5301. * @returns {Node}
  5302. */
  5303. const transpose = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  5304. /**
  5305. * Returns the determinant of a matrix.
  5306. *
  5307. * @tsl
  5308. * @function
  5309. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  5310. * @returns {Node<float>}
  5311. */
  5312. const determinant = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DETERMINANT ).setParameterLength( 1 );
  5313. /**
  5314. * Returns the inverse of a matrix.
  5315. *
  5316. * @tsl
  5317. * @function
  5318. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  5319. * @returns {Node<mat2|mat3|mat4>}
  5320. */
  5321. const inverse = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE ).setParameterLength( 1 );
  5322. // 2 inputs
  5323. /**
  5324. * Returns the least of the given values.
  5325. *
  5326. * @tsl
  5327. * @function
  5328. * @param {...(Node | number)} values - The values to compare.
  5329. * @returns {Node}
  5330. */
  5331. const min$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  5332. /**
  5333. * Returns the greatest of the given values.
  5334. *
  5335. * @tsl
  5336. * @function
  5337. * @param {...(Node | number)} values - The values to compare.
  5338. * @returns {Node}
  5339. */
  5340. const max$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  5341. /**
  5342. * Generate a step function by comparing two values.
  5343. *
  5344. * @tsl
  5345. * @function
  5346. * @param {Node | number} x - The y parameter.
  5347. * @param {Node | number} y - The x parameter.
  5348. * @returns {Node}
  5349. */
  5350. const step = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.STEP ).setParameterLength( 2 );
  5351. /**
  5352. * Calculates the reflection direction for an incident vector.
  5353. *
  5354. * @tsl
  5355. * @function
  5356. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5357. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5358. * @returns {Node<vec2|vec3|vec4>}
  5359. */
  5360. const reflect = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  5361. /**
  5362. * Calculates the distance between two points.
  5363. *
  5364. * @tsl
  5365. * @function
  5366. * @param {Node<vec2|vec3|vec4>} x - The first point.
  5367. * @param {Node<vec2|vec3|vec4>} y - The second point.
  5368. * @returns {Node<float>}
  5369. */
  5370. const distance = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  5371. /**
  5372. * Calculates the absolute difference between two values.
  5373. *
  5374. * @tsl
  5375. * @function
  5376. * @param {Node | number} x - The first parameter.
  5377. * @param {Node | number} y - The second parameter.
  5378. * @returns {Node}
  5379. */
  5380. const difference = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  5381. /**
  5382. * Calculates the dot product of two vectors.
  5383. *
  5384. * @tsl
  5385. * @function
  5386. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  5387. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  5388. * @returns {Node<float>}
  5389. */
  5390. const dot = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DOT ).setParameterLength( 2 );
  5391. /**
  5392. * Calculates the cross product of two vectors.
  5393. *
  5394. * @tsl
  5395. * @function
  5396. * @param {Node<vec2|vec3>} x - The first vector.
  5397. * @param {Node<vec2|vec3>} y - The second vector.
  5398. * @returns {Node<float|vec3>}
  5399. */
  5400. const cross = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  5401. /**
  5402. * Return the value of the first parameter raised to the power of the second one.
  5403. *
  5404. * @tsl
  5405. * @function
  5406. * @param {Node | number} x - The first parameter.
  5407. * @param {Node | number} y - The second parameter.
  5408. * @returns {Node}
  5409. */
  5410. const pow = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW ).setParameterLength( 2 );
  5411. /**
  5412. * Returns the square of the parameter.
  5413. *
  5414. * @tsl
  5415. * @function
  5416. * @param {Node | number} x - The first parameter.
  5417. * @returns {Node}
  5418. */
  5419. const pow2 = ( x ) => mul( x, x );
  5420. /**
  5421. * Returns the cube of the parameter.
  5422. *
  5423. * @tsl
  5424. * @function
  5425. * @param {Node | number} x - The first parameter.
  5426. * @returns {Node}
  5427. */
  5428. const pow3 = ( x ) => mul( x, x, x );
  5429. /**
  5430. * Returns the fourth power of the parameter.
  5431. *
  5432. * @tsl
  5433. * @function
  5434. * @param {Node | number} x - The first parameter.
  5435. * @returns {Node}
  5436. */
  5437. const pow4 = ( x ) => mul( x, x, x, x );
  5438. /**
  5439. * Transforms the direction of a vector by a matrix and then normalizes the result.
  5440. *
  5441. * @tsl
  5442. * @function
  5443. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  5444. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  5445. * @returns {Node}
  5446. */
  5447. const transformDirection = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  5448. /**
  5449. * Returns the cube root of a number.
  5450. *
  5451. * @tsl
  5452. * @function
  5453. * @param {Node | number} a - The first parameter.
  5454. * @returns {Node}
  5455. */
  5456. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  5457. /**
  5458. * Calculate the squared length of a vector.
  5459. *
  5460. * @tsl
  5461. * @function
  5462. * @param {Node<vec2|vec3|vec4>} a - The vector.
  5463. * @returns {Node<float>}
  5464. */
  5465. const lengthSq = ( a ) => dot( a, a );
  5466. /**
  5467. * Linearly interpolates between two values.
  5468. *
  5469. * @tsl
  5470. * @function
  5471. * @param {Node | number} a - The first parameter.
  5472. * @param {Node | number} b - The second parameter.
  5473. * @param {Node | number} t - The interpolation value.
  5474. * @returns {Node}
  5475. */
  5476. const mix = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIX ).setParameterLength( 3 );
  5477. /**
  5478. * Constrains a value to lie between two further values.
  5479. *
  5480. * @tsl
  5481. * @function
  5482. * @param {Node | number} value - The value to constrain.
  5483. * @param {Node | number} [low=0] - The lower bound.
  5484. * @param {Node | number} [high=1] - The upper bound.
  5485. * @returns {Node}
  5486. */
  5487. const clamp = ( value, low = 0, high = 1 ) => new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) );
  5488. /**
  5489. * Constrains a value between `0` and `1`.
  5490. *
  5491. * @tsl
  5492. * @function
  5493. * @param {Node | number} value - The value to constrain.
  5494. * @returns {Node}
  5495. */
  5496. const saturate = ( value ) => clamp( value );
  5497. /**
  5498. * Calculates the refraction direction for an incident vector.
  5499. *
  5500. * @tsl
  5501. * @function
  5502. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5503. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5504. * @param {Node<float>} eta - The ratio of indices of refraction.
  5505. * @returns {Node<vec2|vec3|vec4>}
  5506. */
  5507. const refract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  5508. /**
  5509. * Performs a Hermite interpolation between two values.
  5510. *
  5511. * @tsl
  5512. * @function
  5513. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5514. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5515. * @param {Node | number} x - The source value for interpolation.
  5516. * @returns {Node}
  5517. */
  5518. const smoothstep = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  5519. /**
  5520. * Returns a vector pointing in the same direction as another.
  5521. *
  5522. * @tsl
  5523. * @function
  5524. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  5525. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5526. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  5527. * @returns {Node<vec2|vec3|vec4>}
  5528. */
  5529. const faceForward = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  5530. /**
  5531. * Returns a random value for the given uv.
  5532. *
  5533. * @tsl
  5534. * @function
  5535. * @param {Node<vec2>} uv - The uv node.
  5536. * @returns {Node<float>}
  5537. */
  5538. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  5539. const a = 12.9898, b = 78.233, c = 43758.5453;
  5540. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  5541. return fract( sin( sn ).mul( c ) );
  5542. } );
  5543. /**
  5544. * Alias for `mix()` with a different parameter order.
  5545. *
  5546. * @tsl
  5547. * @function
  5548. * @param {Node | number} t - The interpolation value.
  5549. * @param {Node | number} e1 - The first parameter.
  5550. * @param {Node | number} e2 - The second parameter.
  5551. * @returns {Node}
  5552. */
  5553. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  5554. /**
  5555. * Alias for `smoothstep()` with a different parameter order.
  5556. *
  5557. * @tsl
  5558. * @function
  5559. * @param {Node | number} x - The source value for interpolation.
  5560. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5561. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5562. * @returns {Node}
  5563. */
  5564. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  5565. /**
  5566. * Alias for `step()` with a different parameter order.
  5567. *
  5568. * @tsl
  5569. * @function
  5570. * @param {Node | number} x - The source value for interpolation.
  5571. * @param {Node | number} edge - The edge value.
  5572. * @returns {Node}
  5573. */
  5574. const stepElement = ( x, edge ) => step( edge, x );
  5575. // GLSL alias function
  5576. const faceforward = faceForward;
  5577. const inversesqrt = inverseSqrt;
  5578. // Method chaining
  5579. addMethodChaining( 'all', all );
  5580. addMethodChaining( 'any', any );
  5581. addMethodChaining( 'radians', radians );
  5582. addMethodChaining( 'degrees', degrees );
  5583. addMethodChaining( 'exp', exp );
  5584. addMethodChaining( 'exp2', exp2 );
  5585. addMethodChaining( 'log', log );
  5586. addMethodChaining( 'log2', log2 );
  5587. addMethodChaining( 'sqrt', sqrt );
  5588. addMethodChaining( 'inverseSqrt', inverseSqrt );
  5589. addMethodChaining( 'floor', floor );
  5590. addMethodChaining( 'ceil', ceil );
  5591. addMethodChaining( 'normalize', normalize );
  5592. addMethodChaining( 'fract', fract );
  5593. addMethodChaining( 'sin', sin );
  5594. addMethodChaining( 'sinh', sinh );
  5595. addMethodChaining( 'cos', cos );
  5596. addMethodChaining( 'cosh', cosh );
  5597. addMethodChaining( 'tan', tan );
  5598. addMethodChaining( 'tanh', tanh );
  5599. addMethodChaining( 'asin', asin );
  5600. addMethodChaining( 'asinh', asinh );
  5601. addMethodChaining( 'acos', acos );
  5602. addMethodChaining( 'acosh', acosh );
  5603. addMethodChaining( 'atan', atan );
  5604. addMethodChaining( 'atanh', atanh );
  5605. addMethodChaining( 'abs', abs );
  5606. addMethodChaining( 'sign', sign );
  5607. addMethodChaining( 'length', length );
  5608. addMethodChaining( 'lengthSq', lengthSq );
  5609. addMethodChaining( 'negate', negate );
  5610. addMethodChaining( 'oneMinus', oneMinus );
  5611. addMethodChaining( 'dFdx', dFdx );
  5612. addMethodChaining( 'dFdy', dFdy );
  5613. addMethodChaining( 'round', round );
  5614. addMethodChaining( 'reciprocal', reciprocal );
  5615. addMethodChaining( 'trunc', trunc );
  5616. addMethodChaining( 'fwidth', fwidth );
  5617. addMethodChaining( 'min', min$1 );
  5618. addMethodChaining( 'max', max$1 );
  5619. addMethodChaining( 'step', stepElement );
  5620. addMethodChaining( 'reflect', reflect );
  5621. addMethodChaining( 'distance', distance );
  5622. addMethodChaining( 'dot', dot );
  5623. addMethodChaining( 'cross', cross );
  5624. addMethodChaining( 'pow', pow );
  5625. addMethodChaining( 'pow2', pow2 );
  5626. addMethodChaining( 'pow3', pow3 );
  5627. addMethodChaining( 'pow4', pow4 );
  5628. addMethodChaining( 'transformDirection', transformDirection );
  5629. addMethodChaining( 'mix', mixElement );
  5630. addMethodChaining( 'clamp', clamp );
  5631. addMethodChaining( 'refract', refract );
  5632. addMethodChaining( 'smoothstep', smoothstepElement );
  5633. addMethodChaining( 'faceForward', faceForward );
  5634. addMethodChaining( 'difference', difference );
  5635. addMethodChaining( 'saturate', saturate );
  5636. addMethodChaining( 'cbrt', cbrt );
  5637. addMethodChaining( 'transpose', transpose );
  5638. addMethodChaining( 'determinant', determinant );
  5639. addMethodChaining( 'inverse', inverse );
  5640. addMethodChaining( 'rand', rand );
  5641. /**
  5642. * Represents a logical `if/else` statement. Can be used as an alternative
  5643. * to the `If()`/`Else()` syntax.
  5644. *
  5645. * The corresponding TSL `select()` looks like so:
  5646. * ```js
  5647. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  5648. * ```
  5649. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  5650. * determine the outcome of the entire statement.
  5651. *
  5652. * @augments Node
  5653. */
  5654. class ConditionalNode extends Node {
  5655. static get type() {
  5656. return 'ConditionalNode';
  5657. }
  5658. /**
  5659. * Constructs a new conditional node.
  5660. *
  5661. * @param {Node} condNode - The node that defines the condition.
  5662. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5663. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5664. */
  5665. constructor( condNode, ifNode, elseNode = null ) {
  5666. super();
  5667. /**
  5668. * The node that defines the condition.
  5669. *
  5670. * @type {Node}
  5671. */
  5672. this.condNode = condNode;
  5673. /**
  5674. * The node that is evaluate when the condition ends up `true`.
  5675. *
  5676. * @type {Node}
  5677. */
  5678. this.ifNode = ifNode;
  5679. /**
  5680. * The node that is evaluate when the condition ends up `false`.
  5681. *
  5682. * @type {?Node}
  5683. * @default null
  5684. */
  5685. this.elseNode = elseNode;
  5686. }
  5687. /**
  5688. * This method is overwritten since the node type is inferred from the if/else
  5689. * nodes.
  5690. *
  5691. * @param {NodeBuilder} builder - The current node builder.
  5692. * @return {string} The node type.
  5693. */
  5694. generateNodeType( builder ) {
  5695. const { ifNode, elseNode } = builder.getNodeProperties( this );
  5696. if ( ifNode === undefined ) {
  5697. // fallback setup
  5698. builder.flowBuildStage( this, 'setup' );
  5699. return this.getNodeType( builder );
  5700. }
  5701. const ifType = ifNode.getNodeType( builder );
  5702. if ( elseNode !== null ) {
  5703. const elseType = elseNode.getNodeType( builder );
  5704. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  5705. return elseType;
  5706. }
  5707. }
  5708. return ifType;
  5709. }
  5710. setup( builder ) {
  5711. const condNode = this.condNode;
  5712. const ifNode = this.ifNode.isolate();
  5713. const elseNode = this.elseNode ? this.elseNode.isolate() : null;
  5714. //
  5715. const currentNodeBlock = builder.context.nodeBlock;
  5716. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  5717. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  5718. //
  5719. const isUniformFlow = builder.context.uniformFlow;
  5720. const properties = builder.getNodeProperties( this );
  5721. properties.condNode = condNode;
  5722. properties.ifNode = isUniformFlow ? ifNode : ifNode.context( { nodeBlock: ifNode } );
  5723. properties.elseNode = elseNode ? ( isUniformFlow ? elseNode : elseNode.context( { nodeBlock: elseNode } ) ) : null;
  5724. }
  5725. generate( builder, output ) {
  5726. const type = this.getNodeType( builder );
  5727. const nodeData = builder.getDataFromNode( this );
  5728. if ( nodeData.nodeProperty !== undefined ) {
  5729. return nodeData.nodeProperty;
  5730. }
  5731. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  5732. const functionNode = builder.currentFunctionNode;
  5733. const needsOutput = output !== 'void';
  5734. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  5735. nodeData.nodeProperty = nodeProperty;
  5736. const nodeSnippet = condNode.build( builder, 'bool' );
  5737. const isUniformFlow = builder.context.uniformFlow;
  5738. if ( isUniformFlow && elseNode !== null ) {
  5739. const ifSnippet = ifNode.build( builder, type );
  5740. const elseSnippet = elseNode.build( builder, type );
  5741. const mathSnippet = builder.getTernary( nodeSnippet, ifSnippet, elseSnippet );
  5742. // TODO: If node property already exists return something else
  5743. return builder.format( mathSnippet, type, output );
  5744. }
  5745. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  5746. let ifSnippet = ifNode.build( builder, type );
  5747. if ( ifSnippet ) {
  5748. if ( needsOutput ) {
  5749. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  5750. } else {
  5751. ifSnippet = 'return ' + ifSnippet + ';';
  5752. if ( functionNode === null ) {
  5753. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.', this.stackTrace );
  5754. ifSnippet = '// ' + ifSnippet;
  5755. }
  5756. }
  5757. }
  5758. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  5759. if ( elseNode !== null ) {
  5760. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5761. let elseSnippet = elseNode.build( builder, type );
  5762. if ( elseSnippet ) {
  5763. if ( needsOutput ) {
  5764. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5765. } else {
  5766. elseSnippet = 'return ' + elseSnippet + ';';
  5767. if ( functionNode === null ) {
  5768. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.', this.stackTrace );
  5769. elseSnippet = '// ' + elseSnippet;
  5770. }
  5771. }
  5772. }
  5773. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5774. } else {
  5775. builder.addFlowCode( '\n\n' );
  5776. }
  5777. return builder.format( nodeProperty, type, output );
  5778. }
  5779. }
  5780. /**
  5781. * TSL function for creating a conditional node.
  5782. *
  5783. * @tsl
  5784. * @function
  5785. * @param {Node} condNode - The node that defines the condition.
  5786. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5787. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5788. * @returns {ConditionalNode}
  5789. */
  5790. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5791. addMethodChaining( 'select', select );
  5792. /**
  5793. * This node can be used as a context management component for another node.
  5794. * {@link NodeBuilder} performs its node building process in a specific context and
  5795. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5796. *
  5797. * ```js
  5798. *node.context( { getUV: () => customCoord } );
  5799. *\// or
  5800. *material.contextNode = context( { getUV: () => customCoord } );
  5801. *\// or
  5802. *renderer.contextNode = context( { getUV: () => customCoord } );
  5803. *\// or
  5804. *scenePass.contextNode = context( { getUV: () => customCoord } );
  5805. *```
  5806. * @augments Node
  5807. */
  5808. class ContextNode extends Node {
  5809. static get type() {
  5810. return 'ContextNode';
  5811. }
  5812. /**
  5813. * Constructs a new context node.
  5814. *
  5815. * @param {Node} node - The node whose context should be modified.
  5816. * @param {Object} [value={}] - The modified context data.
  5817. */
  5818. constructor( node = null, value = {} ) {
  5819. super();
  5820. /**
  5821. * This flag can be used for type testing.
  5822. *
  5823. * @type {boolean}
  5824. * @readonly
  5825. * @default true
  5826. */
  5827. this.isContextNode = true;
  5828. /**
  5829. * The node whose context should be modified.
  5830. *
  5831. * @type {Node}
  5832. */
  5833. this.node = node;
  5834. /**
  5835. * The modified context data.
  5836. *
  5837. * @type {Object}
  5838. * @default {}
  5839. */
  5840. this.value = value;
  5841. }
  5842. /**
  5843. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5844. *
  5845. * @return {Node} A reference to {@link ContextNode#node}.
  5846. */
  5847. getScope() {
  5848. return this.node.getScope();
  5849. }
  5850. /**
  5851. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5852. *
  5853. * @param {NodeBuilder} builder - The current node builder.
  5854. * @return {string} The node type.
  5855. */
  5856. generateNodeType( builder ) {
  5857. return this.node.getNodeType( builder );
  5858. }
  5859. /**
  5860. * Gathers the context data from all parent context nodes.
  5861. *
  5862. * @return {Object} The gathered context data.
  5863. */
  5864. getFlowContextData() {
  5865. const children = [];
  5866. this.traverse( ( node ) => {
  5867. if ( node.isContextNode === true ) {
  5868. children.push( node.value );
  5869. }
  5870. } );
  5871. return Object.assign( {}, ...children );
  5872. }
  5873. /**
  5874. * This method is overwritten to ensure it returns the member type of {@link ContextNode#node}.
  5875. *
  5876. * @param {NodeBuilder} builder - The current node builder.
  5877. * @param {string} name - The member name.
  5878. * @returns {string} The member type.
  5879. */
  5880. getMemberType( builder, name ) {
  5881. return this.node.getMemberType( builder, name );
  5882. }
  5883. analyze( builder ) {
  5884. const previousContext = builder.addContext( this.value );
  5885. this.node.build( builder );
  5886. builder.setContext( previousContext );
  5887. }
  5888. setup( builder ) {
  5889. const previousContext = builder.addContext( this.value );
  5890. this.node.build( builder );
  5891. builder.setContext( previousContext );
  5892. }
  5893. generate( builder, output ) {
  5894. const previousContext = builder.addContext( this.value );
  5895. const snippet = this.node.build( builder, output );
  5896. builder.setContext( previousContext );
  5897. return snippet;
  5898. }
  5899. }
  5900. /**
  5901. * TSL function for creating a context node.
  5902. *
  5903. * @tsl
  5904. * @function
  5905. * @param {Node|Object} [nodeOrValue={}] - The node whose context should be modified or the modified context data.
  5906. * @param {Object} [value={}] - The modified context data.
  5907. * @returns {ContextNode}
  5908. */
  5909. const context = ( nodeOrValue = null, value = {} ) => {
  5910. let node = nodeOrValue;
  5911. if ( node === null || node.isNode !== true ) {
  5912. value = node || value;
  5913. node = null;
  5914. }
  5915. return new ContextNode( node, value );
  5916. };
  5917. /**
  5918. * TSL function for defining a uniformFlow context value for a given node.
  5919. *
  5920. * @tsl
  5921. * @function
  5922. * @param {Node} node - The node whose dependencies should all execute within a uniform control-flow path.
  5923. * @returns {ContextNode}
  5924. */
  5925. const uniformFlow = ( node ) => context( node, { uniformFlow: true } );
  5926. /**
  5927. * TSL function for defining a name for the context value for a given node.
  5928. *
  5929. * @tsl
  5930. * @function
  5931. * @param {Node} node - The node whose context should be modified.
  5932. * @param {string} name - The name to set.
  5933. * @returns {ContextNode}
  5934. */
  5935. const setName = ( node, name ) => context( node, { nodeName: name } );
  5936. /**
  5937. * TSL function for defining a built-in shadow context for a given node.
  5938. *
  5939. * @tsl
  5940. * @function
  5941. * @param {ShadowNode} shadowNode - The shadow node representing the light's shadow.
  5942. * @param {Light} light - The light associated with the shadow.
  5943. * @param {Node} [node=null] - The node whose context should be modified.
  5944. * @returns {ContextNode}
  5945. */
  5946. function builtinShadowContext( shadowNode, light, node = null ) {
  5947. return context( node, {
  5948. getShadow: ( { light: shadowLight, shadowColorNode } ) => {
  5949. if ( light === shadowLight ) {
  5950. return shadowColorNode.mul( shadowNode );
  5951. }
  5952. return shadowColorNode;
  5953. }
  5954. } );
  5955. }
  5956. /**
  5957. * TSL function for defining a built-in ambient occlusion context for a given node.
  5958. *
  5959. * @tsl
  5960. * @function
  5961. * @param {Node} aoNode - The ambient occlusion value node to apply.
  5962. * @param {Node} [node=null] - The node whose context should be modified.
  5963. * @returns {ContextNode}
  5964. */
  5965. function builtinAOContext( aoNode, node = null ) {
  5966. return context( node, {
  5967. getAO: ( inputNode, { material } ) => {
  5968. if ( material.transparent === true ) return inputNode;
  5969. return inputNode !== null ? inputNode.mul( aoNode ) : aoNode;
  5970. }
  5971. } );
  5972. }
  5973. /**
  5974. * TSL function for defining a label context value for a given node.
  5975. *
  5976. * @tsl
  5977. * @function
  5978. * @deprecated
  5979. * @param {Node} node - The node whose context should be modified.
  5980. * @param {string} name - The name/label to set.
  5981. * @returns {ContextNode}
  5982. */
  5983. function label( node, name ) {
  5984. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  5985. return setName( node, name );
  5986. }
  5987. addMethodChaining( 'context', context );
  5988. addMethodChaining( 'label', label );
  5989. addMethodChaining( 'uniformFlow', uniformFlow );
  5990. addMethodChaining( 'setName', setName );
  5991. addMethodChaining( 'builtinShadowContext', ( node, shadowNode, light ) => builtinShadowContext( shadowNode, light, node ) );
  5992. addMethodChaining( 'builtinAOContext', ( node, aoValue ) => builtinAOContext( aoValue, node ) );
  5993. /**
  5994. * Class for representing shader variables as nodes. Variables are created from
  5995. * existing nodes like the following:
  5996. *
  5997. * ```js
  5998. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5999. * ```
  6000. *
  6001. * @augments Node
  6002. */
  6003. class VarNode extends Node {
  6004. static get type() {
  6005. return 'VarNode';
  6006. }
  6007. /**
  6008. * Constructs a new variable node.
  6009. *
  6010. * @param {Node} node - The node for which a variable should be created.
  6011. * @param {?string} [name=null] - The name of the variable in the shader.
  6012. * @param {boolean} [readOnly=false] - The read-only flag.
  6013. */
  6014. constructor( node, name = null, readOnly = false ) {
  6015. super();
  6016. /**
  6017. * The node for which a variable should be created.
  6018. *
  6019. * @type {Node}
  6020. */
  6021. this.node = node;
  6022. /**
  6023. * The name of the variable in the shader. If no name is defined,
  6024. * the node system auto-generates one.
  6025. *
  6026. * @type {?string}
  6027. * @default null
  6028. */
  6029. this.name = name;
  6030. /**
  6031. * `VarNode` sets this property to `true` by default.
  6032. *
  6033. * @type {boolean}
  6034. * @default true
  6035. */
  6036. this.global = true;
  6037. /**
  6038. * This flag can be used for type testing.
  6039. *
  6040. * @type {boolean}
  6041. * @readonly
  6042. * @default true
  6043. */
  6044. this.isVarNode = true;
  6045. /**
  6046. *
  6047. * The read-only flag.
  6048. *
  6049. * @type {boolean}
  6050. * @default false
  6051. */
  6052. this.readOnly = readOnly;
  6053. /**
  6054. *
  6055. * Add this flag to the node system to indicate that this node require parents.
  6056. *
  6057. * @type {boolean}
  6058. * @default true
  6059. */
  6060. this.parents = true;
  6061. /**
  6062. * This flag is used to indicate that this node is used for intent.
  6063. *
  6064. * @type {boolean}
  6065. * @default false
  6066. */
  6067. this.intent = false;
  6068. }
  6069. /**
  6070. * Sets the intent flag for this node.
  6071. *
  6072. * This flag is used to indicate that this node is used for intent
  6073. * and should not be built directly. Instead, it is used to indicate that
  6074. * the node should be treated as a variable intent.
  6075. *
  6076. * It's useful for assigning variables without needing creating a new variable node.
  6077. *
  6078. * @param {boolean} value - The value to set for the intent flag.
  6079. * @returns {VarNode} This node.
  6080. */
  6081. setIntent( value ) {
  6082. this.intent = value;
  6083. return this;
  6084. }
  6085. /**
  6086. * Checks if this node is used for intent.
  6087. *
  6088. * @param {NodeBuilder} builder - The node builder.
  6089. * @returns {boolean} Whether this node is used for intent.
  6090. */
  6091. isIntent( builder ) {
  6092. const data = builder.getDataFromNode( this );
  6093. if ( data.forceDeclaration === true ) return false;
  6094. return this.intent;
  6095. }
  6096. /**
  6097. * Returns the intent flag of this node.
  6098. *
  6099. * @return {boolean} The intent flag.
  6100. */
  6101. getIntent() {
  6102. return this.intent;
  6103. }
  6104. getMemberType( builder, name ) {
  6105. return this.node.getMemberType( builder, name );
  6106. }
  6107. getElementType( builder ) {
  6108. return this.node.getElementType( builder );
  6109. }
  6110. generateNodeType( builder ) {
  6111. return this.node.getNodeType( builder );
  6112. }
  6113. getArrayCount( builder ) {
  6114. return this.node.getArrayCount( builder );
  6115. }
  6116. isAssign( builder ) {
  6117. const data = builder.getDataFromNode( this );
  6118. return data.assign;
  6119. }
  6120. build( ...params ) {
  6121. const builder = params[ 0 ];
  6122. if ( this._hasStack( builder ) === false && builder.buildStage === 'setup' ) {
  6123. if ( builder.context.nodeLoop || builder.context.nodeBlock ) {
  6124. let addBefore = false;
  6125. if ( this.node.isShaderCallNodeInternal && this.node.shaderNode.getLayout() === null ) {
  6126. if ( builder.fnCall && builder.fnCall.shaderNode ) {
  6127. const shaderNodeData = builder.getDataFromNode( this.node.shaderNode );
  6128. if ( shaderNodeData.hasLoop ) {
  6129. const data = builder.getDataFromNode( this );
  6130. data.forceDeclaration = true;
  6131. addBefore = true;
  6132. }
  6133. }
  6134. }
  6135. const baseStack = builder.getBaseStack();
  6136. if ( addBefore ) {
  6137. baseStack.addToStackBefore( this );
  6138. } else {
  6139. baseStack.addToStack( this );
  6140. }
  6141. }
  6142. }
  6143. if ( this.isIntent( builder ) ) {
  6144. if ( this.isAssign( builder ) !== true ) {
  6145. return this.node.build( ...params );
  6146. }
  6147. }
  6148. return super.build( ...params );
  6149. }
  6150. generate( builder ) {
  6151. const { node, name, readOnly } = this;
  6152. const { renderer } = builder;
  6153. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  6154. let isDeterministic = false;
  6155. let shouldTreatAsReadOnly = false;
  6156. if ( readOnly ) {
  6157. isDeterministic = builder.isDeterministic( node );
  6158. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  6159. }
  6160. const nodeType = this.getNodeType( builder );
  6161. if ( nodeType == 'void' ) {
  6162. if ( this.isIntent( builder ) !== true ) {
  6163. error( 'TSL: ".toVar()" can not be used with void type.', this.stackTrace );
  6164. }
  6165. const snippet = node.build( builder );
  6166. return snippet;
  6167. }
  6168. const vectorType = builder.getVectorType( nodeType );
  6169. const snippet = node.build( builder, vectorType );
  6170. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  6171. const propertyName = builder.getPropertyName( nodeVar );
  6172. let declarationPrefix = propertyName;
  6173. if ( shouldTreatAsReadOnly ) {
  6174. if ( isWebGPUBackend ) {
  6175. declarationPrefix = isDeterministic
  6176. ? `const ${ propertyName }`
  6177. : `let ${ propertyName }`;
  6178. } else {
  6179. const count = node.getArrayCount( builder );
  6180. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  6181. }
  6182. }
  6183. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  6184. return propertyName;
  6185. }
  6186. _hasStack( builder ) {
  6187. const nodeData = builder.getDataFromNode( this );
  6188. return nodeData.stack !== undefined;
  6189. }
  6190. }
  6191. /**
  6192. * TSL function for creating a var node.
  6193. *
  6194. * @tsl
  6195. * @function
  6196. * @param {Node} node - The node for which a variable should be created.
  6197. * @param {?string} name - The name of the variable in the shader.
  6198. * @returns {VarNode}
  6199. */
  6200. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  6201. /**
  6202. * TSL function for creating a var node.
  6203. *
  6204. * @tsl
  6205. * @function
  6206. * @param {Node} node - The node for which a variable should be created.
  6207. * @param {?string} name - The name of the variable in the shader.
  6208. * @returns {VarNode}
  6209. */
  6210. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  6211. /**
  6212. * TSL function for creating a const node.
  6213. *
  6214. * @tsl
  6215. * @function
  6216. * @param {Node} node - The node for which a constant should be created.
  6217. * @param {?string} name - The name of the constant in the shader.
  6218. * @returns {VarNode}
  6219. */
  6220. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  6221. //
  6222. //
  6223. /**
  6224. * TSL function for creating a var intent node.
  6225. *
  6226. * @tsl
  6227. * @function
  6228. * @param {Node} node - The node for which a variable should be created.
  6229. * @param {?string} name - The name of the variable in the shader.
  6230. * @returns {VarNode}
  6231. */
  6232. const VarIntent = ( node ) => {
  6233. return createVar( node ).setIntent( true ).toStack();
  6234. };
  6235. // Method chaining
  6236. addMethodChaining( 'toVar', Var );
  6237. addMethodChaining( 'toConst', Const );
  6238. addMethodChaining( 'toVarIntent', VarIntent );
  6239. /**
  6240. * This node is used to build a sub-build in the node system.
  6241. *
  6242. * @augments Node
  6243. * @param {Node} node - The node to be built in the sub-build.
  6244. * @param {string} name - The name of the sub-build.
  6245. * @param {?string} [nodeType=null] - The type of the node, if known.
  6246. */
  6247. class SubBuildNode extends Node {
  6248. static get type() {
  6249. return 'SubBuild';
  6250. }
  6251. constructor( node, name, nodeType = null ) {
  6252. super( nodeType );
  6253. /**
  6254. * The node to be built in the sub-build.
  6255. *
  6256. * @type {Node}
  6257. */
  6258. this.node = node;
  6259. /**
  6260. * The name of the sub-build.
  6261. *
  6262. * @type {string}
  6263. */
  6264. this.name = name;
  6265. /**
  6266. * This flag can be used for type testing.
  6267. *
  6268. * @type {boolean}
  6269. * @readonly
  6270. * @default true
  6271. */
  6272. this.isSubBuildNode = true;
  6273. }
  6274. generateNodeType( builder ) {
  6275. if ( this.nodeType !== null ) return this.nodeType;
  6276. builder.addSubBuild( this.name );
  6277. const nodeType = this.node.getNodeType( builder );
  6278. builder.removeSubBuild();
  6279. return nodeType;
  6280. }
  6281. build( builder, ...params ) {
  6282. builder.addSubBuild( this.name );
  6283. const data = this.node.build( builder, ...params );
  6284. builder.removeSubBuild();
  6285. return data;
  6286. }
  6287. }
  6288. /**
  6289. * Creates a new sub-build node.
  6290. *
  6291. * @tsl
  6292. * @function
  6293. * @param {Node} node - The node to be built in the sub-build.
  6294. * @param {string} name - The name of the sub-build.
  6295. * @param {?string} [type=null] - The type of the node, if known.
  6296. * @returns {Node} A node object wrapping the SubBuildNode instance.
  6297. */
  6298. const subBuild = ( node, name, type = null ) => new SubBuildNode( nodeObject( node ), name, type );
  6299. /**
  6300. * Class for representing shader varyings as nodes. Varyings are create from
  6301. * existing nodes like the following:
  6302. *
  6303. * ```js
  6304. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  6305. * ```
  6306. *
  6307. * @augments Node
  6308. */
  6309. class VaryingNode extends Node {
  6310. static get type() {
  6311. return 'VaryingNode';
  6312. }
  6313. /**
  6314. * Constructs a new varying node.
  6315. *
  6316. * @param {Node} node - The node for which a varying should be created.
  6317. * @param {?string} name - The name of the varying in the shader.
  6318. */
  6319. constructor( node, name = null ) {
  6320. super();
  6321. /**
  6322. * The node for which a varying should be created.
  6323. *
  6324. * @type {Node}
  6325. */
  6326. this.node = subBuild( node, 'VERTEX' );
  6327. /**
  6328. * The name of the varying in the shader. If no name is defined,
  6329. * the node system auto-generates one.
  6330. *
  6331. * @type {?string}
  6332. * @default null
  6333. */
  6334. this.name = name;
  6335. /**
  6336. * This flag can be used for type testing.
  6337. *
  6338. * @type {boolean}
  6339. * @readonly
  6340. * @default true
  6341. */
  6342. this.isVaryingNode = true;
  6343. /**
  6344. * The interpolation type of the varying data.
  6345. *
  6346. * @type {?string}
  6347. * @default null
  6348. */
  6349. this.interpolationType = null;
  6350. /**
  6351. * The interpolation sampling type of varying data.
  6352. *
  6353. * @type {?string}
  6354. * @default null
  6355. */
  6356. this.interpolationSampling = null;
  6357. /**
  6358. * This flag is used for global cache.
  6359. *
  6360. * @type {boolean}
  6361. * @default true
  6362. */
  6363. this.global = true;
  6364. }
  6365. /**
  6366. * Defines the interpolation type of the varying.
  6367. *
  6368. * @param {string} type - The interpolation type.
  6369. * @param {?string} sampling - The interpolation sampling type
  6370. * @return {VaryingNode} A reference to this node.
  6371. */
  6372. setInterpolation( type, sampling = null ) {
  6373. this.interpolationType = type;
  6374. this.interpolationSampling = sampling;
  6375. return this;
  6376. }
  6377. getHash( builder ) {
  6378. return this.name || super.getHash( builder );
  6379. }
  6380. generateNodeType( builder ) {
  6381. // VaryingNode is auto type
  6382. return this.node.getNodeType( builder );
  6383. }
  6384. /**
  6385. * This method performs the setup of a varying node with the current node builder.
  6386. *
  6387. * @param {NodeBuilder} builder - The current node builder.
  6388. * @return {NodeVarying} The node varying from the node builder.
  6389. */
  6390. setupVarying( builder ) {
  6391. const properties = builder.getNodeProperties( this );
  6392. let varying = properties.varying;
  6393. if ( varying === undefined ) {
  6394. const name = this.name;
  6395. const type = this.getNodeType( builder );
  6396. const interpolationType = this.interpolationType;
  6397. const interpolationSampling = this.interpolationSampling;
  6398. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  6399. properties.node = subBuild( this.node, 'VERTEX' );
  6400. }
  6401. // this property can be used to check if the varying can be optimized for a variable
  6402. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  6403. return varying;
  6404. }
  6405. setup( builder ) {
  6406. this.setupVarying( builder );
  6407. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  6408. }
  6409. analyze( builder ) {
  6410. this.setupVarying( builder );
  6411. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  6412. }
  6413. generate( builder ) {
  6414. const propertyKey = builder.getSubBuildProperty( 'property', builder.currentStack );
  6415. const properties = builder.getNodeProperties( this );
  6416. const varying = this.setupVarying( builder );
  6417. if ( properties[ propertyKey ] === undefined ) {
  6418. const type = this.getNodeType( builder );
  6419. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  6420. // force node run in vertex stage
  6421. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, properties.node, type, propertyName );
  6422. properties[ propertyKey ] = propertyName;
  6423. }
  6424. return builder.getPropertyName( varying );
  6425. }
  6426. }
  6427. /**
  6428. * TSL function for creating a varying node.
  6429. *
  6430. * @tsl
  6431. * @function
  6432. * @param {Node} node - The node for which a varying should be created.
  6433. * @param {?string} name - The name of the varying in the shader.
  6434. * @returns {VaryingNode}
  6435. */
  6436. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  6437. /**
  6438. * Computes a node in the vertex stage.
  6439. *
  6440. * @tsl
  6441. * @function
  6442. * @param {Node} node - The node which should be executed in the vertex stage.
  6443. * @returns {VaryingNode}
  6444. */
  6445. const vertexStage = ( node ) => varying( node );
  6446. addMethodChaining( 'toVarying', varying );
  6447. addMethodChaining( 'toVertexStage', vertexStage );
  6448. /**
  6449. * Converts the given color value from sRGB to linear-sRGB color space.
  6450. *
  6451. * @tsl
  6452. * @function
  6453. * @param {Node<vec3>} color - The sRGB color.
  6454. * @return {Node<vec3>} The linear-sRGB color.
  6455. */
  6456. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6457. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  6458. const b = color.mul( 0.0773993808 );
  6459. const factor = color.lessThanEqual( 0.04045 );
  6460. const rgbResult = mix( a, b, factor );
  6461. return rgbResult;
  6462. } ).setLayout( {
  6463. name: 'sRGBTransferEOTF',
  6464. type: 'vec3',
  6465. inputs: [
  6466. { name: 'color', type: 'vec3' }
  6467. ]
  6468. } );
  6469. /**
  6470. * Converts the given color value from linear-sRGB to sRGB color space.
  6471. *
  6472. * @tsl
  6473. * @function
  6474. * @param {Node<vec3>} color - The linear-sRGB color.
  6475. * @return {Node<vec3>} The sRGB color.
  6476. */
  6477. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6478. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  6479. const b = color.mul( 12.92 );
  6480. const factor = color.lessThanEqual( 0.0031308 );
  6481. const rgbResult = mix( a, b, factor );
  6482. return rgbResult;
  6483. } ).setLayout( {
  6484. name: 'sRGBTransferOETF',
  6485. type: 'vec3',
  6486. inputs: [
  6487. { name: 'color', type: 'vec3' }
  6488. ]
  6489. } );
  6490. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  6491. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  6492. /**
  6493. * This node represents a color space conversion. Meaning it converts
  6494. * a color value from a source to a target color space.
  6495. *
  6496. * @augments TempNode
  6497. */
  6498. class ColorSpaceNode extends TempNode {
  6499. static get type() {
  6500. return 'ColorSpaceNode';
  6501. }
  6502. /**
  6503. * Constructs a new color space node.
  6504. *
  6505. * @param {Node} colorNode - Represents the color to convert.
  6506. * @param {string} source - The source color space.
  6507. * @param {string} target - The target color space.
  6508. */
  6509. constructor( colorNode, source, target ) {
  6510. super( 'vec4' );
  6511. /**
  6512. * Represents the color to convert.
  6513. *
  6514. * @type {Node}
  6515. */
  6516. this.colorNode = colorNode;
  6517. /**
  6518. * The source color space.
  6519. *
  6520. * @type {string}
  6521. */
  6522. this.source = source;
  6523. /**
  6524. * The target color space.
  6525. *
  6526. * @type {string}
  6527. */
  6528. this.target = target;
  6529. }
  6530. /**
  6531. * This method resolves the constants `WORKING_COLOR_SPACE` and
  6532. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  6533. * color management and renderer.
  6534. *
  6535. * @param {NodeBuilder} builder - The current node builder.
  6536. * @param {string} colorSpace - The color space to resolve.
  6537. * @return {string} The resolved color space.
  6538. */
  6539. resolveColorSpace( builder, colorSpace ) {
  6540. if ( colorSpace === WORKING_COLOR_SPACE ) {
  6541. return ColorManagement.workingColorSpace;
  6542. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  6543. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  6544. }
  6545. return colorSpace;
  6546. }
  6547. setup( builder ) {
  6548. const { colorNode } = this;
  6549. const source = this.resolveColorSpace( builder, this.source );
  6550. const target = this.resolveColorSpace( builder, this.target );
  6551. let outputNode = colorNode;
  6552. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  6553. return outputNode;
  6554. }
  6555. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  6556. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  6557. }
  6558. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  6559. outputNode = vec4(
  6560. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  6561. outputNode.a
  6562. );
  6563. }
  6564. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  6565. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  6566. }
  6567. return outputNode;
  6568. }
  6569. }
  6570. /**
  6571. * TSL function for converting a given color node from the current working color space to the given color space.
  6572. *
  6573. * @tsl
  6574. * @function
  6575. * @param {Node} node - Represents the node to convert.
  6576. * @param {string} targetColorSpace - The target color space.
  6577. * @returns {ColorSpaceNode}
  6578. */
  6579. const workingToColorSpace = ( node, targetColorSpace ) => new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace );
  6580. /**
  6581. * TSL function for converting a given color node from the given color space to the current working color space.
  6582. *
  6583. * @tsl
  6584. * @function
  6585. * @param {Node} node - Represents the node to convert.
  6586. * @param {string} sourceColorSpace - The source color space.
  6587. * @returns {ColorSpaceNode}
  6588. */
  6589. const colorSpaceToWorking = ( node, sourceColorSpace ) => new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE );
  6590. /**
  6591. * TSL function for converting a given color node from one color space to another one.
  6592. *
  6593. * @tsl
  6594. * @function
  6595. * @param {Node} node - Represents the node to convert.
  6596. * @param {string} sourceColorSpace - The source color space.
  6597. * @param {string} targetColorSpace - The target color space.
  6598. * @returns {ColorSpaceNode}
  6599. */
  6600. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace );
  6601. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  6602. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  6603. // TODO: Avoid duplicated code and use only ReferenceBaseNode or ReferenceNode
  6604. /**
  6605. * This class is only relevant if the referenced property is array-like.
  6606. * In this case, `ReferenceElementNode` allows to refer to a specific
  6607. * element inside the data structure via an index.
  6608. *
  6609. * @augments ArrayElementNode
  6610. */
  6611. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  6612. static get type() {
  6613. return 'ReferenceElementNode';
  6614. }
  6615. /**
  6616. * Constructs a new reference element node.
  6617. *
  6618. * @param {ReferenceBaseNode} referenceNode - The reference node.
  6619. * @param {Node} indexNode - The index node that defines the element access.
  6620. */
  6621. constructor( referenceNode, indexNode ) {
  6622. super( referenceNode, indexNode );
  6623. /**
  6624. * Similar to {@link ReferenceBaseNode#reference}, an additional
  6625. * property references to the current node.
  6626. *
  6627. * @type {?ReferenceBaseNode}
  6628. * @default null
  6629. */
  6630. this.referenceNode = referenceNode;
  6631. /**
  6632. * This flag can be used for type testing.
  6633. *
  6634. * @type {boolean}
  6635. * @readonly
  6636. * @default true
  6637. */
  6638. this.isReferenceElementNode = true;
  6639. }
  6640. /**
  6641. * This method is overwritten since the node type is inferred from
  6642. * the uniform type of the reference node.
  6643. *
  6644. * @return {string} The node type.
  6645. */
  6646. generateNodeType() {
  6647. return this.referenceNode.uniformType;
  6648. }
  6649. generate( builder ) {
  6650. const snippet = super.generate( builder );
  6651. const arrayType = this.referenceNode.getNodeType();
  6652. const elementType = this.getNodeType();
  6653. return builder.format( snippet, arrayType, elementType );
  6654. }
  6655. };
  6656. /**
  6657. * Base class for nodes which establishes a reference to a property of another object.
  6658. * In this way, the value of the node is automatically linked to the value of
  6659. * referenced object. Reference nodes internally represent the linked value
  6660. * as a uniform.
  6661. *
  6662. * @augments Node
  6663. */
  6664. class ReferenceBaseNode extends Node {
  6665. static get type() {
  6666. return 'ReferenceBaseNode';
  6667. }
  6668. /**
  6669. * Constructs a new reference base node.
  6670. *
  6671. * @param {string} property - The name of the property the node refers to.
  6672. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  6673. * @param {?Object} [object=null] - The object the property belongs to.
  6674. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  6675. */
  6676. constructor( property, uniformType, object = null, count = null ) {
  6677. super();
  6678. /**
  6679. * The name of the property the node refers to.
  6680. *
  6681. * @type {string}
  6682. */
  6683. this.property = property;
  6684. /**
  6685. * The uniform type that should be used to represent the property value.
  6686. *
  6687. * @type {string}
  6688. */
  6689. this.uniformType = uniformType;
  6690. /**
  6691. * The object the property belongs to.
  6692. *
  6693. * @type {?Object}
  6694. * @default null
  6695. */
  6696. this.object = object;
  6697. /**
  6698. * When the linked property is an array, this parameter defines its length.
  6699. *
  6700. * @type {?number}
  6701. * @default null
  6702. */
  6703. this.count = count;
  6704. /**
  6705. * The property name might have dots so nested properties can be referred.
  6706. * The hierarchy of the names is stored inside this array.
  6707. *
  6708. * @type {Array<string>}
  6709. */
  6710. this.properties = property.split( '.' );
  6711. /**
  6712. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  6713. * since the final reference might be updated from calling code.
  6714. *
  6715. * @type {?Object}
  6716. * @default null
  6717. */
  6718. this.reference = object;
  6719. /**
  6720. * The uniform node that holds the value of the reference node.
  6721. *
  6722. * @type {UniformNode}
  6723. * @default null
  6724. */
  6725. this.node = null;
  6726. /**
  6727. * The uniform group of the internal uniform.
  6728. *
  6729. * @type {UniformGroupNode}
  6730. * @default null
  6731. */
  6732. this.group = null;
  6733. /**
  6734. * Overwritten since reference nodes are updated per object.
  6735. *
  6736. * @type {string}
  6737. * @default 'object'
  6738. */
  6739. this.updateType = NodeUpdateType.OBJECT;
  6740. }
  6741. /**
  6742. * Sets the uniform group for this reference node.
  6743. *
  6744. * @param {UniformGroupNode} group - The uniform group to set.
  6745. * @return {ReferenceBaseNode} A reference to this node.
  6746. */
  6747. setGroup( group ) {
  6748. this.group = group;
  6749. return this;
  6750. }
  6751. /**
  6752. * When the referred property is array-like, this method can be used
  6753. * to access elements via an index node.
  6754. *
  6755. * @param {IndexNode} indexNode - indexNode.
  6756. * @return {ReferenceElementNode} A reference to an element.
  6757. */
  6758. element( indexNode ) {
  6759. return new ReferenceElementNode$1( this, nodeObject( indexNode ) );
  6760. }
  6761. /**
  6762. * Sets the node type which automatically defines the internal
  6763. * uniform type.
  6764. *
  6765. * @param {string} uniformType - The type to set.
  6766. */
  6767. setNodeType( uniformType ) {
  6768. const node = uniform( null, uniformType );
  6769. if ( this.group !== null ) {
  6770. node.setGroup( this.group );
  6771. }
  6772. this.node = node;
  6773. }
  6774. /**
  6775. * This method is overwritten since the node type is inferred from
  6776. * the type of the reference node.
  6777. *
  6778. * @param {NodeBuilder} builder - The current node builder.
  6779. * @return {string} The node type.
  6780. */
  6781. generateNodeType( builder ) {
  6782. if ( this.node === null ) {
  6783. this.updateReference( builder );
  6784. this.updateValue();
  6785. }
  6786. return this.node.getNodeType( builder );
  6787. }
  6788. /**
  6789. * Returns the property value from the given referred object.
  6790. *
  6791. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  6792. * @return {any} The value.
  6793. */
  6794. getValueFromReference( object = this.reference ) {
  6795. const { properties } = this;
  6796. let value = object[ properties[ 0 ] ];
  6797. for ( let i = 1; i < properties.length; i ++ ) {
  6798. value = value[ properties[ i ] ];
  6799. }
  6800. return value;
  6801. }
  6802. /**
  6803. * Allows to update the reference based on the given state. The state is only
  6804. * evaluated {@link ReferenceBaseNode#object} is not set.
  6805. *
  6806. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6807. * @return {Object} The updated reference.
  6808. */
  6809. updateReference( state ) {
  6810. this.reference = this.object !== null ? this.object : state.object;
  6811. return this.reference;
  6812. }
  6813. /**
  6814. * The output of the reference node is the internal uniform node.
  6815. *
  6816. * @return {UniformNode} The output node.
  6817. */
  6818. setup() {
  6819. this.updateValue();
  6820. return this.node;
  6821. }
  6822. /**
  6823. * Overwritten to update the internal uniform value.
  6824. *
  6825. * @param {NodeFrame} frame - A reference to the current node frame.
  6826. */
  6827. update( /*frame*/ ) {
  6828. this.updateValue();
  6829. }
  6830. /**
  6831. * Retrieves the value from the referred object property and uses it
  6832. * to updated the internal uniform.
  6833. */
  6834. updateValue() {
  6835. if ( this.node === null ) this.setNodeType( this.uniformType );
  6836. const value = this.getValueFromReference();
  6837. if ( Array.isArray( value ) ) {
  6838. this.node.array = value;
  6839. } else {
  6840. this.node.value = value;
  6841. }
  6842. }
  6843. }
  6844. /**
  6845. * TSL function for creating a reference base node.
  6846. *
  6847. * @tsl
  6848. * @function
  6849. * @param {string} name - The name of the property the node refers to.
  6850. * @param {string} type - The uniform type that should be used to represent the property value.
  6851. * @param {Object} object - The object the property belongs to.
  6852. * @returns {ReferenceBaseNode}
  6853. */
  6854. const reference$1 = ( name, type, object ) => new ReferenceBaseNode( name, type, object );
  6855. /**
  6856. * This node is a special type of reference node which is intended
  6857. * for linking renderer properties with node values.
  6858. * ```js
  6859. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  6860. * ```
  6861. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  6862. * automatically be updated.
  6863. *
  6864. * @augments ReferenceBaseNode
  6865. */
  6866. class RendererReferenceNode extends ReferenceBaseNode {
  6867. static get type() {
  6868. return 'RendererReferenceNode';
  6869. }
  6870. /**
  6871. * Constructs a new renderer reference node.
  6872. *
  6873. * @param {string} property - The name of the property the node refers to.
  6874. * @param {string} inputType - The uniform type that should be used to represent the property value.
  6875. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6876. * the node refers to the renderer of the current state.
  6877. */
  6878. constructor( property, inputType, renderer = null ) {
  6879. super( property, inputType, renderer );
  6880. /**
  6881. * The renderer the property belongs to. When no renderer is set,
  6882. * the node refers to the renderer of the current state.
  6883. *
  6884. * @type {?Renderer}
  6885. * @default null
  6886. */
  6887. this.renderer = renderer;
  6888. this.setGroup( renderGroup );
  6889. }
  6890. /**
  6891. * Updates the reference based on the given state. The state is only evaluated
  6892. * {@link RendererReferenceNode#renderer} is not set.
  6893. *
  6894. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6895. * @return {Object} The updated reference.
  6896. */
  6897. updateReference( state ) {
  6898. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  6899. return this.reference;
  6900. }
  6901. }
  6902. /**
  6903. * TSL function for creating a renderer reference node.
  6904. *
  6905. * @tsl
  6906. * @function
  6907. * @param {string} name - The name of the property the node refers to.
  6908. * @param {string} type - The uniform type that should be used to represent the property value.
  6909. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6910. * the node refers to the renderer of the current state.
  6911. * @returns {RendererReferenceNode}
  6912. */
  6913. const rendererReference = ( name, type, renderer = null ) => new RendererReferenceNode( name, type, renderer );
  6914. /**
  6915. * This node represents a tone mapping operation.
  6916. *
  6917. * @augments TempNode
  6918. */
  6919. class ToneMappingNode extends TempNode {
  6920. static get type() {
  6921. return 'ToneMappingNode';
  6922. }
  6923. /**
  6924. * Constructs a new tone mapping node.
  6925. *
  6926. * @param {number} toneMapping - The tone mapping type.
  6927. * @param {Node} exposureNode - The tone mapping exposure.
  6928. * @param {Node} [colorNode=null] - The color node to process.
  6929. */
  6930. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  6931. super( 'vec3' );
  6932. /**
  6933. * The tone mapping type.
  6934. *
  6935. * @private
  6936. * @type {number}
  6937. */
  6938. this._toneMapping = toneMapping;
  6939. /**
  6940. * The tone mapping exposure.
  6941. *
  6942. * @type {Node}
  6943. * @default null
  6944. */
  6945. this.exposureNode = exposureNode;
  6946. /**
  6947. * Represents the color to process.
  6948. *
  6949. * @type {?Node}
  6950. * @default null
  6951. */
  6952. this.colorNode = colorNode;
  6953. }
  6954. /**
  6955. * Overwrites the default `customCacheKey()` implementation by including the tone
  6956. * mapping type into the cache key.
  6957. *
  6958. * @return {number} The hash.
  6959. */
  6960. customCacheKey() {
  6961. return hash$1( this._toneMapping );
  6962. }
  6963. /**
  6964. * Sets the tone mapping type.
  6965. *
  6966. * @param {number} value - The tone mapping type.
  6967. * @return {ToneMappingNode} A reference to this node.
  6968. */
  6969. setToneMapping( value ) {
  6970. this._toneMapping = value;
  6971. return this;
  6972. }
  6973. /**
  6974. * Gets the tone mapping type.
  6975. *
  6976. * @returns {number} The tone mapping type.
  6977. */
  6978. getToneMapping() {
  6979. return this._toneMapping;
  6980. }
  6981. setup( builder ) {
  6982. const colorNode = this.colorNode || builder.context.color;
  6983. const toneMapping = this._toneMapping;
  6984. if ( toneMapping === NoToneMapping ) return colorNode;
  6985. let outputNode = null;
  6986. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  6987. if ( toneMappingFn !== null ) {
  6988. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  6989. } else {
  6990. error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  6991. outputNode = colorNode;
  6992. }
  6993. return outputNode;
  6994. }
  6995. }
  6996. /**
  6997. * TSL function for creating a tone mapping node.
  6998. *
  6999. * @tsl
  7000. * @function
  7001. * @param {number} mapping - The tone mapping type.
  7002. * @param {Node<float> | number} exposure - The tone mapping exposure.
  7003. * @param {Node<vec3> | Color} color - The color node to process.
  7004. * @returns {ToneMappingNode<vec3>}
  7005. */
  7006. const toneMapping = ( mapping, exposure, color ) => new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) );
  7007. /**
  7008. * TSL object that represents the global tone mapping exposure of the renderer.
  7009. *
  7010. * @tsl
  7011. * @type {RendererReferenceNode<vec3>}
  7012. */
  7013. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  7014. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  7015. /**
  7016. * Internal buffer attribute library.
  7017. *
  7018. * @private
  7019. * @type {WeakMap<TypedArray, InterleavedBuffer>}
  7020. */
  7021. const _bufferLib = new WeakMap();
  7022. /**
  7023. * Internal method for retrieving or creating interleaved buffers.
  7024. *
  7025. * @private
  7026. * @param {TypedArray} value - The attribute data.
  7027. * @param {number} itemSize - The attribute item size.
  7028. * @returns {InterleavedBuffer} The interleaved buffer.
  7029. */
  7030. function _getBufferAttribute( value, itemSize ) {
  7031. let buffer = _bufferLib.get( value );
  7032. if ( buffer === undefined ) {
  7033. buffer = new InterleavedBuffer( value, itemSize );
  7034. _bufferLib.set( value, buffer );
  7035. }
  7036. return buffer;
  7037. }
  7038. /**
  7039. * In earlier `three.js` versions it was only possible to define attribute data
  7040. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  7041. * on the node level.
  7042. * ```js
  7043. * const geometry = new THREE.PlaneGeometry();
  7044. * const positionAttribute = geometry.getAttribute( 'position' );
  7045. *
  7046. * const colors = [];
  7047. * for ( let i = 0; i < position.count; i ++ ) {
  7048. * colors.push( 1, 0, 0 );
  7049. * }
  7050. *
  7051. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  7052. * ```
  7053. * This new approach is especially interesting when geometry data are generated via
  7054. * compute shaders. The below line converts a storage buffer into an attribute node.
  7055. * ```js
  7056. * material.positionNode = positionBuffer.toAttribute();
  7057. * ```
  7058. * @augments InputNode
  7059. */
  7060. class BufferAttributeNode extends InputNode {
  7061. static get type() {
  7062. return 'BufferAttributeNode';
  7063. }
  7064. /**
  7065. * Constructs a new buffer attribute node.
  7066. *
  7067. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  7068. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  7069. * @param {number} [bufferStride=0] - The buffer stride.
  7070. * @param {number} [bufferOffset=0] - The buffer offset.
  7071. */
  7072. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  7073. super( value, bufferType );
  7074. /**
  7075. * This flag can be used for type testing.
  7076. *
  7077. * @type {boolean}
  7078. * @readonly
  7079. * @default true
  7080. */
  7081. this.isBufferNode = true;
  7082. /**
  7083. * The buffer type (e.g. `'vec3'`).
  7084. *
  7085. * @type {?string}
  7086. * @default null
  7087. */
  7088. this.bufferType = bufferType;
  7089. /**
  7090. * The buffer stride.
  7091. *
  7092. * @type {number}
  7093. * @default 0
  7094. */
  7095. this.bufferStride = bufferStride;
  7096. /**
  7097. * The buffer offset.
  7098. *
  7099. * @type {number}
  7100. * @default 0
  7101. */
  7102. this.bufferOffset = bufferOffset;
  7103. /**
  7104. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  7105. * if you are planning to update the attribute data per frame.
  7106. *
  7107. * @type {number}
  7108. * @default StaticDrawUsage
  7109. */
  7110. this.usage = StaticDrawUsage;
  7111. /**
  7112. * Whether the attribute is instanced or not.
  7113. *
  7114. * @type {boolean}
  7115. * @default false
  7116. */
  7117. this.instanced = false;
  7118. /**
  7119. * A reference to the buffer attribute.
  7120. *
  7121. * @type {?BufferAttribute}
  7122. * @default null
  7123. */
  7124. this.attribute = null;
  7125. /**
  7126. * `BufferAttributeNode` sets this property to `true` by default.
  7127. *
  7128. * @type {boolean}
  7129. * @default true
  7130. */
  7131. this.global = true;
  7132. if ( value && value.isBufferAttribute === true && value.itemSize <= 4 ) {
  7133. this.attribute = value;
  7134. this.usage = value.usage;
  7135. this.instanced = value.isInstancedBufferAttribute;
  7136. }
  7137. }
  7138. /**
  7139. * This method is overwritten since the attribute data might be shared
  7140. * and thus the hash should be shared as well.
  7141. *
  7142. * @param {NodeBuilder} builder - The current node builder.
  7143. * @return {string} The hash.
  7144. */
  7145. getHash( builder ) {
  7146. let id;
  7147. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  7148. let bufferData = builder.globalCache.getData( this.value );
  7149. if ( bufferData === undefined ) {
  7150. bufferData = {
  7151. node: this
  7152. };
  7153. builder.globalCache.setData( this.value, bufferData );
  7154. }
  7155. id = bufferData.node.id;
  7156. } else {
  7157. id = this.id;
  7158. }
  7159. return String( id );
  7160. }
  7161. /**
  7162. * This method is overwritten since the node type is inferred from
  7163. * the buffer attribute.
  7164. *
  7165. * @param {NodeBuilder} builder - The current node builder.
  7166. * @return {string} The node type.
  7167. */
  7168. generateNodeType( builder ) {
  7169. if ( this.bufferType === null ) {
  7170. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  7171. }
  7172. return this.bufferType;
  7173. }
  7174. /**
  7175. * Depending on which value was passed to the node, `setup()` behaves
  7176. * differently. If no instance of `BufferAttribute` was passed, the method
  7177. * creates an internal attribute and configures it respectively.
  7178. *
  7179. * @param {NodeBuilder} builder - The current node builder.
  7180. */
  7181. setup( builder ) {
  7182. if ( this.attribute !== null ) return;
  7183. //
  7184. const type = this.getNodeType( builder );
  7185. const itemSize = builder.getTypeLength( type );
  7186. const value = this.value;
  7187. const stride = this.bufferStride || itemSize;
  7188. const offset = this.bufferOffset;
  7189. let buffer;
  7190. if ( value.isInterleavedBuffer === true ) {
  7191. buffer = value;
  7192. } else if ( value.isBufferAttribute === true ) {
  7193. buffer = _getBufferAttribute( value.array, stride );
  7194. } else {
  7195. buffer = _getBufferAttribute( value, stride );
  7196. }
  7197. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  7198. buffer.setUsage( this.usage );
  7199. this.attribute = bufferAttribute;
  7200. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  7201. }
  7202. /**
  7203. * Generates the code snippet of the buffer attribute node.
  7204. *
  7205. * @param {NodeBuilder} builder - The current node builder.
  7206. * @return {string} The generated code snippet.
  7207. */
  7208. generate( builder ) {
  7209. const nodeType = this.getNodeType( builder );
  7210. const nodeName = builder.context.nodeName;
  7211. if ( nodeName !== undefined ) delete builder.context.nodeName; // deleting when consumed
  7212. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType, nodeName );
  7213. const propertyName = builder.getPropertyName( nodeAttribute );
  7214. let output = null;
  7215. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  7216. this.name = propertyName;
  7217. output = propertyName;
  7218. } else {
  7219. let varyingName;
  7220. if ( nodeName ) {
  7221. varyingName = nodeName + 'Varying';
  7222. }
  7223. const nodeVarying = varying( this, varyingName );
  7224. output = nodeVarying.build( builder, nodeType );
  7225. }
  7226. return output;
  7227. }
  7228. /**
  7229. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  7230. *
  7231. * @param {NodeBuilder} builder - The current node builder.
  7232. * @return {string} The input type.
  7233. */
  7234. getInputType( /*builder*/ ) {
  7235. return 'bufferAttribute';
  7236. }
  7237. /**
  7238. * Sets the `usage` property to the given value.
  7239. *
  7240. * @param {number} value - The usage to set.
  7241. * @return {BufferAttributeNode} A reference to this node.
  7242. */
  7243. setUsage( value ) {
  7244. this.usage = value;
  7245. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  7246. this.attribute.usage = value;
  7247. }
  7248. return this;
  7249. }
  7250. /**
  7251. * Sets the `instanced` property to the given value.
  7252. *
  7253. * @param {boolean} value - The value to set.
  7254. * @return {BufferAttributeNode} A reference to this node.
  7255. */
  7256. setInstanced( value ) {
  7257. this.instanced = value;
  7258. return this;
  7259. }
  7260. }
  7261. /**
  7262. * Internal method for creating buffer attribute nodes.
  7263. *
  7264. * @private
  7265. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7266. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7267. * @param {number} [stride=0] - The buffer stride.
  7268. * @param {number} [offset=0] - The buffer offset.
  7269. * @param {number} [usage=StaticDrawUsage] - The buffer usage.
  7270. * @param {boolean} [instanced=false] - Whether the buffer is instanced.
  7271. * @returns {BufferAttributeNode|Node} The buffer attribute node.
  7272. */
  7273. function createBufferAttribute( array, type = null, stride = 0, offset = 0, usage = StaticDrawUsage, instanced = false ) {
  7274. if ( type === 'mat3' || ( type === null && array.itemSize === 9 ) ) {
  7275. return mat3(
  7276. new BufferAttributeNode( array, 'vec3', 9, 0 ).setUsage( usage ).setInstanced( instanced ),
  7277. new BufferAttributeNode( array, 'vec3', 9, 3 ).setUsage( usage ).setInstanced( instanced ),
  7278. new BufferAttributeNode( array, 'vec3', 9, 6 ).setUsage( usage ).setInstanced( instanced )
  7279. );
  7280. } else if ( type === 'mat4' || ( type === null && array.itemSize === 16 ) ) {
  7281. return mat4(
  7282. new BufferAttributeNode( array, 'vec4', 16, 0 ).setUsage( usage ).setInstanced( instanced ),
  7283. new BufferAttributeNode( array, 'vec4', 16, 4 ).setUsage( usage ).setInstanced( instanced ),
  7284. new BufferAttributeNode( array, 'vec4', 16, 8 ).setUsage( usage ).setInstanced( instanced ),
  7285. new BufferAttributeNode( array, 'vec4', 16, 12 ).setUsage( usage ).setInstanced( instanced )
  7286. );
  7287. }
  7288. return new BufferAttributeNode( array, type, stride, offset ).setUsage( usage );
  7289. }
  7290. /**
  7291. * TSL function for creating a buffer attribute node.
  7292. *
  7293. * @tsl
  7294. * @function
  7295. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7296. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7297. * @param {number} [stride=0] - The buffer stride.
  7298. * @param {number} [offset=0] - The buffer offset.
  7299. * @returns {BufferAttributeNode|Node}
  7300. */
  7301. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset );
  7302. /**
  7303. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  7304. * Use this function if attribute data are updated per frame.
  7305. *
  7306. * @tsl
  7307. * @function
  7308. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7309. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7310. * @param {number} [stride=0] - The buffer stride.
  7311. * @param {number} [offset=0] - The buffer offset.
  7312. * @returns {BufferAttributeNode|Node}
  7313. */
  7314. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, DynamicDrawUsage );
  7315. /**
  7316. * TSL function for creating a buffer attribute node but with enabled instancing
  7317. *
  7318. * @tsl
  7319. * @function
  7320. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7321. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7322. * @param {number} [stride=0] - The buffer stride.
  7323. * @param {number} [offset=0] - The buffer offset.
  7324. * @returns {BufferAttributeNode|Node}
  7325. */
  7326. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, StaticDrawUsage, true );
  7327. /**
  7328. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  7329. *
  7330. * @tsl
  7331. * @function
  7332. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7333. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7334. * @param {number} [stride=0] - The buffer stride.
  7335. * @param {number} [offset=0] - The buffer offset.
  7336. * @returns {BufferAttributeNode|Node}
  7337. */
  7338. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, DynamicDrawUsage, true );
  7339. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  7340. /**
  7341. * This class represents shader indices of different types. The following predefined node
  7342. * objects cover frequent use cases:
  7343. *
  7344. * - `vertexIndex`: The index of a vertex within a mesh.
  7345. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  7346. * - `drawIndex`: The index of a draw call.
  7347. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  7348. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  7349. * - `subgroupIndex`: The index of a compute invocation's subgroup within its workgroup.
  7350. *
  7351. * @augments Node
  7352. */
  7353. class IndexNode extends Node {
  7354. static get type() {
  7355. return 'IndexNode';
  7356. }
  7357. /**
  7358. * Constructs a new index node.
  7359. *
  7360. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationGlobal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  7361. */
  7362. constructor( scope ) {
  7363. super( 'uint' );
  7364. /**
  7365. * The scope of the index node.
  7366. *
  7367. * @type {string}
  7368. */
  7369. this.scope = scope;
  7370. /**
  7371. * This flag can be used for type testing.
  7372. *
  7373. * @type {boolean}
  7374. * @readonly
  7375. * @default true
  7376. */
  7377. this.isIndexNode = true;
  7378. }
  7379. generate( builder ) {
  7380. const nodeType = this.getNodeType( builder );
  7381. const scope = this.scope;
  7382. let propertyName;
  7383. if ( scope === IndexNode.VERTEX ) {
  7384. propertyName = builder.getVertexIndex();
  7385. } else if ( scope === IndexNode.INSTANCE ) {
  7386. propertyName = builder.getInstanceIndex();
  7387. } else if ( scope === IndexNode.DRAW ) {
  7388. propertyName = builder.getDrawIndex();
  7389. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  7390. propertyName = builder.getInvocationLocalIndex();
  7391. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  7392. propertyName = builder.getInvocationSubgroupIndex();
  7393. } else if ( scope === IndexNode.SUBGROUP ) {
  7394. propertyName = builder.getSubgroupIndex();
  7395. } else {
  7396. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  7397. }
  7398. let output;
  7399. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  7400. output = propertyName;
  7401. } else {
  7402. const nodeVarying = varying( this );
  7403. output = nodeVarying.build( builder, nodeType );
  7404. }
  7405. return output;
  7406. }
  7407. }
  7408. IndexNode.VERTEX = 'vertex';
  7409. IndexNode.INSTANCE = 'instance';
  7410. IndexNode.SUBGROUP = 'subgroup';
  7411. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  7412. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  7413. IndexNode.DRAW = 'draw';
  7414. /**
  7415. * TSL object that represents the index of a vertex within a mesh.
  7416. *
  7417. * @tsl
  7418. * @type {IndexNode}
  7419. */
  7420. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  7421. /**
  7422. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  7423. *
  7424. * @tsl
  7425. * @type {IndexNode}
  7426. */
  7427. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  7428. /**
  7429. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  7430. *
  7431. * @tsl
  7432. * @type {IndexNode}
  7433. */
  7434. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  7435. /**
  7436. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  7437. *
  7438. * @tsl
  7439. * @type {IndexNode}
  7440. */
  7441. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  7442. /**
  7443. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  7444. *
  7445. * @tsl
  7446. * @type {IndexNode}
  7447. */
  7448. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  7449. /**
  7450. * TSL object that represents the index of a draw call.
  7451. *
  7452. * @tsl
  7453. * @type {IndexNode}
  7454. */
  7455. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  7456. /**
  7457. * Represents a compute shader node.
  7458. *
  7459. * @augments Node
  7460. */
  7461. class ComputeNode extends Node {
  7462. static get type() {
  7463. return 'ComputeNode';
  7464. }
  7465. /**
  7466. * Constructs a new compute node.
  7467. *
  7468. * @param {Node} computeNode - The node that defines the compute shader logic.
  7469. * @param {Array<number>} workgroupSize - An array defining the X, Y, and Z dimensions of the workgroup for compute shader execution.
  7470. */
  7471. constructor( computeNode, workgroupSize ) {
  7472. super( 'void' );
  7473. /**
  7474. * This flag can be used for type testing.
  7475. *
  7476. * @type {boolean}
  7477. * @readonly
  7478. * @default true
  7479. */
  7480. this.isComputeNode = true;
  7481. /**
  7482. * The node that defines the compute shader logic.
  7483. *
  7484. * @type {Node}
  7485. */
  7486. this.computeNode = computeNode;
  7487. /**
  7488. * An array defining the X, Y, and Z dimensions of the workgroup for compute shader execution.
  7489. *
  7490. * @type {Array<number>}
  7491. * @default [ 64 ]
  7492. */
  7493. this.workgroupSize = workgroupSize;
  7494. /**
  7495. * The total number of threads (invocations) to execute. If it is a number, it will be used
  7496. * to automatically generate bounds checking against `instanceIndex`.
  7497. *
  7498. * @type {number|Array<number>}
  7499. */
  7500. this.count = null;
  7501. /**
  7502. * The dispatch size for workgroups on X, Y, and Z axes.
  7503. * Used directly if `count` is not provided.
  7504. *
  7505. * @type {number|Array<number>}
  7506. */
  7507. this.dispatchSize = null;
  7508. /**
  7509. * The version of the node.
  7510. *
  7511. * @type {number}
  7512. */
  7513. this.version = 1;
  7514. /**
  7515. * The name or label of the uniform.
  7516. *
  7517. * @type {string}
  7518. * @default ''
  7519. */
  7520. this.name = '';
  7521. /**
  7522. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  7523. * is executed once per object by default.
  7524. *
  7525. * @type {string}
  7526. * @default 'object'
  7527. */
  7528. this.updateBeforeType = NodeUpdateType.OBJECT;
  7529. /**
  7530. * A callback executed when the compute node finishes initialization.
  7531. *
  7532. * @type {?Function}
  7533. */
  7534. this.onInitFunction = null;
  7535. /**
  7536. * A uniform node holding the dispatch count for bounds checking.
  7537. * Created automatically when `count` is a number.
  7538. *
  7539. * @type {?UniformNode}
  7540. */
  7541. this.countNode = null;
  7542. }
  7543. /**
  7544. * Executes the `dispose` event for this node.
  7545. */
  7546. dispose() {
  7547. this.dispatchEvent( { type: 'dispose' } );
  7548. }
  7549. /**
  7550. * Sets the {@link ComputeNode#name} property.
  7551. *
  7552. * @param {string} name - The name of the uniform.
  7553. * @return {ComputeNode} A reference to this node.
  7554. */
  7555. setName( name ) {
  7556. this.name = name;
  7557. return this;
  7558. }
  7559. /**
  7560. * Sets the {@link ComputeNode#name} property.
  7561. *
  7562. * @deprecated
  7563. * @param {string} name - The name of the uniform.
  7564. * @return {ComputeNode} A reference to this node.
  7565. */
  7566. label( name ) {
  7567. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.', new StackTrace() ); // @deprecated r179
  7568. return this.setName( name );
  7569. }
  7570. /**
  7571. * Sets the callback to run during initialization.
  7572. *
  7573. * @param {Function} callback - The callback function.
  7574. * @return {ComputeNode} A reference to this node.
  7575. */
  7576. onInit( callback ) {
  7577. this.onInitFunction = callback;
  7578. return this;
  7579. }
  7580. /**
  7581. * The method execute the compute for this node.
  7582. *
  7583. * @param {NodeFrame} frame - A reference to the current node frame.
  7584. */
  7585. updateBefore( { renderer } ) {
  7586. renderer.compute( this );
  7587. }
  7588. setup( builder ) {
  7589. if ( this.count !== null && this.countNode === null ) {
  7590. this.countNode = uniform( this.count, 'uint' ).onObjectUpdate( () => this.count );
  7591. }
  7592. const result = this.computeNode.build( builder );
  7593. if ( result ) {
  7594. const properties = builder.getNodeProperties( this );
  7595. properties.outputComputeNode = result.outputNode;
  7596. result.outputNode = null;
  7597. }
  7598. return result;
  7599. }
  7600. generate( builder, output ) {
  7601. const { shaderStage } = builder;
  7602. if ( shaderStage === 'compute' ) {
  7603. const snippet = this.computeNode.build( builder, 'void' );
  7604. if ( snippet !== '' ) {
  7605. builder.addLineFlowCode( snippet, this );
  7606. }
  7607. if ( this.count !== null && builder.allowEarlyReturns === true ) {
  7608. const countSnippet = this.countNode.build( builder, 'uint' );
  7609. const indexSnippet = instanceIndex.build( builder, 'uint' );
  7610. builder.flow.code = `${ builder.tab }if ( ${ indexSnippet } >= ${ countSnippet } ) { return; }\n\n${ builder.flow.code }`;
  7611. }
  7612. } else {
  7613. const properties = builder.getNodeProperties( this );
  7614. const outputComputeNode = properties.outputComputeNode;
  7615. if ( outputComputeNode ) {
  7616. return outputComputeNode.build( builder, output );
  7617. }
  7618. }
  7619. }
  7620. }
  7621. /**
  7622. * TSL function for creating a compute kernel node.
  7623. *
  7624. * @tsl
  7625. * @function
  7626. * @param {Node} node - The TSL logic for the compute shader.
  7627. * @param {Array<number>} [workgroupSize=[64]] - The workgroup size.
  7628. * @returns {ComputeNode}
  7629. */
  7630. const computeKernel = ( node, workgroupSize = [ 64 ] ) => {
  7631. if ( workgroupSize.length === 0 || workgroupSize.length > 3 ) {
  7632. error( 'TSL: compute() workgroupSize must have 1, 2, or 3 elements', new StackTrace() );
  7633. }
  7634. for ( let i = 0; i < workgroupSize.length; i ++ ) {
  7635. const val = workgroupSize[ i ];
  7636. if ( typeof val !== 'number' || val <= 0 || ! Number.isInteger( val ) ) {
  7637. error( `TSL: compute() workgroupSize element at index [ ${ i } ] must be a positive integer`, new StackTrace() );
  7638. }
  7639. }
  7640. // Implicit fill-up to [ x, y, z ] with 1s, just like WGSL treats @workgroup_size when fewer dimensions are specified
  7641. while ( workgroupSize.length < 3 ) workgroupSize.push( 1 );
  7642. //
  7643. return new ComputeNode( nodeObject( node ), workgroupSize );
  7644. };
  7645. /**
  7646. * TSL function for creating a compute node.
  7647. *
  7648. * @tsl
  7649. * @function
  7650. * @param {Node} node - The TSL logic for the compute shader.
  7651. * @param {number|Array<number>} count - The compute count or dispatch size.
  7652. * @param {Array<number>} [workgroupSize=[64]] - The workgroup size.
  7653. * @returns {ComputeNode}
  7654. , */
  7655. const compute = ( node, count, workgroupSize ) => {
  7656. const computeNode = computeKernel( node, workgroupSize );
  7657. if ( typeof count === 'number' ) {
  7658. computeNode.count = count;
  7659. } else {
  7660. computeNode.dispatchSize = count;
  7661. }
  7662. return computeNode;
  7663. };
  7664. addMethodChaining( 'compute', compute );
  7665. addMethodChaining( 'computeKernel', computeKernel );
  7666. /**
  7667. * This node can be used as a cache management component for another node.
  7668. * Caching is in general used by default in {@link NodeBuilder} but this node
  7669. * allows the usage of a shared parent cache during the build process.
  7670. *
  7671. * @augments Node
  7672. */
  7673. class IsolateNode extends Node {
  7674. static get type() {
  7675. return 'IsolateNode';
  7676. }
  7677. /**
  7678. * Constructs a new cache node.
  7679. *
  7680. * @param {Node} node - The node that should be cached.
  7681. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7682. */
  7683. constructor( node, parent = true ) {
  7684. super();
  7685. /**
  7686. * The node that should be cached.
  7687. *
  7688. * @type {Node}
  7689. */
  7690. this.node = node;
  7691. /**
  7692. * Whether this node refers to a shared parent cache or not.
  7693. *
  7694. * @type {boolean}
  7695. * @default true
  7696. */
  7697. this.parent = parent;
  7698. /**
  7699. * This flag can be used for type testing.
  7700. *
  7701. * @type {boolean}
  7702. * @readonly
  7703. * @default true
  7704. */
  7705. this.isIsolateNode = true;
  7706. }
  7707. generateNodeType( builder ) {
  7708. const previousCache = builder.getCache();
  7709. const cache = builder.getCacheFromNode( this, this.parent );
  7710. builder.setCache( cache );
  7711. const nodeType = this.node.getNodeType( builder );
  7712. builder.setCache( previousCache );
  7713. return nodeType;
  7714. }
  7715. build( builder, ...params ) {
  7716. const previousCache = builder.getCache();
  7717. const cache = builder.getCacheFromNode( this, this.parent );
  7718. builder.setCache( cache );
  7719. const data = this.node.build( builder, ...params );
  7720. builder.setCache( previousCache );
  7721. return data;
  7722. }
  7723. setParent( parent ) {
  7724. this.parent = parent;
  7725. return this;
  7726. }
  7727. getParent() {
  7728. return this.parent;
  7729. }
  7730. }
  7731. /**
  7732. * TSL function for creating a cache node.
  7733. *
  7734. * @tsl
  7735. * @function
  7736. * @param {Node} node - The node that should be cached.
  7737. * @returns {IsolateNode}
  7738. */
  7739. const isolate = ( node ) => new IsolateNode( nodeObject( node ) );
  7740. /**
  7741. * TSL function for creating a cache node.
  7742. *
  7743. * @tsl
  7744. * @function
  7745. * @deprecated
  7746. * @param {Node} node - The node that should be cached.
  7747. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7748. * @returns {IsolateNode}
  7749. */
  7750. function cache( node, parent = true ) {
  7751. warn( 'TSL: "cache()" has been deprecated. Use "isolate()" instead.' ); // @deprecated r181
  7752. return isolate( node ).setParent( parent );
  7753. }
  7754. addMethodChaining( 'cache', cache );
  7755. addMethodChaining( 'isolate', isolate );
  7756. /**
  7757. * The class generates the code of a given node but returns another node in the output.
  7758. * This can be used to call a method or node that does not return a value, i.e.
  7759. * type `void` on an input where returning a value is required. Example:
  7760. *
  7761. * ```js
  7762. * material.colorNode = myColor.bypass( runVoidFn() )
  7763. *```
  7764. *
  7765. * @augments Node
  7766. */
  7767. class BypassNode extends Node {
  7768. static get type() {
  7769. return 'BypassNode';
  7770. }
  7771. /**
  7772. * Constructs a new bypass node.
  7773. *
  7774. * @param {Node} outputNode - The output node.
  7775. * @param {Node} callNode - The call node.
  7776. */
  7777. constructor( outputNode, callNode ) {
  7778. super();
  7779. /**
  7780. * This flag can be used for type testing.
  7781. *
  7782. * @type {boolean}
  7783. * @readonly
  7784. * @default true
  7785. */
  7786. this.isBypassNode = true;
  7787. /**
  7788. * The output node.
  7789. *
  7790. * @type {Node}
  7791. */
  7792. this.outputNode = outputNode;
  7793. /**
  7794. * The call node.
  7795. *
  7796. * @type {Node}
  7797. */
  7798. this.callNode = callNode;
  7799. }
  7800. generateNodeType( builder ) {
  7801. return this.outputNode.getNodeType( builder );
  7802. }
  7803. generate( builder ) {
  7804. const snippet = this.callNode.build( builder, 'void' );
  7805. if ( snippet !== '' ) {
  7806. builder.addLineFlowCode( snippet, this );
  7807. }
  7808. return this.outputNode.build( builder );
  7809. }
  7810. }
  7811. /**
  7812. * TSL function for creating a bypass node.
  7813. *
  7814. * @tsl
  7815. * @function
  7816. * @param {Node} outputNode - The output node.
  7817. * @param {Node} callNode - The call node.
  7818. * @returns {BypassNode}
  7819. */
  7820. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  7821. addMethodChaining( 'bypass', bypass );
  7822. /**
  7823. * This node allows to remap a node value from one range into another. E.g a value of
  7824. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  7825. * `remap` takes care of that and converts the original value of `0.4` to `0.5`.
  7826. *
  7827. * @tsl
  7828. * @function
  7829. * @param {Node} node - The node that should be remapped.
  7830. * @param {Node} inLowNode - The source or current lower bound of the range.
  7831. * @param {Node} inHighNode - The source or current upper bound of the range.
  7832. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7833. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7834. * @returns {Node}
  7835. */
  7836. const remap = /*@__PURE__*/ Fn( ( [ node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ), doClamp = bool( false ) ] ) => {
  7837. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  7838. if ( defined( doClamp ) ) t = t.clamp();
  7839. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  7840. } );
  7841. /**
  7842. * This node allows to remap a node value from one range into another but with enabled clamping. E.g a value of
  7843. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  7844. * `remapClamp` takes care of that and converts the original value of `0.4` to `0.5`.
  7845. *
  7846. * @tsl
  7847. * @function
  7848. * @param {Node} node - The node that should be remapped.
  7849. * @param {Node} inLowNode - The source or current lower bound of the range.
  7850. * @param {Node} inHighNode - The source or current upper bound of the range.
  7851. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7852. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7853. * @returns {Node}
  7854. */
  7855. function remapClamp( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  7856. return remap( node, inLowNode, inHighNode, outLowNode, outHighNode, true );
  7857. }
  7858. addMethodChaining( 'remap', remap );
  7859. addMethodChaining( 'remapClamp', remapClamp );
  7860. /**
  7861. * This class can be used to implement basic expressions in shader code.
  7862. * Basic examples for that are `return`, `continue` or `discard` statements.
  7863. *
  7864. * @augments Node
  7865. */
  7866. class ExpressionNode extends Node {
  7867. static get type() {
  7868. return 'ExpressionNode';
  7869. }
  7870. /**
  7871. * Constructs a new expression node.
  7872. *
  7873. * @param {string} [snippet=''] - The native code snippet.
  7874. * @param {string} [nodeType='void'] - The node type.
  7875. */
  7876. constructor( snippet = '', nodeType = 'void' ) {
  7877. super( nodeType );
  7878. /**
  7879. * The native code snippet.
  7880. *
  7881. * @type {string}
  7882. * @default ''
  7883. */
  7884. this.snippet = snippet;
  7885. }
  7886. generate( builder, output ) {
  7887. const type = this.getNodeType( builder );
  7888. const snippet = this.snippet;
  7889. if ( type === 'void' ) {
  7890. builder.addLineFlowCode( snippet, this );
  7891. } else {
  7892. return builder.format( snippet, type, output );
  7893. }
  7894. }
  7895. }
  7896. /**
  7897. * TSL function for creating an expression node.
  7898. *
  7899. * @tsl
  7900. * @function
  7901. * @param {string} [snippet] - The native code snippet.
  7902. * @param {?string} [nodeType='void'] - The node type.
  7903. * @returns {ExpressionNode}
  7904. */
  7905. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  7906. /**
  7907. * Represents a `discard` shader operation in TSL.
  7908. *
  7909. * @tsl
  7910. * @function
  7911. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  7912. * @return {Node} The `discard` expression.
  7913. */
  7914. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  7915. /**
  7916. * Represents a `return` shader operation in TSL.
  7917. *
  7918. * @tsl
  7919. * @function
  7920. * @return {ExpressionNode} The `return` expression.
  7921. */
  7922. const Return = () => expression( 'return' ).toStack();
  7923. addMethodChaining( 'discard', Discard );
  7924. /**
  7925. * Premultiplies the RGB channels of a color by its alpha channel.
  7926. *
  7927. * This function is useful for converting a non-premultiplied alpha color
  7928. * into a premultiplied alpha format, where the RGB values are scaled
  7929. * by the alpha value. Premultiplied alpha is often used in graphics
  7930. * rendering for certain operations, such as compositing and image processing.
  7931. *
  7932. * @tsl
  7933. * @function
  7934. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  7935. * @return {Node<vec4>} The color with premultiplied alpha.
  7936. */
  7937. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  7938. return vec4( color.rgb.mul( color.a ), color.a );
  7939. }, { color: 'vec4', return: 'vec4' } );
  7940. /**
  7941. * Unpremultiplies the RGB channels of a color by its alpha channel.
  7942. *
  7943. * This function is useful for converting a premultiplied alpha color
  7944. * back into a non-premultiplied alpha format, where the RGB values are
  7945. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  7946. * rendering for certain operations, such as compositing and image processing.
  7947. *
  7948. * @tsl
  7949. * @function
  7950. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  7951. * @return {Node<vec4>} The color with non-premultiplied alpha.
  7952. */
  7953. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  7954. return color.a.equal( 0 ).select( vec4( 0 ), vec4( color.rgb.div( color.a ), color.a ) );
  7955. }, { color: 'vec4', return: 'vec4' } );
  7956. /**
  7957. * Normally, tone mapping and color conversion happens automatically just
  7958. * before outputting a pixel to the default (screen) framebuffer. In certain
  7959. * post processing setups this is too late because some effects such as FXAA
  7960. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  7961. * to apply tone mapping and color space conversion at an arbitrary point
  7962. * in the effect chain.
  7963. *
  7964. * When applying tone mapping and color space conversion manually with this node,
  7965. * you have to set {@link RenderPipeline#outputColorTransform} to `false`.
  7966. *
  7967. * ```js
  7968. * const postProcessing = new RenderPipeline( renderer );
  7969. * postProcessing.outputColorTransform = false;
  7970. *
  7971. * const scenePass = pass( scene, camera );
  7972. * const outputPass = renderOutput( scenePass );
  7973. *
  7974. * postProcessing.outputNode = outputPass;
  7975. * ```
  7976. *
  7977. * @augments TempNode
  7978. */
  7979. class RenderOutputNode extends TempNode {
  7980. static get type() {
  7981. return 'RenderOutputNode';
  7982. }
  7983. /**
  7984. * Constructs a new render output node.
  7985. *
  7986. * @param {Node} colorNode - The color node to process.
  7987. * @param {?number} toneMapping - The tone mapping type.
  7988. * @param {?string} outputColorSpace - The output color space.
  7989. */
  7990. constructor( colorNode, toneMapping, outputColorSpace ) {
  7991. super( 'vec4' );
  7992. /**
  7993. * The color node to process.
  7994. *
  7995. * @type {Node}
  7996. */
  7997. this.colorNode = colorNode;
  7998. /**
  7999. * The tone mapping type.
  8000. *
  8001. * @private
  8002. * @type {?number}
  8003. */
  8004. this._toneMapping = toneMapping;
  8005. /**
  8006. * The output color space.
  8007. *
  8008. * @type {?string}
  8009. */
  8010. this.outputColorSpace = outputColorSpace;
  8011. /**
  8012. * This flag can be used for type testing.
  8013. *
  8014. * @type {boolean}
  8015. * @readonly
  8016. * @default true
  8017. */
  8018. this.isRenderOutputNode = true;
  8019. }
  8020. /**
  8021. * Sets the tone mapping type.
  8022. *
  8023. * @param {number} value - The tone mapping type.
  8024. * @return {ToneMappingNode} A reference to this node.
  8025. */
  8026. setToneMapping( value ) {
  8027. this._toneMapping = value;
  8028. return this;
  8029. }
  8030. /**
  8031. * Gets the tone mapping type.
  8032. *
  8033. * @returns {number} The tone mapping type.
  8034. */
  8035. getToneMapping() {
  8036. return this._toneMapping;
  8037. }
  8038. setup( { context } ) {
  8039. let outputNode = this.colorNode || context.color;
  8040. // clamp alpha
  8041. outputNode = vec4( outputNode.rgb, outputNode.a.clamp( 0.0, 1.0 ) );
  8042. // unpremultiply
  8043. outputNode = unpremultiplyAlpha( outputNode );
  8044. // tone mapping
  8045. const toneMapping = ( this._toneMapping !== null ? this._toneMapping : context.toneMapping ) || NoToneMapping;
  8046. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  8047. if ( toneMapping !== NoToneMapping ) {
  8048. outputNode = outputNode.toneMapping( toneMapping );
  8049. }
  8050. // working to output color space
  8051. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  8052. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  8053. }
  8054. // premultiply in output color space
  8055. outputNode = premultiplyAlpha( outputNode );
  8056. return outputNode;
  8057. }
  8058. }
  8059. /**
  8060. * TSL function for creating a render output node.
  8061. *
  8062. * @tsl
  8063. * @function
  8064. * @param {Node} color - The color node to process.
  8065. * @param {?number} [toneMapping=null] - The tone mapping type.
  8066. * @param {?string} [outputColorSpace=null] - The output color space.
  8067. * @returns {RenderOutputNode}
  8068. */
  8069. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace );
  8070. addMethodChaining( 'renderOutput', renderOutput );
  8071. class DebugNode extends TempNode {
  8072. static get type() {
  8073. return 'DebugNode';
  8074. }
  8075. constructor( node, callback = null ) {
  8076. super();
  8077. this.node = node;
  8078. this.callback = callback;
  8079. }
  8080. generateNodeType( builder ) {
  8081. return this.node.getNodeType( builder );
  8082. }
  8083. setup( builder ) {
  8084. return this.node.build( builder );
  8085. }
  8086. analyze( builder ) {
  8087. return this.node.build( builder );
  8088. }
  8089. generate( builder ) {
  8090. const callback = this.callback;
  8091. const snippet = this.node.build( builder );
  8092. if ( callback !== null ) {
  8093. callback( builder, snippet );
  8094. } else {
  8095. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  8096. const border = '-'.repeat( title.length );
  8097. let code = '';
  8098. code += '// #' + title + '#\n';
  8099. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  8100. code += '/* ... */ ' + snippet + ' /* ... */\n';
  8101. code += '// #' + border + '#\n';
  8102. log$1( code );
  8103. }
  8104. return snippet;
  8105. }
  8106. }
  8107. /**
  8108. * TSL function for creating a debug node.
  8109. *
  8110. * @tsl
  8111. * @function
  8112. * @param {Node} node - The node to debug.
  8113. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  8114. * @returns {DebugNode}
  8115. */
  8116. const debug = ( node, callback = null ) => new DebugNode( nodeObject( node ), callback ).toStack();
  8117. addMethodChaining( 'debug', debug );
  8118. /**
  8119. * InspectorBase is the base class for all inspectors.
  8120. *
  8121. * @class InspectorBase
  8122. * @augments EventDispatcher
  8123. */
  8124. class InspectorBase extends EventDispatcher {
  8125. /**
  8126. * Creates a new InspectorBase.
  8127. */
  8128. constructor() {
  8129. super();
  8130. /**
  8131. * The renderer associated with this inspector.
  8132. *
  8133. * @type {WebGLRenderer}
  8134. * @private
  8135. */
  8136. this._renderer = null;
  8137. /**
  8138. * The current frame being processed.
  8139. *
  8140. * @type {Object}
  8141. */
  8142. this.currentFrame = null;
  8143. }
  8144. /**
  8145. * Returns the node frame for the current renderer.
  8146. *
  8147. * @return {Object} The node frame.
  8148. */
  8149. get nodeFrame() {
  8150. return this._renderer._nodes.nodeFrame;
  8151. }
  8152. /**
  8153. * Sets the renderer for this inspector.
  8154. *
  8155. * @param {WebGLRenderer} renderer - The renderer to associate with this inspector.
  8156. * @return {InspectorBase} This inspector instance.
  8157. */
  8158. setRenderer( renderer ) {
  8159. this._renderer = renderer;
  8160. return this;
  8161. }
  8162. /**
  8163. * Returns the renderer associated with this inspector.
  8164. *
  8165. * @return {WebGLRenderer} The associated renderer.
  8166. */
  8167. getRenderer() {
  8168. return this._renderer;
  8169. }
  8170. /**
  8171. * Initializes the inspector.
  8172. */
  8173. init() { }
  8174. /**
  8175. * Called when a frame begins.
  8176. */
  8177. begin() { }
  8178. /**
  8179. * Called when a frame ends.
  8180. */
  8181. finish() { }
  8182. /**
  8183. * Inspects a node.
  8184. *
  8185. * @param {Node} node - The node to inspect.
  8186. */
  8187. inspect( /*node*/ ) { }
  8188. /**
  8189. * When a compute operation is performed.
  8190. *
  8191. * @param {ComputeNode} computeNode - The compute node being executed.
  8192. * @param {number|Array<number>} dispatchSizeOrCount - The dispatch size or count.
  8193. */
  8194. computeAsync( /*computeNode, dispatchSizeOrCount*/ ) { }
  8195. /**
  8196. * Called when a compute operation begins.
  8197. *
  8198. * @param {string} uid - A unique identifier for the render context.
  8199. * @param {ComputeNode} computeNode - The compute node being executed.
  8200. */
  8201. beginCompute( /*uid, computeNode*/ ) { }
  8202. /**
  8203. * Called when a compute operation ends.
  8204. *
  8205. * @param {string} uid - A unique identifier for the render context.
  8206. * @param {ComputeNode} computeNode - The compute node being executed.
  8207. */
  8208. finishCompute( /*uid*/ ) { }
  8209. /**
  8210. * Called when a render operation begins.
  8211. *
  8212. * @param {string} uid - A unique identifier for the render context.
  8213. * @param {Scene} scene - The scene being rendered.
  8214. * @param {Camera} camera - The camera being used for rendering.
  8215. * @param {?WebGLRenderTarget} renderTarget - The render target, if any.
  8216. */
  8217. beginRender( /*uid, scene, camera, renderTarget*/ ) { }
  8218. /**
  8219. * Called when an animation loop ends.
  8220. *
  8221. * @param {string} uid - A unique identifier for the render context.
  8222. */
  8223. finishRender( /*uid*/ ) { }
  8224. /**
  8225. * Called when a texture copy operation is performed.
  8226. *
  8227. * @param {Texture} srcTexture - The source texture.
  8228. * @param {Texture} dstTexture - The destination texture.
  8229. */
  8230. copyTextureToTexture( /*srcTexture, dstTexture*/ ) { }
  8231. /**
  8232. * Called when a framebuffer copy operation is performed.
  8233. *
  8234. * @param {Texture} framebufferTexture - The texture associated with the framebuffer.
  8235. */
  8236. copyFramebufferToTexture( /*framebufferTexture*/ ) { }
  8237. }
  8238. /**
  8239. * InspectorNode is a wrapper node that allows inspection of node values during rendering.
  8240. * It can be used to debug or analyze node outputs in the rendering pipeline.
  8241. *
  8242. * @augments Node
  8243. */
  8244. class InspectorNode extends Node {
  8245. /**
  8246. * Returns the type of the node.
  8247. *
  8248. * @returns {string}
  8249. */
  8250. static get type() {
  8251. return 'InspectorNode';
  8252. }
  8253. /**
  8254. * Creates an InspectorNode.
  8255. *
  8256. * @param {Node} node - The node to inspect.
  8257. * @param {string} [name=''] - Optional name for the inspector node.
  8258. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  8259. */
  8260. constructor( node, name = '', callback = null ) {
  8261. super();
  8262. this.node = node;
  8263. this.name = name;
  8264. this.callback = callback;
  8265. this.updateType = NodeUpdateType.FRAME;
  8266. this.isInspectorNode = true;
  8267. }
  8268. /**
  8269. * Returns the name of the inspector node.
  8270. *
  8271. * @returns {string}
  8272. */
  8273. getName() {
  8274. return this.name || this.node.name;
  8275. }
  8276. /**
  8277. * Updates the inspector node, allowing inspection of the wrapped node.
  8278. *
  8279. * @param {NodeFrame} frame - A reference to the current node frame.
  8280. */
  8281. update( frame ) {
  8282. frame.renderer.inspector.inspect( this );
  8283. }
  8284. /**
  8285. * Returns the type of the wrapped node.
  8286. *
  8287. * @param {NodeBuilder} builder - The node builder.
  8288. * @returns {string}
  8289. */
  8290. generateNodeType( builder ) {
  8291. return this.node.getNodeType( builder );
  8292. }
  8293. /**
  8294. * Sets up the inspector node.
  8295. *
  8296. * @param {NodeBuilder} builder - The node builder.
  8297. * @returns {Node} The setup node.
  8298. */
  8299. setup( builder ) {
  8300. let node = this.node;
  8301. if ( builder.context.inspector === true && this.callback !== null ) {
  8302. node = this.callback( node );
  8303. }
  8304. if ( builder.renderer.backend.isWebGPUBackend !== true && builder.renderer.inspector.constructor !== InspectorBase ) {
  8305. warnOnce( 'TSL: ".toInspector()" is only available with WebGPU.' );
  8306. }
  8307. return node;
  8308. }
  8309. }
  8310. /**
  8311. * Creates an inspector node to wrap around a given node for inspection purposes.
  8312. *
  8313. * @tsl
  8314. * @param {Node} node - The node to inspect.
  8315. * @param {string} [name=''] - Optional name for the inspector node.
  8316. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  8317. * @returns {Node} The inspector node.
  8318. */
  8319. function inspector( node, name = '', callback = null ) {
  8320. node = nodeObject( node );
  8321. return node.before( new InspectorNode( node, name, callback ) );
  8322. }
  8323. addMethodChaining( 'toInspector', inspector );
  8324. function addNodeElement( name/*, nodeElement*/ ) {
  8325. warn( 'TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  8326. }
  8327. /**
  8328. * Base class for representing shader attributes as nodes.
  8329. *
  8330. * @augments Node
  8331. */
  8332. class AttributeNode extends Node {
  8333. static get type() {
  8334. return 'AttributeNode';
  8335. }
  8336. /**
  8337. * Constructs a new attribute node.
  8338. *
  8339. * @param {string} attributeName - The name of the attribute.
  8340. * @param {?string} nodeType - The node type.
  8341. */
  8342. constructor( attributeName, nodeType = null ) {
  8343. super( nodeType );
  8344. /**
  8345. * `AttributeNode` sets this property to `true` by default.
  8346. *
  8347. * @type {boolean}
  8348. * @default true
  8349. */
  8350. this.global = true;
  8351. this._attributeName = attributeName;
  8352. }
  8353. getHash( builder ) {
  8354. return this.getAttributeName( builder );
  8355. }
  8356. generateNodeType( builder ) {
  8357. let nodeType = this.nodeType;
  8358. if ( nodeType === null ) {
  8359. const attributeName = this.getAttributeName( builder );
  8360. if ( builder.hasGeometryAttribute( attributeName ) ) {
  8361. const attribute = builder.geometry.getAttribute( attributeName );
  8362. nodeType = builder.getTypeFromAttribute( attribute );
  8363. } else {
  8364. nodeType = 'float';
  8365. }
  8366. }
  8367. return nodeType;
  8368. }
  8369. /**
  8370. * Sets the attribute name to the given value. The method can be
  8371. * overwritten in derived classes if the final name must be computed
  8372. * analytically.
  8373. *
  8374. * @param {string} attributeName - The name of the attribute.
  8375. * @return {AttributeNode} A reference to this node.
  8376. */
  8377. setAttributeName( attributeName ) {
  8378. this._attributeName = attributeName;
  8379. return this;
  8380. }
  8381. /**
  8382. * Returns the attribute name of this node. The method can be
  8383. * overwritten in derived classes if the final name must be computed
  8384. * analytically.
  8385. *
  8386. * @param {NodeBuilder} builder - The current node builder.
  8387. * @return {string} The attribute name.
  8388. */
  8389. getAttributeName( /*builder*/ ) {
  8390. return this._attributeName;
  8391. }
  8392. generate( builder ) {
  8393. const attributeName = this.getAttributeName( builder );
  8394. const nodeType = this.getNodeType( builder );
  8395. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  8396. if ( geometryAttribute === true ) {
  8397. const attribute = builder.geometry.getAttribute( attributeName );
  8398. const attributeType = builder.getTypeFromAttribute( attribute );
  8399. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  8400. if ( builder.shaderStage === 'vertex' ) {
  8401. return builder.format( nodeAttribute.name, attributeType, nodeType );
  8402. } else {
  8403. const nodeVarying = varying( this );
  8404. return nodeVarying.build( builder, nodeType );
  8405. }
  8406. } else {
  8407. warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  8408. return builder.generateConst( nodeType );
  8409. }
  8410. }
  8411. serialize( data ) {
  8412. super.serialize( data );
  8413. data.global = this.global;
  8414. data._attributeName = this._attributeName;
  8415. }
  8416. deserialize( data ) {
  8417. super.deserialize( data );
  8418. this.global = data.global;
  8419. this._attributeName = data._attributeName;
  8420. }
  8421. }
  8422. /**
  8423. * TSL function for creating an attribute node.
  8424. *
  8425. * @tsl
  8426. * @function
  8427. * @param {string} name - The name of the attribute.
  8428. * @param {?string} [nodeType=null] - The node type.
  8429. * @returns {AttributeNode}
  8430. */
  8431. const attribute = ( name, nodeType = null ) => new AttributeNode( name, nodeType );
  8432. /**
  8433. * TSL function for creating an uv attribute node with the given index.
  8434. *
  8435. * @tsl
  8436. * @function
  8437. * @param {number} [index=0] - The uv index.
  8438. * @return {AttributeNode<vec2>} The uv attribute node.
  8439. */
  8440. const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  8441. /**
  8442. * A node that represents the dimensions of a texture. The texture size is
  8443. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  8444. * or `textureSize()`.
  8445. *
  8446. * @augments Node
  8447. */
  8448. class TextureSizeNode extends Node {
  8449. static get type() {
  8450. return 'TextureSizeNode';
  8451. }
  8452. /**
  8453. * Constructs a new texture size node.
  8454. *
  8455. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  8456. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  8457. */
  8458. constructor( textureNode, levelNode = null ) {
  8459. super( 'uvec2' );
  8460. /**
  8461. * This flag can be used for type testing.
  8462. *
  8463. * @type {boolean}
  8464. * @readonly
  8465. * @default true
  8466. */
  8467. this.isTextureSizeNode = true;
  8468. /**
  8469. * A texture node which size should be retrieved.
  8470. *
  8471. * @type {TextureNode}
  8472. */
  8473. this.textureNode = textureNode;
  8474. /**
  8475. * A level node which defines the requested mip.
  8476. *
  8477. * @type {Node<int>}
  8478. * @default null
  8479. */
  8480. this.levelNode = levelNode;
  8481. }
  8482. generate( builder, output ) {
  8483. const textureProperty = this.textureNode.build( builder, 'property' );
  8484. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  8485. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  8486. }
  8487. }
  8488. /**
  8489. * TSL function for creating a texture size node.
  8490. *
  8491. * @tsl
  8492. * @function
  8493. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  8494. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  8495. * @returns {TextureSizeNode}
  8496. */
  8497. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  8498. /**
  8499. * A special type of uniform node that computes the
  8500. * maximum mipmap level for a given texture node.
  8501. *
  8502. * ```js
  8503. * const level = maxMipLevel( textureNode );
  8504. * ```
  8505. *
  8506. * @augments UniformNode
  8507. */
  8508. class MaxMipLevelNode extends UniformNode {
  8509. static get type() {
  8510. return 'MaxMipLevelNode';
  8511. }
  8512. /**
  8513. * Constructs a new max mip level node.
  8514. *
  8515. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  8516. */
  8517. constructor( textureNode ) {
  8518. super( 0 );
  8519. /**
  8520. * The texture node to compute the max mip level for.
  8521. *
  8522. * @private
  8523. * @type {TextureNode}
  8524. */
  8525. this._textureNode = textureNode;
  8526. /**
  8527. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  8528. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  8529. *
  8530. * @type {string}
  8531. * @default 'frame'
  8532. */
  8533. this.updateType = NodeUpdateType.FRAME;
  8534. }
  8535. /**
  8536. * The texture node to compute the max mip level for.
  8537. *
  8538. * @readonly
  8539. * @type {TextureNode}
  8540. */
  8541. get textureNode() {
  8542. return this._textureNode;
  8543. }
  8544. /**
  8545. * The texture.
  8546. *
  8547. * @readonly
  8548. * @type {Texture}
  8549. */
  8550. get texture() {
  8551. return this._textureNode.value;
  8552. }
  8553. update() {
  8554. const texture = this.texture;
  8555. const images = texture.images;
  8556. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  8557. if ( image && image.width !== undefined ) {
  8558. const { width, height } = image;
  8559. this.value = Math.log2( Math.max( width, height ) );
  8560. }
  8561. }
  8562. }
  8563. /**
  8564. * TSL function for creating a max mip level node.
  8565. *
  8566. * @tsl
  8567. * @function
  8568. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  8569. * @returns {MaxMipLevelNode}
  8570. */
  8571. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  8572. /**
  8573. * Custom error class for node-related errors, including stack trace information.
  8574. */
  8575. class NodeError extends Error {
  8576. constructor( message, stackTrace = null ) {
  8577. super( message );
  8578. /**
  8579. * The name of the error.
  8580. *
  8581. * @type {string}
  8582. */
  8583. this.name = 'NodeError';
  8584. /**
  8585. * The stack trace associated with the error.
  8586. *
  8587. * @type {?StackTrace}
  8588. */
  8589. this.stackTrace = stackTrace;
  8590. }
  8591. }
  8592. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  8593. /**
  8594. * This type of uniform node represents a 2D texture.
  8595. *
  8596. * @augments UniformNode
  8597. */
  8598. class TextureNode extends UniformNode {
  8599. static get type() {
  8600. return 'TextureNode';
  8601. }
  8602. /**
  8603. * Constructs a new texture node.
  8604. *
  8605. * @param {Texture} [value=EmptyTexture] - The texture.
  8606. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8607. * @param {?Node<int>} [levelNode=null] - The level node.
  8608. * @param {?Node<float>} [biasNode=null] - The bias node.
  8609. */
  8610. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  8611. super( value );
  8612. /**
  8613. * This flag can be used for type testing.
  8614. *
  8615. * @type {boolean}
  8616. * @readonly
  8617. * @default true
  8618. */
  8619. this.isTextureNode = true;
  8620. /**
  8621. * Represents the texture coordinates.
  8622. *
  8623. * @type {?Node<vec2|vec3>}
  8624. * @default null
  8625. */
  8626. this.uvNode = uvNode;
  8627. /**
  8628. * Represents the mip level that should be selected.
  8629. *
  8630. * @type {?Node<int>}
  8631. * @default null
  8632. */
  8633. this.levelNode = levelNode;
  8634. /**
  8635. * Represents the bias to be applied during level-of-detail computation.
  8636. *
  8637. * @type {?Node<float>}
  8638. * @default null
  8639. */
  8640. this.biasNode = biasNode;
  8641. /**
  8642. * Represents a reference value a texture sample is compared to.
  8643. *
  8644. * @type {?Node<float>}
  8645. * @default null
  8646. */
  8647. this.compareNode = null;
  8648. /**
  8649. * When using texture arrays, the depth node defines the layer to select.
  8650. *
  8651. * @type {?Node<int>}
  8652. * @default null
  8653. */
  8654. this.depthNode = null;
  8655. /**
  8656. * When defined, a texture is sampled using explicit gradients.
  8657. *
  8658. * @type {?Array<Node<vec2>>}
  8659. * @default null
  8660. */
  8661. this.gradNode = null;
  8662. /**
  8663. * Represents the optional index constant of the channel to gather.
  8664. * This must be in range [0, 3] and a compile-time constant.
  8665. *
  8666. * @type {?Node<int>}
  8667. * @default null
  8668. */
  8669. this.gatherNode = null;
  8670. /**
  8671. * Represents the optional texel offset applied to the unnormalized texture
  8672. * coordinate before sampling the texture.
  8673. *
  8674. * @type {?Node<ivec2|ivec3>}
  8675. * @default null
  8676. */
  8677. this.offsetNode = null;
  8678. /**
  8679. * Whether texture values should be sampled or fetched.
  8680. *
  8681. * @type {boolean}
  8682. * @default true
  8683. */
  8684. this.sampler = true;
  8685. /**
  8686. * Whether the uv transformation matrix should be
  8687. * automatically updated or not. Use `setUpdateMatrix()`
  8688. * if you want to change the value of the property.
  8689. *
  8690. * @type {boolean}
  8691. * @default false
  8692. */
  8693. this.updateMatrix = false;
  8694. /**
  8695. * By default the `update()` method is not executed. Depending on
  8696. * whether a uv transformation matrix and/or flipY is applied, `update()`
  8697. * is executed per object.
  8698. *
  8699. * @type {string}
  8700. * @default 'none'
  8701. */
  8702. this.updateType = NodeUpdateType.NONE;
  8703. /**
  8704. * The reference node.
  8705. *
  8706. * @type {?Node}
  8707. * @default null
  8708. */
  8709. this.referenceNode = null;
  8710. /**
  8711. * The texture value is stored in a private property.
  8712. *
  8713. * @private
  8714. * @type {Texture}
  8715. */
  8716. this._value = value;
  8717. /**
  8718. * The uniform node that represents the uv transformation matrix.
  8719. *
  8720. * @private
  8721. * @type {?UniformNode<mat3>}
  8722. * @default null
  8723. */
  8724. this._matrixUniform = null;
  8725. /**
  8726. * The uniform node that represents the y-flip. Only required for WebGL.
  8727. *
  8728. * @private
  8729. * @type {?UniformNode<bool>}
  8730. * @default null
  8731. */
  8732. this._flipYUniform = null;
  8733. this.setUpdateMatrix( uvNode === null );
  8734. }
  8735. set value( value ) {
  8736. if ( this.referenceNode ) {
  8737. this.referenceNode.value = value;
  8738. } else {
  8739. this._value = value;
  8740. }
  8741. }
  8742. /**
  8743. * The texture value.
  8744. *
  8745. * @type {Texture}
  8746. */
  8747. get value() {
  8748. return this.referenceNode ? this.referenceNode.value : this._value;
  8749. }
  8750. /**
  8751. * Overwritten since the uniform hash is defined by the texture's UUID.
  8752. *
  8753. * @param {NodeBuilder} builder - The current node builder.
  8754. * @return {string} The uniform hash.
  8755. */
  8756. getUniformHash( /*builder*/ ) {
  8757. return this.value.uuid;
  8758. }
  8759. /**
  8760. * Overwritten since the node type is inferred from the texture type.
  8761. *
  8762. * @param {NodeBuilder} builder - The current node builder.
  8763. * @return {string} The node type.
  8764. */
  8765. generateNodeType( /*builder*/ ) {
  8766. if ( this.value.isDepthTexture === true ) {
  8767. if ( this.gatherNode === null ) return 'float';
  8768. return 'vec4';
  8769. }
  8770. if ( this.value.type === UnsignedIntType ) {
  8771. return 'uvec4';
  8772. } else if ( this.value.type === IntType ) {
  8773. return 'ivec4';
  8774. }
  8775. return 'vec4';
  8776. }
  8777. /**
  8778. * Overwrites the default implementation to return a fixed value `'texture'`.
  8779. *
  8780. * @param {NodeBuilder} builder - The current node builder.
  8781. * @return {string} The input type.
  8782. */
  8783. getInputType( /*builder*/ ) {
  8784. return 'texture';
  8785. }
  8786. /**
  8787. * Returns a default uvs based on the current texture's channel.
  8788. *
  8789. * @return {AttributeNode<vec2>} The default uvs.
  8790. */
  8791. getDefaultUV() {
  8792. return uv$1( this.value.channel );
  8793. }
  8794. /**
  8795. * Overwritten to always return the texture reference of the node.
  8796. *
  8797. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  8798. * @return {Texture} The texture reference.
  8799. */
  8800. updateReference( /*state*/ ) {
  8801. return this.value;
  8802. }
  8803. /**
  8804. * Transforms the given uv node with the texture transformation matrix.
  8805. *
  8806. * @param {Node} uvNode - The uv node to transform.
  8807. * @return {Node} The transformed uv node.
  8808. */
  8809. getTransformedUV( uvNode ) {
  8810. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  8811. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  8812. }
  8813. /**
  8814. * Defines whether the uv transformation matrix should automatically be updated or not.
  8815. *
  8816. * @param {boolean} value - The update toggle.
  8817. * @return {TextureNode} A reference to this node.
  8818. */
  8819. setUpdateMatrix( value ) {
  8820. this.updateMatrix = value;
  8821. return this;
  8822. }
  8823. /**
  8824. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  8825. * to modify the uv node for correct sampling.
  8826. *
  8827. * @param {NodeBuilder} builder - The current node builder.
  8828. * @param {Node} uvNode - The uv node to setup.
  8829. * @return {Node} The updated uv node.
  8830. */
  8831. setupUV( builder, uvNode ) {
  8832. if ( builder.isFlipY() ) {
  8833. if ( this._flipYUniform === null ) this._flipYUniform = uniform( false );
  8834. uvNode = uvNode.toVar();
  8835. if ( this.sampler ) {
  8836. uvNode = this._flipYUniform.select( uvNode.flipY(), uvNode );
  8837. } else {
  8838. uvNode = this._flipYUniform.select( uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) ), uvNode );
  8839. }
  8840. }
  8841. return uvNode;
  8842. }
  8843. /**
  8844. * Setups texture node by preparing the internal nodes for code generation.
  8845. *
  8846. * @param {NodeBuilder} builder - The current node builder.
  8847. */
  8848. setup( builder ) {
  8849. const properties = builder.getNodeProperties( this );
  8850. properties.referenceNode = this.referenceNode;
  8851. //
  8852. const texture = this.value;
  8853. if ( ! texture || texture.isTexture !== true ) {
  8854. throw new NodeError( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().', this.stackTrace );
  8855. }
  8856. //
  8857. const uvNode = Fn( () => {
  8858. let uvNode = this.uvNode;
  8859. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  8860. uvNode = builder.context.getUV( this, builder );
  8861. }
  8862. if ( ! uvNode ) uvNode = this.getDefaultUV();
  8863. if ( this.updateMatrix === true ) {
  8864. uvNode = this.getTransformedUV( uvNode );
  8865. }
  8866. uvNode = this.setupUV( builder, uvNode );
  8867. //
  8868. this.updateType = ( this._matrixUniform !== null || this._flipYUniform !== null ) ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  8869. //
  8870. return uvNode;
  8871. } )();
  8872. //
  8873. let levelNode = this.levelNode;
  8874. if ( levelNode === null && builder.context.getTextureLevel ) {
  8875. levelNode = builder.context.getTextureLevel( this );
  8876. }
  8877. //
  8878. let compareNode = null;
  8879. let compareStepNode = null;
  8880. if ( this.compareNode !== null ) {
  8881. if ( builder.renderer.hasCompatibility( Compatibility.TEXTURE_COMPARE ) ) {
  8882. compareNode = this.compareNode;
  8883. } else {
  8884. const compareFunction = texture.compareFunction;
  8885. if ( compareFunction === null || compareFunction === LessCompare || compareFunction === LessEqualCompare || compareFunction === GreaterCompare || compareFunction === GreaterEqualCompare ) {
  8886. compareStepNode = this.compareNode;
  8887. } else {
  8888. compareNode = this.compareNode;
  8889. warnOnce( 'TSL: Only "LessCompare", "LessEqualCompare", "GreaterCompare" and "GreaterEqualCompare" are supported for depth texture comparison fallback.' );
  8890. }
  8891. }
  8892. }
  8893. properties.uvNode = uvNode;
  8894. properties.levelNode = levelNode;
  8895. properties.biasNode = this.biasNode;
  8896. properties.compareNode = compareNode;
  8897. properties.compareStepNode = compareStepNode;
  8898. properties.gradNode = this.gradNode;
  8899. properties.gatherNode = this.gatherNode;
  8900. properties.depthNode = this.depthNode;
  8901. properties.offsetNode = this.offsetNode;
  8902. }
  8903. /**
  8904. * Generates the uv code snippet.
  8905. *
  8906. * @param {NodeBuilder} builder - The current node builder.
  8907. * @param {Node} uvNode - The uv node to generate code for.
  8908. * @return {string} The generated code snippet.
  8909. */
  8910. generateUV( builder, uvNode ) {
  8911. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  8912. }
  8913. /**
  8914. * Generates the offset code snippet.
  8915. *
  8916. * @param {NodeBuilder} builder - The current node builder.
  8917. * @param {Node} offsetNode - The offset node to generate code for.
  8918. * @return {string} The generated code snippet.
  8919. */
  8920. generateOffset( builder, offsetNode ) {
  8921. return offsetNode.build( builder, 'ivec2' );
  8922. }
  8923. /**
  8924. * Generates the snippet for the texture sampling.
  8925. *
  8926. * @param {NodeBuilder} builder - The current node builder.
  8927. * @param {string} textureProperty - The texture property.
  8928. * @param {string} uvSnippet - The uv snippet.
  8929. * @param {?string} levelSnippet - The level snippet.
  8930. * @param {?string} biasSnippet - The bias snippet.
  8931. * @param {?string} depthSnippet - The depth snippet.
  8932. * @param {?string} compareSnippet - The compare snippet.
  8933. * @param {?Array<string>} gradSnippet - The grad snippet.
  8934. * @param {?string} gatherSnippet - The gather snippet.
  8935. * @param {?string} offsetSnippet - The offset snippet.
  8936. * @param {?string} flipYSnippet - The y-flip snippet. Only used for WebGL.
  8937. * @return {string} The generated code snippet.
  8938. */
  8939. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, gatherSnippet, offsetSnippet, flipYSnippet ) {
  8940. const texture = this.value;
  8941. let snippet;
  8942. if ( biasSnippet ) {
  8943. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet );
  8944. } else if ( gradSnippet ) {
  8945. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet );
  8946. } else if ( gatherSnippet ) {
  8947. if ( compareSnippet ) {
  8948. snippet = builder.generateTextureGatherCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, flipYSnippet );
  8949. } else {
  8950. snippet = builder.generateTextureGather( texture, textureProperty, uvSnippet, gatherSnippet, depthSnippet, offsetSnippet, flipYSnippet );
  8951. }
  8952. } else if ( compareSnippet ) {
  8953. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet );
  8954. } else if ( this.sampler === false ) {
  8955. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8956. } else if ( levelSnippet ) {
  8957. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8958. } else {
  8959. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet );
  8960. }
  8961. return snippet;
  8962. }
  8963. /**
  8964. * Generates the code snippet of the texture node.
  8965. *
  8966. * @param {NodeBuilder} builder - The current node builder.
  8967. * @param {string} output - The current output.
  8968. * @return {string} The generated code snippet.
  8969. */
  8970. generate( builder, output ) {
  8971. const texture = this.value;
  8972. const properties = builder.getNodeProperties( this );
  8973. const textureProperty = super.generate( builder, 'property' );
  8974. if ( /^sampler/.test( output ) ) {
  8975. return textureProperty + '_sampler';
  8976. } else if ( builder.isReference( output ) ) {
  8977. return textureProperty;
  8978. } else {
  8979. const nodeData = builder.getDataFromNode( this );
  8980. let nodeType = this.getNodeType( builder );
  8981. let propertyName = nodeData.propertyName;
  8982. if ( propertyName === undefined ) {
  8983. const { uvNode, levelNode, biasNode, compareNode, compareStepNode, depthNode, gradNode, gatherNode, offsetNode } = properties;
  8984. const uvSnippet = this.generateUV( builder, uvNode );
  8985. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  8986. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  8987. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  8988. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  8989. const compareStepSnippet = compareStepNode ? compareStepNode.build( builder, 'float' ) : null;
  8990. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  8991. const gatherSnippet = gatherNode ? gatherNode.build( builder, 'int' ) : null;
  8992. const offsetSnippet = offsetNode ? this.generateOffset( builder, offsetNode ) : null;
  8993. const flipYSnippet = this._flipYUniform ? this._flipYUniform.build( builder, 'bool' ) : null;
  8994. if ( gatherSnippet ) {
  8995. nodeType = 'vec4';
  8996. }
  8997. let finalDepthSnippet = depthSnippet;
  8998. if ( finalDepthSnippet === null && texture.isArrayTexture && this.isTexture3DNode !== true ) {
  8999. finalDepthSnippet = '0';
  9000. }
  9001. const nodeVar = builder.getVarFromNode( this );
  9002. propertyName = builder.getPropertyName( nodeVar );
  9003. let snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, finalDepthSnippet, compareSnippet, gradSnippet, gatherSnippet, offsetSnippet, flipYSnippet );
  9004. if ( compareStepSnippet !== null ) {
  9005. const compareFunction = texture.compareFunction;
  9006. if ( compareFunction === GreaterCompare || compareFunction === GreaterEqualCompare ) {
  9007. snippet = step( expression( snippet, nodeType ), expression( compareStepSnippet, 'float' ) ).build( builder, nodeType );
  9008. } else {
  9009. snippet = step( expression( compareStepSnippet, 'float' ), expression( snippet, nodeType ) ).build( builder, nodeType );
  9010. }
  9011. }
  9012. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  9013. nodeData.snippet = snippet;
  9014. nodeData.propertyName = propertyName;
  9015. }
  9016. let snippet = propertyName;
  9017. if ( builder.needsToWorkingColorSpace( texture ) ) {
  9018. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  9019. }
  9020. return builder.format( snippet, nodeType, output );
  9021. }
  9022. }
  9023. /**
  9024. * Sets the sampler value.
  9025. *
  9026. * @param {boolean} value - The sampler value to set.
  9027. * @return {TextureNode} A reference to this texture node.
  9028. */
  9029. setSampler( value ) {
  9030. this.sampler = value;
  9031. return this;
  9032. }
  9033. /**
  9034. * Returns the sampler value.
  9035. *
  9036. * @return {boolean} The sampler value.
  9037. */
  9038. getSampler() {
  9039. return this.sampler;
  9040. }
  9041. // @TODO: Move to TSL
  9042. /**
  9043. * Samples the texture with the given uv node.
  9044. *
  9045. * @param {Node} uvNode - The uv node.
  9046. * @return {TextureNode} A texture node representing the texture sample.
  9047. */
  9048. sample( uvNode ) {
  9049. const textureNode = this.clone();
  9050. textureNode.uvNode = nodeObject( uvNode );
  9051. textureNode.referenceNode = this.getBase();
  9052. return nodeObject( textureNode );
  9053. }
  9054. /**
  9055. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  9056. *
  9057. * @param {Node<uvec2>} uvNode - The uv node.
  9058. * @returns {TextureNode} A texture node representing the texture load.
  9059. */
  9060. load( uvNode ) {
  9061. return this.sample( uvNode ).setSampler( false );
  9062. }
  9063. /**
  9064. * Samples a blurred version of the texture by defining an internal bias.
  9065. *
  9066. * @param {Node<float>} amountNode - How blurred the texture should be.
  9067. * @return {TextureNode} A texture node representing the texture sample.
  9068. */
  9069. blur( amountNode ) {
  9070. const textureNode = this.clone();
  9071. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  9072. textureNode.referenceNode = this.getBase();
  9073. const map = textureNode.value;
  9074. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  9075. warn( 'TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  9076. textureNode.biasNode = null;
  9077. }
  9078. return nodeObject( textureNode );
  9079. }
  9080. /**
  9081. * Samples a specific mip of the texture.
  9082. *
  9083. * @param {Node<int>} levelNode - The mip level to sample.
  9084. * @return {TextureNode} A texture node representing the texture sample.
  9085. */
  9086. level( levelNode ) {
  9087. const textureNode = this.clone();
  9088. textureNode.levelNode = nodeObject( levelNode );
  9089. textureNode.referenceNode = this.getBase();
  9090. return nodeObject( textureNode );
  9091. }
  9092. /**
  9093. * Returns the texture size of the requested level.
  9094. *
  9095. * @param {Node<int>} levelNode - The level to compute the size for.
  9096. * @return {TextureSizeNode} The texture size.
  9097. */
  9098. size( levelNode ) {
  9099. return textureSize( this, levelNode );
  9100. }
  9101. /**
  9102. * Samples the texture with the given bias.
  9103. *
  9104. * @param {Node<float>} biasNode - The bias node.
  9105. * @return {TextureNode} A texture node representing the texture sample.
  9106. */
  9107. bias( biasNode ) {
  9108. const textureNode = this.clone();
  9109. textureNode.biasNode = nodeObject( biasNode );
  9110. textureNode.referenceNode = this.getBase();
  9111. return nodeObject( textureNode );
  9112. }
  9113. /**
  9114. * Returns the base texture of this node.
  9115. * @return {TextureNode} The base texture node.
  9116. */
  9117. getBase() {
  9118. return this.referenceNode ? this.referenceNode.getBase() : this;
  9119. }
  9120. /**
  9121. * Samples the texture by executing a compare operation.
  9122. *
  9123. * @param {Node<float>} compareNode - The node that defines the compare value.
  9124. * @return {TextureNode} A texture node representing the texture sample.
  9125. */
  9126. compare( compareNode ) {
  9127. const textureNode = this.clone();
  9128. textureNode.compareNode = nodeObject( compareNode );
  9129. textureNode.referenceNode = this.getBase();
  9130. return nodeObject( textureNode );
  9131. }
  9132. /**
  9133. * Samples the texture using an explicit gradient.
  9134. *
  9135. * @param {Node<vec2>} gradNodeX - The gradX node.
  9136. * @param {Node<vec2>} gradNodeY - The gradY node.
  9137. * @return {TextureNode} A texture node representing the texture sample.
  9138. */
  9139. grad( gradNodeX, gradNodeY ) {
  9140. const textureNode = this.clone();
  9141. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  9142. textureNode.referenceNode = this.getBase();
  9143. return nodeObject( textureNode );
  9144. }
  9145. /**
  9146. * Gathers four texels from the texture.
  9147. *
  9148. * @param {[Node<int>]} gatherNode - The index of the channel to read. This must be in range [0, 3] and a compile-time constant.
  9149. * @return {TextureNode} A texture node representing the texture sample.
  9150. */
  9151. gather( gatherNode = 0 ) {
  9152. const textureNode = this.clone();
  9153. textureNode.gatherNode = nodeObject( gatherNode );
  9154. textureNode.referenceNode = this.getBase();
  9155. return nodeObject( textureNode );
  9156. }
  9157. /**
  9158. * Samples the texture by defining a depth node.
  9159. *
  9160. * @param {Node<int>} depthNode - The depth node.
  9161. * @return {TextureNode} A texture node representing the texture sample.
  9162. */
  9163. depth( depthNode ) {
  9164. const textureNode = this.clone();
  9165. textureNode.depthNode = nodeObject( depthNode );
  9166. textureNode.referenceNode = this.getBase();
  9167. return nodeObject( textureNode );
  9168. }
  9169. /**
  9170. * Samples the texture by defining an offset node.
  9171. *
  9172. * @param {Node<ivec2>} offsetNode - The offset node.
  9173. * @return {TextureNode} A texture node representing the texture sample.
  9174. */
  9175. offset( offsetNode ) {
  9176. const textureNode = this.clone();
  9177. textureNode.offsetNode = nodeObject( offsetNode );
  9178. textureNode.referenceNode = this.getBase();
  9179. return nodeObject( textureNode );
  9180. }
  9181. // --
  9182. serialize( data ) {
  9183. super.serialize( data );
  9184. data.value = this.value.toJSON( data.meta ).uuid;
  9185. data.sampler = this.sampler;
  9186. data.updateMatrix = this.updateMatrix;
  9187. data.updateType = this.updateType;
  9188. }
  9189. deserialize( data ) {
  9190. super.deserialize( data );
  9191. this.value = data.meta.textures[ data.value ];
  9192. this.sampler = data.sampler;
  9193. this.updateMatrix = data.updateMatrix;
  9194. this.updateType = data.updateType;
  9195. }
  9196. /**
  9197. * The update is used to implement the update of the uv transformation matrix.
  9198. */
  9199. update() {
  9200. const texture = this.value;
  9201. const matrixUniform = this._matrixUniform;
  9202. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  9203. if ( texture.matrixAutoUpdate === true ) {
  9204. texture.updateMatrix();
  9205. }
  9206. //
  9207. const flipYUniform = this._flipYUniform;
  9208. if ( flipYUniform !== null ) {
  9209. flipYUniform.value = ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true );
  9210. }
  9211. }
  9212. /**
  9213. * Clones the texture node.
  9214. *
  9215. * @return {TextureNode} The cloned texture node.
  9216. */
  9217. clone() {
  9218. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  9219. newNode.sampler = this.sampler;
  9220. newNode.depthNode = this.depthNode;
  9221. newNode.compareNode = this.compareNode;
  9222. newNode.gradNode = this.gradNode;
  9223. newNode.gatherNode = this.gatherNode;
  9224. newNode.offsetNode = this.offsetNode;
  9225. return newNode;
  9226. }
  9227. }
  9228. /**
  9229. * TSL function for creating a texture node.
  9230. *
  9231. * @tsl
  9232. * @function
  9233. * @param {?Texture} value - The texture.
  9234. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  9235. * @param {?Node<int>} [levelNode=null] - The level node.
  9236. * @param {?Node<float>} [biasNode=null] - The bias node.
  9237. * @returns {TextureNode}
  9238. */
  9239. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  9240. /**
  9241. * TSL function for creating a texture node or sample a texture node already existing.
  9242. *
  9243. * @tsl
  9244. * @function
  9245. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  9246. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  9247. * @param {?Node<int>} [levelNode=null] - The level node.
  9248. * @param {?Node<float>} [biasNode=null] - The bias node.
  9249. * @returns {TextureNode}
  9250. */
  9251. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  9252. let textureNode;
  9253. if ( value && value.isTextureNode === true ) {
  9254. textureNode = nodeObject( value.clone() );
  9255. textureNode.referenceNode = value.getBase(); // Ensure the reference is set to the original node
  9256. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  9257. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  9258. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  9259. } else {
  9260. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  9261. }
  9262. return textureNode;
  9263. };
  9264. /**
  9265. * TSL function for creating a uniform texture node.
  9266. *
  9267. * @tsl
  9268. * @function
  9269. * @param {?Texture} value - The texture.
  9270. * @returns {TextureNode}
  9271. */
  9272. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  9273. /**
  9274. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  9275. *
  9276. * @tsl
  9277. * @function
  9278. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  9279. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  9280. * @param {?Node<int>} [levelNode=null] - The level node.
  9281. * @param {?Node<float>} [biasNode=null] - The bias node.
  9282. * @returns {TextureNode}
  9283. */
  9284. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  9285. const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  9286. /**
  9287. * Converts a texture or texture node to a sampler.
  9288. *
  9289. * @tsl
  9290. * @function
  9291. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  9292. * @returns {Node}
  9293. */
  9294. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  9295. /**
  9296. * Converts a texture or texture node to a sampler comparison.
  9297. *
  9298. * @tsl
  9299. * @function
  9300. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  9301. * @returns {Node}
  9302. */
  9303. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  9304. /**
  9305. * A special type of uniform node which represents array-like data
  9306. * as uniform buffers. The access usually happens via `element()`
  9307. * which returns an instance of {@link ArrayElementNode}. For example:
  9308. *
  9309. * ```js
  9310. * const bufferNode = buffer( array, 'mat4', count );
  9311. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  9312. * ```
  9313. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  9314. * since it handles more input types and automatically cares about buffer paddings.
  9315. *
  9316. * @augments UniformNode
  9317. */
  9318. class BufferNode extends UniformNode {
  9319. static get type() {
  9320. return 'BufferNode';
  9321. }
  9322. /**
  9323. * Constructs a new buffer node.
  9324. *
  9325. * @param {Array<number>} value - Array-like buffer data.
  9326. * @param {string} bufferType - The data type of the buffer.
  9327. * @param {number} [bufferCount=0] - The count of buffer elements.
  9328. */
  9329. constructor( value, bufferType, bufferCount = 0 ) {
  9330. super( value, bufferType );
  9331. /**
  9332. * This flag can be used for type testing.
  9333. *
  9334. * @type {boolean}
  9335. * @readonly
  9336. * @default true
  9337. */
  9338. this.isBufferNode = true;
  9339. /**
  9340. * The data type of the buffer.
  9341. *
  9342. * @type {string}
  9343. */
  9344. this.bufferType = bufferType;
  9345. /**
  9346. * The uniform node that holds the value of the reference node.
  9347. *
  9348. * @type {number}
  9349. * @default 0
  9350. */
  9351. this.bufferCount = bufferCount;
  9352. /**
  9353. * An array of update ranges.
  9354. *
  9355. * @type {Array<{start: number, count: number}>}
  9356. */
  9357. this.updateRanges = [];
  9358. }
  9359. /**
  9360. * Adds a range of data in the data array to be updated on the GPU.
  9361. *
  9362. * @param {number} start - Position at which to start update.
  9363. * @param {number} count - The number of components to update.
  9364. */
  9365. addUpdateRange( start, count ) {
  9366. this.updateRanges.push( { start, count } );
  9367. }
  9368. /**
  9369. * Clears the update ranges.
  9370. */
  9371. clearUpdateRanges() {
  9372. this.updateRanges.length = 0;
  9373. }
  9374. /**
  9375. * The data type of the buffer elements.
  9376. *
  9377. * @param {NodeBuilder} builder - The current node builder.
  9378. * @return {string} The element type.
  9379. */
  9380. getElementType( builder ) {
  9381. return this.getNodeType( builder );
  9382. }
  9383. /**
  9384. * Overwrites the default implementation to return a fixed value `'buffer'`.
  9385. *
  9386. * @param {NodeBuilder} builder - The current node builder.
  9387. * @return {string} The input type.
  9388. */
  9389. getInputType( /*builder*/ ) {
  9390. return 'buffer';
  9391. }
  9392. }
  9393. /**
  9394. * TSL function for creating a buffer node.
  9395. *
  9396. * @tsl
  9397. * @function
  9398. * @param {Array<number>} value - Array-like buffer data.
  9399. * @param {string} type - The data type of a buffer element.
  9400. * @param {number} count - The count of buffer elements.
  9401. * @returns {BufferNode}
  9402. */
  9403. const buffer = ( value, type, count ) => new BufferNode( value, type, count );
  9404. /**
  9405. * Represents the element access on uniform array nodes.
  9406. *
  9407. * @augments ArrayElementNode
  9408. */
  9409. class UniformArrayElementNode extends ArrayElementNode {
  9410. static get type() {
  9411. return 'UniformArrayElementNode';
  9412. }
  9413. /**
  9414. * Constructs a new buffer node.
  9415. *
  9416. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  9417. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  9418. */
  9419. constructor( uniformArrayNode, indexNode ) {
  9420. super( uniformArrayNode, indexNode );
  9421. /**
  9422. * This flag can be used for type testing.
  9423. *
  9424. * @type {boolean}
  9425. * @readonly
  9426. * @default true
  9427. */
  9428. this.isArrayBufferElementNode = true;
  9429. }
  9430. generate( builder ) {
  9431. const snippet = super.generate( builder );
  9432. const type = this.getNodeType( builder );
  9433. const paddedType = this.node.getPaddedType();
  9434. return builder.format( snippet, paddedType, type );
  9435. }
  9436. }
  9437. /**
  9438. * Similar to {@link BufferNode} this module represents array-like data as
  9439. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  9440. * data types in the array (e.g `three.js` primitives) and automatically
  9441. * manage buffer padding. It should be the first choice when working with
  9442. * uniforms buffers.
  9443. * ```js
  9444. * const tintColors = uniformArray( [
  9445. * new Color( 1, 0, 0 ),
  9446. * new Color( 0, 1, 0 ),
  9447. * new Color( 0, 0, 1 )
  9448. * ], 'color' );
  9449. *
  9450. * const redColor = tintColors.element( 0 );
  9451. *
  9452. * @augments BufferNode
  9453. */
  9454. class UniformArrayNode extends BufferNode {
  9455. static get type() {
  9456. return 'UniformArrayNode';
  9457. }
  9458. /**
  9459. * Constructs a new uniform array node.
  9460. *
  9461. * @param {Array<any>} value - Array holding the buffer data.
  9462. * @param {?string} [elementType=null] - The data type of a buffer element.
  9463. */
  9464. constructor( value, elementType = null ) {
  9465. super( null );
  9466. /**
  9467. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  9468. * hold number primitives as well as three.js objects like vectors, matrices
  9469. * or colors.
  9470. *
  9471. * @type {Array<any>}
  9472. */
  9473. this.array = value;
  9474. /**
  9475. * The data type of an array element.
  9476. *
  9477. * @type {string}
  9478. */
  9479. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  9480. /**
  9481. * The padded type. Uniform buffers must conform to a certain buffer layout
  9482. * so a separate type is computed to ensure correct buffer size.
  9483. *
  9484. * @type {string}
  9485. */
  9486. this.paddedType = this.getPaddedType();
  9487. /**
  9488. * Overwritten since uniform array nodes are updated per render.
  9489. *
  9490. * @type {string}
  9491. * @default 'render'
  9492. */
  9493. this.updateType = NodeUpdateType.RENDER;
  9494. /**
  9495. * This flag can be used for type testing.
  9496. *
  9497. * @type {boolean}
  9498. * @readonly
  9499. * @default true
  9500. */
  9501. this.isArrayBufferNode = true;
  9502. }
  9503. /**
  9504. * This method is overwritten since the node type is inferred from the
  9505. * {@link UniformArrayNode#paddedType}.
  9506. *
  9507. * @param {NodeBuilder} builder - The current node builder.
  9508. * @return {string} The node type.
  9509. */
  9510. generateNodeType( /*builder*/ ) {
  9511. return this.paddedType;
  9512. }
  9513. /**
  9514. * The data type of the array elements.
  9515. *
  9516. * @param {NodeBuilder} builder - The current node builder.
  9517. * @return {string} The element type.
  9518. */
  9519. getElementType() {
  9520. return this.elementType;
  9521. }
  9522. /**
  9523. * Returns the padded type based on the element type.
  9524. *
  9525. * @return {string} The padded type.
  9526. */
  9527. getPaddedType() {
  9528. const elementType = this.elementType;
  9529. let paddedType = 'vec4';
  9530. if ( elementType === 'mat2' ) {
  9531. paddedType = 'mat2';
  9532. } else if ( /mat/.test( elementType ) === true ) {
  9533. paddedType = 'mat4';
  9534. } else if ( elementType.charAt( 0 ) === 'i' ) {
  9535. paddedType = 'ivec4';
  9536. } else if ( elementType.charAt( 0 ) === 'u' ) {
  9537. paddedType = 'uvec4';
  9538. }
  9539. return paddedType;
  9540. }
  9541. /**
  9542. * The update makes sure to correctly transfer the data from the (complex) objects
  9543. * in the array to the internal, correctly padded value buffer.
  9544. *
  9545. * @param {NodeFrame} frame - A reference to the current node frame.
  9546. */
  9547. update( /*frame*/ ) {
  9548. const { array, value } = this;
  9549. const elementType = this.elementType;
  9550. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  9551. for ( let i = 0; i < array.length; i ++ ) {
  9552. const index = i * 4;
  9553. value[ index ] = array[ i ];
  9554. }
  9555. } else if ( elementType === 'color' ) {
  9556. for ( let i = 0; i < array.length; i ++ ) {
  9557. const index = i * 4;
  9558. const vector = array[ i ];
  9559. value[ index ] = vector.r;
  9560. value[ index + 1 ] = vector.g;
  9561. value[ index + 2 ] = vector.b || 0;
  9562. //value[ index + 3 ] = vector.a || 0;
  9563. }
  9564. } else if ( elementType === 'mat2' ) {
  9565. for ( let i = 0; i < array.length; i ++ ) {
  9566. const index = i * 4;
  9567. const matrix = array[ i ];
  9568. value[ index ] = matrix.elements[ 0 ];
  9569. value[ index + 1 ] = matrix.elements[ 1 ];
  9570. value[ index + 2 ] = matrix.elements[ 2 ];
  9571. value[ index + 3 ] = matrix.elements[ 3 ];
  9572. }
  9573. } else if ( elementType === 'mat3' ) {
  9574. for ( let i = 0; i < array.length; i ++ ) {
  9575. const index = i * 16;
  9576. const matrix = array[ i ];
  9577. value[ index ] = matrix.elements[ 0 ];
  9578. value[ index + 1 ] = matrix.elements[ 1 ];
  9579. value[ index + 2 ] = matrix.elements[ 2 ];
  9580. value[ index + 4 ] = matrix.elements[ 3 ];
  9581. value[ index + 5 ] = matrix.elements[ 4 ];
  9582. value[ index + 6 ] = matrix.elements[ 5 ];
  9583. value[ index + 8 ] = matrix.elements[ 6 ];
  9584. value[ index + 9 ] = matrix.elements[ 7 ];
  9585. value[ index + 10 ] = matrix.elements[ 8 ];
  9586. value[ index + 15 ] = 1;
  9587. }
  9588. } else if ( elementType === 'mat4' ) {
  9589. for ( let i = 0; i < array.length; i ++ ) {
  9590. const index = i * 16;
  9591. const matrix = array[ i ];
  9592. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  9593. value[ index + i ] = matrix.elements[ i ];
  9594. }
  9595. }
  9596. } else {
  9597. for ( let i = 0; i < array.length; i ++ ) {
  9598. const index = i * 4;
  9599. const vector = array[ i ];
  9600. value[ index ] = vector.x;
  9601. value[ index + 1 ] = vector.y;
  9602. value[ index + 2 ] = vector.z || 0;
  9603. value[ index + 3 ] = vector.w || 0;
  9604. }
  9605. }
  9606. }
  9607. /**
  9608. * Implement the value buffer creation based on the array data.
  9609. *
  9610. * @param {NodeBuilder} builder - A reference to the current node builder.
  9611. * @return {null}
  9612. */
  9613. setup( builder ) {
  9614. const length = this.array.length;
  9615. const elementType = this.elementType;
  9616. let arrayType = Float32Array;
  9617. const paddedType = this.paddedType;
  9618. const paddedElementLength = builder.getTypeLength( paddedType );
  9619. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  9620. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  9621. this.value = new arrayType( length * paddedElementLength );
  9622. this.bufferCount = length;
  9623. this.bufferType = paddedType;
  9624. this.update(); // initialize the buffer values
  9625. return super.setup( builder );
  9626. }
  9627. /**
  9628. * Overwrites the default `element()` method to provide element access
  9629. * based on {@link UniformArrayNode}.
  9630. *
  9631. * @param {IndexNode} indexNode - The index node.
  9632. * @return {UniformArrayElementNode}
  9633. */
  9634. element( indexNode ) {
  9635. return new UniformArrayElementNode( this, nodeObject( indexNode ) );
  9636. }
  9637. }
  9638. /**
  9639. * TSL function for creating an uniform array node.
  9640. *
  9641. * @tsl
  9642. * @function
  9643. * @param {Array<any>} values - Array-like data.
  9644. * @param {?string} [nodeType] - The data type of the array elements.
  9645. * @returns {UniformArrayNode}
  9646. */
  9647. const uniformArray = ( values, nodeType ) => new UniformArrayNode( values, nodeType );
  9648. /**
  9649. * The node allows to set values for built-in shader variables. That is
  9650. * required for features like hardware-accelerated vertex clipping.
  9651. *
  9652. * @augments Node
  9653. */
  9654. class BuiltinNode extends Node {
  9655. /**
  9656. * Constructs a new builtin node.
  9657. *
  9658. * @param {string} name - The name of the built-in shader variable.
  9659. */
  9660. constructor( name ) {
  9661. super( 'float' );
  9662. /**
  9663. * The name of the built-in shader variable.
  9664. *
  9665. * @type {string}
  9666. */
  9667. this.name = name;
  9668. /**
  9669. * This flag can be used for type testing.
  9670. *
  9671. * @type {boolean}
  9672. * @readonly
  9673. * @default true
  9674. */
  9675. this.isBuiltinNode = true;
  9676. }
  9677. /**
  9678. * Generates the code snippet of the builtin node.
  9679. *
  9680. * @param {NodeBuilder} builder - The current node builder.
  9681. * @return {string} The generated code snippet.
  9682. */
  9683. generate( /* builder */ ) {
  9684. return this.name;
  9685. }
  9686. }
  9687. /**
  9688. * TSL function for creating a builtin node.
  9689. *
  9690. * @tsl
  9691. * @function
  9692. * @param {string} name - The name of the built-in shader variable.
  9693. * @returns {BuiltinNode}
  9694. */
  9695. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  9696. let _screenSizeVec, _viewportVec;
  9697. /**
  9698. * This node provides a collection of screen related metrics.
  9699. * Depending on {@link ScreenNode#scope}, the nodes can represent
  9700. * resolution or viewport data as well as fragment or uv coordinates.
  9701. *
  9702. * @augments Node
  9703. */
  9704. class ScreenNode extends Node {
  9705. static get type() {
  9706. return 'ScreenNode';
  9707. }
  9708. /**
  9709. * Constructs a new screen node.
  9710. *
  9711. * @param {('coordinate'|'viewport'|'size'|'uv'|'dpr')} scope - The node's scope.
  9712. */
  9713. constructor( scope ) {
  9714. super();
  9715. /**
  9716. * The node represents different metric depending on which scope is selected.
  9717. *
  9718. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  9719. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  9720. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  9721. * - `ScreenNode.UV`: Normalized coordinates.
  9722. * - `ScreenNode.DPR`: Device pixel ratio.
  9723. *
  9724. * @type {('coordinate'|'viewport'|'size'|'uv'|'dpr')}
  9725. */
  9726. this.scope = scope;
  9727. /**
  9728. * This output node.
  9729. *
  9730. * @private
  9731. * @type {?Node}
  9732. * @default null
  9733. */
  9734. this._output = null;
  9735. /**
  9736. * This flag can be used for type testing.
  9737. *
  9738. * @type {boolean}
  9739. * @readonly
  9740. * @default true
  9741. */
  9742. this.isViewportNode = true;
  9743. }
  9744. /**
  9745. * This method is overwritten since the node type depends on the selected scope.
  9746. *
  9747. * @return {('float'|'vec2'|'vec4')} The node type.
  9748. */
  9749. generateNodeType() {
  9750. if ( this.scope === ScreenNode.DPR ) return 'float';
  9751. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  9752. else return 'vec2';
  9753. }
  9754. /**
  9755. * This method is overwritten since the node's update type depends on the selected scope.
  9756. *
  9757. * @return {NodeUpdateType} The update type.
  9758. */
  9759. getUpdateType() {
  9760. let updateType = NodeUpdateType.NONE;
  9761. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT || this.scope === ScreenNode.DPR ) {
  9762. updateType = NodeUpdateType.RENDER;
  9763. }
  9764. this.updateType = updateType;
  9765. return updateType;
  9766. }
  9767. /**
  9768. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  9769. * from the current renderer.
  9770. *
  9771. * @param {NodeFrame} frame - A reference to the current node frame.
  9772. */
  9773. update( { renderer } ) {
  9774. const renderTarget = renderer.getRenderTarget();
  9775. if ( this.scope === ScreenNode.VIEWPORT ) {
  9776. if ( renderTarget !== null ) {
  9777. _viewportVec.copy( renderTarget.viewport );
  9778. } else {
  9779. renderer.getViewport( _viewportVec );
  9780. _viewportVec.multiplyScalar( renderer.getPixelRatio() );
  9781. }
  9782. } else if ( this.scope === ScreenNode.DPR ) {
  9783. this._output.value = renderer.getPixelRatio();
  9784. } else {
  9785. if ( renderTarget !== null ) {
  9786. _screenSizeVec.width = renderTarget.width;
  9787. _screenSizeVec.height = renderTarget.height;
  9788. } else {
  9789. renderer.getDrawingBufferSize( _screenSizeVec );
  9790. }
  9791. }
  9792. }
  9793. setup( /*builder*/ ) {
  9794. const scope = this.scope;
  9795. let output = null;
  9796. if ( scope === ScreenNode.SIZE ) {
  9797. output = uniform( _screenSizeVec || ( _screenSizeVec = new Vector2() ) );
  9798. } else if ( scope === ScreenNode.VIEWPORT ) {
  9799. output = uniform( _viewportVec || ( _viewportVec = new Vector4() ) );
  9800. } else if ( scope === ScreenNode.DPR ) {
  9801. output = uniform( 1 );
  9802. } else {
  9803. output = vec2( screenCoordinate.div( screenSize ) );
  9804. }
  9805. this._output = output;
  9806. return output;
  9807. }
  9808. generate( builder ) {
  9809. if ( this.scope === ScreenNode.COORDINATE ) {
  9810. let coord = builder.getFragCoord();
  9811. if ( builder.isFlipY() ) {
  9812. // follow webgpu standards
  9813. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  9814. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  9815. }
  9816. return coord;
  9817. }
  9818. return super.generate( builder );
  9819. }
  9820. }
  9821. ScreenNode.COORDINATE = 'coordinate';
  9822. ScreenNode.VIEWPORT = 'viewport';
  9823. ScreenNode.SIZE = 'size';
  9824. ScreenNode.UV = 'uv';
  9825. ScreenNode.DPR = 'dpr';
  9826. // Screen
  9827. /**
  9828. * TSL object that represents the current DPR.
  9829. *
  9830. * @tsl
  9831. * @type {ScreenNode<float>}
  9832. */
  9833. const screenDPR = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.DPR );
  9834. /**
  9835. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  9836. *
  9837. * @tsl
  9838. * @type {ScreenNode<vec2>}
  9839. */
  9840. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  9841. /**
  9842. * TSL object that represents the screen resolution in physical pixel units.
  9843. *
  9844. * @tsl
  9845. * @type {ScreenNode<vec2>}
  9846. */
  9847. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  9848. /**
  9849. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  9850. *
  9851. * @tsl
  9852. * @type {ScreenNode<vec2>}
  9853. */
  9854. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  9855. // Viewport
  9856. /**
  9857. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  9858. *
  9859. * @tsl
  9860. * @type {ScreenNode<vec4>}
  9861. */
  9862. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  9863. /**
  9864. * TSL object that represents the viewport resolution in physical pixel units.
  9865. *
  9866. * @tsl
  9867. * @type {ScreenNode<vec2>}
  9868. */
  9869. const viewportSize = viewport.zw;
  9870. /**
  9871. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  9872. *
  9873. * @tsl
  9874. * @type {ScreenNode<vec2>}
  9875. */
  9876. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  9877. /**
  9878. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  9879. *
  9880. * @tsl
  9881. * @type {ScreenNode<vec2>}
  9882. */
  9883. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  9884. // Deprecated
  9885. /**
  9886. * @deprecated since r169. Use {@link screenSize} instead.
  9887. */
  9888. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  9889. warn( 'TSL: "viewportResolution" is deprecated. Use "screenSize" instead.', new StackTrace() );
  9890. return screenSize;
  9891. }, 'vec2' ).once() )();
  9892. // Cache node uniforms
  9893. let _cameraProjectionMatrixBase = null;
  9894. let _cameraProjectionMatrixArray = null;
  9895. let _cameraProjectionMatrixInverseBase = null;
  9896. let _cameraProjectionMatrixInverseArray = null;
  9897. let _cameraViewMatrixBase = null;
  9898. let _cameraViewMatrixArray = null;
  9899. let _cameraWorldMatrixBase = null;
  9900. let _cameraWorldMatrixArray = null;
  9901. let _cameraNormalMatrixBase = null;
  9902. let _cameraNormalMatrixArray = null;
  9903. let _cameraPositionBase = null;
  9904. let _cameraPositionArray = null;
  9905. let _cameraViewportBase = null;
  9906. let _cameraViewportArray = null;
  9907. /**
  9908. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  9909. *
  9910. * @tsl
  9911. * @type {UniformNode<uint>}
  9912. */
  9913. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setName( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  9914. /**
  9915. * TSL object that represents the `near` value of the camera used for the current render.
  9916. *
  9917. * @tsl
  9918. * @type {UniformNode<float>}
  9919. */
  9920. const cameraNear = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  9921. /**
  9922. * TSL object that represents the `far` value of the camera used for the current render.
  9923. *
  9924. * @tsl
  9925. * @type {UniformNode<float>}
  9926. */
  9927. const cameraFar = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  9928. /**
  9929. * TSL object that represents the projection matrix of the camera used for the current render.
  9930. *
  9931. * @tsl
  9932. * @type {UniformNode<mat4>}
  9933. */
  9934. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9935. let cameraProjectionMatrix;
  9936. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9937. const matrices = [];
  9938. for ( const subCamera of camera.cameras ) {
  9939. matrices.push( subCamera.projectionMatrix );
  9940. }
  9941. if ( _cameraProjectionMatrixArray === null ) {
  9942. _cameraProjectionMatrixArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatrices' );
  9943. } else {
  9944. _cameraProjectionMatrixArray.array = matrices;
  9945. }
  9946. cameraProjectionMatrix = _cameraProjectionMatrixArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrix' );
  9947. } else {
  9948. if ( _cameraProjectionMatrixBase === null ) {
  9949. _cameraProjectionMatrixBase = uniform( camera.projectionMatrix ).setName( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  9950. }
  9951. cameraProjectionMatrix = _cameraProjectionMatrixBase;
  9952. }
  9953. return cameraProjectionMatrix;
  9954. } ).once() )();
  9955. /**
  9956. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  9957. *
  9958. * @tsl
  9959. * @type {UniformNode<mat4>}
  9960. */
  9961. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9962. let cameraProjectionMatrixInverse;
  9963. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9964. const matrices = [];
  9965. for ( const subCamera of camera.cameras ) {
  9966. matrices.push( subCamera.projectionMatrixInverse );
  9967. }
  9968. if ( _cameraProjectionMatrixInverseArray === null ) {
  9969. _cameraProjectionMatrixInverseArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatricesInverse' );
  9970. } else {
  9971. _cameraProjectionMatrixInverseArray.array = matrices;
  9972. }
  9973. cameraProjectionMatrixInverse = _cameraProjectionMatrixInverseArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrixInverse' );
  9974. } else {
  9975. if ( _cameraProjectionMatrixInverseBase === null ) {
  9976. _cameraProjectionMatrixInverseBase = uniform( camera.projectionMatrixInverse ).setName( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  9977. }
  9978. cameraProjectionMatrixInverse = _cameraProjectionMatrixInverseBase;
  9979. }
  9980. return cameraProjectionMatrixInverse;
  9981. } ).once() )();
  9982. /**
  9983. * TSL object that represents the view matrix of the camera used for the current render.
  9984. *
  9985. * @tsl
  9986. * @type {UniformNode<mat4>}
  9987. */
  9988. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9989. let cameraViewMatrix;
  9990. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9991. const matrices = [];
  9992. for ( const subCamera of camera.cameras ) {
  9993. matrices.push( subCamera.matrixWorldInverse );
  9994. }
  9995. if ( _cameraViewMatrixArray === null ) {
  9996. _cameraViewMatrixArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraViewMatrices' );
  9997. } else {
  9998. _cameraViewMatrixArray.array = matrices;
  9999. }
  10000. cameraViewMatrix = _cameraViewMatrixArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraViewMatrix' );
  10001. } else {
  10002. if ( _cameraViewMatrixBase === null ) {
  10003. _cameraViewMatrixBase = uniform( camera.matrixWorldInverse ).setName( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  10004. }
  10005. cameraViewMatrix = _cameraViewMatrixBase;
  10006. }
  10007. return cameraViewMatrix;
  10008. } ).once() )();
  10009. /**
  10010. * TSL object that represents the world matrix of the camera used for the current render.
  10011. *
  10012. * @tsl
  10013. * @type {UniformNode<mat4>}
  10014. */
  10015. const cameraWorldMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  10016. let cameraWorldMatrix;
  10017. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  10018. const matrices = [];
  10019. for ( const subCamera of camera.cameras ) {
  10020. matrices.push( subCamera.matrixWorld );
  10021. }
  10022. if ( _cameraWorldMatrixArray === null ) {
  10023. _cameraWorldMatrixArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraWorldMatrices' );
  10024. } else {
  10025. _cameraWorldMatrixArray.array = matrices;
  10026. }
  10027. cameraWorldMatrix = _cameraWorldMatrixArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraWorldMatrix' );
  10028. } else {
  10029. if ( _cameraWorldMatrixBase === null ) {
  10030. _cameraWorldMatrixBase = uniform( camera.matrixWorld ).setName( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  10031. }
  10032. cameraWorldMatrix = _cameraWorldMatrixBase;
  10033. }
  10034. return cameraWorldMatrix;
  10035. } ).once() )();
  10036. /**
  10037. * TSL object that represents the normal matrix of the camera used for the current render.
  10038. *
  10039. * @tsl
  10040. * @type {UniformNode<mat3>}
  10041. */
  10042. const cameraNormalMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  10043. let cameraNormalMatrix;
  10044. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  10045. const matrices = [];
  10046. for ( const subCamera of camera.cameras ) {
  10047. matrices.push( subCamera.normalMatrix );
  10048. }
  10049. if ( _cameraNormalMatrixArray === null ) {
  10050. _cameraNormalMatrixArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraNormalMatrices' );
  10051. } else {
  10052. _cameraNormalMatrixArray.array = matrices;
  10053. }
  10054. cameraNormalMatrix = _cameraNormalMatrixArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraNormalMatrix' );
  10055. } else {
  10056. if ( _cameraNormalMatrixBase === null ) {
  10057. _cameraNormalMatrixBase = uniform( camera.normalMatrix ).setName( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  10058. }
  10059. cameraNormalMatrix = _cameraNormalMatrixBase;
  10060. }
  10061. return cameraNormalMatrix;
  10062. } ).once() )();
  10063. /**
  10064. * TSL object that represents the position in world space of the camera used for the current render.
  10065. *
  10066. * @tsl
  10067. * @type {UniformNode<vec3>}
  10068. */
  10069. const cameraPosition = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  10070. let cameraPosition;
  10071. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  10072. const positions = [];
  10073. for ( let i = 0, l = camera.cameras.length; i < l; i ++ ) {
  10074. positions.push( new Vector3() );
  10075. }
  10076. if ( _cameraPositionArray === null ) {
  10077. _cameraPositionArray = uniformArray( positions ).setGroup( renderGroup ).setName( 'cameraPositions' ).onRenderUpdate( ( { camera }, self ) => {
  10078. const subCameras = camera.cameras;
  10079. const array = self.array;
  10080. for ( let i = 0, l = subCameras.length; i < l; i ++ ) {
  10081. array[ i ].setFromMatrixPosition( subCameras[ i ].matrixWorld );
  10082. }
  10083. } );
  10084. } else {
  10085. _cameraPositionArray.array = positions;
  10086. }
  10087. cameraPosition = _cameraPositionArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraPosition' );
  10088. } else {
  10089. if ( _cameraPositionBase === null ) {
  10090. _cameraPositionBase = uniform( new Vector3() ).setName( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  10091. }
  10092. cameraPosition = _cameraPositionBase;
  10093. }
  10094. return cameraPosition;
  10095. } ).once() )();
  10096. /**
  10097. * TSL object that represents the viewport of the camera used for the current render.
  10098. *
  10099. * @tsl
  10100. * @type {UniformNode<vec4>}
  10101. */
  10102. const cameraViewport = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  10103. let cameraViewport;
  10104. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  10105. const viewports = [];
  10106. for ( const subCamera of camera.cameras ) {
  10107. viewports.push( subCamera.viewport );
  10108. }
  10109. if ( _cameraViewportArray === null ) {
  10110. _cameraViewportArray = uniformArray( viewports, 'vec4' ).setGroup( renderGroup ).setName( 'cameraViewports' );
  10111. } else {
  10112. _cameraViewportArray.array = viewports;
  10113. }
  10114. cameraViewport = _cameraViewportArray.element( cameraIndex ).toConst( 'cameraViewport' );
  10115. } else {
  10116. if ( _cameraViewportBase === null ) {
  10117. // Fallback for single camera
  10118. _cameraViewportBase = vec4( 0, 0, screenSize.x, screenSize.y ).toConst( 'cameraViewport' );
  10119. }
  10120. cameraViewport = _cameraViewportBase;
  10121. }
  10122. return cameraViewport;
  10123. } ).once() )();
  10124. const _sphere = /*@__PURE__*/ new Sphere();
  10125. /**
  10126. * This node can be used to access transformation related metrics of 3D objects.
  10127. * Depending on the selected scope, a different metric is represented as a uniform
  10128. * in the shader. The following scopes are supported:
  10129. *
  10130. * - `POSITION`: The object's position in world space.
  10131. * - `VIEW_POSITION`: The object's position in view/camera space.
  10132. * - `DIRECTION`: The object's direction in world space.
  10133. * - `SCALE`: The object's scale in world space.
  10134. * - `WORLD_MATRIX`: The object's matrix in world space.
  10135. *
  10136. * @augments Node
  10137. */
  10138. class Object3DNode extends Node {
  10139. static get type() {
  10140. return 'Object3DNode';
  10141. }
  10142. /**
  10143. * Constructs a new object 3D node.
  10144. *
  10145. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  10146. * @param {?Object3D} [object3d=null] - The 3D object.
  10147. */
  10148. constructor( scope, object3d = null ) {
  10149. super();
  10150. /**
  10151. * The node reports a different type of transformation depending on the scope.
  10152. *
  10153. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  10154. */
  10155. this.scope = scope;
  10156. /**
  10157. * The 3D object.
  10158. *
  10159. * @type {?Object3D}
  10160. * @default null
  10161. */
  10162. this.object3d = object3d;
  10163. /**
  10164. * Overwritten since this type of node is updated per object.
  10165. *
  10166. * @type {string}
  10167. * @default 'object'
  10168. */
  10169. this.updateType = NodeUpdateType.OBJECT;
  10170. /**
  10171. * Holds the value of the node as a uniform.
  10172. *
  10173. * @type {UniformNode}
  10174. */
  10175. this.uniformNode = new UniformNode( null );
  10176. }
  10177. /**
  10178. * Overwritten since the node type is inferred from the scope.
  10179. *
  10180. * @return {('mat4'|'vec3'|'float')} The node type.
  10181. */
  10182. generateNodeType() {
  10183. const scope = this.scope;
  10184. if ( scope === Object3DNode.WORLD_MATRIX ) {
  10185. return 'mat4';
  10186. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  10187. return 'vec3';
  10188. } else if ( scope === Object3DNode.RADIUS ) {
  10189. return 'float';
  10190. }
  10191. }
  10192. /**
  10193. * Updates the uniform value depending on the scope.
  10194. *
  10195. * @param {NodeFrame} frame - The current node frame.
  10196. */
  10197. update( frame ) {
  10198. const object = this.object3d;
  10199. const uniformNode = this.uniformNode;
  10200. const scope = this.scope;
  10201. if ( scope === Object3DNode.WORLD_MATRIX ) {
  10202. uniformNode.value = object.matrixWorld;
  10203. } else if ( scope === Object3DNode.POSITION ) {
  10204. uniformNode.value = uniformNode.value || new Vector3();
  10205. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  10206. } else if ( scope === Object3DNode.SCALE ) {
  10207. uniformNode.value = uniformNode.value || new Vector3();
  10208. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  10209. } else if ( scope === Object3DNode.DIRECTION ) {
  10210. uniformNode.value = uniformNode.value || new Vector3();
  10211. object.getWorldDirection( uniformNode.value );
  10212. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  10213. const camera = frame.camera;
  10214. uniformNode.value = uniformNode.value || new Vector3();
  10215. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  10216. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  10217. } else if ( scope === Object3DNode.RADIUS ) {
  10218. const geometry = frame.object.geometry;
  10219. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  10220. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  10221. uniformNode.value = _sphere.radius;
  10222. }
  10223. }
  10224. /**
  10225. * Generates the code snippet of the uniform node. The node type of the uniform
  10226. * node also depends on the selected scope.
  10227. *
  10228. * @param {NodeBuilder} builder - The current node builder.
  10229. * @return {string} The generated code snippet.
  10230. */
  10231. generate( builder ) {
  10232. const scope = this.scope;
  10233. if ( scope === Object3DNode.WORLD_MATRIX ) {
  10234. this.uniformNode.nodeType = 'mat4';
  10235. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  10236. this.uniformNode.nodeType = 'vec3';
  10237. } else if ( scope === Object3DNode.RADIUS ) {
  10238. this.uniformNode.nodeType = 'float';
  10239. }
  10240. return this.uniformNode.build( builder );
  10241. }
  10242. serialize( data ) {
  10243. super.serialize( data );
  10244. data.scope = this.scope;
  10245. }
  10246. deserialize( data ) {
  10247. super.deserialize( data );
  10248. this.scope = data.scope;
  10249. }
  10250. }
  10251. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  10252. Object3DNode.POSITION = 'position';
  10253. Object3DNode.SCALE = 'scale';
  10254. Object3DNode.VIEW_POSITION = 'viewPosition';
  10255. Object3DNode.DIRECTION = 'direction';
  10256. Object3DNode.RADIUS = 'radius';
  10257. /**
  10258. * TSL function for creating an object 3D node that represents the object's direction in world space.
  10259. *
  10260. * @tsl
  10261. * @function
  10262. * @param {?Object3D} [object3d] - The 3D object.
  10263. * @returns {Object3DNode<vec3>}
  10264. */
  10265. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  10266. /**
  10267. * TSL function for creating an object 3D node that represents the object's world matrix.
  10268. *
  10269. * @tsl
  10270. * @function
  10271. * @param {?Object3D} [object3d] - The 3D object.
  10272. * @returns {Object3DNode<mat4>}
  10273. */
  10274. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  10275. /**
  10276. * TSL function for creating an object 3D node that represents the object's position in world space.
  10277. *
  10278. * @tsl
  10279. * @function
  10280. * @param {?Object3D} [object3d] - The 3D object.
  10281. * @returns {Object3DNode<vec3>}
  10282. */
  10283. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  10284. /**
  10285. * TSL function for creating an object 3D node that represents the object's scale in world space.
  10286. *
  10287. * @tsl
  10288. * @function
  10289. * @param {?Object3D} [object3d] - The 3D object.
  10290. * @returns {Object3DNode<vec3>}
  10291. */
  10292. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  10293. /**
  10294. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  10295. *
  10296. * @tsl
  10297. * @function
  10298. * @param {?Object3D} [object3d] - The 3D object.
  10299. * @returns {Object3DNode<vec3>}
  10300. */
  10301. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  10302. /**
  10303. * TSL function for creating an object 3D node that represents the object's radius.
  10304. *
  10305. * @tsl
  10306. * @function
  10307. * @param {?Object3D} [object3d] - The 3D object.
  10308. * @returns {Object3DNode<float>}
  10309. */
  10310. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  10311. /**
  10312. * This type of node is a specialized version of `Object3DNode`
  10313. * with larger set of model related metrics. Unlike `Object3DNode`,
  10314. * `ModelNode` extracts the reference to the 3D object from the
  10315. * current node frame state.
  10316. *
  10317. * @augments Object3DNode
  10318. */
  10319. class ModelNode extends Object3DNode {
  10320. static get type() {
  10321. return 'ModelNode';
  10322. }
  10323. /**
  10324. * Constructs a new object model node.
  10325. *
  10326. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  10327. */
  10328. constructor( scope ) {
  10329. super( scope );
  10330. }
  10331. /**
  10332. * Extracts the model reference from the frame state and then
  10333. * updates the uniform value depending on the scope.
  10334. *
  10335. * @param {NodeFrame} frame - The current node frame.
  10336. */
  10337. update( frame ) {
  10338. this.object3d = frame.object;
  10339. super.update( frame );
  10340. }
  10341. }
  10342. /**
  10343. * TSL object that represents the object's direction in world space.
  10344. *
  10345. * @tsl
  10346. * @type {ModelNode<vec3>}
  10347. */
  10348. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  10349. /**
  10350. * TSL object that represents the object's world matrix.
  10351. *
  10352. * @tsl
  10353. * @type {ModelNode<mat4>}
  10354. */
  10355. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  10356. /**
  10357. * TSL object that represents the object's position in world space.
  10358. *
  10359. * @tsl
  10360. * @type {ModelNode<vec3>}
  10361. */
  10362. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  10363. /**
  10364. * TSL object that represents the object's scale in world space.
  10365. *
  10366. * @tsl
  10367. * @type {ModelNode<vec3>}
  10368. */
  10369. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  10370. /**
  10371. * TSL object that represents the object's position in view/camera space.
  10372. *
  10373. * @tsl
  10374. * @type {ModelNode<vec3>}
  10375. */
  10376. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  10377. /**
  10378. * TSL object that represents the object's radius.
  10379. *
  10380. * @tsl
  10381. * @type {ModelNode<float>}
  10382. */
  10383. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  10384. /**
  10385. * TSL object that represents the object's normal matrix.
  10386. *
  10387. * @tsl
  10388. * @type {UniformNode<mat3>}
  10389. */
  10390. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  10391. /**
  10392. * TSL object that represents the object's inverse world matrix.
  10393. *
  10394. * @tsl
  10395. * @type {UniformNode<mat4>}
  10396. */
  10397. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  10398. /**
  10399. * TSL object that represents the object's model view matrix.
  10400. *
  10401. * @tsl
  10402. * @type {Node<mat4>}
  10403. */
  10404. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  10405. return builder.context.modelViewMatrix || mediumpModelViewMatrix;
  10406. } ).once() )().toVar( 'modelViewMatrix' );
  10407. // GPU Precision
  10408. /**
  10409. * TSL object that represents the object's model view in `mediump` precision.
  10410. *
  10411. * @tsl
  10412. * @type {Node<mat4>}
  10413. */
  10414. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  10415. // CPU Precision
  10416. /**
  10417. * TSL object that represents the object's model view in `highp` precision
  10418. * which is achieved by computing the matrix in JS and not in the shader.
  10419. *
  10420. * @tsl
  10421. * @type {Node<mat4>}
  10422. */
  10423. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  10424. builder.context.isHighPrecisionModelViewMatrix = true;
  10425. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  10426. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  10427. } );
  10428. } ).once() )().toVar( 'highpModelViewMatrix' );
  10429. /**
  10430. * TSL object that represents the object's model normal view in `highp` precision
  10431. * which is achieved by computing the matrix in JS and not in the shader.
  10432. *
  10433. * @tsl
  10434. * @type {Node<mat3>}
  10435. */
  10436. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  10437. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  10438. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  10439. if ( isHighPrecisionModelViewMatrix !== true ) {
  10440. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  10441. }
  10442. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  10443. } );
  10444. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  10445. /**
  10446. * TSL object that represents the clip space position of the current rendered object.
  10447. *
  10448. * @tsl
  10449. * @type {VaryingNode<vec4>}
  10450. */
  10451. const clipSpace = /*@__PURE__*/ ( Fn( ( builder ) => {
  10452. if ( builder.shaderStage !== 'fragment' ) {
  10453. warnOnce( 'TSL: `clipSpace` is only available in fragment stage.' );
  10454. return vec4();
  10455. }
  10456. return builder.context.clipSpace.toVarying( 'v_clipSpace' );
  10457. } ).once() )();
  10458. /**
  10459. * TSL object that represents the position attribute of the current rendered object.
  10460. *
  10461. * @tsl
  10462. * @type {AttributeNode<vec3>}
  10463. */
  10464. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  10465. /**
  10466. * TSL object that represents the vertex position in local space of the current rendered object.
  10467. *
  10468. * @tsl
  10469. * @type {AttributeNode<vec3>}
  10470. */
  10471. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  10472. /**
  10473. * TSL object that represents the previous vertex position in local space of the current rendered object.
  10474. * Used in context of {@link VelocityNode} for rendering motion vectors.
  10475. *
  10476. * @tsl
  10477. * @type {AttributeNode<vec3>}
  10478. */
  10479. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  10480. /**
  10481. * TSL object that represents the vertex position in world space of the current rendered object.
  10482. *
  10483. * @tsl
  10484. * @type {VaryingNode<vec3>}
  10485. */
  10486. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  10487. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getSubBuildProperty( 'v_positionWorld' ) );
  10488. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  10489. /**
  10490. * TSL object that represents the position world direction of the current rendered object.
  10491. *
  10492. * @tsl
  10493. * @type {Node<vec3>}
  10494. */
  10495. const positionWorldDirection = /*@__PURE__*/ ( Fn( () => {
  10496. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' );
  10497. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  10498. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  10499. /**
  10500. * TSL object that represents the vertex position in view space of the current rendered object.
  10501. *
  10502. * @tsl
  10503. * @type {VaryingNode<vec3>}
  10504. */
  10505. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  10506. if ( builder.shaderStage === 'fragment' && builder.material.vertexNode ) {
  10507. // reconstruct view position from clip space
  10508. const viewPos = cameraProjectionMatrixInverse.mul( clipSpace );
  10509. return viewPos.xyz.div( viewPos.w ).toVar( 'positionView' );
  10510. }
  10511. return builder.context.setupPositionView().toVarying( 'v_positionView' );
  10512. }, 'vec3' ).once( [ 'POSITION', 'VERTEX' ] ) )();
  10513. /**
  10514. * TSL object that represents the position view direction of the current rendered object.
  10515. *
  10516. * @tsl
  10517. * @type {VaryingNode<vec3>}
  10518. */
  10519. const positionViewDirection = /*@__PURE__*/ ( Fn( ( builder ) => {
  10520. let output;
  10521. if ( builder.camera.isOrthographicCamera ) {
  10522. output = vec3( 0, 0, 1 );
  10523. } else {
  10524. output = positionView.negate().toVarying( 'v_positionViewDirection' ).normalize();
  10525. }
  10526. return output.toVar( 'positionViewDirection' );
  10527. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  10528. /**
  10529. * This node can be used to evaluate whether a primitive is front or back facing.
  10530. *
  10531. * @augments Node
  10532. */
  10533. class FrontFacingNode extends Node {
  10534. static get type() {
  10535. return 'FrontFacingNode';
  10536. }
  10537. /**
  10538. * Constructs a new front facing node.
  10539. */
  10540. constructor() {
  10541. super( 'bool' );
  10542. /**
  10543. * This flag can be used for type testing.
  10544. *
  10545. * @type {boolean}
  10546. * @readonly
  10547. * @default true
  10548. */
  10549. this.isFrontFacingNode = true;
  10550. }
  10551. generate( builder ) {
  10552. if ( builder.shaderStage !== 'fragment' ) return 'true';
  10553. //
  10554. const { material } = builder;
  10555. if ( material.side === BackSide ) {
  10556. return 'false';
  10557. }
  10558. return builder.getFrontFacing();
  10559. }
  10560. }
  10561. /**
  10562. * TSL object that represents whether a primitive is front or back facing
  10563. *
  10564. * @tsl
  10565. * @type {FrontFacingNode<bool>}
  10566. */
  10567. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  10568. /**
  10569. * TSL object that represents the front facing status as a number instead of a bool.
  10570. * `1` means front facing, `-1` means back facing.
  10571. *
  10572. * @tsl
  10573. * @type {Node<float>}
  10574. */
  10575. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  10576. /**
  10577. * Converts a direction vector to a face direction vector based on the material's side.
  10578. *
  10579. * If the material is set to `BackSide`, the direction is inverted.
  10580. * If the material is set to `DoubleSide`, the direction is multiplied by `faceDirection`.
  10581. *
  10582. * @tsl
  10583. * @param {Node<vec3>} direction - The direction vector to convert.
  10584. * @returns {Node<vec3>} The converted direction vector.
  10585. */
  10586. const directionToFaceDirection = /*@__PURE__*/ Fn( ( [ direction ], { material } ) => {
  10587. const side = material.side;
  10588. if ( side === BackSide ) {
  10589. direction = direction.mul( -1 );
  10590. } else if ( side === DoubleSide ) {
  10591. direction = direction.mul( faceDirection );
  10592. }
  10593. return direction;
  10594. } );
  10595. /**
  10596. * TSL object that represents the normal attribute of the current rendered object in local space.
  10597. *
  10598. * @tsl
  10599. * @type {Node<vec3>}
  10600. */
  10601. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  10602. /**
  10603. * TSL object that represents the vertex normal of the current rendered object in local space.
  10604. *
  10605. * @tsl
  10606. * @type {Node<vec3>}
  10607. */
  10608. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  10609. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  10610. warn( 'TSL: Vertex attribute "normal" not found on geometry.' );
  10611. return vec3( 0, 1, 0 );
  10612. }
  10613. return normalGeometry;
  10614. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  10615. /**
  10616. * TSL object that represents the flat vertex normal of the current rendered object in view space.
  10617. *
  10618. * @tsl
  10619. * @type {Node<vec3>}
  10620. */
  10621. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  10622. /**
  10623. * TSL object that represents the vertex normal of the current rendered object in view space.
  10624. *
  10625. * @tsl
  10626. * @type {Node<vec3>}
  10627. */
  10628. const normalViewGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  10629. let node;
  10630. if ( builder.isFlatShading() ) {
  10631. node = normalFlat;
  10632. } else {
  10633. node = transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry' ).normalize();
  10634. }
  10635. return node;
  10636. }, 'vec3' ).once() )().toVar( 'normalViewGeometry' );
  10637. /**
  10638. * TSL object that represents the vertex normal of the current rendered object in world space.
  10639. *
  10640. * @tsl
  10641. * @type {Node<vec3>}
  10642. */
  10643. const normalWorldGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  10644. let normal = normalViewGeometry.transformDirection( cameraViewMatrix );
  10645. if ( builder.isFlatShading() !== true ) {
  10646. normal = normal.toVarying( 'v_normalWorldGeometry' );
  10647. }
  10648. return normal.normalize().toVar( 'normalWorldGeometry' );
  10649. }, 'vec3' ).once() )();
  10650. /**
  10651. * TSL object that represents the vertex normal of the current rendered object in view space.
  10652. *
  10653. * @tsl
  10654. * @type {Node<vec3>}
  10655. */
  10656. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  10657. let node;
  10658. if ( builder.subBuildFn === 'NORMAL' || builder.subBuildFn === 'VERTEX' ) {
  10659. node = normalViewGeometry;
  10660. if ( builder.isFlatShading() !== true ) {
  10661. node = directionToFaceDirection( node );
  10662. }
  10663. } else {
  10664. // Use custom context to avoid side effects from nodes overwriting getUV, getTextureLevel in the context (e.g. EnvironmentNode)
  10665. node = builder.context.setupNormal().context( { getUV: null, getTextureLevel: null } );
  10666. }
  10667. return node;
  10668. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'normalView' );
  10669. /**
  10670. * TSL object that represents the vertex normal of the current rendered object in world space.
  10671. *
  10672. * @tsl
  10673. * @type {Node<vec3>}
  10674. */
  10675. const normalWorld = /*@__PURE__*/ normalView.transformDirection( cameraViewMatrix ).toVar( 'normalWorld' );
  10676. /**
  10677. * TSL object that represents the clearcoat vertex normal of the current rendered object in view space.
  10678. *
  10679. * @tsl
  10680. * @type {Node<vec3>}
  10681. */
  10682. const clearcoatNormalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, context } ) => {
  10683. let node;
  10684. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  10685. node = normalView;
  10686. } else {
  10687. // Use custom context to avoid side effects from nodes overwriting getUV, getTextureLevel in the context (e.g. EnvironmentNode)
  10688. node = context.setupClearcoatNormal().context( { getUV: null, getTextureLevel: null } );
  10689. }
  10690. return node;
  10691. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'clearcoatNormalView' );
  10692. /**
  10693. * Transforms the normal with the given matrix.
  10694. *
  10695. * @tsl
  10696. * @function
  10697. * @param {Node<vec3>} normal - The normal.
  10698. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  10699. * @return {Node<vec3>} The transformed normal.
  10700. */
  10701. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  10702. const m = mat3( matrix );
  10703. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  10704. return m.mul( transformedNormal ).xyz;
  10705. } );
  10706. /**
  10707. * Transforms the given normal from local to view space.
  10708. *
  10709. * @tsl
  10710. * @function
  10711. * @param {Node<vec3>} normal - The normal.
  10712. * @param {NodeBuilder} builder - The current node builder.
  10713. * @return {Node<vec3>} The transformed normal.
  10714. */
  10715. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  10716. const modelNormalViewMatrix = builder.context.modelNormalViewMatrix;
  10717. if ( modelNormalViewMatrix ) {
  10718. return modelNormalViewMatrix.transformDirection( normal );
  10719. }
  10720. //
  10721. const transformedNormal = modelNormalMatrix.mul( normal );
  10722. return cameraViewMatrix.transformDirection( transformedNormal );
  10723. } );
  10724. // Deprecated
  10725. /**
  10726. * TSL object that represents the transformed vertex normal of the current rendered object in view space.
  10727. *
  10728. * @tsl
  10729. * @type {Node<vec3>}
  10730. * @deprecated since r178. Use `normalView` instead.
  10731. */
  10732. const transformedNormalView = ( Fn( () => { // @deprecated, r177
  10733. warn( 'TSL: "transformedNormalView" is deprecated. Use "normalView" instead.' );
  10734. return normalView;
  10735. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10736. /**
  10737. * TSL object that represents the transformed vertex normal of the current rendered object in world space.
  10738. *
  10739. * @tsl
  10740. * @type {Node<vec3>}
  10741. * @deprecated since r178. Use `normalWorld` instead.
  10742. */
  10743. const transformedNormalWorld = ( Fn( () => { // @deprecated, r177
  10744. warn( 'TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.' );
  10745. return normalWorld;
  10746. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10747. /**
  10748. * TSL object that represents the transformed clearcoat vertex normal of the current rendered object in view space.
  10749. *
  10750. * @tsl
  10751. * @type {Node<vec3>}
  10752. * @deprecated since r178. Use `clearcoatNormalView` instead.
  10753. */
  10754. const transformedClearcoatNormalView = ( Fn( () => { // @deprecated, r177
  10755. warn( 'TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.' );
  10756. return clearcoatNormalView;
  10757. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10758. const _m1$1 = /*@__PURE__*/ new Matrix4();
  10759. /**
  10760. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  10761. *
  10762. * @tsl
  10763. * @type {UniformNode<float>}
  10764. */
  10765. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  10766. /**
  10767. * TSL object that represents the intensity of environment maps of PBR materials.
  10768. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  10769. *
  10770. * @tsl
  10771. * @type {Node<float>}
  10772. */
  10773. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  10774. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  10775. } );
  10776. /**
  10777. * TSL object that represents the rotation of environment maps.
  10778. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  10779. * rotation of `scene.environment` instead.
  10780. *
  10781. * @tsl
  10782. * @type {Node<mat4>}
  10783. */
  10784. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  10785. return frame.material;
  10786. } ).onObjectUpdate( function ( { material, scene } ) {
  10787. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  10788. if ( rotation ) {
  10789. // note: since the matrix is orthonormal, we can use the more-efficient transpose() in lieu of invert()
  10790. _m1$1.makeRotationFromEuler( rotation ).transpose();
  10791. } else {
  10792. _m1$1.identity();
  10793. }
  10794. return _m1$1;
  10795. } );
  10796. /**
  10797. * The reflect vector in view space.
  10798. *
  10799. * @tsl
  10800. * @type {Node<vec3>}
  10801. */
  10802. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( normalView );
  10803. /**
  10804. * The refract vector in view space.
  10805. *
  10806. * @tsl
  10807. * @type {Node<vec3>}
  10808. */
  10809. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( normalView, materialRefractionRatio );
  10810. /**
  10811. * Used for sampling cube maps when using cube reflection mapping.
  10812. *
  10813. * @tsl
  10814. * @type {Node<vec3>}
  10815. */
  10816. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  10817. /**
  10818. * Used for sampling cube maps when using cube refraction mapping.
  10819. *
  10820. * @tsl
  10821. * @type {Node<vec3>}
  10822. */
  10823. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  10824. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  10825. /**
  10826. * This type of uniform node represents a cube texture.
  10827. *
  10828. * @augments TextureNode
  10829. */
  10830. class CubeTextureNode extends TextureNode {
  10831. static get type() {
  10832. return 'CubeTextureNode';
  10833. }
  10834. /**
  10835. * Constructs a new cube texture node.
  10836. *
  10837. * @param {CubeTexture} value - The cube texture.
  10838. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10839. * @param {?Node<int>} [levelNode=null] - The level node.
  10840. * @param {?Node<float>} [biasNode=null] - The bias node.
  10841. */
  10842. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  10843. super( value, uvNode, levelNode, biasNode );
  10844. /**
  10845. * This flag can be used for type testing.
  10846. *
  10847. * @type {boolean}
  10848. * @readonly
  10849. * @default true
  10850. */
  10851. this.isCubeTextureNode = true;
  10852. }
  10853. /**
  10854. * Overwrites the default implementation to return the appropriate cube texture type.
  10855. *
  10856. * @param {NodeBuilder} builder - The current node builder.
  10857. * @return {string} The input type.
  10858. */
  10859. getInputType( /*builder*/ ) {
  10860. if ( this.value.isDepthTexture === true ) {
  10861. return 'cubeDepthTexture';
  10862. }
  10863. return 'cubeTexture';
  10864. }
  10865. /**
  10866. * Returns a default uvs based on the mapping type of the cube texture.
  10867. *
  10868. * @return {Node<vec3>} The default uv attribute.
  10869. */
  10870. getDefaultUV() {
  10871. const texture = this.value;
  10872. if ( texture.mapping === CubeReflectionMapping ) {
  10873. return reflectVector;
  10874. } else if ( texture.mapping === CubeRefractionMapping ) {
  10875. return refractVector;
  10876. } else {
  10877. error( 'CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  10878. return vec3( 0, 0, 0 );
  10879. }
  10880. }
  10881. /**
  10882. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  10883. * for cube textures. The uv transformation matrix is not applied to cube textures.
  10884. *
  10885. * @param {boolean} value - The update toggle.
  10886. */
  10887. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  10888. /**
  10889. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  10890. * to modify the uv node for correct sampling.
  10891. *
  10892. * @param {NodeBuilder} builder - The current node builder.
  10893. * @param {Node} uvNode - The uv node to setup.
  10894. * @return {Node} The updated uv node.
  10895. */
  10896. setupUV( builder, uvNode ) {
  10897. const texture = this.value;
  10898. // Depth textures (shadow maps) - no environment rotation, Y flip for WebGPU
  10899. if ( texture.isDepthTexture === true ) {
  10900. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  10901. return vec3( uvNode.x, uvNode.y.negate(), uvNode.z );
  10902. }
  10903. return uvNode;
  10904. }
  10905. // rotate first
  10906. uvNode = materialEnvRotation.mul( uvNode );
  10907. // flip
  10908. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  10909. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  10910. }
  10911. return uvNode;
  10912. }
  10913. /**
  10914. * Generates the uv code snippet.
  10915. *
  10916. * @param {NodeBuilder} builder - The current node builder.
  10917. * @param {Node} cubeUV - The uv node to generate code for.
  10918. * @return {string} The generated code snippet.
  10919. */
  10920. generateUV( builder, cubeUV ) {
  10921. return cubeUV.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  10922. }
  10923. }
  10924. /**
  10925. * TSL function for creating a cube texture node.
  10926. *
  10927. * @tsl
  10928. * @function
  10929. * @param {CubeTexture} value - The cube texture.
  10930. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10931. * @param {?Node<int>} [levelNode=null] - The level node.
  10932. * @param {?Node<float>} [biasNode=null] - The bias node.
  10933. * @returns {CubeTextureNode}
  10934. */
  10935. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  10936. /**
  10937. * TSL function for creating a cube texture uniform node.
  10938. *
  10939. * @tsl
  10940. * @function
  10941. * @param {?(CubeTexture|CubeTextureNode)} [value=EmptyTexture] - The cube texture.
  10942. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10943. * @param {?Node<int>} [levelNode=null] - The level node.
  10944. * @param {?Node<float>} [biasNode=null] - The bias node.
  10945. * @returns {CubeTextureNode}
  10946. */
  10947. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  10948. let textureNode;
  10949. if ( value && value.isCubeTextureNode === true ) {
  10950. textureNode = nodeObject( value.clone() );
  10951. textureNode.referenceNode = value; // Ensure the reference is set to the original node
  10952. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  10953. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  10954. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  10955. } else {
  10956. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  10957. }
  10958. return textureNode;
  10959. };
  10960. /**
  10961. * TSL function for creating a uniform cube texture node.
  10962. *
  10963. * @tsl
  10964. * @function
  10965. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  10966. * @returns {CubeTextureNode}
  10967. */
  10968. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  10969. // TODO: Avoid duplicated code and use only ReferenceBaseNode or ReferenceNode
  10970. /**
  10971. * This class is only relevant if the referenced property is array-like.
  10972. * In this case, `ReferenceElementNode` allows to refer to a specific
  10973. * element inside the data structure via an index.
  10974. *
  10975. * @augments ArrayElementNode
  10976. */
  10977. class ReferenceElementNode extends ArrayElementNode {
  10978. static get type() {
  10979. return 'ReferenceElementNode';
  10980. }
  10981. /**
  10982. * Constructs a new reference element node.
  10983. *
  10984. * @param {?ReferenceNode} referenceNode - The reference node.
  10985. * @param {Node} indexNode - The index node that defines the element access.
  10986. */
  10987. constructor( referenceNode, indexNode ) {
  10988. super( referenceNode, indexNode );
  10989. /**
  10990. * Similar to {@link ReferenceNode#reference}, an additional
  10991. * property references to the current node.
  10992. *
  10993. * @type {?ReferenceNode}
  10994. * @default null
  10995. */
  10996. this.referenceNode = referenceNode;
  10997. /**
  10998. * This flag can be used for type testing.
  10999. *
  11000. * @type {boolean}
  11001. * @readonly
  11002. * @default true
  11003. */
  11004. this.isReferenceElementNode = true;
  11005. }
  11006. /**
  11007. * This method is overwritten since the node type is inferred from
  11008. * the uniform type of the reference node.
  11009. *
  11010. * @return {string} The node type.
  11011. */
  11012. generateNodeType() {
  11013. return this.referenceNode.uniformType;
  11014. }
  11015. generate( builder ) {
  11016. const snippet = super.generate( builder );
  11017. const arrayType = this.referenceNode.getNodeType( builder );
  11018. const elementType = this.getNodeType( builder );
  11019. return builder.format( snippet, arrayType, elementType );
  11020. }
  11021. }
  11022. /**
  11023. * This type of node establishes a reference to a property of another object.
  11024. * In this way, the value of the node is automatically linked to the value of
  11025. * referenced object. Reference nodes internally represent the linked value
  11026. * as a uniform.
  11027. *
  11028. * @augments Node
  11029. */
  11030. class ReferenceNode extends Node {
  11031. static get type() {
  11032. return 'ReferenceNode';
  11033. }
  11034. /**
  11035. * Constructs a new reference node.
  11036. *
  11037. * @param {string} property - The name of the property the node refers to.
  11038. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  11039. * @param {?Object} [object=null] - The object the property belongs to.
  11040. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  11041. */
  11042. constructor( property, uniformType, object = null, count = null ) {
  11043. super();
  11044. /**
  11045. * The name of the property the node refers to.
  11046. *
  11047. * @type {string}
  11048. */
  11049. this.property = property;
  11050. /**
  11051. * The uniform type that should be used to represent the property value.
  11052. *
  11053. * @type {string}
  11054. */
  11055. this.uniformType = uniformType;
  11056. /**
  11057. * The object the property belongs to.
  11058. *
  11059. * @type {?Object}
  11060. * @default null
  11061. */
  11062. this.object = object;
  11063. /**
  11064. * When the linked property is an array, this parameter defines its length.
  11065. *
  11066. * @type {?number}
  11067. * @default null
  11068. */
  11069. this.count = count;
  11070. /**
  11071. * The property name might have dots so nested properties can be referred.
  11072. * The hierarchy of the names is stored inside this array.
  11073. *
  11074. * @type {Array<string>}
  11075. */
  11076. this.properties = property.split( '.' );
  11077. /**
  11078. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  11079. * since the final reference might be updated from calling code.
  11080. *
  11081. * @type {?Object}
  11082. * @default null
  11083. */
  11084. this.reference = object;
  11085. /**
  11086. * The uniform node that holds the value of the reference node.
  11087. *
  11088. * @type {UniformNode}
  11089. * @default null
  11090. */
  11091. this.node = null;
  11092. /**
  11093. * The uniform group of the internal uniform.
  11094. *
  11095. * @type {UniformGroupNode}
  11096. * @default null
  11097. */
  11098. this.group = null;
  11099. /**
  11100. * An optional label of the internal uniform node.
  11101. *
  11102. * @type {?string}
  11103. * @default null
  11104. */
  11105. this.name = null;
  11106. /**
  11107. * Overwritten since reference nodes are updated per object.
  11108. *
  11109. * @type {string}
  11110. * @default 'object'
  11111. */
  11112. this.updateType = NodeUpdateType.OBJECT;
  11113. }
  11114. /**
  11115. * When the referred property is array-like, this method can be used
  11116. * to access elements via an index node.
  11117. *
  11118. * @param {IndexNode} indexNode - indexNode.
  11119. * @return {ReferenceElementNode} A reference to an element.
  11120. */
  11121. element( indexNode ) {
  11122. return new ReferenceElementNode( this, nodeObject( indexNode ) );
  11123. }
  11124. /**
  11125. * Sets the uniform group for this reference node.
  11126. *
  11127. * @param {UniformGroupNode} group - The uniform group to set.
  11128. * @return {ReferenceNode} A reference to this node.
  11129. */
  11130. setGroup( group ) {
  11131. this.group = group;
  11132. return this;
  11133. }
  11134. /**
  11135. * Sets the name for the internal uniform.
  11136. *
  11137. * @param {string} name - The label to set.
  11138. * @return {ReferenceNode} A reference to this node.
  11139. */
  11140. setName( name ) {
  11141. this.name = name;
  11142. return this;
  11143. }
  11144. /**
  11145. * Sets the label for the internal uniform.
  11146. *
  11147. * @deprecated
  11148. * @param {string} name - The label to set.
  11149. * @return {ReferenceNode} A reference to this node.
  11150. */
  11151. label( name ) {
  11152. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  11153. return this.setName( name );
  11154. }
  11155. /**
  11156. * Sets the node type which automatically defines the internal
  11157. * uniform type.
  11158. *
  11159. * @param {string} uniformType - The type to set.
  11160. */
  11161. setNodeType( uniformType ) {
  11162. let node = null;
  11163. if ( this.count !== null ) {
  11164. node = buffer( null, uniformType, this.count );
  11165. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  11166. node = uniformArray( null, uniformType );
  11167. } else if ( uniformType === 'texture' ) {
  11168. node = texture( null );
  11169. } else if ( uniformType === 'cubeTexture' ) {
  11170. node = cubeTexture( null );
  11171. } else {
  11172. node = uniform( null, uniformType );
  11173. }
  11174. if ( this.group !== null ) {
  11175. node.setGroup( this.group );
  11176. }
  11177. if ( this.name !== null ) node.setName( this.name );
  11178. this.node = node;
  11179. }
  11180. /**
  11181. * This method is overwritten since the node type is inferred from
  11182. * the type of the reference node.
  11183. *
  11184. * @param {NodeBuilder} builder - The current node builder.
  11185. * @return {string} The node type.
  11186. */
  11187. generateNodeType( builder ) {
  11188. if ( this.node === null ) {
  11189. this.updateReference( builder );
  11190. this.updateValue();
  11191. }
  11192. return this.node.getNodeType( builder );
  11193. }
  11194. /**
  11195. * Returns the property value from the given referred object.
  11196. *
  11197. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  11198. * @return {any} The value.
  11199. */
  11200. getValueFromReference( object = this.reference ) {
  11201. const { properties } = this;
  11202. let value = object[ properties[ 0 ] ];
  11203. for ( let i = 1; i < properties.length; i ++ ) {
  11204. value = value[ properties[ i ] ];
  11205. }
  11206. return value;
  11207. }
  11208. /**
  11209. * Allows to update the reference based on the given state. The state is only
  11210. * evaluated {@link ReferenceNode#object} is not set.
  11211. *
  11212. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  11213. * @return {Object} The updated reference.
  11214. */
  11215. updateReference( state ) {
  11216. this.reference = this.object !== null ? this.object : state.object;
  11217. return this.reference;
  11218. }
  11219. /**
  11220. * The output of the reference node is the internal uniform node.
  11221. *
  11222. * @param {NodeBuilder} builder - The current node builder.
  11223. * @return {UniformNode} The output node.
  11224. */
  11225. setup( /* builder */ ) {
  11226. this.updateValue();
  11227. return this.node;
  11228. }
  11229. /**
  11230. * Overwritten to update the internal uniform value.
  11231. *
  11232. * @param {NodeFrame} frame - A reference to the current node frame.
  11233. */
  11234. update( /*frame*/ ) {
  11235. this.updateValue();
  11236. }
  11237. /**
  11238. * Retrieves the value from the referred object property and uses it
  11239. * to updated the internal uniform.
  11240. */
  11241. updateValue() {
  11242. if ( this.node === null ) this.setNodeType( this.uniformType );
  11243. const value = this.getValueFromReference();
  11244. if ( Array.isArray( value ) ) {
  11245. this.node.array = value;
  11246. } else {
  11247. this.node.value = value;
  11248. }
  11249. }
  11250. }
  11251. /**
  11252. * TSL function for creating a reference node.
  11253. *
  11254. * @tsl
  11255. * @function
  11256. * @param {string} name - The name of the property the node refers to.
  11257. * @param {string} type - The uniform type that should be used to represent the property value.
  11258. * @param {?Object} [object] - The object the property belongs to.
  11259. * @returns {ReferenceNode}
  11260. */
  11261. const reference = ( name, type, object ) => new ReferenceNode( name, type, object );
  11262. /**
  11263. * TSL function for creating a reference node. Use this function if you want need a reference
  11264. * to an array-like property that should be represented as a uniform buffer.
  11265. *
  11266. * @tsl
  11267. * @function
  11268. * @param {string} name - The name of the property the node refers to.
  11269. * @param {string} type - The uniform type that should be used to represent the property value.
  11270. * @param {number} count - The number of value inside the array-like object.
  11271. * @param {Object} object - An array-like object the property belongs to.
  11272. * @returns {ReferenceNode}
  11273. */
  11274. const referenceBuffer = ( name, type, count, object ) => new ReferenceNode( name, type, object, count );
  11275. /**
  11276. * This node is a special type of reference node which is intended
  11277. * for linking material properties with node values.
  11278. * ```js
  11279. * const opacityNode = materialReference( 'opacity', 'float', material );
  11280. * ```
  11281. * When changing `material.opacity`, the node value of `opacityNode` will
  11282. * automatically be updated.
  11283. *
  11284. * @augments ReferenceNode
  11285. */
  11286. class MaterialReferenceNode extends ReferenceNode {
  11287. static get type() {
  11288. return 'MaterialReferenceNode';
  11289. }
  11290. /**
  11291. * Constructs a new material reference node.
  11292. *
  11293. * @param {string} property - The name of the property the node refers to.
  11294. * @param {string} inputType - The uniform type that should be used to represent the property value.
  11295. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  11296. * the node refers to the material of the current rendered object.
  11297. */
  11298. constructor( property, inputType, material = null ) {
  11299. super( property, inputType, material );
  11300. /**
  11301. * The material the property belongs to. When no material is set,
  11302. * the node refers to the material of the current rendered object.
  11303. *
  11304. * @type {?Material}
  11305. * @default null
  11306. */
  11307. this.material = material;
  11308. /**
  11309. * This flag can be used for type testing.
  11310. *
  11311. * @type {boolean}
  11312. * @readonly
  11313. * @default true
  11314. */
  11315. this.isMaterialReferenceNode = true;
  11316. }
  11317. /**
  11318. * Updates the reference based on the given state. The state is only evaluated
  11319. * {@link MaterialReferenceNode#material} is not set.
  11320. *
  11321. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  11322. * @return {Object} The updated reference.
  11323. */
  11324. updateReference( state ) {
  11325. this.reference = this.material !== null ? this.material : state.material;
  11326. return this.reference;
  11327. }
  11328. }
  11329. /**
  11330. * TSL function for creating a material reference node.
  11331. *
  11332. * @tsl
  11333. * @function
  11334. * @param {string} name - The name of the property the node refers to.
  11335. * @param {string} type - The uniform type that should be used to represent the property value.
  11336. * @param {?Material} [material=null] - The material the property belongs to.
  11337. * When no material is set, the node refers to the material of the current rendered object.
  11338. * @returns {MaterialReferenceNode}
  11339. */
  11340. const materialReference = ( name, type, material = null ) => new MaterialReferenceNode( name, type, material );
  11341. // Normal Mapping Without Precomputed Tangents
  11342. // http://www.thetenthplanet.de/archives/1180
  11343. const uv = uv$1();
  11344. const q0 = positionView.dFdx();
  11345. const q1 = positionView.dFdy();
  11346. const st0 = uv.dFdx();
  11347. const st1 = uv.dFdy();
  11348. const N = normalView;
  11349. const q1perp = q1.cross( N );
  11350. const q0perp = N.cross( q0 );
  11351. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  11352. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  11353. const det = T.dot( T ).max( B.dot( B ) );
  11354. const scale$1 = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() );
  11355. /**
  11356. * Tangent vector in view space, computed dynamically from geometry and UV derivatives.
  11357. * Useful for normal mapping without precomputed tangents.
  11358. *
  11359. * Reference: http://www.thetenthplanet.de/archives/1180
  11360. *
  11361. * @tsl
  11362. * @type {Node<vec3>}
  11363. */
  11364. const tangentViewFrame = /*@__PURE__*/ T.mul( scale$1 ).toVar( 'tangentViewFrame' );
  11365. /**
  11366. * Bitangent vector in view space, computed dynamically from geometry and UV derivatives.
  11367. * Complements the tangentViewFrame for constructing the tangent space basis.
  11368. *
  11369. * Reference: http://www.thetenthplanet.de/archives/1180
  11370. *
  11371. * @tsl
  11372. * @type {Node<vec3>}
  11373. */
  11374. const bitangentViewFrame = /*@__PURE__*/ B.mul( scale$1 ).toVar( 'bitangentViewFrame' );
  11375. /**
  11376. * TSL object that represents the tangent attribute of the current rendered object.
  11377. *
  11378. * @tsl
  11379. * @type {Node<vec4>}
  11380. */
  11381. const tangentGeometry = /*@__PURE__*/ attribute( 'tangent', 'vec4' );
  11382. /**
  11383. * TSL object that represents the vertex tangent in local space of the current rendered object.
  11384. *
  11385. * @tsl
  11386. * @type {Node<vec3>}
  11387. */
  11388. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  11389. /**
  11390. * TSL object that represents the vertex tangent in view space of the current rendered object.
  11391. *
  11392. * @tsl
  11393. * @type {Node<vec3>}
  11394. */
  11395. const tangentView = /*@__PURE__*/ ( Fn( ( builder ) => {
  11396. let node;
  11397. if ( builder.subBuildFn === 'VERTEX' || builder.geometry.hasAttribute( 'tangent' ) ) {
  11398. node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize();
  11399. } else {
  11400. node = tangentViewFrame;
  11401. }
  11402. if ( builder.isFlatShading() !== true ) {
  11403. node = directionToFaceDirection( node );
  11404. }
  11405. return node;
  11406. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' );
  11407. /**
  11408. * TSL object that represents the vertex tangent in world space of the current rendered object.
  11409. *
  11410. * @tsl
  11411. * @type {Node<vec3>}
  11412. */
  11413. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  11414. /**
  11415. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  11416. *
  11417. * @tsl
  11418. * @private
  11419. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  11420. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  11421. * @returns {Node<vec3>} The bitangent node.
  11422. */
  11423. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], builder ) => {
  11424. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  11425. if ( builder.subBuildFn === 'NORMAL' && builder.isFlatShading() !== true ) {
  11426. bitangent = bitangent.toVarying( varyingName );
  11427. }
  11428. return bitangent;
  11429. } ).once( [ 'NORMAL' ] );
  11430. /**
  11431. * TSL object that represents the bitangent attribute of the current rendered object.
  11432. *
  11433. * @tsl
  11434. * @type {Node<vec3>}
  11435. */
  11436. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  11437. /**
  11438. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  11439. *
  11440. * @tsl
  11441. * @type {Node<vec3>}
  11442. */
  11443. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  11444. /**
  11445. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  11446. *
  11447. * @tsl
  11448. * @type {Node<vec3>}
  11449. */
  11450. const bitangentView = /*@__PURE__*/ ( Fn( ( builder ) => {
  11451. let node;
  11452. if ( builder.subBuildFn === 'VERTEX' || builder.geometry.hasAttribute( 'tangent' ) ) {
  11453. node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize();
  11454. } else {
  11455. node = bitangentViewFrame;
  11456. }
  11457. if ( builder.isFlatShading() !== true ) {
  11458. node = directionToFaceDirection( node );
  11459. }
  11460. return node;
  11461. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' );
  11462. /**
  11463. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  11464. *
  11465. * @tsl
  11466. * @type {Node<vec3>}
  11467. */
  11468. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  11469. /**
  11470. * TSL object that represents the TBN matrix in view space.
  11471. *
  11472. * @tsl
  11473. * @type {Node<mat3>}
  11474. */
  11475. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView ).toVar( 'TBNViewMatrix' );
  11476. /**
  11477. * TSL object that represents the parallax direction.
  11478. *
  11479. * @tsl
  11480. * @type {Node<mat3>}
  11481. */
  11482. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  11483. /**
  11484. * TSL function for computing parallax uv coordinates.
  11485. *
  11486. * @tsl
  11487. * @function
  11488. * @param {Node<vec2>} uv - A uv node.
  11489. * @param {Node<vec2>} scale - A scale node.
  11490. * @returns {Node<vec2>} Parallax uv coordinates.
  11491. */
  11492. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  11493. /**
  11494. * TSL function for computing bent normals.
  11495. *
  11496. * @tsl
  11497. * @function
  11498. * @returns {Node<vec3>} Bent normals.
  11499. */
  11500. const bentNormalView = /*@__PURE__*/ ( Fn( () => {
  11501. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  11502. let bentNormal = anisotropyB.cross( positionViewDirection );
  11503. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  11504. bentNormal = mix( bentNormal, normalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  11505. return bentNormal;
  11506. } ).once() )();
  11507. /**
  11508. * Packs a direction vector into a color value.
  11509. *
  11510. * @tsl
  11511. * @function
  11512. * @param {Node<vec3>} node - The direction to pack.
  11513. * @return {Node<vec3>} The color.
  11514. */
  11515. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  11516. /**
  11517. * Unpacks a color value into a direction vector.
  11518. *
  11519. * @tsl
  11520. * @function
  11521. * @param {Node<vec3>} node - The color to unpack.
  11522. * @return {Node<vec3>} The direction.
  11523. */
  11524. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  11525. /**
  11526. * Unpacks a tangent space normal, reconstructing the Z component by projecting the X,Y coordinates onto the hemisphere.
  11527. * The X,Y coordinates are expected to be in the [-1, 1] range.
  11528. *
  11529. * @tsl
  11530. * @function
  11531. * @param {Node<vec2>} xy - The X,Y coordinates of the normal.
  11532. * @return {Node<vec3>} The resulting normal.
  11533. */
  11534. const unpackNormal = ( xy ) => vec3( xy, sqrt( saturate( float( 1.0 ).sub( dot( xy, xy ) ) ) ) );
  11535. /**
  11536. * This class can be used for applying normals maps to materials.
  11537. *
  11538. * ```js
  11539. * material.normalNode = normalMap( texture( normalTex ) );
  11540. * ```
  11541. *
  11542. * @augments TempNode
  11543. */
  11544. class NormalMapNode extends TempNode {
  11545. static get type() {
  11546. return 'NormalMapNode';
  11547. }
  11548. /**
  11549. * Constructs a new normal map node.
  11550. *
  11551. * @param {Node<vec3>} node - Represents the normal map data.
  11552. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  11553. */
  11554. constructor( node, scaleNode = null ) {
  11555. super( 'vec3' );
  11556. /**
  11557. * Represents the normal map data.
  11558. *
  11559. * @type {Node<vec3>}
  11560. */
  11561. this.node = node;
  11562. /**
  11563. * Controls the intensity of the effect.
  11564. *
  11565. * @type {?Node<vec2>}
  11566. * @default null
  11567. */
  11568. this.scaleNode = scaleNode;
  11569. /**
  11570. * The normal map type.
  11571. *
  11572. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  11573. * @default TangentSpaceNormalMap
  11574. */
  11575. this.normalMapType = TangentSpaceNormalMap;
  11576. /**
  11577. * Controls how to unpack the sampled normal map values.
  11578. *
  11579. * @type {string}
  11580. * @default NoNormalPacking
  11581. */
  11582. this.unpackNormalMode = NoNormalPacking;
  11583. }
  11584. setup( builder ) {
  11585. const { normalMapType, scaleNode, unpackNormalMode } = this;
  11586. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  11587. if ( normalMapType === TangentSpaceNormalMap ) {
  11588. if ( unpackNormalMode === NormalRGPacking ) {
  11589. normalMap = unpackNormal( normalMap.xy );
  11590. } else if ( unpackNormalMode === NormalGAPacking ) {
  11591. normalMap = unpackNormal( normalMap.yw );
  11592. } else if ( unpackNormalMode !== NoNormalPacking ) {
  11593. error( `THREE.NodeMaterial: Unexpected unpack normal mode: ${ unpackNormalMode }` );
  11594. }
  11595. } else {
  11596. if ( unpackNormalMode !== NoNormalPacking ) {
  11597. error( `THREE.NodeMaterial: Normal map type '${ normalMapType }' is not compatible with unpack normal mode '${ unpackNormalMode }'` );
  11598. }
  11599. }
  11600. if ( scaleNode !== null ) {
  11601. let scale = scaleNode;
  11602. if ( builder.isFlatShading() === true ) {
  11603. scale = directionToFaceDirection( scale );
  11604. }
  11605. normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z );
  11606. }
  11607. let output = null;
  11608. if ( normalMapType === ObjectSpaceNormalMap ) {
  11609. output = transformNormalToView( normalMap );
  11610. } else if ( normalMapType === TangentSpaceNormalMap ) {
  11611. output = TBNViewMatrix.mul( normalMap ).normalize();
  11612. } else {
  11613. error( `NodeMaterial: Unsupported normal map type: ${ normalMapType }` );
  11614. output = normalView; // Fallback to default normal view
  11615. }
  11616. return output;
  11617. }
  11618. }
  11619. /**
  11620. * TSL function for creating a normal map node.
  11621. *
  11622. * @tsl
  11623. * @function
  11624. * @param {Node<vec3>} node - Represents the normal map data.
  11625. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  11626. * @returns {NormalMapNode}
  11627. */
  11628. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  11629. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  11630. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  11631. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  11632. // It's used to preserve the same TextureNode instance
  11633. const sampleTexture = ( callback ) => textureNode.isolate().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } );
  11634. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  11635. return vec2(
  11636. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  11637. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  11638. ).mul( bumpScale );
  11639. } );
  11640. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  11641. const perturbNormalArb = Fn( ( inputs ) => {
  11642. const { surf_pos, surf_norm, dHdxy } = inputs;
  11643. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  11644. const vSigmaX = surf_pos.dFdx().normalize();
  11645. const vSigmaY = surf_pos.dFdy().normalize();
  11646. const vN = surf_norm; // normalized
  11647. const R1 = vSigmaY.cross( vN );
  11648. const R2 = vN.cross( vSigmaX );
  11649. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  11650. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  11651. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  11652. } );
  11653. /**
  11654. * This class can be used for applying bump maps to materials.
  11655. *
  11656. * ```js
  11657. * material.normalNode = bumpMap( texture( bumpTex ) );
  11658. * ```
  11659. *
  11660. * @augments TempNode
  11661. */
  11662. class BumpMapNode extends TempNode {
  11663. static get type() {
  11664. return 'BumpMapNode';
  11665. }
  11666. /**
  11667. * Constructs a new bump map node.
  11668. *
  11669. * @param {Node<float>} textureNode - Represents the bump map data.
  11670. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  11671. */
  11672. constructor( textureNode, scaleNode = null ) {
  11673. super( 'vec3' );
  11674. /**
  11675. * Represents the bump map data.
  11676. *
  11677. * @type {Node<float>}
  11678. */
  11679. this.textureNode = textureNode;
  11680. /**
  11681. * Controls the intensity of the bump effect.
  11682. *
  11683. * @type {?Node<float>}
  11684. * @default null
  11685. */
  11686. this.scaleNode = scaleNode;
  11687. }
  11688. setup() {
  11689. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  11690. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  11691. return perturbNormalArb( {
  11692. surf_pos: positionView,
  11693. surf_norm: normalView,
  11694. dHdxy
  11695. } );
  11696. }
  11697. }
  11698. /**
  11699. * TSL function for creating a bump map node.
  11700. *
  11701. * @tsl
  11702. * @function
  11703. * @param {Node<float>} textureNode - Represents the bump map data.
  11704. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  11705. * @returns {BumpMapNode}
  11706. */
  11707. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  11708. const _propertyCache = new Map();
  11709. /**
  11710. * This class should simplify the node access to material properties.
  11711. * It internal uses reference nodes to make sure changes to material
  11712. * properties are automatically reflected to predefined TSL objects
  11713. * like e.g. `materialColor`.
  11714. *
  11715. * @augments Node
  11716. */
  11717. class MaterialNode extends Node {
  11718. static get type() {
  11719. return 'MaterialNode';
  11720. }
  11721. /**
  11722. * Constructs a new material node.
  11723. *
  11724. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  11725. */
  11726. constructor( scope ) {
  11727. super();
  11728. /**
  11729. * The scope defines what material property is referred by the node.
  11730. *
  11731. * @type {string}
  11732. */
  11733. this.scope = scope;
  11734. }
  11735. /**
  11736. * Returns a cached reference node for the given property and type.
  11737. *
  11738. * @param {string} property - The name of the material property.
  11739. * @param {string} type - The uniform type of the property.
  11740. * @return {MaterialReferenceNode} A material reference node representing the property access.
  11741. */
  11742. getCache( property, type ) {
  11743. let node = _propertyCache.get( property );
  11744. if ( node === undefined ) {
  11745. node = materialReference( property, type );
  11746. _propertyCache.set( property, node );
  11747. }
  11748. return node;
  11749. }
  11750. /**
  11751. * Returns a float-typed material reference node for the given property name.
  11752. *
  11753. * @param {string} property - The name of the material property.
  11754. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  11755. */
  11756. getFloat( property ) {
  11757. return this.getCache( property, 'float' );
  11758. }
  11759. /**
  11760. * Returns a color-typed material reference node for the given property name.
  11761. *
  11762. * @param {string} property - The name of the material property.
  11763. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  11764. */
  11765. getColor( property ) {
  11766. return this.getCache( property, 'color' );
  11767. }
  11768. /**
  11769. * Returns a texture-typed material reference node for the given property name.
  11770. *
  11771. * @param {string} property - The name of the material property.
  11772. * @return {MaterialReferenceNode} A material reference node representing the property access.
  11773. */
  11774. getTexture( property ) {
  11775. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  11776. }
  11777. /**
  11778. * The node setup is done depending on the selected scope. Multiple material properties
  11779. * might be grouped into a single node composition if they logically belong together.
  11780. *
  11781. * @param {NodeBuilder} builder - The current node builder.
  11782. * @return {Node} The node representing the selected scope.
  11783. */
  11784. setup( builder ) {
  11785. const material = builder.context.material;
  11786. const scope = this.scope;
  11787. let node = null;
  11788. if ( scope === MaterialNode.COLOR ) {
  11789. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  11790. if ( material.map && material.map.isTexture === true ) {
  11791. node = colorNode.mul( this.getTexture( 'map' ) );
  11792. } else {
  11793. node = colorNode;
  11794. }
  11795. } else if ( scope === MaterialNode.OPACITY ) {
  11796. const opacityNode = this.getFloat( scope );
  11797. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  11798. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  11799. } else {
  11800. node = opacityNode;
  11801. }
  11802. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  11803. if ( material.specularMap && material.specularMap.isTexture === true ) {
  11804. node = this.getTexture( 'specular' ).r;
  11805. } else {
  11806. node = float( 1 );
  11807. }
  11808. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  11809. const specularIntensityNode = this.getFloat( scope );
  11810. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  11811. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  11812. } else {
  11813. node = specularIntensityNode;
  11814. }
  11815. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  11816. const specularColorNode = this.getColor( scope );
  11817. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  11818. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  11819. } else {
  11820. node = specularColorNode;
  11821. }
  11822. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  11823. const roughnessNode = this.getFloat( scope );
  11824. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  11825. node = roughnessNode.mul( this.getTexture( scope ).g );
  11826. } else {
  11827. node = roughnessNode;
  11828. }
  11829. } else if ( scope === MaterialNode.METALNESS ) {
  11830. const metalnessNode = this.getFloat( scope );
  11831. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  11832. node = metalnessNode.mul( this.getTexture( scope ).b );
  11833. } else {
  11834. node = metalnessNode;
  11835. }
  11836. } else if ( scope === MaterialNode.EMISSIVE ) {
  11837. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  11838. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  11839. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  11840. node = emissiveNode.mul( this.getTexture( scope ) );
  11841. } else {
  11842. node = emissiveNode;
  11843. }
  11844. } else if ( scope === MaterialNode.NORMAL ) {
  11845. if ( material.normalMap ) {
  11846. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  11847. node.normalMapType = material.normalMapType;
  11848. if ( material.normalMap.format == RGFormat || material.normalMap.format == RED_GREEN_RGTC2_Format || material.normalMap.format == RG11_EAC_Format ) {
  11849. node.unpackNormalMode = NormalRGPacking;
  11850. }
  11851. } else if ( material.bumpMap ) {
  11852. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  11853. } else {
  11854. node = normalView;
  11855. }
  11856. } else if ( scope === MaterialNode.CLEARCOAT ) {
  11857. const clearcoatNode = this.getFloat( scope );
  11858. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  11859. node = clearcoatNode.mul( this.getTexture( scope ).r );
  11860. } else {
  11861. node = clearcoatNode;
  11862. }
  11863. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  11864. const clearcoatRoughnessNode = this.getFloat( scope );
  11865. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  11866. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  11867. } else {
  11868. node = clearcoatRoughnessNode;
  11869. }
  11870. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  11871. if ( material.clearcoatNormalMap ) {
  11872. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  11873. } else {
  11874. node = normalView;
  11875. }
  11876. } else if ( scope === MaterialNode.SHEEN ) {
  11877. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  11878. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  11879. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  11880. } else {
  11881. node = sheenNode;
  11882. }
  11883. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  11884. const sheenRoughnessNode = this.getFloat( scope );
  11885. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  11886. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  11887. } else {
  11888. node = sheenRoughnessNode;
  11889. }
  11890. node = node.clamp( 0.0001, 1.0 );
  11891. } else if ( scope === MaterialNode.ANISOTROPY ) {
  11892. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  11893. const anisotropyPolar = this.getTexture( scope );
  11894. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  11895. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  11896. } else {
  11897. node = materialAnisotropyVector;
  11898. }
  11899. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  11900. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  11901. if ( material.iridescenceThicknessMap ) {
  11902. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  11903. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  11904. } else {
  11905. node = iridescenceThicknessMaximum;
  11906. }
  11907. } else if ( scope === MaterialNode.TRANSMISSION ) {
  11908. const transmissionNode = this.getFloat( scope );
  11909. if ( material.transmissionMap ) {
  11910. node = transmissionNode.mul( this.getTexture( scope ).r );
  11911. } else {
  11912. node = transmissionNode;
  11913. }
  11914. } else if ( scope === MaterialNode.THICKNESS ) {
  11915. const thicknessNode = this.getFloat( scope );
  11916. if ( material.thicknessMap ) {
  11917. node = thicknessNode.mul( this.getTexture( scope ).g );
  11918. } else {
  11919. node = thicknessNode;
  11920. }
  11921. } else if ( scope === MaterialNode.IOR ) {
  11922. node = this.getFloat( scope );
  11923. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  11924. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  11925. } else if ( scope === MaterialNode.AO ) {
  11926. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  11927. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  11928. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  11929. } else {
  11930. const outputType = this.getNodeType( builder );
  11931. node = this.getCache( scope, outputType );
  11932. }
  11933. return node;
  11934. }
  11935. }
  11936. MaterialNode.ALPHA_TEST = 'alphaTest';
  11937. MaterialNode.COLOR = 'color';
  11938. MaterialNode.OPACITY = 'opacity';
  11939. MaterialNode.SHININESS = 'shininess';
  11940. MaterialNode.SPECULAR = 'specular';
  11941. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  11942. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  11943. MaterialNode.SPECULAR_COLOR = 'specularColor';
  11944. MaterialNode.REFLECTIVITY = 'reflectivity';
  11945. MaterialNode.ROUGHNESS = 'roughness';
  11946. MaterialNode.METALNESS = 'metalness';
  11947. MaterialNode.NORMAL = 'normal';
  11948. MaterialNode.CLEARCOAT = 'clearcoat';
  11949. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  11950. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  11951. MaterialNode.EMISSIVE = 'emissive';
  11952. MaterialNode.ROTATION = 'rotation';
  11953. MaterialNode.SHEEN = 'sheen';
  11954. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  11955. MaterialNode.ANISOTROPY = 'anisotropy';
  11956. MaterialNode.IRIDESCENCE = 'iridescence';
  11957. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  11958. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  11959. MaterialNode.IOR = 'ior';
  11960. MaterialNode.TRANSMISSION = 'transmission';
  11961. MaterialNode.THICKNESS = 'thickness';
  11962. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  11963. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  11964. MaterialNode.LINE_SCALE = 'scale';
  11965. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  11966. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  11967. MaterialNode.LINE_WIDTH = 'linewidth';
  11968. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  11969. MaterialNode.POINT_SIZE = 'size';
  11970. MaterialNode.DISPERSION = 'dispersion';
  11971. MaterialNode.LIGHT_MAP = 'light';
  11972. MaterialNode.AO = 'ao';
  11973. /**
  11974. * TSL object that represents alpha test of the current material.
  11975. *
  11976. * @tsl
  11977. * @type {Node<float>}
  11978. */
  11979. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  11980. /**
  11981. * TSL object that represents the diffuse color of the current material.
  11982. * The value is composed via `color` * `map`.
  11983. *
  11984. * @tsl
  11985. * @type {Node<vec3>}
  11986. */
  11987. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  11988. /**
  11989. * TSL object that represents the shininess of the current material.
  11990. *
  11991. * @tsl
  11992. * @type {Node<float>}
  11993. */
  11994. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  11995. /**
  11996. * TSL object that represents the emissive color of the current material.
  11997. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  11998. *
  11999. * @tsl
  12000. * @type {Node<vec3>}
  12001. */
  12002. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  12003. /**
  12004. * TSL object that represents the opacity of the current material.
  12005. * The value is composed via `opacity` * `alphaMap`.
  12006. *
  12007. * @tsl
  12008. * @type {Node<float>}
  12009. */
  12010. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  12011. /**
  12012. * TSL object that represents the specular of the current material.
  12013. *
  12014. * @tsl
  12015. * @type {Node<vec3>}
  12016. */
  12017. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  12018. /**
  12019. * TSL object that represents the specular intensity of the current material.
  12020. * The value is composed via `specularIntensity` * `specularMap.a`.
  12021. *
  12022. * @tsl
  12023. * @type {Node<float>}
  12024. */
  12025. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  12026. /**
  12027. * TSL object that represents the specular color of the current material.
  12028. * The value is composed via `specularColor` * `specularMap.rgb`.
  12029. *
  12030. * @tsl
  12031. * @type {Node<vec3>}
  12032. */
  12033. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  12034. /**
  12035. * TSL object that represents the specular strength of the current material.
  12036. * The value is composed via `specularMap.r`.
  12037. *
  12038. * @tsl
  12039. * @type {Node<float>}
  12040. */
  12041. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  12042. /**
  12043. * TSL object that represents the reflectivity of the current material.
  12044. *
  12045. * @tsl
  12046. * @type {Node<float>}
  12047. */
  12048. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  12049. /**
  12050. * TSL object that represents the roughness of the current material.
  12051. * The value is composed via `roughness` * `roughnessMap.g`.
  12052. *
  12053. * @tsl
  12054. * @type {Node<float>}
  12055. */
  12056. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  12057. /**
  12058. * TSL object that represents the metalness of the current material.
  12059. * The value is composed via `metalness` * `metalnessMap.b`.
  12060. *
  12061. * @tsl
  12062. * @type {Node<float>}
  12063. */
  12064. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  12065. /**
  12066. * TSL object that represents the normal of the current material.
  12067. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  12068. *
  12069. * @tsl
  12070. * @type {Node<vec3>}
  12071. */
  12072. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  12073. /**
  12074. * TSL object that represents the clearcoat of the current material.
  12075. * The value is composed via `clearcoat` * `clearcoatMap.r`
  12076. *
  12077. * @tsl
  12078. * @type {Node<float>}
  12079. */
  12080. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  12081. /**
  12082. * TSL object that represents the clearcoat roughness of the current material.
  12083. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  12084. *
  12085. * @tsl
  12086. * @type {Node<float>}
  12087. */
  12088. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  12089. /**
  12090. * TSL object that represents the clearcoat normal of the current material.
  12091. * The value will be either `clearcoatNormalMap` or `normalView`.
  12092. *
  12093. * @tsl
  12094. * @type {Node<vec3>}
  12095. */
  12096. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  12097. /**
  12098. * TSL object that represents the rotation of the current sprite material.
  12099. *
  12100. * @tsl
  12101. * @type {Node<float>}
  12102. */
  12103. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  12104. /**
  12105. * TSL object that represents the sheen color of the current material.
  12106. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  12107. *
  12108. * @tsl
  12109. * @type {Node<vec3>}
  12110. */
  12111. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  12112. /**
  12113. * TSL object that represents the sheen roughness of the current material.
  12114. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  12115. *
  12116. * @tsl
  12117. * @type {Node<float>}
  12118. */
  12119. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  12120. /**
  12121. * TSL object that represents the anisotropy of the current material.
  12122. *
  12123. * @tsl
  12124. * @type {Node<vec2>}
  12125. */
  12126. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  12127. /**
  12128. * TSL object that represents the iridescence of the current material.
  12129. *
  12130. * @tsl
  12131. * @type {Node<float>}
  12132. */
  12133. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  12134. /**
  12135. * TSL object that represents the iridescence IOR of the current material.
  12136. *
  12137. * @tsl
  12138. * @type {Node<float>}
  12139. */
  12140. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  12141. /**
  12142. * TSL object that represents the iridescence thickness of the current material.
  12143. *
  12144. * @tsl
  12145. * @type {Node<float>}
  12146. */
  12147. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  12148. /**
  12149. * TSL object that represents the transmission of the current material.
  12150. * The value is composed via `transmission` * `transmissionMap.r`.
  12151. *
  12152. * @tsl
  12153. * @type {Node<float>}
  12154. */
  12155. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  12156. /**
  12157. * TSL object that represents the thickness of the current material.
  12158. * The value is composed via `thickness` * `thicknessMap.g`.
  12159. *
  12160. * @tsl
  12161. * @type {Node<float>}
  12162. */
  12163. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  12164. /**
  12165. * TSL object that represents the IOR of the current material.
  12166. *
  12167. * @tsl
  12168. * @type {Node<float>}
  12169. */
  12170. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  12171. /**
  12172. * TSL object that represents the attenuation distance of the current material.
  12173. *
  12174. * @tsl
  12175. * @type {Node<float>}
  12176. */
  12177. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  12178. /**
  12179. * TSL object that represents the attenuation color of the current material.
  12180. *
  12181. * @tsl
  12182. * @type {Node<vec3>}
  12183. */
  12184. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  12185. /**
  12186. * TSL object that represents the scale of the current dashed line material.
  12187. *
  12188. * @tsl
  12189. * @type {Node<float>}
  12190. */
  12191. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  12192. /**
  12193. * TSL object that represents the dash size of the current dashed line material.
  12194. *
  12195. * @tsl
  12196. * @type {Node<float>}
  12197. */
  12198. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  12199. /**
  12200. * TSL object that represents the gap size of the current dashed line material.
  12201. *
  12202. * @tsl
  12203. * @type {Node<float>}
  12204. */
  12205. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  12206. /**
  12207. * TSL object that represents the line width of the current line material.
  12208. *
  12209. * @tsl
  12210. * @type {Node<float>}
  12211. */
  12212. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  12213. /**
  12214. * TSL object that represents the dash offset of the current line material.
  12215. *
  12216. * @tsl
  12217. * @type {Node<float>}
  12218. */
  12219. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  12220. /**
  12221. * TSL object that represents the point size of the current points material.
  12222. *
  12223. * @tsl
  12224. * @type {Node<float>}
  12225. */
  12226. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  12227. /**
  12228. * TSL object that represents the dispersion of the current material.
  12229. *
  12230. * @tsl
  12231. * @type {Node<float>}
  12232. */
  12233. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  12234. /**
  12235. * TSL object that represents the light map of the current material.
  12236. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  12237. *
  12238. * @tsl
  12239. * @type {Node<vec3>}
  12240. */
  12241. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  12242. /**
  12243. * TSL object that represents the ambient occlusion map of the current material.
  12244. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  12245. *
  12246. * @tsl
  12247. * @type {Node<float>}
  12248. */
  12249. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  12250. /**
  12251. * TSL object that represents the anisotropy vector of the current material.
  12252. *
  12253. * @tsl
  12254. * @type {Node<vec2>}
  12255. */
  12256. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  12257. return frame.material;
  12258. } ).onRenderUpdate( function ( { material } ) {
  12259. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  12260. } );
  12261. /**
  12262. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  12263. *
  12264. * @tsl
  12265. * @type {VaryingNode<vec4>}
  12266. */
  12267. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  12268. return builder.context.setupModelViewProjection();
  12269. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  12270. /**
  12271. * This class enables element access on instances of {@link StorageBufferNode}.
  12272. * In most cases, it is indirectly used when accessing elements with the
  12273. * {@link StorageBufferNode#element} method.
  12274. *
  12275. * ```js
  12276. * const position = positionStorage.element( instanceIndex );
  12277. * ```
  12278. *
  12279. * @augments ArrayElementNode
  12280. */
  12281. class StorageArrayElementNode extends ArrayElementNode {
  12282. static get type() {
  12283. return 'StorageArrayElementNode';
  12284. }
  12285. /**
  12286. * Constructs storage buffer element node.
  12287. *
  12288. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  12289. * @param {Node} indexNode - The index node that defines the element access.
  12290. */
  12291. constructor( storageBufferNode, indexNode ) {
  12292. super( storageBufferNode, indexNode );
  12293. /**
  12294. * This flag can be used for type testing.
  12295. *
  12296. * @type {boolean}
  12297. * @readonly
  12298. * @default true
  12299. */
  12300. this.isStorageArrayElementNode = true;
  12301. }
  12302. /**
  12303. * The storage buffer node.
  12304. *
  12305. * @param {Node} value
  12306. * @type {StorageBufferNode}
  12307. */
  12308. set storageBufferNode( value ) {
  12309. this.node = value;
  12310. }
  12311. get storageBufferNode() {
  12312. return this.node;
  12313. }
  12314. getMemberType( builder, name ) {
  12315. const structTypeNode = this.storageBufferNode.structTypeNode;
  12316. if ( structTypeNode ) {
  12317. return structTypeNode.getMemberType( builder, name );
  12318. }
  12319. return 'void';
  12320. }
  12321. setup( builder ) {
  12322. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  12323. if ( this.node.isPBO === true ) {
  12324. builder.setupPBO( this.node );
  12325. }
  12326. }
  12327. return super.setup( builder );
  12328. }
  12329. generate( builder, output ) {
  12330. let snippet;
  12331. const isAssignContext = builder.context.assign;
  12332. //
  12333. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  12334. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  12335. snippet = builder.generatePBO( this );
  12336. } else {
  12337. snippet = this.node.build( builder );
  12338. }
  12339. } else {
  12340. snippet = super.generate( builder );
  12341. }
  12342. if ( isAssignContext !== true ) {
  12343. const type = this.getNodeType( builder );
  12344. snippet = builder.format( snippet, type, output );
  12345. }
  12346. return snippet;
  12347. }
  12348. }
  12349. /**
  12350. * TSL function for creating a storage element node.
  12351. *
  12352. * @tsl
  12353. * @function
  12354. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  12355. * @param {Node} indexNode - The index node that defines the element access.
  12356. * @returns {StorageArrayElementNode}
  12357. */
  12358. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  12359. /**
  12360. * This node is used in context of compute shaders and allows to define a
  12361. * storage buffer for data. A typical workflow is to create instances of
  12362. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  12363. * setup up a compute shader that writes into the buffers and then convert
  12364. * the storage buffers to attribute nodes for rendering.
  12365. *
  12366. * ```js
  12367. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  12368. *
  12369. * const computeInit = Fn( () => { // the compute shader
  12370. *
  12371. * const position = positionBuffer.element( instanceIndex );
  12372. *
  12373. * // compute position data
  12374. *
  12375. * position.x = 1;
  12376. * position.y = 1;
  12377. * position.z = 1;
  12378. *
  12379. * } )().compute( particleCount );
  12380. *
  12381. * const particleMaterial = new THREE.SpriteNodeMaterial();
  12382. * particleMaterial.positionNode = positionBuffer.toAttribute();
  12383. *
  12384. * renderer.computeAsync( computeInit );
  12385. *
  12386. * ```
  12387. *
  12388. * @augments BufferNode
  12389. */
  12390. class StorageBufferNode extends BufferNode {
  12391. static get type() {
  12392. return 'StorageBufferNode';
  12393. }
  12394. /**
  12395. * Constructs a new storage buffer node.
  12396. *
  12397. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12398. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  12399. * @param {number} [bufferCount=0] - The buffer count.
  12400. */
  12401. constructor( value, bufferType = null, bufferCount = 0 ) {
  12402. let nodeType, structTypeNode = null;
  12403. if ( bufferType && bufferType.isStruct ) {
  12404. nodeType = 'struct';
  12405. structTypeNode = bufferType.layout;
  12406. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  12407. bufferCount = value.count;
  12408. }
  12409. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  12410. nodeType = getTypeFromLength( value.itemSize );
  12411. bufferCount = value.count;
  12412. } else {
  12413. nodeType = bufferType;
  12414. }
  12415. super( value, nodeType, bufferCount );
  12416. /**
  12417. * This flag can be used for type testing.
  12418. *
  12419. * @type {boolean}
  12420. * @readonly
  12421. * @default true
  12422. */
  12423. this.isStorageBufferNode = true;
  12424. /**
  12425. * The buffer struct type.
  12426. *
  12427. * @type {?StructTypeNode}
  12428. * @default null
  12429. */
  12430. this.structTypeNode = structTypeNode;
  12431. /**
  12432. * The access type of the texture node.
  12433. *
  12434. * @type {string}
  12435. * @default 'readWrite'
  12436. */
  12437. this.access = NodeAccess.READ_WRITE;
  12438. /**
  12439. * Whether the node is atomic or not.
  12440. *
  12441. * @type {boolean}
  12442. * @default false
  12443. */
  12444. this.isAtomic = false;
  12445. /**
  12446. * Whether the node represents a PBO or not.
  12447. * Only relevant for WebGL.
  12448. *
  12449. * @type {boolean}
  12450. * @default false
  12451. */
  12452. this.isPBO = false;
  12453. /**
  12454. * A reference to the internal buffer attribute node.
  12455. *
  12456. * @private
  12457. * @type {?BufferAttributeNode}
  12458. * @default null
  12459. */
  12460. this._attribute = null;
  12461. /**
  12462. * A reference to the internal varying node.
  12463. *
  12464. * @private
  12465. * @type {?VaryingNode}
  12466. * @default null
  12467. */
  12468. this._varying = null;
  12469. /**
  12470. * `StorageBufferNode` sets this property to `true` by default.
  12471. *
  12472. * @type {boolean}
  12473. * @default true
  12474. */
  12475. this.global = true;
  12476. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  12477. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  12478. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  12479. else value.isStorageBufferAttribute = true;
  12480. }
  12481. }
  12482. /**
  12483. * This method is overwritten since the buffer data might be shared
  12484. * and thus the hash should be shared as well.
  12485. *
  12486. * @param {NodeBuilder} builder - The current node builder.
  12487. * @return {string} The hash.
  12488. */
  12489. getHash( builder ) {
  12490. let id;
  12491. if ( this.bufferCount === 0 ) {
  12492. let bufferData = builder.globalCache.getData( this.value );
  12493. if ( bufferData === undefined ) {
  12494. bufferData = {
  12495. node: this
  12496. };
  12497. builder.globalCache.setData( this.value, bufferData );
  12498. }
  12499. id = bufferData.node.id;
  12500. } else {
  12501. id = this.id;
  12502. }
  12503. return String( id );
  12504. }
  12505. /**
  12506. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  12507. *
  12508. * @param {NodeBuilder} builder - The current node builder.
  12509. * @return {string} The input type.
  12510. */
  12511. getInputType( /*builder*/ ) {
  12512. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  12513. }
  12514. /**
  12515. * Enables element access with the given index node.
  12516. *
  12517. * @param {IndexNode} indexNode - The index node.
  12518. * @return {StorageArrayElementNode} A node representing the element access.
  12519. */
  12520. element( indexNode ) {
  12521. return storageElement( this, indexNode );
  12522. }
  12523. /**
  12524. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  12525. *
  12526. * @param {boolean} value - The value so set.
  12527. * @return {StorageBufferNode} A reference to this node.
  12528. */
  12529. setPBO( value ) {
  12530. this.isPBO = value;
  12531. return this;
  12532. }
  12533. /**
  12534. * Returns the `isPBO` value.
  12535. *
  12536. * @return {boolean} Whether the node represents a PBO or not.
  12537. */
  12538. getPBO() {
  12539. return this.isPBO;
  12540. }
  12541. /**
  12542. * Defines the node access.
  12543. *
  12544. * @param {string} value - The node access.
  12545. * @return {StorageBufferNode} A reference to this node.
  12546. */
  12547. setAccess( value ) {
  12548. this.access = value;
  12549. return this;
  12550. }
  12551. /**
  12552. * Convenience method for configuring a read-only node access.
  12553. *
  12554. * @return {StorageBufferNode} A reference to this node.
  12555. */
  12556. toReadOnly() {
  12557. return this.setAccess( NodeAccess.READ_ONLY );
  12558. }
  12559. /**
  12560. * Defines whether the node is atomic or not.
  12561. *
  12562. * @param {boolean} value - The atomic flag.
  12563. * @return {StorageBufferNode} A reference to this node.
  12564. */
  12565. setAtomic( value ) {
  12566. this.isAtomic = value;
  12567. return this;
  12568. }
  12569. /**
  12570. * Convenience method for making this node atomic.
  12571. *
  12572. * @return {StorageBufferNode} A reference to this node.
  12573. */
  12574. toAtomic() {
  12575. return this.setAtomic( true );
  12576. }
  12577. /**
  12578. * Returns attribute data for this storage buffer node.
  12579. *
  12580. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  12581. */
  12582. getAttributeData() {
  12583. if ( this._attribute === null ) {
  12584. this._attribute = bufferAttribute( this.value );
  12585. this._varying = varying( this._attribute );
  12586. }
  12587. return {
  12588. attribute: this._attribute,
  12589. varying: this._varying
  12590. };
  12591. }
  12592. /**
  12593. * This method is overwritten since the node type from the availability of storage buffers
  12594. * and the attribute data.
  12595. *
  12596. * @param {NodeBuilder} builder - The current node builder.
  12597. * @return {string} The node type.
  12598. */
  12599. generateNodeType( builder ) {
  12600. if ( this.structTypeNode !== null ) {
  12601. return this.structTypeNode.getNodeType( builder );
  12602. }
  12603. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12604. return super.generateNodeType( builder );
  12605. }
  12606. const { attribute } = this.getAttributeData();
  12607. return attribute.getNodeType( builder );
  12608. }
  12609. /**
  12610. * Returns the type of a member of the struct.
  12611. *
  12612. * @param {NodeBuilder} builder - The current node builder.
  12613. * @param {string} name - The name of the member.
  12614. * @return {string} The type of the member.
  12615. */
  12616. getMemberType( builder, name ) {
  12617. if ( this.structTypeNode !== null ) {
  12618. return this.structTypeNode.getMemberType( builder, name );
  12619. }
  12620. return 'void';
  12621. }
  12622. /**
  12623. * Generates the code snippet of the storage buffer node.
  12624. *
  12625. * @param {NodeBuilder} builder - The current node builder.
  12626. * @return {string} The generated code snippet.
  12627. */
  12628. generate( builder ) {
  12629. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  12630. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12631. return super.generate( builder );
  12632. }
  12633. const { attribute, varying } = this.getAttributeData();
  12634. const output = varying.build( builder );
  12635. builder.registerTransform( output, attribute );
  12636. return output;
  12637. }
  12638. }
  12639. /**
  12640. * TSL function for creating a storage buffer node.
  12641. *
  12642. * @tsl
  12643. * @function
  12644. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12645. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  12646. * @param {number} [count=0] - The buffer count.
  12647. * @returns {StorageBufferNode}
  12648. */
  12649. const storage = ( value, type = null, count = 0 ) => new StorageBufferNode( value, type, count );
  12650. /**
  12651. * This node implements the vertex shader logic which is required
  12652. * when rendering 3D objects via instancing. The code makes sure
  12653. * vertex positions, normals and colors can be modified via instanced
  12654. * data.
  12655. *
  12656. * @augments Node
  12657. */
  12658. class InstanceNode extends Node {
  12659. static get type() {
  12660. return 'InstanceNode';
  12661. }
  12662. /**
  12663. * Constructs a new instance node.
  12664. *
  12665. * @param {number} count - The number of instances.
  12666. * @param {InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  12667. * @param {?InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  12668. */
  12669. constructor( count, instanceMatrix, instanceColor = null ) {
  12670. super( 'void' );
  12671. /**
  12672. * The number of instances.
  12673. *
  12674. * @type {number}
  12675. */
  12676. this.count = count;
  12677. /**
  12678. * Instanced buffer attribute representing the transformation of instances.
  12679. *
  12680. * @type {InstancedBufferAttribute}
  12681. */
  12682. this.instanceMatrix = instanceMatrix;
  12683. /**
  12684. * Instanced buffer attribute representing the color of instances.
  12685. *
  12686. * @type {InstancedBufferAttribute}
  12687. */
  12688. this.instanceColor = instanceColor;
  12689. /**
  12690. * The node that represents the instance matrix data.
  12691. *
  12692. * @type {?Node}
  12693. */
  12694. this.instanceMatrixNode = null;
  12695. /**
  12696. * The node that represents the instance color data.
  12697. *
  12698. * @type {?Node}
  12699. * @default null
  12700. */
  12701. this.instanceColorNode = null;
  12702. /**
  12703. * The update type is set to `frame` since an update
  12704. * of instanced buffer data must be checked per frame.
  12705. *
  12706. * @type {string}
  12707. * @default 'frame'
  12708. */
  12709. this.updateType = NodeUpdateType.FRAME;
  12710. /**
  12711. * A reference to a buffer that is used by `instanceMatrixNode`.
  12712. *
  12713. * @type {?InstancedInterleavedBuffer}
  12714. */
  12715. this.buffer = null;
  12716. /**
  12717. * A reference to a buffer that is used by `instanceColorNode`.
  12718. *
  12719. * @type {?InstancedBufferAttribute}
  12720. */
  12721. this.bufferColor = null;
  12722. /**
  12723. * The previous instance matrices. Required for computing motion vectors.
  12724. *
  12725. * @type {?Node}
  12726. * @default null
  12727. */
  12728. this.previousInstanceMatrixNode = null;
  12729. }
  12730. /**
  12731. * Tracks whether the matrix data is provided via a storage buffer.
  12732. *
  12733. * @type {boolean}
  12734. */
  12735. get isStorageMatrix() {
  12736. const { instanceMatrix } = this;
  12737. return instanceMatrix && instanceMatrix.isStorageInstancedBufferAttribute === true;
  12738. }
  12739. /**
  12740. * Tracks whether the color data is provided via a storage buffer.
  12741. *
  12742. * @type {boolean}
  12743. */
  12744. get isStorageColor() {
  12745. const { instanceColor } = this;
  12746. return instanceColor && instanceColor.isStorageInstancedBufferAttribute === true;
  12747. }
  12748. /**
  12749. * Setups the internal buffers and nodes and assigns the transformed vertex data
  12750. * to predefined node variables for accumulation. That follows the same patterns
  12751. * like with morph and skinning nodes.
  12752. *
  12753. * @param {NodeBuilder} builder - The current node builder.
  12754. */
  12755. setup( builder ) {
  12756. let { instanceMatrixNode, instanceColorNode } = this;
  12757. // instance matrix
  12758. if ( instanceMatrixNode === null ) {
  12759. instanceMatrixNode = this._createInstanceMatrixNode( true, builder );
  12760. this.instanceMatrixNode = instanceMatrixNode;
  12761. }
  12762. // instance color
  12763. const { instanceColor, isStorageColor } = this;
  12764. if ( instanceColor && instanceColorNode === null ) {
  12765. if ( isStorageColor ) {
  12766. instanceColorNode = storage( instanceColor, 'vec3', Math.max( instanceColor.count, 1 ) ).element( instanceIndex );
  12767. } else {
  12768. const bufferAttribute = new InstancedBufferAttribute( instanceColor.array, 3 );
  12769. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  12770. this.bufferColor = bufferAttribute;
  12771. instanceColorNode = vec3( bufferFn( bufferAttribute, 'vec3', 3, 0 ) );
  12772. }
  12773. this.instanceColorNode = instanceColorNode;
  12774. }
  12775. // POSITION
  12776. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  12777. positionLocal.assign( instancePosition );
  12778. if ( builder.needsPreviousData() ) {
  12779. positionPrevious.assign( this.getPreviousInstancedPosition( builder ) );
  12780. }
  12781. // NORMAL
  12782. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  12783. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  12784. // ASSIGNS
  12785. normalLocal.assign( instanceNormal );
  12786. }
  12787. // COLOR
  12788. if ( this.instanceColorNode !== null ) {
  12789. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  12790. }
  12791. }
  12792. /**
  12793. * Checks if the internal buffers require an update.
  12794. *
  12795. * @param {NodeFrame} frame - The current node frame.
  12796. */
  12797. update( frame ) {
  12798. if ( this.buffer !== null && this.isStorageMatrix !== true ) {
  12799. this.buffer.clearUpdateRanges();
  12800. this.buffer.updateRanges.push( ... this.instanceMatrix.updateRanges );
  12801. // update version if necessary
  12802. if ( this.instanceMatrix.version !== this.buffer.version ) {
  12803. this.buffer.version = this.instanceMatrix.version;
  12804. }
  12805. }
  12806. if ( this.instanceColor && this.bufferColor !== null && this.isStorageColor !== true ) {
  12807. this.bufferColor.clearUpdateRanges();
  12808. this.bufferColor.updateRanges.push( ... this.instanceColor.updateRanges );
  12809. if ( this.instanceColor.version !== this.bufferColor.version ) {
  12810. this.bufferColor.version = this.instanceColor.version;
  12811. }
  12812. }
  12813. if ( this.previousInstanceMatrixNode !== null ) {
  12814. frame.object.previousInstanceMatrix.array.set( this.instanceMatrix.array );
  12815. }
  12816. }
  12817. /**
  12818. * Computes the transformed/instanced vertex position of the previous frame.
  12819. *
  12820. * @param {NodeBuilder} builder - The current node builder.
  12821. * @return {Node<vec3>} The instanced position from the previous frame.
  12822. */
  12823. getPreviousInstancedPosition( builder ) {
  12824. const instancedMesh = builder.object;
  12825. if ( this.previousInstanceMatrixNode === null ) {
  12826. instancedMesh.previousInstanceMatrix = this.instanceMatrix.clone();
  12827. this.previousInstanceMatrixNode = this._createInstanceMatrixNode( false, builder );
  12828. }
  12829. return this.previousInstanceMatrixNode.mul( positionPrevious ).xyz;
  12830. }
  12831. /**
  12832. * Creates a node representing the instance matrix data.
  12833. *
  12834. * @private
  12835. * @param {boolean} assignBuffer - Whether the created interleaved buffer should be assigned to the `buffer` member or not.
  12836. * @param {NodeBuilder} builder - A reference to the current node builder.
  12837. * @return {Node} The instance matrix node.
  12838. */
  12839. _createInstanceMatrixNode( assignBuffer, builder ) {
  12840. let instanceMatrixNode;
  12841. const { instanceMatrix } = this;
  12842. const { count } = instanceMatrix;
  12843. if ( this.isStorageMatrix ) {
  12844. instanceMatrixNode = storage( instanceMatrix, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  12845. } else {
  12846. const uniformBufferSize = count * 16 * 4; // count * 16 components * 4 bytes (float)
  12847. if ( uniformBufferSize <= builder.getUniformBufferLimit() ) {
  12848. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  12849. } else {
  12850. const interleaved = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  12851. if ( assignBuffer === true ) this.buffer = interleaved;
  12852. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  12853. const instanceBuffers = [
  12854. bufferFn( interleaved, 'vec4', 16, 0 ),
  12855. bufferFn( interleaved, 'vec4', 16, 4 ),
  12856. bufferFn( interleaved, 'vec4', 16, 8 ),
  12857. bufferFn( interleaved, 'vec4', 16, 12 )
  12858. ];
  12859. instanceMatrixNode = mat4( ...instanceBuffers );
  12860. }
  12861. }
  12862. return instanceMatrixNode;
  12863. }
  12864. }
  12865. /**
  12866. * TSL function for creating an instance node.
  12867. *
  12868. * @tsl
  12869. * @function
  12870. * @param {number} count - The number of instances.
  12871. * @param {InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  12872. * @param {?InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  12873. * @returns {InstanceNode}
  12874. */
  12875. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  12876. /**
  12877. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  12878. * It allows an easier setup of the instance node.
  12879. *
  12880. * @augments InstanceNode
  12881. */
  12882. class InstancedMeshNode extends InstanceNode {
  12883. static get type() {
  12884. return 'InstancedMeshNode';
  12885. }
  12886. /**
  12887. * Constructs a new instanced mesh node.
  12888. *
  12889. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  12890. */
  12891. constructor( instancedMesh ) {
  12892. const { count, instanceMatrix, instanceColor } = instancedMesh;
  12893. super( count, instanceMatrix, instanceColor );
  12894. /**
  12895. * A reference to the instanced mesh.
  12896. *
  12897. * @type {InstancedMesh}
  12898. */
  12899. this.instancedMesh = instancedMesh;
  12900. }
  12901. }
  12902. /**
  12903. * TSL function for creating an instanced mesh node.
  12904. *
  12905. * @tsl
  12906. * @function
  12907. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  12908. * @returns {InstancedMeshNode}
  12909. */
  12910. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  12911. /**
  12912. * This node implements the vertex shader logic which is required
  12913. * when rendering 3D objects via batching. `BatchNode` must be used
  12914. * with instances of {@link BatchedMesh}.
  12915. *
  12916. * @augments Node
  12917. */
  12918. class BatchNode extends Node {
  12919. static get type() {
  12920. return 'BatchNode';
  12921. }
  12922. /**
  12923. * Constructs a new batch node.
  12924. *
  12925. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  12926. */
  12927. constructor( batchMesh ) {
  12928. super( 'void' );
  12929. /**
  12930. * A reference to batched mesh.
  12931. *
  12932. * @type {BatchedMesh}
  12933. */
  12934. this.batchMesh = batchMesh;
  12935. /**
  12936. * The batching index node.
  12937. *
  12938. * @type {?IndexNode}
  12939. * @default null
  12940. */
  12941. this.batchingIdNode = null;
  12942. }
  12943. /**
  12944. * Setups the internal buffers and nodes and assigns the transformed vertex data
  12945. * to predefined node variables for accumulation. That follows the same patterns
  12946. * like with morph and skinning nodes.
  12947. *
  12948. * @param {NodeBuilder} builder - The current node builder.
  12949. */
  12950. setup( builder ) {
  12951. if ( this.batchingIdNode === null ) {
  12952. if ( builder.getDrawIndex() === null ) {
  12953. this.batchingIdNode = instanceIndex;
  12954. } else {
  12955. this.batchingIdNode = drawIndex;
  12956. }
  12957. }
  12958. const getIndirectIndex = Fn( ( [ id ] ) => {
  12959. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x ).toConst();
  12960. const x = int( id ).mod( size ).toConst();
  12961. const y = int( id ).div( size ).toConst();
  12962. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  12963. } ).setLayout( {
  12964. name: 'getIndirectIndex',
  12965. type: 'uint',
  12966. inputs: [
  12967. { name: 'id', type: 'int' }
  12968. ]
  12969. } );
  12970. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  12971. const matricesTexture = this.batchMesh._matricesTexture;
  12972. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x ).toConst();
  12973. const j = float( indirectId ).mul( 4 ).toInt().toConst();
  12974. const x = j.mod( size ).toConst();
  12975. const y = j.div( size ).toConst();
  12976. const batchingMatrix = mat4(
  12977. textureLoad( matricesTexture, ivec2( x, y ) ),
  12978. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  12979. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  12980. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  12981. );
  12982. const colorsTexture = this.batchMesh._colorsTexture;
  12983. if ( colorsTexture !== null ) {
  12984. const getBatchingColor = Fn( ( [ id ] ) => {
  12985. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x ).toConst();
  12986. const j = id;
  12987. const x = j.mod( size ).toConst();
  12988. const y = j.div( size ).toConst();
  12989. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  12990. } ).setLayout( {
  12991. name: 'getBatchingColor',
  12992. type: 'vec3',
  12993. inputs: [
  12994. { name: 'id', type: 'int' }
  12995. ]
  12996. } );
  12997. const color = getBatchingColor( indirectId );
  12998. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  12999. }
  13000. const bm = mat3( batchingMatrix );
  13001. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  13002. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  13003. const batchingNormal = bm.mul( transformedNormal ).xyz;
  13004. normalLocal.assign( batchingNormal );
  13005. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  13006. tangentLocal.mulAssign( bm );
  13007. }
  13008. }
  13009. }
  13010. /**
  13011. * TSL function for creating a batch node.
  13012. *
  13013. * @tsl
  13014. * @function
  13015. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  13016. * @returns {BatchNode}
  13017. */
  13018. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  13019. const _frameId = new WeakMap();
  13020. /**
  13021. * This node implements the vertex transformation shader logic which is required
  13022. * for skinning/skeletal animation.
  13023. *
  13024. * @augments Node
  13025. */
  13026. class SkinningNode extends Node {
  13027. static get type() {
  13028. return 'SkinningNode';
  13029. }
  13030. /**
  13031. * Constructs a new skinning node.
  13032. *
  13033. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  13034. */
  13035. constructor( skinnedMesh ) {
  13036. super( 'void' );
  13037. /**
  13038. * The skinned mesh.
  13039. *
  13040. * @type {SkinnedMesh}
  13041. */
  13042. this.skinnedMesh = skinnedMesh;
  13043. /**
  13044. * The update type overwritten since skinning nodes are updated per object.
  13045. *
  13046. * @type {string}
  13047. */
  13048. this.updateType = NodeUpdateType.OBJECT;
  13049. //
  13050. /**
  13051. * The skin index attribute.
  13052. *
  13053. * @type {AttributeNode}
  13054. */
  13055. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  13056. /**
  13057. * The skin weight attribute.
  13058. *
  13059. * @type {AttributeNode}
  13060. */
  13061. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  13062. /**
  13063. * The bind matrix node.
  13064. *
  13065. * @type {Node<mat4>}
  13066. */
  13067. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  13068. /**
  13069. * The bind matrix inverse node.
  13070. *
  13071. * @type {Node<mat4>}
  13072. */
  13073. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  13074. /**
  13075. * The bind matrices as a uniform buffer node.
  13076. *
  13077. * @type {Node}
  13078. */
  13079. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  13080. /**
  13081. * The current vertex position in local space.
  13082. *
  13083. * @type {Node<vec3>}
  13084. */
  13085. this.positionNode = positionLocal;
  13086. /**
  13087. * The result of vertex position in local space.
  13088. *
  13089. * @type {Node<vec3>}
  13090. */
  13091. this.toPositionNode = positionLocal;
  13092. /**
  13093. * The previous bind matrices as a uniform buffer node.
  13094. * Required for computing motion vectors.
  13095. *
  13096. * @type {?Node}
  13097. * @default null
  13098. */
  13099. this.previousBoneMatricesNode = null;
  13100. }
  13101. /**
  13102. * Transforms the given vertex position via skinning.
  13103. *
  13104. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  13105. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  13106. * @return {Node<vec3>} The transformed vertex position.
  13107. */
  13108. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  13109. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  13110. const boneMatX = boneMatrices.element( skinIndexNode.x );
  13111. const boneMatY = boneMatrices.element( skinIndexNode.y );
  13112. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  13113. const boneMatW = boneMatrices.element( skinIndexNode.w );
  13114. // POSITION
  13115. const skinVertex = bindMatrixNode.mul( position );
  13116. const skinned = add(
  13117. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  13118. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  13119. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  13120. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  13121. );
  13122. return bindMatrixInverseNode.mul( skinned ).xyz;
  13123. }
  13124. /**
  13125. * Transforms the given vertex normal and tangent via skinning.
  13126. *
  13127. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  13128. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  13129. * @param {Node<vec3>} [tangent=tangentLocal] - The vertex tangent in local space.
  13130. * @return {{skinNormal: Node<vec3>, skinTangent:Node<vec3>}} The transformed vertex normal and tangent.
  13131. */
  13132. getSkinnedNormalAndTangent( boneMatrices = this.boneMatricesNode, normal = normalLocal, tangent = tangentLocal ) {
  13133. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  13134. const boneMatX = boneMatrices.element( skinIndexNode.x );
  13135. const boneMatY = boneMatrices.element( skinIndexNode.y );
  13136. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  13137. const boneMatW = boneMatrices.element( skinIndexNode.w );
  13138. // NORMAL and TANGENT
  13139. let skinMatrix = add(
  13140. skinWeightNode.x.mul( boneMatX ),
  13141. skinWeightNode.y.mul( boneMatY ),
  13142. skinWeightNode.z.mul( boneMatZ ),
  13143. skinWeightNode.w.mul( boneMatW )
  13144. );
  13145. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  13146. const skinNormal = skinMatrix.transformDirection( normal ).xyz;
  13147. const skinTangent = skinMatrix.transformDirection( tangent ).xyz;
  13148. return { skinNormal, skinTangent };
  13149. }
  13150. /**
  13151. * Computes the transformed/skinned vertex position of the previous frame.
  13152. *
  13153. * @param {NodeBuilder} builder - The current node builder.
  13154. * @return {Node<vec3>} The skinned position from the previous frame.
  13155. */
  13156. getPreviousSkinnedPosition( builder ) {
  13157. const skinnedMesh = builder.object;
  13158. if ( this.previousBoneMatricesNode === null ) {
  13159. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  13160. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  13161. }
  13162. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  13163. }
  13164. /**
  13165. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  13166. *
  13167. * @param {NodeBuilder} builder - The current node builder.
  13168. * @return {Node<vec3>} The transformed vertex position.
  13169. */
  13170. setup( builder ) {
  13171. if ( builder.needsPreviousData() ) {
  13172. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  13173. }
  13174. const skinPosition = this.getSkinnedPosition();
  13175. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  13176. //
  13177. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  13178. const { skinNormal, skinTangent } = this.getSkinnedNormalAndTangent();
  13179. normalLocal.assign( skinNormal );
  13180. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  13181. tangentLocal.assign( skinTangent );
  13182. }
  13183. }
  13184. return skinPosition;
  13185. }
  13186. /**
  13187. * Generates the code snippet of the skinning node.
  13188. *
  13189. * @param {NodeBuilder} builder - The current node builder.
  13190. * @param {string} output - The current output.
  13191. * @return {string} The generated code snippet.
  13192. */
  13193. generate( builder, output ) {
  13194. if ( output !== 'void' ) {
  13195. return super.generate( builder, output );
  13196. }
  13197. }
  13198. /**
  13199. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  13200. *
  13201. * @param {NodeFrame} frame - The current node frame.
  13202. */
  13203. update( frame ) {
  13204. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  13205. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  13206. _frameId.set( skeleton, frame.frameId );
  13207. if ( this.previousBoneMatricesNode !== null ) {
  13208. if ( skeleton.previousBoneMatrices === null ) {
  13209. // cloned skeletons miss "previousBoneMatrices" in their first updated
  13210. skeleton.previousBoneMatrices = new Float32Array( skeleton.boneMatrices );
  13211. }
  13212. skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  13213. }
  13214. skeleton.update();
  13215. }
  13216. }
  13217. /**
  13218. * TSL function for creating a skinning node.
  13219. *
  13220. * @tsl
  13221. * @function
  13222. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  13223. * @returns {SkinningNode}
  13224. */
  13225. const skinning = ( skinnedMesh ) => new SkinningNode( skinnedMesh );
  13226. /**
  13227. * TSL function for computing skinning.
  13228. *
  13229. * @tsl
  13230. * @function
  13231. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  13232. * @param {Node<vec3>} [toPosition=null] - The target position.
  13233. * @returns {SkinningNode}
  13234. */
  13235. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  13236. const node = new SkinningNode( skinnedMesh );
  13237. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  13238. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  13239. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  13240. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  13241. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  13242. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  13243. node.toPositionNode = toPosition;
  13244. return nodeObject( node );
  13245. };
  13246. /**
  13247. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  13248. * ```js
  13249. * Loop( count, ( { i } ) => {
  13250. *
  13251. * } );
  13252. * ```
  13253. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  13254. * ```js
  13255. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  13256. *
  13257. * } );
  13258. *```
  13259. * Nested loops can be defined in a compacted form:
  13260. * ```js
  13261. * Loop( 10, 5, ( { i, j } ) => {
  13262. *
  13263. * } );
  13264. * ```
  13265. * Loops that should run backwards can be defined like so:
  13266. * ```js
  13267. * Loop( { start: 10 }, () => {} );
  13268. * ```
  13269. * It is possible to execute with boolean values, similar to the `while` syntax.
  13270. * ```js
  13271. * const value = float( 0 ).toVar();
  13272. *
  13273. * Loop( value.lessThan( 10 ), () => {
  13274. *
  13275. * value.addAssign( 1 );
  13276. *
  13277. * } );
  13278. * ```
  13279. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  13280. * @augments Node
  13281. */
  13282. class LoopNode extends Node {
  13283. static get type() {
  13284. return 'LoopNode';
  13285. }
  13286. /**
  13287. * Constructs a new loop node.
  13288. *
  13289. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  13290. */
  13291. constructor( params = [] ) {
  13292. super( 'void' );
  13293. this.params = params;
  13294. }
  13295. /**
  13296. * Returns a loop variable name based on an index. The pattern is
  13297. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  13298. *
  13299. * @param {number} index - The index.
  13300. * @return {string} The loop variable name.
  13301. */
  13302. getVarName( index ) {
  13303. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  13304. }
  13305. /**
  13306. * Returns properties about this node.
  13307. *
  13308. * @param {NodeBuilder} builder - The current node builder.
  13309. * @return {Object} The node properties.
  13310. */
  13311. getProperties( builder ) {
  13312. const properties = builder.getNodeProperties( this );
  13313. if ( properties.stackNode !== undefined ) return properties;
  13314. //
  13315. const inputs = {};
  13316. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  13317. const param = this.params[ i ];
  13318. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  13319. const type = ( param.isNode !== true && param.type ) || 'int';
  13320. inputs[ name ] = expression( name, type );
  13321. }
  13322. const stack = builder.addStack();
  13323. const fnCall = this.params[ this.params.length - 1 ]( inputs );
  13324. properties.returnsNode = fnCall.context( { nodeLoop: fnCall } );
  13325. properties.stackNode = stack;
  13326. const baseParam = this.params[ 0 ];
  13327. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  13328. const fnUpdateCall = Fn( this.params[ 0 ].update )( inputs );
  13329. properties.updateNode = fnUpdateCall.context( { nodeLoop: fnUpdateCall } );
  13330. }
  13331. builder.removeStack();
  13332. return properties;
  13333. }
  13334. setup( builder ) {
  13335. // setup properties
  13336. this.getProperties( builder );
  13337. if ( builder.fnCall ) {
  13338. const shaderNodeData = builder.getDataFromNode( builder.fnCall.shaderNode );
  13339. shaderNodeData.hasLoop = true;
  13340. }
  13341. }
  13342. generate( builder ) {
  13343. const properties = this.getProperties( builder );
  13344. const params = this.params;
  13345. const stackNode = properties.stackNode;
  13346. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  13347. const param = params[ i ];
  13348. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  13349. if ( param.isNode ) {
  13350. if ( param.getNodeType( builder ) === 'bool' ) {
  13351. isWhile = true;
  13352. type = 'bool';
  13353. end = param.build( builder, type );
  13354. } else {
  13355. type = 'int';
  13356. name = this.getVarName( i );
  13357. start = '0';
  13358. end = param.build( builder, type );
  13359. condition = '<';
  13360. }
  13361. } else {
  13362. type = param.type || 'int';
  13363. name = param.name || this.getVarName( i );
  13364. start = param.start;
  13365. end = param.end;
  13366. condition = param.condition;
  13367. update = param.update;
  13368. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  13369. else if ( start && start.isNode ) start = start.build( builder, type );
  13370. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  13371. else if ( end && end.isNode ) end = end.build( builder, type );
  13372. if ( start !== undefined && end === undefined ) {
  13373. start = start + ' - 1';
  13374. end = '0';
  13375. condition = '>=';
  13376. } else if ( end !== undefined && start === undefined ) {
  13377. start = '0';
  13378. condition = '<';
  13379. }
  13380. if ( condition === undefined ) {
  13381. if ( Number( start ) > Number( end ) ) {
  13382. condition = '>=';
  13383. } else {
  13384. condition = '<';
  13385. }
  13386. }
  13387. }
  13388. let loopSnippet;
  13389. if ( isWhile ) {
  13390. loopSnippet = `while ( ${ end } )`;
  13391. } else {
  13392. const internalParam = { start, end};
  13393. //
  13394. const startSnippet = internalParam.start;
  13395. const endSnippet = internalParam.end;
  13396. let updateSnippet;
  13397. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  13398. if ( update !== undefined && update !== null ) {
  13399. switch ( typeof update ) {
  13400. case 'function':
  13401. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  13402. const snippet = flow.code.replace( /\t|;/g, '' );
  13403. updateSnippet = snippet;
  13404. break;
  13405. case 'number':
  13406. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  13407. break;
  13408. case 'string':
  13409. updateSnippet = name + ' ' + update;
  13410. break;
  13411. default:
  13412. if ( update.isNode ) {
  13413. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  13414. } else {
  13415. error( 'TSL: \'Loop( { update: ... } )\' is not a function, string or number.', this.stackTrace );
  13416. updateSnippet = 'break /* invalid update */';
  13417. }
  13418. }
  13419. } else {
  13420. if ( type === 'int' || type === 'uint' ) {
  13421. update = condition.includes( '<' ) ? '++' : '--';
  13422. } else {
  13423. update = deltaOperator() + ' 1.';
  13424. }
  13425. updateSnippet = name + ' ' + update;
  13426. }
  13427. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  13428. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  13429. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  13430. }
  13431. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  13432. }
  13433. const stackSnippet = stackNode.build( builder, 'void' );
  13434. properties.returnsNode.build( builder, 'void' );
  13435. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  13436. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  13437. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  13438. }
  13439. builder.addFlowTab();
  13440. }
  13441. }
  13442. /**
  13443. * TSL function for creating a loop node.
  13444. *
  13445. * @tsl
  13446. * @function
  13447. * @param {...any} params - A list of parameters.
  13448. * @returns {LoopNode}
  13449. */
  13450. const Loop = ( ...params ) => new LoopNode( nodeArray( params, 'int' ) ).toStack();
  13451. /**
  13452. * TSL function for creating a `Continue()` expression.
  13453. *
  13454. * @tsl
  13455. * @function
  13456. * @returns {ExpressionNode}
  13457. */
  13458. const Continue = () => expression( 'continue' ).toStack();
  13459. /**
  13460. * TSL function for creating a `Break()` expression.
  13461. *
  13462. * @tsl
  13463. * @function
  13464. * @returns {ExpressionNode}
  13465. */
  13466. const Break = () => expression( 'break' ).toStack();
  13467. const _morphTextures = /*@__PURE__*/ new WeakMap();
  13468. const _morphVec4 = /*@__PURE__*/ new Vector4();
  13469. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  13470. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  13471. const y = texelIndex.div( width );
  13472. const x = texelIndex.sub( y.mul( width ) );
  13473. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  13474. return bufferAttrib.mul( influence );
  13475. } );
  13476. function getEntry( geometry ) {
  13477. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  13478. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  13479. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  13480. // instead of using attributes, the WebGL 2 code path encodes morph targets
  13481. // into an array of data textures. Each layer represents a single morph target.
  13482. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  13483. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  13484. let entry = _morphTextures.get( geometry );
  13485. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  13486. if ( entry !== undefined ) entry.texture.dispose();
  13487. const morphTargets = geometry.morphAttributes.position || [];
  13488. const morphNormals = geometry.morphAttributes.normal || [];
  13489. const morphColors = geometry.morphAttributes.color || [];
  13490. let vertexDataCount = 0;
  13491. if ( hasMorphPosition === true ) vertexDataCount = 1;
  13492. if ( hasMorphNormals === true ) vertexDataCount = 2;
  13493. if ( hasMorphColors === true ) vertexDataCount = 3;
  13494. let width = geometry.attributes.position.count * vertexDataCount;
  13495. let height = 1;
  13496. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  13497. if ( width > maxTextureSize ) {
  13498. height = Math.ceil( width / maxTextureSize );
  13499. width = maxTextureSize;
  13500. }
  13501. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  13502. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  13503. bufferTexture.type = FloatType;
  13504. bufferTexture.needsUpdate = true;
  13505. // fill buffer
  13506. const vertexDataStride = vertexDataCount * 4;
  13507. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  13508. const morphTarget = morphTargets[ i ];
  13509. const morphNormal = morphNormals[ i ];
  13510. const morphColor = morphColors[ i ];
  13511. const offset = width * height * 4 * i;
  13512. for ( let j = 0; j < morphTarget.count; j ++ ) {
  13513. const stride = j * vertexDataStride;
  13514. if ( hasMorphPosition === true ) {
  13515. _morphVec4.fromBufferAttribute( morphTarget, j );
  13516. buffer[ offset + stride + 0 ] = _morphVec4.x;
  13517. buffer[ offset + stride + 1 ] = _morphVec4.y;
  13518. buffer[ offset + stride + 2 ] = _morphVec4.z;
  13519. buffer[ offset + stride + 3 ] = 0;
  13520. }
  13521. if ( hasMorphNormals === true ) {
  13522. _morphVec4.fromBufferAttribute( morphNormal, j );
  13523. buffer[ offset + stride + 4 ] = _morphVec4.x;
  13524. buffer[ offset + stride + 5 ] = _morphVec4.y;
  13525. buffer[ offset + stride + 6 ] = _morphVec4.z;
  13526. buffer[ offset + stride + 7 ] = 0;
  13527. }
  13528. if ( hasMorphColors === true ) {
  13529. _morphVec4.fromBufferAttribute( morphColor, j );
  13530. buffer[ offset + stride + 8 ] = _morphVec4.x;
  13531. buffer[ offset + stride + 9 ] = _morphVec4.y;
  13532. buffer[ offset + stride + 10 ] = _morphVec4.z;
  13533. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  13534. }
  13535. }
  13536. }
  13537. entry = {
  13538. count: morphTargetsCount,
  13539. texture: bufferTexture,
  13540. stride: vertexDataCount,
  13541. size: new Vector2( width, height )
  13542. };
  13543. _morphTextures.set( geometry, entry );
  13544. function disposeTexture() {
  13545. bufferTexture.dispose();
  13546. _morphTextures.delete( geometry );
  13547. geometry.removeEventListener( 'dispose', disposeTexture );
  13548. }
  13549. geometry.addEventListener( 'dispose', disposeTexture );
  13550. }
  13551. return entry;
  13552. }
  13553. /**
  13554. * This node implements the vertex transformation shader logic which is required
  13555. * for morph target animation.
  13556. *
  13557. * @augments Node
  13558. */
  13559. class MorphNode extends Node {
  13560. static get type() {
  13561. return 'MorphNode';
  13562. }
  13563. /**
  13564. * Constructs a new morph node.
  13565. *
  13566. * @param {Mesh} mesh - The mesh holding the morph targets.
  13567. */
  13568. constructor( mesh ) {
  13569. super( 'void' );
  13570. /**
  13571. * The mesh holding the morph targets.
  13572. *
  13573. * @type {Mesh}
  13574. */
  13575. this.mesh = mesh;
  13576. /**
  13577. * A uniform node which represents the morph base influence value.
  13578. *
  13579. * @type {UniformNode<float>}
  13580. */
  13581. this.morphBaseInfluence = uniform( 1 );
  13582. /**
  13583. * The update type overwritten since morph nodes are updated per object.
  13584. *
  13585. * @type {string}
  13586. */
  13587. this.updateType = NodeUpdateType.OBJECT;
  13588. }
  13589. /**
  13590. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  13591. *
  13592. * @param {NodeBuilder} builder - The current node builder.
  13593. */
  13594. setup( builder ) {
  13595. const { geometry } = builder;
  13596. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  13597. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  13598. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  13599. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  13600. // nodes
  13601. const { texture: bufferMap, stride, size } = getEntry( geometry );
  13602. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  13603. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  13604. const width = int( size.width );
  13605. Loop( morphTargetsCount, ( { i } ) => {
  13606. const influence = float( 0 ).toVar();
  13607. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  13608. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  13609. } else {
  13610. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  13611. }
  13612. If( influence.notEqual( 0 ), () => {
  13613. if ( hasMorphPosition === true ) {
  13614. positionLocal.addAssign( getMorph( {
  13615. bufferMap,
  13616. influence,
  13617. stride,
  13618. width,
  13619. depth: i,
  13620. offset: int( 0 )
  13621. } ) );
  13622. }
  13623. if ( hasMorphNormals === true ) {
  13624. normalLocal.addAssign( getMorph( {
  13625. bufferMap,
  13626. influence,
  13627. stride,
  13628. width,
  13629. depth: i,
  13630. offset: int( 1 )
  13631. } ) );
  13632. }
  13633. } );
  13634. } );
  13635. }
  13636. /**
  13637. * Updates the state of the morphed mesh by updating the base influence.
  13638. *
  13639. * @param {NodeFrame} frame - The current node frame.
  13640. */
  13641. update( /*frame*/ ) {
  13642. const morphBaseInfluence = this.morphBaseInfluence;
  13643. if ( this.mesh.geometry.morphTargetsRelative ) {
  13644. morphBaseInfluence.value = 1;
  13645. } else {
  13646. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  13647. }
  13648. }
  13649. }
  13650. /**
  13651. * TSL function for creating a morph node.
  13652. *
  13653. * @tsl
  13654. * @function
  13655. * @param {Mesh} mesh - The mesh holding the morph targets.
  13656. * @returns {MorphNode}
  13657. */
  13658. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  13659. /**
  13660. * Base class for lighting nodes.
  13661. *
  13662. * @augments Node
  13663. */
  13664. class LightingNode extends Node {
  13665. static get type() {
  13666. return 'LightingNode';
  13667. }
  13668. /**
  13669. * Constructs a new lighting node.
  13670. */
  13671. constructor() {
  13672. super( 'vec3' );
  13673. /**
  13674. * This flag can be used for type testing.
  13675. *
  13676. * @type {boolean}
  13677. * @readonly
  13678. * @default true
  13679. */
  13680. this.isLightingNode = true;
  13681. }
  13682. }
  13683. /**
  13684. * A generic class that can be used by nodes which contribute
  13685. * ambient occlusion to the scene. E.g. an ambient occlusion map
  13686. * node can be used as input for this module. Used in {@link NodeMaterial}.
  13687. *
  13688. * @augments LightingNode
  13689. */
  13690. class AONode extends LightingNode {
  13691. static get type() {
  13692. return 'AONode';
  13693. }
  13694. /**
  13695. * Constructs a new AO node.
  13696. *
  13697. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  13698. */
  13699. constructor( aoNode = null ) {
  13700. super();
  13701. /**
  13702. * The ambient occlusion node.
  13703. *
  13704. * @type {?Node<float>}
  13705. * @default null
  13706. */
  13707. this.aoNode = aoNode;
  13708. }
  13709. setup( builder ) {
  13710. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  13711. }
  13712. }
  13713. /**
  13714. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  13715. * by adding lighting specific context data. It represents the runtime context of
  13716. * {@link LightsNode}.
  13717. *
  13718. * @augments ContextNode
  13719. */
  13720. class LightingContextNode extends ContextNode {
  13721. static get type() {
  13722. return 'LightingContextNode';
  13723. }
  13724. /**
  13725. * Constructs a new lighting context node.
  13726. *
  13727. * @param {LightsNode} lightsNode - The lights node.
  13728. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  13729. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  13730. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  13731. */
  13732. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  13733. super( lightsNode );
  13734. /**
  13735. * The current lighting model.
  13736. *
  13737. * @type {?LightingModel}
  13738. * @default null
  13739. */
  13740. this.lightingModel = lightingModel;
  13741. /**
  13742. * A backdrop node.
  13743. *
  13744. * @type {?Node<vec3>}
  13745. * @default null
  13746. */
  13747. this.backdropNode = backdropNode;
  13748. /**
  13749. * A backdrop alpha node.
  13750. *
  13751. * @type {?Node<float>}
  13752. * @default null
  13753. */
  13754. this.backdropAlphaNode = backdropAlphaNode;
  13755. this._value = null;
  13756. }
  13757. /**
  13758. * Returns a lighting context object.
  13759. *
  13760. * @return {{
  13761. * radiance: Node<vec3>,
  13762. * irradiance: Node<vec3>,
  13763. * iblIrradiance: Node<vec3>,
  13764. * ambientOcclusion: Node<float>,
  13765. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  13766. * backdrop: Node<vec3>,
  13767. * backdropAlpha: Node<float>
  13768. * }} The lighting context object.
  13769. */
  13770. getContext() {
  13771. const { backdropNode, backdropAlphaNode } = this;
  13772. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  13773. directSpecular = vec3().toVar( 'directSpecular' ),
  13774. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  13775. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  13776. const reflectedLight = {
  13777. directDiffuse,
  13778. directSpecular,
  13779. indirectDiffuse,
  13780. indirectSpecular
  13781. };
  13782. const context = {
  13783. radiance: vec3().toVar( 'radiance' ),
  13784. irradiance: vec3().toVar( 'irradiance' ),
  13785. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  13786. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  13787. reflectedLight,
  13788. backdrop: backdropNode,
  13789. backdropAlpha: backdropAlphaNode
  13790. };
  13791. return context;
  13792. }
  13793. setup( builder ) {
  13794. this.value = this._value || ( this._value = this.getContext() );
  13795. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  13796. return super.setup( builder );
  13797. }
  13798. }
  13799. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  13800. /**
  13801. * A generic class that can be used by nodes which contribute
  13802. * irradiance to the scene. E.g. a light map node can be used
  13803. * as input for this module. Used in {@link NodeMaterial}.
  13804. *
  13805. * @augments LightingNode
  13806. */
  13807. class IrradianceNode extends LightingNode {
  13808. static get type() {
  13809. return 'IrradianceNode';
  13810. }
  13811. /**
  13812. * Constructs a new irradiance node.
  13813. *
  13814. * @param {Node<vec3>} node - A node contributing irradiance.
  13815. */
  13816. constructor( node ) {
  13817. super();
  13818. /**
  13819. * A node contributing irradiance.
  13820. *
  13821. * @type {Node<vec3>}
  13822. */
  13823. this.node = node;
  13824. }
  13825. setup( builder ) {
  13826. builder.context.irradiance.addAssign( this.node );
  13827. }
  13828. }
  13829. const _size$5 = /*@__PURE__*/ new Vector2();
  13830. /**
  13831. * A special type of texture node which represents the data of the current viewport
  13832. * as a texture. The module extracts data from the current bound framebuffer with
  13833. * a copy operation so no extra render pass is required to produce the texture data
  13834. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  13835. * variety of effects like refractive or transmissive materials.
  13836. *
  13837. * @augments TextureNode
  13838. */
  13839. class ViewportTextureNode extends TextureNode {
  13840. static get type() {
  13841. return 'ViewportTextureNode';
  13842. }
  13843. /**
  13844. * Constructs a new viewport texture node.
  13845. *
  13846. * @param {Node} [uvNode=screenUV] - The uv node.
  13847. * @param {?Node} [levelNode=null] - The level node.
  13848. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13849. */
  13850. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  13851. let defaultFramebuffer = null;
  13852. if ( framebufferTexture === null ) {
  13853. defaultFramebuffer = new FramebufferTexture();
  13854. defaultFramebuffer.minFilter = LinearMipmapLinearFilter;
  13855. framebufferTexture = defaultFramebuffer;
  13856. } else {
  13857. defaultFramebuffer = framebufferTexture;
  13858. }
  13859. super( framebufferTexture, uvNode, levelNode );
  13860. /**
  13861. * Whether to generate mipmaps or not.
  13862. *
  13863. * @type {boolean}
  13864. * @default false
  13865. */
  13866. this.generateMipmaps = false;
  13867. /**
  13868. * The reference framebuffer texture. This is used to store the framebuffer texture
  13869. * for the current render target. If the render target changes, a new framebuffer texture
  13870. * is created automatically.
  13871. *
  13872. * @type {FramebufferTexture}
  13873. * @default null
  13874. */
  13875. this.defaultFramebuffer = defaultFramebuffer;
  13876. /**
  13877. * This flag can be used for type testing.
  13878. *
  13879. * @type {boolean}
  13880. * @readonly
  13881. * @default true
  13882. */
  13883. this.isOutputTextureNode = true;
  13884. /**
  13885. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node should extract
  13886. * the current contents of the bound framebuffer for each render call.
  13887. *
  13888. * @type {string}
  13889. * @default 'render'
  13890. */
  13891. this.updateBeforeType = NodeUpdateType.RENDER;
  13892. /**
  13893. * The framebuffer texture for the current renderer context.
  13894. *
  13895. * @type {WeakMap<RenderTarget, FramebufferTexture>}
  13896. * @private
  13897. */
  13898. this._cacheTextures = new WeakMap();
  13899. }
  13900. /**
  13901. * This methods returns a texture for the given render target or canvas target reference.
  13902. *
  13903. * To avoid rendering errors, `ViewportTextureNode` must use unique framebuffer textures
  13904. * for different render contexts.
  13905. *
  13906. * @param {?(RenderTarget|CanvasTarget)} [reference=null] - The render target or canvas target reference.
  13907. * @return {Texture} The framebuffer texture.
  13908. */
  13909. getTextureForReference( reference = null ) {
  13910. let defaultFramebuffer;
  13911. let cacheTextures;
  13912. if ( this.referenceNode ) {
  13913. defaultFramebuffer = this.referenceNode.defaultFramebuffer;
  13914. cacheTextures = this.referenceNode._cacheTextures;
  13915. } else {
  13916. defaultFramebuffer = this.defaultFramebuffer;
  13917. cacheTextures = this._cacheTextures;
  13918. }
  13919. if ( reference === null ) {
  13920. return defaultFramebuffer;
  13921. }
  13922. if ( cacheTextures.has( reference ) === false ) {
  13923. const framebufferTexture = defaultFramebuffer.clone();
  13924. cacheTextures.set( reference, framebufferTexture );
  13925. }
  13926. return cacheTextures.get( reference );
  13927. }
  13928. updateReference( frame ) {
  13929. const renderer = frame.renderer;
  13930. const renderTarget = renderer.getRenderTarget();
  13931. const canvasTarget = renderer.getCanvasTarget();
  13932. const reference = renderTarget ? renderTarget : canvasTarget;
  13933. this.value = this.getTextureForReference( reference );
  13934. return this.value;
  13935. }
  13936. updateBefore( frame ) {
  13937. const renderer = frame.renderer;
  13938. const renderTarget = renderer.getRenderTarget();
  13939. const canvasTarget = renderer.getCanvasTarget();
  13940. const reference = renderTarget ? renderTarget : canvasTarget;
  13941. if ( reference === null ) {
  13942. renderer.getDrawingBufferSize( _size$5 );
  13943. } else if ( reference.getDrawingBufferSize ) {
  13944. reference.getDrawingBufferSize( _size$5 );
  13945. } else {
  13946. _size$5.set( reference.width, reference.height );
  13947. }
  13948. //
  13949. const framebufferTexture = this.getTextureForReference( reference );
  13950. if ( framebufferTexture.image.width !== _size$5.width || framebufferTexture.image.height !== _size$5.height ) {
  13951. framebufferTexture.image.width = _size$5.width;
  13952. framebufferTexture.image.height = _size$5.height;
  13953. framebufferTexture.needsUpdate = true;
  13954. }
  13955. //
  13956. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  13957. framebufferTexture.generateMipmaps = this.generateMipmaps;
  13958. renderer.copyFramebufferToTexture( framebufferTexture );
  13959. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  13960. }
  13961. clone() {
  13962. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  13963. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  13964. return viewportTextureNode;
  13965. }
  13966. }
  13967. /**
  13968. * TSL function for creating a viewport texture node.
  13969. *
  13970. * @tsl
  13971. * @function
  13972. * @param {?Node} [uvNode=screenUV] - The uv node.
  13973. * @param {?Node} [levelNode=null] - The level node.
  13974. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13975. * @returns {ViewportTextureNode}
  13976. */
  13977. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  13978. /**
  13979. * TSL function for creating a viewport texture node with enabled mipmap generation.
  13980. *
  13981. * @tsl
  13982. * @function
  13983. * @param {?Node} [uvNode=screenUV] - The uv node.
  13984. * @param {?Node} [levelNode=null] - The level node.
  13985. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13986. * @returns {ViewportTextureNode}
  13987. */
  13988. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  13989. // Singleton instances for common usage
  13990. const _singletonOpaqueViewportTextureNode = /*@__PURE__*/ viewportMipTexture();
  13991. /**
  13992. * TSL function for creating a viewport texture node with enabled mipmap generation.
  13993. * The texture should only contain the opaque rendering objects.
  13994. *
  13995. * This should be used just in transparent or transmissive materials.
  13996. *
  13997. * @tsl
  13998. * @function
  13999. * @param {?Node} [uv=screenUV] - The uv node.
  14000. * @param {?Node} [level=null] - The level node.
  14001. * @returns {ViewportTextureNode}
  14002. */
  14003. const viewportOpaqueMipTexture = ( uv = screenUV, level = null ) => _singletonOpaqueViewportTextureNode.sample( uv, level ); // TODO: Use once() when sample() supports it
  14004. let _sharedDepthbuffer = null;
  14005. /**
  14006. * Represents the depth of the current viewport as a texture. This module
  14007. * can be used in combination with viewport texture to achieve effects
  14008. * that require depth evaluation.
  14009. *
  14010. * @augments ViewportTextureNode
  14011. */
  14012. class ViewportDepthTextureNode extends ViewportTextureNode {
  14013. static get type() {
  14014. return 'ViewportDepthTextureNode';
  14015. }
  14016. /**
  14017. * Constructs a new viewport depth texture node.
  14018. *
  14019. * @param {Node} [uvNode=screenUV] - The uv node.
  14020. * @param {?Node} [levelNode=null] - The level node.
  14021. * @param {?DepthTexture} [depthTexture=null] - A depth texture. If not provided, uses a shared depth texture.
  14022. */
  14023. constructor( uvNode = screenUV, levelNode = null, depthTexture = null ) {
  14024. if ( depthTexture === null ) {
  14025. if ( _sharedDepthbuffer === null ) {
  14026. _sharedDepthbuffer = new DepthTexture();
  14027. }
  14028. depthTexture = _sharedDepthbuffer;
  14029. }
  14030. super( uvNode, levelNode, depthTexture );
  14031. }
  14032. }
  14033. /**
  14034. * TSL function for a viewport depth texture node.
  14035. *
  14036. * @tsl
  14037. * @function
  14038. * @param {?Node} [uvNode=screenUV] - The uv node.
  14039. * @param {?Node} [levelNode=null] - The level node.
  14040. * @param {?DepthTexture} [depthTexture=null] - A depth texture. If not provided, a depth texture is created automatically.
  14041. * @returns {ViewportDepthTextureNode}
  14042. */
  14043. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 3 );
  14044. /**
  14045. * This node offers a collection of features in context of the depth logic in the fragment shader.
  14046. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  14047. * fragment or for depth evaluation purposes.
  14048. *
  14049. * @augments Node
  14050. */
  14051. class ViewportDepthNode extends Node {
  14052. static get type() {
  14053. return 'ViewportDepthNode';
  14054. }
  14055. /**
  14056. * Constructs a new viewport depth node.
  14057. *
  14058. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  14059. * @param {?Node} [valueNode=null] - The value node.
  14060. */
  14061. constructor( scope, valueNode = null ) {
  14062. super( 'float' );
  14063. /**
  14064. * The node behaves differently depending on which scope is selected.
  14065. *
  14066. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  14067. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  14068. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  14069. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  14070. *
  14071. * @type {('depth'|'depthBase'|'linearDepth')}
  14072. */
  14073. this.scope = scope;
  14074. /**
  14075. * Can be used to define a custom depth value.
  14076. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  14077. *
  14078. * @type {?Node}
  14079. * @default null
  14080. */
  14081. this.valueNode = valueNode;
  14082. /**
  14083. * This flag can be used for type testing.
  14084. *
  14085. * @type {boolean}
  14086. * @readonly
  14087. * @default true
  14088. */
  14089. this.isViewportDepthNode = true;
  14090. }
  14091. generate( builder ) {
  14092. const { scope } = this;
  14093. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  14094. return builder.getFragDepth();
  14095. }
  14096. return super.generate( builder );
  14097. }
  14098. setup( { camera } ) {
  14099. const { scope } = this;
  14100. const value = this.valueNode;
  14101. let node = null;
  14102. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  14103. if ( value !== null ) {
  14104. node = depthBase().assign( value );
  14105. }
  14106. } else if ( scope === ViewportDepthNode.DEPTH ) {
  14107. if ( camera.isPerspectiveCamera ) {
  14108. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  14109. } else {
  14110. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  14111. }
  14112. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  14113. if ( value !== null ) {
  14114. if ( camera.isPerspectiveCamera ) {
  14115. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  14116. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  14117. } else {
  14118. node = value;
  14119. }
  14120. } else {
  14121. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  14122. }
  14123. }
  14124. return node;
  14125. }
  14126. }
  14127. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  14128. ViewportDepthNode.DEPTH = 'depth';
  14129. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  14130. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  14131. /**
  14132. * TSL function for converting a viewZ value to an orthographic depth value.
  14133. *
  14134. * @tsl
  14135. * @function
  14136. * @param {Node<float>} viewZ - The viewZ node.
  14137. * @param {Node<float>} near - The camera's near value.
  14138. * @param {Node<float>} far - The camera's far value.
  14139. * @returns {Node<float>}
  14140. */
  14141. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  14142. /**
  14143. * TSL function for converting a viewZ value to a reversed orthographic depth value.
  14144. *
  14145. * @tsl
  14146. * @function
  14147. * @param {Node<float>} viewZ - The viewZ node.
  14148. * @param {Node<float>} near - The camera's near value.
  14149. * @param {Node<float>} far - The camera's far value.
  14150. * @returns {Node<float>}
  14151. */
  14152. const viewZToReversedOrthographicDepth = ( viewZ, near, far ) => viewZ.add( far ).div( far.sub( near ) );
  14153. /**
  14154. * TSL function for converting an orthographic depth value to a viewZ value.
  14155. *
  14156. * @tsl
  14157. * @function
  14158. * @param {Node<float>} depth - The orthographic depth.
  14159. * @param {Node<float>} near - The camera's near value.
  14160. * @param {Node<float>} far - The camera's far value.
  14161. * @returns {Node<float>}
  14162. */
  14163. const orthographicDepthToViewZ = /*@__PURE__*/ Fn( ( [ depth, near, far ], builder ) => {
  14164. if ( builder.renderer.reversedDepthBuffer === true ) {
  14165. return far.sub( near ).mul( depth ).sub( far );
  14166. } else {
  14167. return near.sub( far ).mul( depth ).sub( near );
  14168. }
  14169. } );
  14170. /**
  14171. * TSL function for converting a viewZ value to a perspective depth value.
  14172. *
  14173. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  14174. *
  14175. * @tsl
  14176. * @function
  14177. * @param {Node<float>} viewZ - The viewZ node.
  14178. * @param {Node<float>} near - The camera's near value.
  14179. * @param {Node<float>} far - The camera's far value.
  14180. * @returns {Node<float>}
  14181. */
  14182. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  14183. /**
  14184. * TSL function for converting a viewZ value to a reversed perspective depth value.
  14185. *
  14186. * @tsl
  14187. * @function
  14188. * @param {Node<float>} viewZ - The viewZ node.
  14189. * @param {Node<float>} near - The camera's near value.
  14190. * @param {Node<float>} far - The camera's far value.
  14191. * @returns {Node<float>}
  14192. */
  14193. const viewZToReversedPerspectiveDepth = ( viewZ, near, far ) => near.mul( viewZ.add( far ) ).div( viewZ.mul( near.sub( far ) ) );
  14194. /**
  14195. * TSL function for converting a perspective depth value to a viewZ value.
  14196. *
  14197. * @tsl
  14198. * @function
  14199. * @param {Node<float>} depth - The perspective depth.
  14200. * @param {Node<float>} near - The camera's near value.
  14201. * @param {Node<float>} far - The camera's far value.
  14202. * @returns {Node<float>}
  14203. */
  14204. const perspectiveDepthToViewZ = /*@__PURE__*/ Fn( ( [ depth, near, far ], builder ) => {
  14205. if ( builder.renderer.reversedDepthBuffer === true ) {
  14206. return near.mul( far ).div( near.sub( far ).mul( depth ).sub( near ) );
  14207. } else {
  14208. return near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  14209. }
  14210. } );
  14211. /**
  14212. * TSL function for converting a viewZ value to a logarithmic depth value.
  14213. *
  14214. * @tsl
  14215. * @function
  14216. * @param {Node<float>} viewZ - The viewZ node.
  14217. * @param {Node<float>} near - The camera's near value.
  14218. * @param {Node<float>} far - The camera's far value.
  14219. * @returns {Node<float>}
  14220. */
  14221. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  14222. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  14223. // The final logarithmic depth formula used here is adapted from one described in an
  14224. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  14225. // which was an improvement upon an earlier formula one described in an
  14226. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  14227. // Ulrich's formula is the following:
  14228. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  14229. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  14230. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  14231. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  14232. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  14233. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  14234. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  14235. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  14236. // be used, and ultimately Ulrich's "near plane" version was chosen.
  14237. // Outerra eventually made another improvement to their original "C-constant" variant,
  14238. // but it still does not incorporate the camera near plane (for this version,
  14239. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  14240. // Here we make 4 changes to Ulrich's formula:
  14241. // 1. Clamp the camera near plane so we don't divide by 0.
  14242. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  14243. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  14244. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  14245. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  14246. // so we do the same here, hence the 'viewZ.negate()' call.
  14247. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  14248. near = near.max( 1e-6 ).toVar();
  14249. const numerator = log2( viewZ.negate().div( near ) );
  14250. const denominator = log2( far.div( near ) );
  14251. return numerator.div( denominator );
  14252. };
  14253. /**
  14254. * TSL function for converting a logarithmic depth value to a viewZ value.
  14255. *
  14256. * @tsl
  14257. * @function
  14258. * @param {Node<float>} depth - The logarithmic depth.
  14259. * @param {Node<float>} near - The camera's near value.
  14260. * @param {Node<float>} far - The camera's far value.
  14261. * @returns {Node<float>}
  14262. */
  14263. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  14264. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  14265. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  14266. // a negative viewZ).
  14267. const exponent = depth.mul( log( far.div( near ) ) );
  14268. return float( Math.E ).pow( exponent ).mul( near ).negate();
  14269. };
  14270. /**
  14271. * TSL function for defining a value for the current fragment's depth.
  14272. *
  14273. * @tsl
  14274. * @function
  14275. * @param {Node<float>} value - The depth value to set.
  14276. * @returns {ViewportDepthNode<float>}
  14277. */
  14278. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  14279. /**
  14280. * TSL object that represents the depth value for the current fragment.
  14281. *
  14282. * @tsl
  14283. * @type {ViewportDepthNode}
  14284. */
  14285. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  14286. /**
  14287. * TSL function for converting a perspective depth value to linear depth.
  14288. *
  14289. * @tsl
  14290. * @function
  14291. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  14292. * @returns {ViewportDepthNode<float>}
  14293. */
  14294. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  14295. /**
  14296. * TSL object that represents the linear (orthographic) depth value of the current fragment
  14297. *
  14298. * @tsl
  14299. * @type {ViewportDepthNode}
  14300. */
  14301. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  14302. depth.assign = ( value ) => depthBase( value );
  14303. /**
  14304. * This node is used in {@link NodeMaterial} to setup the clipping
  14305. * which can happen hardware-accelerated (if supported) and optionally
  14306. * use alpha-to-coverage for anti-aliasing clipped edges.
  14307. *
  14308. * @augments Node
  14309. */
  14310. class ClippingNode extends Node {
  14311. static get type() {
  14312. return 'ClippingNode';
  14313. }
  14314. /**
  14315. * Constructs a new clipping node.
  14316. *
  14317. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  14318. * the selected scope influences the behavior of the node and what type of code is generated.
  14319. */
  14320. constructor( scope = ClippingNode.DEFAULT ) {
  14321. super();
  14322. /**
  14323. * The node's scope. Similar to other nodes, the selected scope influences
  14324. * the behavior of the node and what type of code is generated.
  14325. *
  14326. * @type {('default'|'hardware'|'alphaToCoverage')}
  14327. */
  14328. this.scope = scope;
  14329. }
  14330. /**
  14331. * Setups the node depending on the selected scope.
  14332. *
  14333. * @param {NodeBuilder} builder - The current node builder.
  14334. * @return {Node} The result node.
  14335. */
  14336. setup( builder ) {
  14337. super.setup( builder );
  14338. const clippingContext = builder.clippingContext;
  14339. const { intersectionPlanes, unionPlanes } = clippingContext;
  14340. this.hardwareClipping = builder.material.hardwareClipping;
  14341. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  14342. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  14343. } else if ( this.scope === ClippingNode.HARDWARE ) {
  14344. return this.setupHardwareClipping( unionPlanes, builder );
  14345. } else {
  14346. return this.setupDefault( intersectionPlanes, unionPlanes );
  14347. }
  14348. }
  14349. /**
  14350. * Setups alpha to coverage.
  14351. *
  14352. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  14353. * @param {Array<Vector4>} unionPlanes - The union planes.
  14354. * @return {Node} The result node.
  14355. */
  14356. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  14357. return Fn( () => {
  14358. const distanceToPlane = float().toVar( 'distanceToPlane' );
  14359. const distanceGradient = float().toVar( 'distanceToGradient' );
  14360. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  14361. const numUnionPlanes = unionPlanes.length;
  14362. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  14363. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  14364. Loop( numUnionPlanes, ( { i } ) => {
  14365. const plane = clippingPlanes.element( i );
  14366. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  14367. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  14368. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  14369. } );
  14370. }
  14371. const numIntersectionPlanes = intersectionPlanes.length;
  14372. if ( numIntersectionPlanes > 0 ) {
  14373. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  14374. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  14375. Loop( numIntersectionPlanes, ( { i } ) => {
  14376. const plane = clippingPlanes.element( i );
  14377. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  14378. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  14379. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  14380. } );
  14381. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  14382. }
  14383. diffuseColor.a.mulAssign( clipOpacity );
  14384. diffuseColor.a.equal( 0.0 ).discard();
  14385. } )();
  14386. }
  14387. /**
  14388. * Setups the default clipping.
  14389. *
  14390. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  14391. * @param {Array<Vector4>} unionPlanes - The union planes.
  14392. * @return {Node} The result node.
  14393. */
  14394. setupDefault( intersectionPlanes, unionPlanes ) {
  14395. return Fn( () => {
  14396. const numUnionPlanes = unionPlanes.length;
  14397. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  14398. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  14399. Loop( numUnionPlanes, ( { i } ) => {
  14400. const plane = clippingPlanes.element( i );
  14401. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  14402. } );
  14403. }
  14404. const numIntersectionPlanes = intersectionPlanes.length;
  14405. if ( numIntersectionPlanes > 0 ) {
  14406. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  14407. const clipped = bool( true ).toVar( 'clipped' );
  14408. Loop( numIntersectionPlanes, ( { i } ) => {
  14409. const plane = clippingPlanes.element( i );
  14410. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  14411. } );
  14412. clipped.discard();
  14413. }
  14414. } )();
  14415. }
  14416. /**
  14417. * Setups hardware clipping.
  14418. *
  14419. * @param {Array<Vector4>} unionPlanes - The union planes.
  14420. * @param {NodeBuilder} builder - The current node builder.
  14421. * @return {Node} The result node.
  14422. */
  14423. setupHardwareClipping( unionPlanes, builder ) {
  14424. const numUnionPlanes = unionPlanes.length;
  14425. builder.enableHardwareClipping( numUnionPlanes );
  14426. return Fn( () => {
  14427. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  14428. const hw_clip_distances = builtin( builder.getClipDistance() );
  14429. Loop( numUnionPlanes, ( { i } ) => {
  14430. const plane = clippingPlanes.element( i );
  14431. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  14432. hw_clip_distances.element( i ).assign( distance );
  14433. } );
  14434. } )();
  14435. }
  14436. }
  14437. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  14438. ClippingNode.DEFAULT = 'default';
  14439. ClippingNode.HARDWARE = 'hardware';
  14440. /**
  14441. * TSL function for setting up the default clipping logic.
  14442. *
  14443. * @tsl
  14444. * @function
  14445. * @returns {ClippingNode}
  14446. */
  14447. const clipping = () => new ClippingNode();
  14448. /**
  14449. * TSL function for setting up alpha to coverage.
  14450. *
  14451. * @tsl
  14452. * @function
  14453. * @returns {ClippingNode}
  14454. */
  14455. const clippingAlpha = () => new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE );
  14456. /**
  14457. * TSL function for setting up hardware-based clipping.
  14458. *
  14459. * @tsl
  14460. * @function
  14461. * @returns {ClippingNode}
  14462. */
  14463. const hardwareClipping = () => new ClippingNode( ClippingNode.HARDWARE );
  14464. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  14465. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  14466. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  14467. 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 ) ) ) ) ) );
  14468. } );
  14469. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  14470. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  14471. } );
  14472. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  14473. // Find the discretized derivatives of our coordinates
  14474. const maxDeriv = max$1(
  14475. length( dFdx( position.xyz ) ),
  14476. length( dFdy( position.xyz ) )
  14477. );
  14478. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  14479. // Find two nearest log-discretized noise scales
  14480. const pixScales = vec2(
  14481. exp2( floor( log2( pixScale ) ) ),
  14482. exp2( ceil( log2( pixScale ) ) )
  14483. );
  14484. // Compute alpha thresholds at our two noise scales
  14485. const alpha = vec2(
  14486. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  14487. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  14488. );
  14489. // Factor to interpolate lerp with
  14490. const lerpFactor = fract( log2( pixScale ) );
  14491. // Interpolate alpha threshold from noise at two scales
  14492. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  14493. // Pass into CDF to compute uniformly distrib threshold
  14494. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  14495. const cases = vec3(
  14496. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  14497. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  14498. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  14499. // Find our final, uniformly distributed alpha threshold (ατ)
  14500. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  14501. // Avoids ατ == 0. Could also do ατ =1-ατ
  14502. return clamp( threshold, 1.0e-6, 1.0 );
  14503. } ).setLayout( {
  14504. name: 'getAlphaHashThreshold',
  14505. type: 'float',
  14506. inputs: [
  14507. { name: 'position', type: 'vec3' }
  14508. ]
  14509. } );
  14510. /**
  14511. * An attribute node for representing vertex colors.
  14512. *
  14513. * @augments AttributeNode
  14514. */
  14515. class VertexColorNode extends AttributeNode {
  14516. static get type() {
  14517. return 'VertexColorNode';
  14518. }
  14519. /**
  14520. * Constructs a new vertex color node.
  14521. *
  14522. * @param {number} index - The attribute index.
  14523. */
  14524. constructor( index ) {
  14525. super( null, 'vec4' );
  14526. /**
  14527. * This flag can be used for type testing.
  14528. *
  14529. * @type {boolean}
  14530. * @readonly
  14531. * @default true
  14532. */
  14533. this.isVertexColorNode = true;
  14534. /**
  14535. * The attribute index to enable more than one sets of vertex colors.
  14536. *
  14537. * @type {number}
  14538. * @default 0
  14539. */
  14540. this.index = index;
  14541. }
  14542. /**
  14543. * Overwrites the default implementation by honoring the attribute index.
  14544. *
  14545. * @param {NodeBuilder} builder - The current node builder.
  14546. * @return {string} The attribute name.
  14547. */
  14548. getAttributeName( /*builder*/ ) {
  14549. const index = this.index;
  14550. return 'color' + ( index > 0 ? index : '' );
  14551. }
  14552. generate( builder ) {
  14553. const attributeName = this.getAttributeName( builder );
  14554. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  14555. let result;
  14556. if ( geometryAttribute === true ) {
  14557. result = super.generate( builder );
  14558. } else {
  14559. // Vertex color fallback should be white
  14560. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  14561. }
  14562. return result;
  14563. }
  14564. serialize( data ) {
  14565. super.serialize( data );
  14566. data.index = this.index;
  14567. }
  14568. deserialize( data ) {
  14569. super.deserialize( data );
  14570. this.index = data.index;
  14571. }
  14572. }
  14573. /**
  14574. * TSL function for creating a reference node.
  14575. *
  14576. * @tsl
  14577. * @function
  14578. * @param {number} [index=0] - The attribute index.
  14579. * @returns {VertexColorNode}
  14580. */
  14581. const vertexColor = ( index = 0 ) => new VertexColorNode( index );
  14582. /**
  14583. * Base class for all node materials.
  14584. *
  14585. * @augments Material
  14586. */
  14587. class NodeMaterial extends Material {
  14588. static get type() {
  14589. return 'NodeMaterial';
  14590. }
  14591. /**
  14592. * Represents the type of the node material.
  14593. *
  14594. * @type {string}
  14595. */
  14596. get type() {
  14597. return this.constructor.type;
  14598. }
  14599. set type( _value ) { /* */ }
  14600. /**
  14601. * Constructs a new node material.
  14602. */
  14603. constructor() {
  14604. super();
  14605. /**
  14606. * This flag can be used for type testing.
  14607. *
  14608. * @type {boolean}
  14609. * @readonly
  14610. * @default true
  14611. */
  14612. this.isNodeMaterial = true;
  14613. /**
  14614. * Whether this material is affected by fog or not.
  14615. *
  14616. * @type {boolean}
  14617. * @default true
  14618. */
  14619. this.fog = true;
  14620. /**
  14621. * Whether this material is affected by lights or not.
  14622. *
  14623. * @type {boolean}
  14624. * @default false
  14625. */
  14626. this.lights = false;
  14627. /**
  14628. * Whether this material uses hardware clipping or not.
  14629. * This property is managed by the engine and should not be
  14630. * modified by apps.
  14631. *
  14632. * @type {boolean}
  14633. * @default false
  14634. */
  14635. this.hardwareClipping = false;
  14636. /**
  14637. * Node materials which set their `lights` property to `true`
  14638. * are affected by all lights of the scene. Sometimes selective
  14639. * lighting is wanted which means only _some_ lights in the scene
  14640. * affect a material. This can be achieved by creating an instance
  14641. * of {@link LightsNode} with a list of selective
  14642. * lights and assign the node to this property.
  14643. *
  14644. * ```js
  14645. * const customLightsNode = lights( [ light1, light2 ] );
  14646. * material.lightsNode = customLightsNode;
  14647. * ```
  14648. *
  14649. * @type {?LightsNode}
  14650. * @default null
  14651. */
  14652. this.lightsNode = null;
  14653. /**
  14654. * The environment of node materials can be defined by an environment
  14655. * map assigned to the `envMap` property or by `Scene.environment`
  14656. * if the node material is a PBR material. This node property allows to overwrite
  14657. * the default behavior and define the environment with a custom node.
  14658. *
  14659. * ```js
  14660. * material.envNode = pmremTexture( renderTarget.texture );
  14661. * ```
  14662. *
  14663. * @type {?Node<vec3>}
  14664. * @default null
  14665. */
  14666. this.envNode = null;
  14667. /**
  14668. * The lighting of node materials might be influenced by ambient occlusion.
  14669. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  14670. * and the respective `aoMapIntensity`. This node property allows to overwrite
  14671. * the default and define the ambient occlusion with a custom node instead.
  14672. *
  14673. * If you don't want to overwrite the diffuse color but modify the existing
  14674. * values instead, use {@link materialAO}.
  14675. *
  14676. * @type {?Node<float>}
  14677. * @default null
  14678. */
  14679. this.aoNode = null;
  14680. /**
  14681. * The diffuse color of node materials is by default inferred from the
  14682. * `color` and `map` properties. This node property allows to overwrite the default
  14683. * and define the diffuse color with a node instead.
  14684. *
  14685. * ```js
  14686. * material.colorNode = color( 0xff0000 ); // define red color
  14687. * ```
  14688. *
  14689. * If you don't want to overwrite the diffuse color but modify the existing
  14690. * values instead, use {@link materialColor}.
  14691. *
  14692. * ```js
  14693. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  14694. * ```
  14695. *
  14696. * @type {?Node<vec3>}
  14697. * @default null
  14698. */
  14699. this.colorNode = null;
  14700. /**
  14701. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  14702. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  14703. * and define the normals with a node instead.
  14704. *
  14705. * If you don't want to overwrite the normals but modify the existing values instead,
  14706. * use {@link materialNormal}.
  14707. *
  14708. * @type {?Node<vec3>}
  14709. * @default null
  14710. */
  14711. this.normalNode = null;
  14712. /**
  14713. * The opacity of node materials is by default inferred from the `opacity`
  14714. * and `alphaMap` properties. This node property allows to overwrite the default
  14715. * and define the opacity with a node instead.
  14716. *
  14717. * If you don't want to overwrite the opacity but modify the existing
  14718. * value instead, use {@link materialOpacity}.
  14719. *
  14720. * @type {?Node<float>}
  14721. * @default null
  14722. */
  14723. this.opacityNode = null;
  14724. /**
  14725. * This node can be used to implement a variety of filter-like effects. The idea is
  14726. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  14727. * to create an arbitrary effect and then assign the node composition to this property.
  14728. * Everything behind the object using this material will now be affected by a filter.
  14729. *
  14730. * ```js
  14731. * const material = new NodeMaterial()
  14732. * material.transparent = true;
  14733. *
  14734. * // everything behind the object will be monochromatic
  14735. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  14736. * ```
  14737. *
  14738. * Backdrop computations are part of the lighting so only lit materials can use this property.
  14739. *
  14740. * @type {?Node<vec3>}
  14741. * @default null
  14742. */
  14743. this.backdropNode = null;
  14744. /**
  14745. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  14746. *
  14747. * @type {?Node<float>}
  14748. * @default null
  14749. */
  14750. this.backdropAlphaNode = null;
  14751. /**
  14752. * The alpha test of node materials is by default inferred from the `alphaTest`
  14753. * property. This node property allows to overwrite the default and define the
  14754. * alpha test with a node instead.
  14755. *
  14756. * If you don't want to overwrite the alpha test but modify the existing
  14757. * value instead, use {@link materialAlphaTest}.
  14758. *
  14759. * @type {?Node<float>}
  14760. * @default null
  14761. */
  14762. this.alphaTestNode = null;
  14763. /**
  14764. * Discards the fragment if the mask value is `false`.
  14765. *
  14766. * @type {?Node<bool>}
  14767. * @default null
  14768. */
  14769. this.maskNode = null;
  14770. /**
  14771. * This node can be used to implement a shadow mask for the material.
  14772. *
  14773. * @type {?Node<bool>}
  14774. * @default null
  14775. */
  14776. this.maskShadowNode = null;
  14777. /**
  14778. * The local vertex positions are computed based on multiple factors like the
  14779. * attribute data, morphing or skinning. This node property allows to overwrite
  14780. * the default and define local vertex positions with nodes instead.
  14781. *
  14782. * If you don't want to overwrite the vertex positions but modify the existing
  14783. * values instead, use {@link positionLocal}.
  14784. *
  14785. *```js
  14786. * material.positionNode = positionLocal.add( displace );
  14787. * ```
  14788. *
  14789. * @type {?Node<vec3>}
  14790. * @default null
  14791. */
  14792. this.positionNode = null;
  14793. /**
  14794. * This node property is intended for logic which modifies geometry data once or per animation step.
  14795. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  14796. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  14797. * can be implemented.
  14798. *
  14799. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  14800. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  14801. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  14802. * eventually assigned to `geometryNode`.
  14803. *
  14804. * @type {?Function}
  14805. * @default null
  14806. */
  14807. this.geometryNode = null;
  14808. /**
  14809. * Allows to overwrite depth values in the fragment shader.
  14810. *
  14811. * @type {?Node<float>}
  14812. * @default null
  14813. */
  14814. this.depthNode = null;
  14815. /**
  14816. * Allows to overwrite the position used for shadow map rendering which
  14817. * is by default {@link positionWorld}, the vertex position
  14818. * in world space.
  14819. *
  14820. * @type {?Node<float>}
  14821. * @default null
  14822. */
  14823. this.receivedShadowPositionNode = null;
  14824. /**
  14825. * Allows to overwrite the geometry position used for shadow map projection which
  14826. * is by default {@link positionLocal}, the vertex position in local space.
  14827. *
  14828. * @type {?Node<float>}
  14829. * @default null
  14830. */
  14831. this.castShadowPositionNode = null;
  14832. /**
  14833. * This node can be used to influence how an object using this node material
  14834. * receive shadows.
  14835. *
  14836. * ```js
  14837. * const totalShadows = float( 1 ).toVar();
  14838. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  14839. * totalShadows.mulAssign( shadow );
  14840. * //return float( 1 ); // bypass received shadows
  14841. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  14842. * } );
  14843. *
  14844. * @type {?(Function|FunctionNode<vec4>)}
  14845. * @default null
  14846. */
  14847. this.receivedShadowNode = null;
  14848. /**
  14849. * This node can be used to influence how an object using this node material
  14850. * casts shadows. To apply a color to shadows, you can simply do:
  14851. *
  14852. * ```js
  14853. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  14854. * ```
  14855. *
  14856. * Which can be nice to fake colored shadows of semi-transparent objects. It
  14857. * is also common to use the property with `Fn` function so checks are performed
  14858. * per fragment.
  14859. *
  14860. * ```js
  14861. * materialCustomShadow.castShadowNode = Fn( () => {
  14862. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  14863. * return materialColor;
  14864. * } )();
  14865. * ```
  14866. *
  14867. * @type {?Node<vec4>}
  14868. * @default null
  14869. */
  14870. this.castShadowNode = null;
  14871. /**
  14872. * This node can be used to define the final output of the material.
  14873. *
  14874. * TODO: Explain the differences to `fragmentNode`.
  14875. *
  14876. * @type {?Node<vec4>}
  14877. * @default null
  14878. */
  14879. this.outputNode = null;
  14880. /**
  14881. * MRT configuration is done on renderer or pass level. This node allows to
  14882. * overwrite what values are written into MRT targets on material level. This
  14883. * can be useful for implementing selective FX features that should only affect
  14884. * specific objects.
  14885. *
  14886. * @type {?MRTNode}
  14887. * @default null
  14888. */
  14889. this.mrtNode = null;
  14890. /**
  14891. * This node property can be used if you need complete freedom in implementing
  14892. * the fragment shader. Assigning a node will replace the built-in material
  14893. * logic used in the fragment stage.
  14894. *
  14895. * @type {?Node<vec4>}
  14896. * @default null
  14897. */
  14898. this.fragmentNode = null;
  14899. /**
  14900. * This node property can be used if you need complete freedom in implementing
  14901. * the vertex shader. Assigning a node will replace the built-in material logic
  14902. * used in the vertex stage.
  14903. *
  14904. * @type {?Node<vec4>}
  14905. * @default null
  14906. */
  14907. this.vertexNode = null;
  14908. /**
  14909. * This node can be used as a global context management component for this material.
  14910. *
  14911. * @type {?ContextNode}
  14912. * @default null
  14913. */
  14914. this.contextNode = null;
  14915. }
  14916. /**
  14917. * Returns an array of child nodes for this material.
  14918. *
  14919. * @private
  14920. * @returns {Array<{property: string, childNode: Node}>}
  14921. */
  14922. _getNodeChildren() {
  14923. const children = [];
  14924. for ( const property of Object.getOwnPropertyNames( this ) ) {
  14925. if ( property.startsWith( '_' ) === true ) continue;
  14926. const object = this[ property ];
  14927. if ( object && object.isNode === true ) {
  14928. children.push( { property, childNode: object } );
  14929. }
  14930. }
  14931. return children;
  14932. }
  14933. /**
  14934. * Allows to define a custom cache key that influence the material key computation
  14935. * for render objects.
  14936. *
  14937. * @return {string} The custom cache key.
  14938. */
  14939. customProgramCacheKey() {
  14940. const values = [];
  14941. for ( const { property, childNode } of this._getNodeChildren() ) {
  14942. values.push( hashString( property.slice( 0, -4 ) ), childNode.getCacheKey() );
  14943. }
  14944. return this.type + hashArray( values );
  14945. }
  14946. /**
  14947. * Builds this material with the given node builder.
  14948. *
  14949. * @param {NodeBuilder} builder - The current node builder.
  14950. */
  14951. build( builder ) {
  14952. this.setup( builder );
  14953. }
  14954. /**
  14955. * Setups a node material observer with the given builder.
  14956. *
  14957. * @param {NodeBuilder} builder - The current node builder.
  14958. * @return {NodeMaterialObserver} The node material observer.
  14959. */
  14960. setupObserver( builder ) {
  14961. return new NodeMaterialObserver( builder );
  14962. }
  14963. /**
  14964. * Setups the vertex and fragment stage of this node material.
  14965. *
  14966. * @param {NodeBuilder} builder - The current node builder.
  14967. */
  14968. setup( builder ) {
  14969. builder.context.setupNormal = () => subBuild( this.setupNormal( builder ), 'NORMAL', 'vec3' );
  14970. builder.context.setupPositionView = () => this.setupPositionView( builder );
  14971. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  14972. const renderer = builder.renderer;
  14973. const renderTarget = renderer.getRenderTarget();
  14974. // < VERTEX STAGE >
  14975. builder.addStack();
  14976. const mvp = this.setupVertex( builder );
  14977. const vertexNode = subBuild( this.vertexNode || mvp, 'VERTEX' );
  14978. builder.context.clipSpace = vertexNode;
  14979. builder.stack.outputNode = vertexNode;
  14980. this.setupHardwareClipping( builder );
  14981. if ( this.geometryNode !== null ) {
  14982. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  14983. }
  14984. builder.addFlow( 'vertex', builder.removeStack() );
  14985. // < FRAGMENT STAGE >
  14986. builder.addStack();
  14987. let resultNode;
  14988. const clippingNode = this.setupClipping( builder );
  14989. if ( this.depthWrite === true || this.depthTest === true ) {
  14990. // only write depth if depth buffer is configured
  14991. if ( renderTarget !== null ) {
  14992. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  14993. } else {
  14994. if ( renderer.depth === true ) this.setupDepth( builder );
  14995. }
  14996. }
  14997. if ( this.fragmentNode === null ) {
  14998. this.setupDiffuseColor( builder );
  14999. this.setupVariants( builder );
  15000. const outgoingLightNode = this.setupLighting( builder );
  15001. if ( clippingNode !== null ) builder.stack.addToStack( clippingNode );
  15002. // force unsigned floats - useful for RenderTargets
  15003. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  15004. resultNode = this.setupOutput( builder, basicOutput );
  15005. // OUTPUT NODE
  15006. output.assign( resultNode );
  15007. //
  15008. const isCustomOutput = this.outputNode !== null;
  15009. if ( isCustomOutput ) resultNode = this.outputNode;
  15010. //
  15011. if ( builder.context.getOutput ) {
  15012. resultNode = builder.context.getOutput( resultNode, builder );
  15013. }
  15014. // MRT
  15015. if ( renderTarget !== null ) {
  15016. const mrt = renderer.getMRT();
  15017. const materialMRT = this.mrtNode;
  15018. if ( mrt !== null ) {
  15019. if ( isCustomOutput ) output.assign( resultNode );
  15020. resultNode = mrt;
  15021. if ( materialMRT !== null ) {
  15022. resultNode = mrt.merge( materialMRT );
  15023. }
  15024. } else if ( materialMRT !== null ) {
  15025. resultNode = materialMRT;
  15026. }
  15027. }
  15028. } else {
  15029. let fragmentNode = this.fragmentNode;
  15030. if ( fragmentNode.isOutputStructNode !== true ) {
  15031. fragmentNode = vec4( fragmentNode );
  15032. }
  15033. resultNode = this.setupOutput( builder, fragmentNode );
  15034. }
  15035. builder.stack.outputNode = resultNode;
  15036. builder.addFlow( 'fragment', builder.removeStack() );
  15037. // < OBSERVER >
  15038. builder.observer = this.setupObserver( builder );
  15039. }
  15040. /**
  15041. * Setups the clipping node.
  15042. *
  15043. * @param {NodeBuilder} builder - The current node builder.
  15044. * @return {ClippingNode} The clipping node.
  15045. */
  15046. setupClipping( builder ) {
  15047. if ( builder.clippingContext === null ) return null;
  15048. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  15049. let result = null;
  15050. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  15051. const samples = builder.renderer.currentSamples;
  15052. if ( this.alphaToCoverage && samples > 1 ) {
  15053. // to be added to flow when the color/alpha value has been determined
  15054. result = clippingAlpha();
  15055. } else {
  15056. builder.stack.addToStack( clipping() );
  15057. }
  15058. }
  15059. return result;
  15060. }
  15061. /**
  15062. * Setups the hardware clipping if available on the current device.
  15063. *
  15064. * @param {NodeBuilder} builder - The current node builder.
  15065. */
  15066. setupHardwareClipping( builder ) {
  15067. this.hardwareClipping = false;
  15068. if ( builder.clippingContext === null ) return;
  15069. const candidateCount = builder.clippingContext.unionPlanes.length;
  15070. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  15071. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  15072. builder.stack.addToStack( hardwareClipping() );
  15073. this.hardwareClipping = true;
  15074. }
  15075. return;
  15076. }
  15077. /**
  15078. * Setups the depth of this material.
  15079. *
  15080. * @param {NodeBuilder} builder - The current node builder.
  15081. */
  15082. setupDepth( builder ) {
  15083. const { renderer, camera } = builder;
  15084. // Depth
  15085. let depthNode = this.depthNode;
  15086. if ( depthNode === null ) {
  15087. const mrt = renderer.getMRT();
  15088. if ( mrt && mrt.has( 'depth' ) ) {
  15089. depthNode = mrt.get( 'depth' );
  15090. } else if ( renderer.logarithmicDepthBuffer === true ) {
  15091. if ( camera.isPerspectiveCamera ) {
  15092. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  15093. } else {
  15094. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  15095. }
  15096. }
  15097. }
  15098. if ( depthNode !== null ) {
  15099. depth.assign( depthNode ).toStack();
  15100. }
  15101. }
  15102. /**
  15103. * Setups the position node in view space. This method exists
  15104. * so derived node materials can modify the implementation e.g. sprite materials.
  15105. *
  15106. * @param {NodeBuilder} builder - The current node builder.
  15107. * @return {Node<vec3>} The position in view space.
  15108. */
  15109. setupPositionView( /*builder*/ ) {
  15110. return modelViewMatrix.mul( positionLocal ).xyz;
  15111. }
  15112. /**
  15113. * Setups the position in clip space.
  15114. *
  15115. * @param {NodeBuilder} builder - The current node builder.
  15116. * @return {Node<vec4>} The position in view space.
  15117. */
  15118. setupModelViewProjection( /*builder*/ ) {
  15119. return cameraProjectionMatrix.mul( positionView );
  15120. }
  15121. /**
  15122. * Setups the logic for the vertex stage.
  15123. *
  15124. * @param {NodeBuilder} builder - The current node builder.
  15125. * @return {Node<vec4>} The position in clip space.
  15126. */
  15127. setupVertex( builder ) {
  15128. builder.addStack();
  15129. this.setupPosition( builder );
  15130. builder.context.position = builder.removeStack();
  15131. return modelViewProjection;
  15132. }
  15133. /**
  15134. * Setups the computation of the position in local space.
  15135. *
  15136. * @param {NodeBuilder} builder - The current node builder.
  15137. * @return {Node<vec3>} The position in local space.
  15138. */
  15139. setupPosition( builder ) {
  15140. const { object, geometry } = builder;
  15141. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  15142. morphReference( object ).toStack();
  15143. }
  15144. if ( object.isSkinnedMesh === true ) {
  15145. skinning( object ).toStack();
  15146. }
  15147. if ( this.displacementMap ) {
  15148. const displacementMap = materialReference( 'displacementMap', 'texture' );
  15149. const displacementScale = materialReference( 'displacementScale', 'float' );
  15150. const displacementBias = materialReference( 'displacementBias', 'float' );
  15151. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  15152. }
  15153. if ( object.isBatchedMesh ) {
  15154. batch( object ).toStack();
  15155. }
  15156. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  15157. instancedMesh( object ).toStack();
  15158. }
  15159. if ( this.positionNode !== null ) {
  15160. positionLocal.assign( subBuild( this.positionNode, 'POSITION', 'vec3' ) );
  15161. }
  15162. return positionLocal;
  15163. }
  15164. /**
  15165. * Setups the computation of the material's diffuse color.
  15166. *
  15167. * @param {NodeBuilder} builder - The current node builder.
  15168. * @param {BufferGeometry} geometry - The geometry.
  15169. */
  15170. setupDiffuseColor( builder ) {
  15171. const { object, geometry } = builder;
  15172. // MASK
  15173. if ( this.maskNode !== null ) {
  15174. // Discard if the mask is `false`
  15175. bool( this.maskNode ).not().discard();
  15176. }
  15177. // COLOR
  15178. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  15179. // VERTEX COLORS
  15180. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  15181. colorNode = colorNode.mul( vertexColor() );
  15182. }
  15183. // INSTANCED COLORS
  15184. if ( object.instanceColor ) {
  15185. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  15186. colorNode = instanceColor.mul( colorNode );
  15187. }
  15188. if ( object.isBatchedMesh && object._colorsTexture ) {
  15189. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  15190. colorNode = batchColor.mul( colorNode );
  15191. }
  15192. // DIFFUSE COLOR
  15193. diffuseColor.assign( colorNode );
  15194. // OPACITY
  15195. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15196. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  15197. // ALPHA TEST
  15198. let alphaTestNode = null;
  15199. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  15200. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  15201. if ( this.alphaToCoverage === true ) {
  15202. diffuseColor.a = smoothstep( alphaTestNode, alphaTestNode.add( fwidth( diffuseColor.a ) ), diffuseColor.a );
  15203. diffuseColor.a.lessThanEqual( 0 ).discard();
  15204. } else {
  15205. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  15206. }
  15207. }
  15208. // ALPHA HASH
  15209. if ( this.alphaHash === true ) {
  15210. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  15211. }
  15212. // OPAQUE
  15213. if ( builder.isOpaque() ) {
  15214. diffuseColor.a.assign( 1.0 );
  15215. }
  15216. }
  15217. /**
  15218. * Abstract interface method that can be implemented by derived materials
  15219. * to setup material-specific node variables.
  15220. *
  15221. * @abstract
  15222. * @param {NodeBuilder} builder - The current node builder.
  15223. */
  15224. setupVariants( /*builder*/ ) {
  15225. // Interface function.
  15226. }
  15227. /**
  15228. * Setups the outgoing light node variable
  15229. *
  15230. * @return {Node<vec3>} The outgoing light node.
  15231. */
  15232. setupOutgoingLight() {
  15233. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  15234. }
  15235. /**
  15236. * Setups the normal node from the material.
  15237. *
  15238. * @return {Node<vec3>} The normal node.
  15239. */
  15240. setupNormal() {
  15241. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  15242. }
  15243. /**
  15244. * Setups the environment node from the material.
  15245. *
  15246. * @param {NodeBuilder} builder - The current node builder.
  15247. * @return {Node<vec4>} The environment node.
  15248. */
  15249. setupEnvironment( /*builder*/ ) {
  15250. let node = null;
  15251. if ( this.envNode ) {
  15252. node = this.envNode;
  15253. } else if ( this.envMap ) {
  15254. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  15255. }
  15256. return node;
  15257. }
  15258. /**
  15259. * Setups the light map node from the material.
  15260. *
  15261. * @param {NodeBuilder} builder - The current node builder.
  15262. * @return {Node<vec3>} The light map node.
  15263. */
  15264. setupLightMap( builder ) {
  15265. let node = null;
  15266. if ( builder.material.lightMap ) {
  15267. node = new IrradianceNode( materialLightMap );
  15268. }
  15269. return node;
  15270. }
  15271. /**
  15272. * Setups the lights node based on the scene, environment and material.
  15273. *
  15274. * @param {NodeBuilder} builder - The current node builder.
  15275. * @return {LightsNode} The lights node.
  15276. */
  15277. setupLights( builder ) {
  15278. const materialLightsNode = [];
  15279. //
  15280. const envNode = this.setupEnvironment( builder );
  15281. if ( envNode && envNode.isLightingNode ) {
  15282. materialLightsNode.push( envNode );
  15283. }
  15284. const lightMapNode = this.setupLightMap( builder );
  15285. if ( lightMapNode && lightMapNode.isLightingNode ) {
  15286. materialLightsNode.push( lightMapNode );
  15287. }
  15288. let aoNode = this.aoNode;
  15289. if ( aoNode === null && builder.material.aoMap ) {
  15290. aoNode = materialAO;
  15291. }
  15292. if ( builder.context.getAO ) {
  15293. aoNode = builder.context.getAO( aoNode, builder );
  15294. }
  15295. if ( aoNode ) {
  15296. materialLightsNode.push( new AONode( aoNode ) );
  15297. }
  15298. let lightsN = this.lightsNode || builder.lightsNode;
  15299. if ( materialLightsNode.length > 0 ) {
  15300. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  15301. }
  15302. return lightsN;
  15303. }
  15304. /**
  15305. * This method should be implemented by most derived materials
  15306. * since it defines the material's lighting model.
  15307. *
  15308. * @abstract
  15309. * @param {NodeBuilder} builder - The current node builder.
  15310. * @return {LightingModel} The lighting model.
  15311. */
  15312. setupLightingModel( /*builder*/ ) {
  15313. // Interface function.
  15314. }
  15315. /**
  15316. * Setups the outgoing light node.
  15317. *
  15318. * @param {NodeBuilder} builder - The current node builder.
  15319. * @return {Node<vec3>} The outgoing light node.
  15320. */
  15321. setupLighting( builder ) {
  15322. const { material } = builder;
  15323. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  15324. // OUTGOING LIGHT
  15325. const lights = this.lights === true || this.lightsNode !== null;
  15326. const lightsNode = lights ? this.setupLights( builder ) : null;
  15327. let outgoingLightNode = this.setupOutgoingLight( builder );
  15328. if ( lightsNode && lightsNode.getScope().hasLights ) {
  15329. const lightingModel = this.setupLightingModel( builder ) || null;
  15330. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  15331. } else if ( backdropNode !== null ) {
  15332. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  15333. }
  15334. // EMISSIVE
  15335. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  15336. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  15337. outgoingLightNode = outgoingLightNode.add( emissive );
  15338. }
  15339. return outgoingLightNode;
  15340. }
  15341. /**
  15342. * Setup the fog.
  15343. *
  15344. * @param {NodeBuilder} builder - The current node builder.
  15345. * @param {Node<vec4>} outputNode - The existing output node.
  15346. * @return {Node<vec4>} The output node.
  15347. */
  15348. setupFog( builder, outputNode ) {
  15349. const fogNode = builder.fogNode;
  15350. if ( fogNode ) {
  15351. output.assign( outputNode );
  15352. outputNode = vec4( fogNode.toVar() );
  15353. }
  15354. return outputNode;
  15355. }
  15356. /**
  15357. * Setups premultiplied alpha.
  15358. *
  15359. * @param {NodeBuilder} builder - The current node builder.
  15360. * @param {Node<vec4>} outputNode - The existing output node.
  15361. * @return {Node<vec4>} The output node.
  15362. */
  15363. setupPremultipliedAlpha( builder, outputNode ) {
  15364. return premultiplyAlpha( outputNode );
  15365. }
  15366. /**
  15367. * Setups the output node.
  15368. *
  15369. * @param {NodeBuilder} builder - The current node builder.
  15370. * @param {Node<vec4>} outputNode - The existing output node.
  15371. * @return {Node<vec4>} The output node.
  15372. */
  15373. setupOutput( builder, outputNode ) {
  15374. // FOG
  15375. if ( this.fog === true ) {
  15376. outputNode = this.setupFog( builder, outputNode );
  15377. }
  15378. // PREMULTIPLIED ALPHA
  15379. if ( this.premultipliedAlpha === true ) {
  15380. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  15381. }
  15382. return outputNode;
  15383. }
  15384. /**
  15385. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  15386. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  15387. * defining all material properties of the classic type in the node type.
  15388. *
  15389. * @param {Material} material - The material to copy properties with their values to this node material.
  15390. */
  15391. setDefaultValues( material ) {
  15392. // This approach is to reuse the native refreshUniforms*
  15393. // and turn available the use of features like transmission and environment in core
  15394. for ( const property in material ) {
  15395. const value = material[ property ];
  15396. if ( this[ property ] === undefined ) {
  15397. this[ property ] = value;
  15398. if ( value && value.clone ) this[ property ] = value.clone();
  15399. }
  15400. }
  15401. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  15402. for ( const key in descriptors ) {
  15403. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  15404. descriptors[ key ].get !== undefined ) {
  15405. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  15406. }
  15407. }
  15408. }
  15409. /**
  15410. * Serializes this material to JSON.
  15411. *
  15412. * @param {?(Object|string)} meta - The meta information for serialization.
  15413. * @return {Object} The serialized node.
  15414. */
  15415. toJSON( meta ) {
  15416. const isRoot = ( meta === undefined || typeof meta === 'string' );
  15417. if ( isRoot ) {
  15418. meta = {
  15419. textures: {},
  15420. images: {},
  15421. nodes: {}
  15422. };
  15423. }
  15424. const data = Material.prototype.toJSON.call( this, meta );
  15425. data.inputNodes = {};
  15426. for ( const { property, childNode } of this._getNodeChildren() ) {
  15427. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  15428. }
  15429. // TODO: Copied from Object3D.toJSON
  15430. function extractFromCache( cache ) {
  15431. const values = [];
  15432. for ( const key in cache ) {
  15433. const data = cache[ key ];
  15434. delete data.metadata;
  15435. values.push( data );
  15436. }
  15437. return values;
  15438. }
  15439. if ( isRoot ) {
  15440. const textures = extractFromCache( meta.textures );
  15441. const images = extractFromCache( meta.images );
  15442. const nodes = extractFromCache( meta.nodes );
  15443. if ( textures.length > 0 ) data.textures = textures;
  15444. if ( images.length > 0 ) data.images = images;
  15445. if ( nodes.length > 0 ) data.nodes = nodes;
  15446. }
  15447. return data;
  15448. }
  15449. /**
  15450. * Copies the properties of the given node material to this instance.
  15451. *
  15452. * @param {NodeMaterial} source - The material to copy.
  15453. * @return {NodeMaterial} A reference to this node material.
  15454. */
  15455. copy( source ) {
  15456. this.lightsNode = source.lightsNode;
  15457. this.envNode = source.envNode;
  15458. this.aoNode = source.aoNode;
  15459. this.colorNode = source.colorNode;
  15460. this.normalNode = source.normalNode;
  15461. this.opacityNode = source.opacityNode;
  15462. this.backdropNode = source.backdropNode;
  15463. this.backdropAlphaNode = source.backdropAlphaNode;
  15464. this.alphaTestNode = source.alphaTestNode;
  15465. this.maskNode = source.maskNode;
  15466. this.maskShadowNode = source.maskShadowNode;
  15467. this.positionNode = source.positionNode;
  15468. this.geometryNode = source.geometryNode;
  15469. this.depthNode = source.depthNode;
  15470. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  15471. this.castShadowPositionNode = source.castShadowPositionNode;
  15472. this.receivedShadowNode = source.receivedShadowNode;
  15473. this.castShadowNode = source.castShadowNode;
  15474. this.outputNode = source.outputNode;
  15475. this.mrtNode = source.mrtNode;
  15476. this.fragmentNode = source.fragmentNode;
  15477. this.vertexNode = source.vertexNode;
  15478. this.contextNode = source.contextNode;
  15479. return super.copy( source );
  15480. }
  15481. }
  15482. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  15483. /**
  15484. * Node material version of {@link LineBasicMaterial}.
  15485. *
  15486. * @augments NodeMaterial
  15487. */
  15488. class LineBasicNodeMaterial extends NodeMaterial {
  15489. static get type() {
  15490. return 'LineBasicNodeMaterial';
  15491. }
  15492. /**
  15493. * Constructs a new line basic node material.
  15494. *
  15495. * @param {Object} [parameters] - The configuration parameter.
  15496. */
  15497. constructor( parameters ) {
  15498. super();
  15499. /**
  15500. * This flag can be used for type testing.
  15501. *
  15502. * @type {boolean}
  15503. * @readonly
  15504. * @default true
  15505. */
  15506. this.isLineBasicNodeMaterial = true;
  15507. this.setDefaultValues( _defaultValues$d );
  15508. this.setValues( parameters );
  15509. }
  15510. }
  15511. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  15512. /**
  15513. * Node material version of {@link LineDashedMaterial}.
  15514. *
  15515. * @augments NodeMaterial
  15516. */
  15517. class LineDashedNodeMaterial extends NodeMaterial {
  15518. static get type() {
  15519. return 'LineDashedNodeMaterial';
  15520. }
  15521. /**
  15522. * Constructs a new line dashed node material.
  15523. *
  15524. * @param {Object} [parameters] - The configuration parameter.
  15525. */
  15526. constructor( parameters ) {
  15527. super();
  15528. /**
  15529. * This flag can be used for type testing.
  15530. *
  15531. * @type {boolean}
  15532. * @readonly
  15533. * @default true
  15534. */
  15535. this.isLineDashedNodeMaterial = true;
  15536. this.setDefaultValues( _defaultValues$c );
  15537. /**
  15538. * The dash offset.
  15539. *
  15540. * @type {number}
  15541. * @default 0
  15542. */
  15543. this.dashOffset = 0;
  15544. /**
  15545. * The offset of dash materials is by default inferred from the `dashOffset`
  15546. * property. This node property allows to overwrite the default
  15547. * and define the offset with a node instead.
  15548. *
  15549. * If you don't want to overwrite the offset but modify the existing
  15550. * value instead, use {@link materialLineDashOffset}.
  15551. *
  15552. * @type {?Node<float>}
  15553. * @default null
  15554. */
  15555. this.offsetNode = null;
  15556. /**
  15557. * The scale of dash materials is by default inferred from the `scale`
  15558. * property. This node property allows to overwrite the default
  15559. * and define the scale with a node instead.
  15560. *
  15561. * If you don't want to overwrite the scale but modify the existing
  15562. * value instead, use {@link materialLineScale}.
  15563. *
  15564. * @type {?Node<float>}
  15565. * @default null
  15566. */
  15567. this.dashScaleNode = null;
  15568. /**
  15569. * The dash size of dash materials is by default inferred from the `dashSize`
  15570. * property. This node property allows to overwrite the default
  15571. * and define the dash size with a node instead.
  15572. *
  15573. * If you don't want to overwrite the dash size but modify the existing
  15574. * value instead, use {@link materialLineDashSize}.
  15575. *
  15576. * @type {?Node<float>}
  15577. * @default null
  15578. */
  15579. this.dashSizeNode = null;
  15580. /**
  15581. * The gap size of dash materials is by default inferred from the `gapSize`
  15582. * property. This node property allows to overwrite the default
  15583. * and define the gap size with a node instead.
  15584. *
  15585. * If you don't want to overwrite the gap size but modify the existing
  15586. * value instead, use {@link materialLineGapSize}.
  15587. *
  15588. * @type {?Node<float>}
  15589. * @default null
  15590. */
  15591. this.gapSizeNode = null;
  15592. this.setValues( parameters );
  15593. }
  15594. /**
  15595. * Setups the dash specific node variables.
  15596. *
  15597. * @param {NodeBuilder} builder - The current node builder.
  15598. */
  15599. setupVariants( /* builder */ ) {
  15600. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15601. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15602. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15603. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15604. dashSize.assign( dashSizeNode );
  15605. gapSize.assign( gapSizeNode );
  15606. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  15607. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  15608. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  15609. }
  15610. }
  15611. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  15612. /**
  15613. * This node material can be used to render lines with a size larger than one
  15614. * by representing them as instanced meshes.
  15615. *
  15616. * @augments NodeMaterial
  15617. */
  15618. class Line2NodeMaterial extends NodeMaterial {
  15619. static get type() {
  15620. return 'Line2NodeMaterial';
  15621. }
  15622. /**
  15623. * Constructs a new node material for wide line rendering.
  15624. *
  15625. * @param {Object} [parameters={}] - The configuration parameter.
  15626. */
  15627. constructor( parameters = {} ) {
  15628. super();
  15629. /**
  15630. * This flag can be used for type testing.
  15631. *
  15632. * @type {boolean}
  15633. * @readonly
  15634. * @default true
  15635. */
  15636. this.isLine2NodeMaterial = true;
  15637. this.setDefaultValues( _defaultValues$b );
  15638. /**
  15639. * Whether vertex colors should be used or not.
  15640. *
  15641. * @type {boolean}
  15642. * @default false
  15643. */
  15644. this.vertexColors = parameters.vertexColors;
  15645. /**
  15646. * The dash offset.
  15647. *
  15648. * @type {number}
  15649. * @default 0
  15650. */
  15651. this.dashOffset = 0;
  15652. /**
  15653. * Defines the lines color.
  15654. *
  15655. * @type {?Node<vec3>}
  15656. * @default null
  15657. */
  15658. this.lineColorNode = null;
  15659. /**
  15660. * Defines the offset.
  15661. *
  15662. * @type {?Node<float>}
  15663. * @default null
  15664. */
  15665. this.offsetNode = null;
  15666. /**
  15667. * Defines the dash scale.
  15668. *
  15669. * @type {?Node<float>}
  15670. * @default null
  15671. */
  15672. this.dashScaleNode = null;
  15673. /**
  15674. * Defines the dash size.
  15675. *
  15676. * @type {?Node<float>}
  15677. * @default null
  15678. */
  15679. this.dashSizeNode = null;
  15680. /**
  15681. * Defines the gap size.
  15682. *
  15683. * @type {?Node<float>}
  15684. * @default null
  15685. */
  15686. this.gapSizeNode = null;
  15687. /**
  15688. * Blending is set to `NoBlending` since transparency
  15689. * is not supported, yet.
  15690. *
  15691. * @type {number}
  15692. * @default 0
  15693. */
  15694. this.blending = NoBlending;
  15695. this._useDash = parameters.dashed;
  15696. this._useAlphaToCoverage = true;
  15697. this._useWorldUnits = false;
  15698. this.setValues( parameters );
  15699. }
  15700. /**
  15701. * Setups the vertex and fragment stage of this node material.
  15702. *
  15703. * @param {NodeBuilder} builder - The current node builder.
  15704. */
  15705. setup( builder ) {
  15706. const { renderer } = builder;
  15707. const useAlphaToCoverage = this._useAlphaToCoverage;
  15708. const vertexColors = this.vertexColors;
  15709. const useDash = this._useDash;
  15710. const useWorldUnits = this._useWorldUnits;
  15711. const trimSegment = Fn( ( { start, end } ) => {
  15712. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  15713. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  15714. const nearEstimate = b.mul( -0.5 ).div( a );
  15715. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  15716. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  15717. } ).setLayout( {
  15718. name: 'trimSegment',
  15719. type: 'vec4',
  15720. inputs: [
  15721. { name: 'start', type: 'vec4' },
  15722. { name: 'end', type: 'vec4' }
  15723. ]
  15724. } );
  15725. this.vertexNode = Fn( () => {
  15726. const instanceStart = attribute( 'instanceStart' );
  15727. const instanceEnd = attribute( 'instanceEnd' );
  15728. // camera space
  15729. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  15730. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  15731. if ( useDash ) {
  15732. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15733. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15734. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  15735. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  15736. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  15737. lineDistance = lineDistance.add( offsetNode );
  15738. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  15739. }
  15740. if ( useWorldUnits ) {
  15741. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  15742. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  15743. }
  15744. const aspect = viewport.z.div( viewport.w );
  15745. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  15746. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  15747. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  15748. // perhaps there is a more elegant solution -- WestLangley
  15749. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  15750. If( perspective, () => {
  15751. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  15752. end.assign( trimSegment( { start: start, end: end } ) );
  15753. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  15754. start.assign( trimSegment( { start: end, end: start } ) );
  15755. } );
  15756. } );
  15757. // clip space
  15758. const clipStart = cameraProjectionMatrix.mul( start );
  15759. const clipEnd = cameraProjectionMatrix.mul( end );
  15760. // ndc space
  15761. const ndcStart = clipStart.xyz.div( clipStart.w );
  15762. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  15763. // direction
  15764. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  15765. // account for clip-space aspect ratio
  15766. dir.x.assign( dir.x.mul( aspect ) );
  15767. dir.assign( dir.normalize() );
  15768. const clip = vec4().toVar();
  15769. if ( useWorldUnits ) {
  15770. // get the offset direction as perpendicular to the view vector
  15771. const worldDir = end.xyz.sub( start.xyz ).normalize();
  15772. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  15773. const worldUp = worldDir.cross( tmpFwd ).normalize();
  15774. const worldFwd = worldDir.cross( worldUp );
  15775. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  15776. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  15777. // height offset
  15778. const hw = materialLineWidth.mul( 0.5 );
  15779. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  15780. // don't extend the line if we're rendering dashes because we
  15781. // won't be rendering the endcaps
  15782. if ( ! useDash ) {
  15783. // cap extension
  15784. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  15785. // add width to the box
  15786. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  15787. // endcaps
  15788. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  15789. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  15790. } );
  15791. }
  15792. // project the worldpos
  15793. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  15794. // shift the depth of the projected points so the line
  15795. // segments overlap neatly
  15796. const clipPose = vec3().toVar();
  15797. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  15798. clip.z.assign( clipPose.z.mul( clip.w ) );
  15799. } else {
  15800. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  15801. // undo aspect ratio adjustment
  15802. dir.x.assign( dir.x.div( aspect ) );
  15803. offset.x.assign( offset.x.div( aspect ) );
  15804. // sign flip
  15805. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  15806. // endcaps
  15807. If( positionGeometry.y.lessThan( 0.0 ), () => {
  15808. offset.assign( offset.sub( dir ) );
  15809. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  15810. offset.assign( offset.add( dir ) );
  15811. } );
  15812. // adjust for linewidth
  15813. offset.assign( offset.mul( materialLineWidth ) );
  15814. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  15815. offset.assign( offset.div( viewport.w.div( screenDPR ) ) );
  15816. // select end
  15817. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  15818. // back to clip space
  15819. offset.assign( offset.mul( clip.w ) );
  15820. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  15821. }
  15822. return clip;
  15823. } )();
  15824. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  15825. const p13 = p1.sub( p3 );
  15826. const p43 = p4.sub( p3 );
  15827. const p21 = p2.sub( p1 );
  15828. const d1343 = p13.dot( p43 );
  15829. const d4321 = p43.dot( p21 );
  15830. const d1321 = p13.dot( p21 );
  15831. const d4343 = p43.dot( p43 );
  15832. const d2121 = p21.dot( p21 );
  15833. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  15834. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  15835. const mua = numer.div( denom ).clamp();
  15836. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  15837. return vec2( mua, mub );
  15838. } );
  15839. this.colorNode = Fn( () => {
  15840. const vUv = uv$1();
  15841. if ( useDash ) {
  15842. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15843. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15844. dashSize.assign( dashSizeNode );
  15845. gapSize.assign( gapSizeNode );
  15846. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  15847. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  15848. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  15849. }
  15850. const alpha = float( 1 ).toVar( 'alpha' );
  15851. if ( useWorldUnits ) {
  15852. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  15853. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  15854. // Find the closest points on the view ray and the line segment
  15855. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  15856. const lineDir = worldEnd.sub( worldStart );
  15857. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  15858. const p1 = worldStart.add( lineDir.mul( params.x ) );
  15859. const p2 = rayEnd.mul( params.y );
  15860. const delta = p1.sub( p2 );
  15861. const len = delta.length();
  15862. const norm = len.div( materialLineWidth );
  15863. if ( ! useDash ) {
  15864. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15865. const dnorm = norm.fwidth();
  15866. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  15867. } else {
  15868. norm.greaterThan( 0.5 ).discard();
  15869. }
  15870. }
  15871. } else {
  15872. // round endcaps
  15873. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15874. const a = vUv.x;
  15875. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15876. const len2 = a.mul( a ).add( b.mul( b ) );
  15877. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  15878. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15879. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  15880. } );
  15881. } else {
  15882. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15883. const a = vUv.x;
  15884. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15885. const len2 = a.mul( a ).add( b.mul( b ) );
  15886. len2.greaterThan( 1.0 ).discard();
  15887. } );
  15888. }
  15889. }
  15890. let lineColorNode;
  15891. if ( this.lineColorNode ) {
  15892. lineColorNode = this.lineColorNode;
  15893. } else {
  15894. if ( vertexColors ) {
  15895. const instanceColorStart = attribute( 'instanceColorStart' );
  15896. const instanceColorEnd = attribute( 'instanceColorEnd' );
  15897. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  15898. lineColorNode = instanceColor.mul( materialColor );
  15899. } else {
  15900. lineColorNode = materialColor;
  15901. }
  15902. }
  15903. return vec4( lineColorNode, alpha );
  15904. } )();
  15905. if ( this.transparent ) {
  15906. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15907. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportOpaqueMipTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  15908. }
  15909. super.setup( builder );
  15910. }
  15911. /**
  15912. * Whether the lines should sized in world units or not.
  15913. * When set to `false` the unit is pixel.
  15914. *
  15915. * @type {boolean}
  15916. * @default false
  15917. */
  15918. get worldUnits() {
  15919. return this._useWorldUnits;
  15920. }
  15921. set worldUnits( value ) {
  15922. if ( this._useWorldUnits !== value ) {
  15923. this._useWorldUnits = value;
  15924. this.needsUpdate = true;
  15925. }
  15926. }
  15927. /**
  15928. * Whether the lines should be dashed or not.
  15929. *
  15930. * @type {boolean}
  15931. * @default false
  15932. */
  15933. get dashed() {
  15934. return this._useDash;
  15935. }
  15936. set dashed( value ) {
  15937. if ( this._useDash !== value ) {
  15938. this._useDash = value;
  15939. this.needsUpdate = true;
  15940. }
  15941. }
  15942. /**
  15943. * Whether alpha to coverage should be used or not.
  15944. *
  15945. * @type {boolean}
  15946. * @default true
  15947. */
  15948. get alphaToCoverage() {
  15949. return this._useAlphaToCoverage;
  15950. }
  15951. set alphaToCoverage( value ) {
  15952. if ( this._useAlphaToCoverage !== value ) {
  15953. this._useAlphaToCoverage = value;
  15954. this.needsUpdate = true;
  15955. }
  15956. }
  15957. /**
  15958. * Copies the properties of the given material to this instance.
  15959. *
  15960. * @param {Line2NodeMaterial} source - The material to copy.
  15961. * @return {Line2NodeMaterial} A reference to this material.
  15962. */
  15963. copy( source ) {
  15964. super.copy( source );
  15965. this.vertexColors = source.vertexColors;
  15966. this.dashOffset = source.dashOffset;
  15967. this.lineColorNode = source.lineColorNode;
  15968. this.offsetNode = source.offsetNode;
  15969. this.dashScaleNode = source.dashScaleNode;
  15970. this.dashSizeNode = source.dashSizeNode;
  15971. this.gapSizeNode = source.gapSizeNode;
  15972. this._useDash = source._useDash;
  15973. this._useAlphaToCoverage = source._useAlphaToCoverage;
  15974. this._useWorldUnits = source._useWorldUnits;
  15975. return this;
  15976. }
  15977. }
  15978. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  15979. /**
  15980. * Node material version of {@link MeshNormalMaterial}.
  15981. *
  15982. * @augments NodeMaterial
  15983. */
  15984. class MeshNormalNodeMaterial extends NodeMaterial {
  15985. static get type() {
  15986. return 'MeshNormalNodeMaterial';
  15987. }
  15988. /**
  15989. * Constructs a new mesh normal node material.
  15990. *
  15991. * @param {Object} [parameters] - The configuration parameter.
  15992. */
  15993. constructor( parameters ) {
  15994. super();
  15995. /**
  15996. * This flag can be used for type testing.
  15997. *
  15998. * @type {boolean}
  15999. * @readonly
  16000. * @default true
  16001. */
  16002. this.isMeshNormalNodeMaterial = true;
  16003. this.setDefaultValues( _defaultValues$a );
  16004. this.setValues( parameters );
  16005. }
  16006. /**
  16007. * Overwrites the default implementation by computing the diffuse color
  16008. * based on the normal data.
  16009. */
  16010. setupDiffuseColor() {
  16011. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  16012. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  16013. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( normalView ), opacityNode ), SRGBColorSpace ) );
  16014. }
  16015. }
  16016. /**
  16017. * TSL function for creating an equirect uv node.
  16018. *
  16019. * Can be used to compute texture coordinates for projecting an
  16020. * equirectangular texture onto a mesh for using it as the scene's
  16021. * background.
  16022. *
  16023. * ```js
  16024. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  16025. * ```
  16026. *
  16027. * @tsl
  16028. * @function
  16029. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  16030. * @returns {Node<vec2>}
  16031. */
  16032. const equirectUV = /*@__PURE__*/ Fn( ( [ dir = positionWorldDirection ] ) => {
  16033. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  16034. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  16035. return vec2( u, v );
  16036. } );
  16037. /**
  16038. * This class represents a cube render target. It is a special version
  16039. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  16040. *
  16041. * @augments RenderTarget
  16042. */
  16043. class CubeRenderTarget extends RenderTarget {
  16044. /**
  16045. * Constructs a new cube render target.
  16046. *
  16047. * @param {number} [size=1] - The size of the render target.
  16048. * @param {RenderTarget~Options} [options] - The configuration object.
  16049. */
  16050. constructor( size = 1, options = {} ) {
  16051. super( size, size, options );
  16052. /**
  16053. * This flag can be used for type testing.
  16054. *
  16055. * @type {boolean}
  16056. * @readonly
  16057. * @default true
  16058. */
  16059. this.isCubeRenderTarget = true;
  16060. const image = { width: size, height: size, depth: 1 };
  16061. const images = [ image, image, image, image, image, image ];
  16062. /**
  16063. * Overwritten with a different texture type.
  16064. *
  16065. * @type {DataArrayTexture}
  16066. */
  16067. this.texture = new CubeTexture( images );
  16068. this._setTextureOptions( options );
  16069. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16070. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16071. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16072. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16073. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16074. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16075. this.texture.isRenderTargetTexture = true;
  16076. }
  16077. /**
  16078. * Converts the given equirectangular texture to a cube map.
  16079. *
  16080. * @param {Renderer} renderer - The renderer.
  16081. * @param {Texture} texture - The equirectangular texture.
  16082. * @return {CubeRenderTarget} A reference to this cube render target.
  16083. */
  16084. fromEquirectangularTexture( renderer, texture$1 ) {
  16085. const currentMinFilter = texture$1.minFilter;
  16086. const currentGenerateMipmaps = texture$1.generateMipmaps;
  16087. texture$1.generateMipmaps = true;
  16088. this.texture.type = texture$1.type;
  16089. this.texture.colorSpace = texture$1.colorSpace;
  16090. this.texture.generateMipmaps = texture$1.generateMipmaps;
  16091. this.texture.minFilter = texture$1.minFilter;
  16092. this.texture.magFilter = texture$1.magFilter;
  16093. const geometry = new BoxGeometry( 5, 5, 5 );
  16094. const uvNode = equirectUV( positionWorldDirection );
  16095. const material = new NodeMaterial();
  16096. material.colorNode = texture( texture$1, uvNode, 0 );
  16097. material.side = BackSide;
  16098. material.blending = NoBlending;
  16099. const mesh = new Mesh( geometry, material );
  16100. const scene = new Scene();
  16101. scene.add( mesh );
  16102. // Avoid blurred poles
  16103. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  16104. const camera = new CubeCamera( 1, 10, this );
  16105. const currentMRT = renderer.getMRT();
  16106. renderer.setMRT( null );
  16107. camera.update( renderer, scene );
  16108. renderer.setMRT( currentMRT );
  16109. texture$1.minFilter = currentMinFilter;
  16110. texture$1.generateMipmaps = currentGenerateMipmaps;
  16111. mesh.geometry.dispose();
  16112. mesh.material.dispose();
  16113. return this;
  16114. }
  16115. /**
  16116. * Clears this cube render target.
  16117. *
  16118. * @param {Renderer} renderer - The renderer.
  16119. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16120. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16121. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16122. */
  16123. clear( renderer, color = true, depth = true, stencil = true ) {
  16124. const currentRenderTarget = renderer.getRenderTarget();
  16125. for ( let i = 0; i < 6; i ++ ) {
  16126. renderer.setRenderTarget( this, i );
  16127. renderer.clear( color, depth, stencil );
  16128. }
  16129. renderer.setRenderTarget( currentRenderTarget );
  16130. }
  16131. }
  16132. const _cache$1 = new WeakMap();
  16133. /**
  16134. * This node can be used to automatically convert environment maps in the
  16135. * equirectangular format into the cube map format.
  16136. *
  16137. * @augments TempNode
  16138. */
  16139. class CubeMapNode extends TempNode {
  16140. static get type() {
  16141. return 'CubeMapNode';
  16142. }
  16143. /**
  16144. * Constructs a new cube map node.
  16145. *
  16146. * @param {Node} envNode - The node representing the environment map.
  16147. */
  16148. constructor( envNode ) {
  16149. super( 'vec3' );
  16150. /**
  16151. * The node representing the environment map.
  16152. *
  16153. * @type {Node}
  16154. */
  16155. this.envNode = envNode;
  16156. /**
  16157. * A reference to the internal cube texture.
  16158. *
  16159. * @private
  16160. * @type {?CubeTexture}
  16161. * @default null
  16162. */
  16163. this._cubeTexture = null;
  16164. /**
  16165. * A reference to the internal cube texture node.
  16166. *
  16167. * @private
  16168. * @type {CubeTextureNode}
  16169. */
  16170. this._cubeTextureNode = cubeTexture( null );
  16171. const defaultTexture = new CubeTexture();
  16172. defaultTexture.isRenderTargetTexture = true;
  16173. /**
  16174. * A default cube texture that acts as a placeholder.
  16175. * It is used when the conversion from equirectangular to cube
  16176. * map has not finished yet for a given texture.
  16177. *
  16178. * @private
  16179. * @type {CubeTexture}
  16180. */
  16181. this._defaultTexture = defaultTexture;
  16182. /**
  16183. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  16184. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  16185. *
  16186. * @type {string}
  16187. * @default 'render'
  16188. */
  16189. this.updateBeforeType = NodeUpdateType.RENDER;
  16190. }
  16191. updateBefore( frame ) {
  16192. const { renderer, material } = frame;
  16193. const envNode = this.envNode;
  16194. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  16195. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  16196. if ( texture && texture.isTexture ) {
  16197. const mapping = texture.mapping;
  16198. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  16199. // check for converted cubemap map
  16200. if ( _cache$1.has( texture ) ) {
  16201. const cubeMap = _cache$1.get( texture );
  16202. mapTextureMapping( cubeMap, texture.mapping );
  16203. this._cubeTexture = cubeMap;
  16204. } else {
  16205. // create cube map from equirectangular map
  16206. const image = texture.image;
  16207. if ( isEquirectangularMapReady$1( image ) ) {
  16208. const renderTarget = new CubeRenderTarget( image.height );
  16209. renderTarget.fromEquirectangularTexture( renderer, texture );
  16210. mapTextureMapping( renderTarget.texture, texture.mapping );
  16211. this._cubeTexture = renderTarget.texture;
  16212. _cache$1.set( texture, renderTarget.texture );
  16213. texture.addEventListener( 'dispose', onTextureDispose );
  16214. } else {
  16215. // default cube texture as fallback when equirectangular texture is not yet loaded
  16216. this._cubeTexture = this._defaultTexture;
  16217. }
  16218. }
  16219. //
  16220. this._cubeTextureNode.value = this._cubeTexture;
  16221. } else {
  16222. // envNode already refers to a cube map
  16223. this._cubeTextureNode = this.envNode;
  16224. }
  16225. }
  16226. }
  16227. }
  16228. setup( builder ) {
  16229. this.updateBefore( builder );
  16230. return this._cubeTextureNode;
  16231. }
  16232. }
  16233. /**
  16234. * Returns true if the given equirectangular image has been fully loaded
  16235. * and is ready for further processing.
  16236. *
  16237. * @private
  16238. * @param {Image} image - The equirectangular image to check.
  16239. * @return {boolean} Whether the image is ready or not.
  16240. */
  16241. function isEquirectangularMapReady$1( image ) {
  16242. if ( image === null || image === undefined ) return false;
  16243. return image.height > 0;
  16244. }
  16245. /**
  16246. * This function is executed when `dispose()` is called on the equirectangular
  16247. * texture. In this case, the generated cube map with its render target
  16248. * is deleted as well.
  16249. *
  16250. * @private
  16251. * @param {Object} event - The event object.
  16252. */
  16253. function onTextureDispose( event ) {
  16254. const texture = event.target;
  16255. texture.removeEventListener( 'dispose', onTextureDispose );
  16256. const renderTarget = _cache$1.get( texture );
  16257. if ( renderTarget !== undefined ) {
  16258. _cache$1.delete( texture );
  16259. renderTarget.dispose();
  16260. }
  16261. }
  16262. /**
  16263. * This function makes sure the generated cube map uses the correct
  16264. * texture mapping that corresponds to the equirectangular original.
  16265. *
  16266. * @private
  16267. * @param {Texture} texture - The cube texture.
  16268. * @param {number} mapping - The original texture mapping.
  16269. */
  16270. function mapTextureMapping( texture, mapping ) {
  16271. if ( mapping === EquirectangularReflectionMapping ) {
  16272. texture.mapping = CubeReflectionMapping;
  16273. } else if ( mapping === EquirectangularRefractionMapping ) {
  16274. texture.mapping = CubeRefractionMapping;
  16275. }
  16276. }
  16277. /**
  16278. * TSL function for creating a cube map node.
  16279. *
  16280. * @tsl
  16281. * @function
  16282. * @param {Node} envNode - The node representing the environment map.
  16283. * @returns {CubeMapNode}
  16284. */
  16285. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  16286. /**
  16287. * Represents a basic model for Image-based lighting (IBL). The environment
  16288. * is defined via environment maps in the equirectangular or cube map format.
  16289. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  16290. * or {@link MeshPhongNodeMaterial}.
  16291. *
  16292. * @augments LightingNode
  16293. */
  16294. class BasicEnvironmentNode extends LightingNode {
  16295. static get type() {
  16296. return 'BasicEnvironmentNode';
  16297. }
  16298. /**
  16299. * Constructs a new basic environment node.
  16300. *
  16301. * @param {Node} [envNode=null] - A node representing the environment.
  16302. */
  16303. constructor( envNode = null ) {
  16304. super();
  16305. /**
  16306. * A node representing the environment.
  16307. *
  16308. * @type {Node}
  16309. * @default null
  16310. */
  16311. this.envNode = envNode;
  16312. }
  16313. setup( builder ) {
  16314. // environment property is used in the finish() method of BasicLightingModel
  16315. builder.context.environment = cubeMapNode( this.envNode );
  16316. }
  16317. }
  16318. /**
  16319. * A specific version of {@link IrradianceNode} that is only relevant
  16320. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  16321. * requires a special scaling factor for the light map.
  16322. *
  16323. * @augments LightingNode
  16324. */
  16325. class BasicLightMapNode extends LightingNode {
  16326. static get type() {
  16327. return 'BasicLightMapNode';
  16328. }
  16329. /**
  16330. * Constructs a new basic light map node.
  16331. *
  16332. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  16333. */
  16334. constructor( lightMapNode = null ) {
  16335. super();
  16336. /**
  16337. * The light map node.
  16338. *
  16339. * @type {?Node<vec3>}
  16340. */
  16341. this.lightMapNode = lightMapNode;
  16342. }
  16343. setup( builder ) {
  16344. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  16345. const RECIPROCAL_PI = float( 1 / Math.PI );
  16346. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  16347. }
  16348. }
  16349. /**
  16350. * Abstract class for implementing lighting models. The module defines
  16351. * multiple methods that concrete lighting models can implement. These
  16352. * methods are executed at different points during the light evaluation
  16353. * process.
  16354. */
  16355. class LightingModel {
  16356. /**
  16357. * This method is intended for setting up lighting model and context data
  16358. * which are later used in the evaluation process.
  16359. *
  16360. * @abstract
  16361. * @param {NodeBuilder} builder - The current node builder.
  16362. */
  16363. start( builder ) {
  16364. // lights ( direct )
  16365. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  16366. // indirect
  16367. this.indirect( builder );
  16368. }
  16369. /**
  16370. * This method is intended for executing final tasks like final updates
  16371. * to the outgoing light.
  16372. *
  16373. * @abstract
  16374. * @param {NodeBuilder} builder - The current node builder.
  16375. */
  16376. finish( /*builder*/ ) { }
  16377. /**
  16378. * This method is intended for implementing the direct light term and
  16379. * executed during the build process of directional, point and spot light nodes.
  16380. *
  16381. * @abstract
  16382. * @param {Object} lightData - The light data.
  16383. * @param {NodeBuilder} builder - The current node builder.
  16384. */
  16385. direct( /*lightData, builder*/ ) { }
  16386. /**
  16387. * This method is intended for implementing the direct light term for
  16388. * rect area light nodes.
  16389. *
  16390. * @abstract
  16391. * @param {Object} lightData - The light data.
  16392. * @param {NodeBuilder} builder - The current node builder.
  16393. */
  16394. directRectArea( /*lightData, builder*/ ) {}
  16395. /**
  16396. * This method is intended for implementing the indirect light term.
  16397. *
  16398. * @abstract
  16399. * @param {NodeBuilder} builder - The current node builder.
  16400. */
  16401. indirect( /*builder*/ ) { }
  16402. /**
  16403. * This method is intended for implementing the ambient occlusion term.
  16404. * Unlike other methods, this method must be called manually by the lighting
  16405. * model in its indirect term.
  16406. *
  16407. * @abstract
  16408. * @param {NodeBuilder} builder - The current node builder.
  16409. */
  16410. ambientOcclusion( /*input, stack, builder*/ ) { }
  16411. }
  16412. /**
  16413. * Represents the lighting model for unlit materials. The only light contribution
  16414. * is baked indirect lighting modulated with ambient occlusion and the material's
  16415. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  16416. *
  16417. * @augments LightingModel
  16418. */
  16419. class BasicLightingModel extends LightingModel {
  16420. /**
  16421. * Constructs a new basic lighting model.
  16422. */
  16423. constructor() {
  16424. super();
  16425. }
  16426. /**
  16427. * Implements the baked indirect lighting with its modulation.
  16428. *
  16429. * @param {NodeBuilder} builder - The current node builder.
  16430. */
  16431. indirect( { context } ) {
  16432. const ambientOcclusion = context.ambientOcclusion;
  16433. const reflectedLight = context.reflectedLight;
  16434. const irradianceLightMap = context.irradianceLightMap;
  16435. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  16436. // accumulation (baked indirect lighting only)
  16437. if ( irradianceLightMap ) {
  16438. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  16439. } else {
  16440. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  16441. }
  16442. // modulation
  16443. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16444. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  16445. }
  16446. /**
  16447. * Implements the environment mapping.
  16448. *
  16449. * @param {NodeBuilder} builder - The current node builder.
  16450. */
  16451. finish( builder ) {
  16452. const { material, context } = builder;
  16453. const outgoingLight = context.outgoingLight;
  16454. const envNode = builder.context.environment;
  16455. if ( envNode ) {
  16456. switch ( material.combine ) {
  16457. case MultiplyOperation:
  16458. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  16459. break;
  16460. case MixOperation:
  16461. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  16462. break;
  16463. case AddOperation:
  16464. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  16465. break;
  16466. default:
  16467. warn( 'BasicLightingModel: Unsupported .combine value:', material.combine );
  16468. break;
  16469. }
  16470. }
  16471. }
  16472. }
  16473. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  16474. /**
  16475. * Node material version of {@link MeshBasicMaterial}.
  16476. *
  16477. * @augments NodeMaterial
  16478. */
  16479. class MeshBasicNodeMaterial extends NodeMaterial {
  16480. static get type() {
  16481. return 'MeshBasicNodeMaterial';
  16482. }
  16483. /**
  16484. * Constructs a new mesh basic node material.
  16485. *
  16486. * @param {Object} [parameters] - The configuration parameter.
  16487. */
  16488. constructor( parameters ) {
  16489. super();
  16490. /**
  16491. * This flag can be used for type testing.
  16492. *
  16493. * @type {boolean}
  16494. * @readonly
  16495. * @default true
  16496. */
  16497. this.isMeshBasicNodeMaterial = true;
  16498. /**
  16499. * Although the basic material is by definition unlit, we set
  16500. * this property to `true` since we use a lighting model to compute
  16501. * the outgoing light of the fragment shader.
  16502. *
  16503. * @type {boolean}
  16504. * @default true
  16505. */
  16506. this.lights = true;
  16507. this.setDefaultValues( _defaultValues$9 );
  16508. this.setValues( parameters );
  16509. }
  16510. /**
  16511. * Basic materials are not affected by normal and bump maps so we
  16512. * return by default {@link normalViewGeometry}.
  16513. *
  16514. * @return {Node<vec3>} The normal node.
  16515. */
  16516. setupNormal() {
  16517. return directionToFaceDirection( normalViewGeometry ); // see #28839
  16518. }
  16519. /**
  16520. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16521. * to implement the default environment mapping.
  16522. *
  16523. * @param {NodeBuilder} builder - The current node builder.
  16524. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16525. */
  16526. setupEnvironment( builder ) {
  16527. const envNode = super.setupEnvironment( builder );
  16528. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16529. }
  16530. /**
  16531. * This method must be overwritten since light maps are evaluated
  16532. * with a special scaling factor for basic materials.
  16533. *
  16534. * @param {NodeBuilder} builder - The current node builder.
  16535. * @return {?BasicLightMapNode<vec3>} The light map node.
  16536. */
  16537. setupLightMap( builder ) {
  16538. let node = null;
  16539. if ( builder.material.lightMap ) {
  16540. node = new BasicLightMapNode( materialLightMap );
  16541. }
  16542. return node;
  16543. }
  16544. /**
  16545. * The material overwrites this method because `lights` is set to `true` but
  16546. * we still want to return the diffuse color as the outgoing light.
  16547. *
  16548. * @return {Node<vec3>} The outgoing light node.
  16549. */
  16550. setupOutgoingLight() {
  16551. return diffuseColor.rgb;
  16552. }
  16553. /**
  16554. * Setups the lighting model.
  16555. *
  16556. * @return {BasicLightingModel} The lighting model.
  16557. */
  16558. setupLightingModel() {
  16559. return new BasicLightingModel();
  16560. }
  16561. }
  16562. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  16563. // Original approximation by Christophe Schlick '94
  16564. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  16565. // Optimized variant (presented by Epic at SIGGRAPH '13)
  16566. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  16567. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  16568. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  16569. } ); // validated
  16570. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  16571. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  16572. } ); // validated
  16573. const G_BlinnPhong_Implicit = () => float( 0.25 );
  16574. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  16575. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  16576. } );
  16577. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16578. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16579. const dotNH = normalView.dot( halfDir ).clamp();
  16580. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16581. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  16582. const G = G_BlinnPhong_Implicit();
  16583. const D = D_BlinnPhong( { dotNH } );
  16584. return F.mul( G ).mul( D );
  16585. } );
  16586. /**
  16587. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  16588. *
  16589. * @augments BasicLightingModel
  16590. */
  16591. class PhongLightingModel extends BasicLightingModel {
  16592. /**
  16593. * Constructs a new phong lighting model.
  16594. *
  16595. * @param {boolean} [specular=true] - Whether specular is supported or not.
  16596. */
  16597. constructor( specular = true ) {
  16598. super();
  16599. /**
  16600. * Whether specular is supported or not. Set this to `false` if you are
  16601. * looking for a Lambert-like material meaning a material for non-shiny
  16602. * surfaces, without specular highlights.
  16603. *
  16604. * @type {boolean}
  16605. * @default true
  16606. */
  16607. this.specular = specular;
  16608. }
  16609. /**
  16610. * Implements the direct lighting. The specular portion is optional an can be controlled
  16611. * with the {@link PhongLightingModel#specular} flag.
  16612. *
  16613. * @param {Object} lightData - The light data.
  16614. */
  16615. direct( { lightDirection, lightColor, reflectedLight } ) {
  16616. const dotNL = normalView.dot( lightDirection ).clamp();
  16617. const irradiance = dotNL.mul( lightColor );
  16618. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  16619. if ( this.specular === true ) {
  16620. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  16621. }
  16622. }
  16623. /**
  16624. * Implements the indirect lighting.
  16625. *
  16626. * @param {NodeBuilder} builder - The current node builder.
  16627. */
  16628. indirect( builder ) {
  16629. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  16630. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16631. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16632. }
  16633. }
  16634. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  16635. /**
  16636. * Node material version of {@link MeshLambertMaterial}.
  16637. *
  16638. * @augments NodeMaterial
  16639. */
  16640. class MeshLambertNodeMaterial extends NodeMaterial {
  16641. static get type() {
  16642. return 'MeshLambertNodeMaterial';
  16643. }
  16644. /**
  16645. * Constructs a new mesh lambert node material.
  16646. *
  16647. * @param {Object} [parameters] - The configuration parameter.
  16648. */
  16649. constructor( parameters ) {
  16650. super();
  16651. /**
  16652. * This flag can be used for type testing.
  16653. *
  16654. * @type {boolean}
  16655. * @readonly
  16656. * @default true
  16657. */
  16658. this.isMeshLambertNodeMaterial = true;
  16659. /**
  16660. * Set to `true` because lambert materials react on lights.
  16661. *
  16662. * @type {boolean}
  16663. * @default true
  16664. */
  16665. this.lights = true;
  16666. this.setDefaultValues( _defaultValues$8 );
  16667. this.setValues( parameters );
  16668. }
  16669. /**
  16670. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16671. * to implement the default environment mapping.
  16672. *
  16673. * @param {NodeBuilder} builder - The current node builder.
  16674. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16675. */
  16676. setupEnvironment( builder ) {
  16677. const envNode = super.setupEnvironment( builder );
  16678. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16679. }
  16680. /**
  16681. * Setups the lighting model.
  16682. *
  16683. * @return {PhongLightingModel} The lighting model.
  16684. */
  16685. setupLightingModel( /*builder*/ ) {
  16686. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  16687. }
  16688. }
  16689. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  16690. /**
  16691. * Node material version of {@link MeshPhongMaterial}.
  16692. *
  16693. * @augments NodeMaterial
  16694. */
  16695. class MeshPhongNodeMaterial extends NodeMaterial {
  16696. static get type() {
  16697. return 'MeshPhongNodeMaterial';
  16698. }
  16699. /**
  16700. * Constructs a new mesh lambert node material.
  16701. *
  16702. * @param {Object} [parameters] - The configuration parameter.
  16703. */
  16704. constructor( parameters ) {
  16705. super();
  16706. /**
  16707. * This flag can be used for type testing.
  16708. *
  16709. * @type {boolean}
  16710. * @readonly
  16711. * @default true
  16712. */
  16713. this.isMeshPhongNodeMaterial = true;
  16714. /**
  16715. * Set to `true` because phong materials react on lights.
  16716. *
  16717. * @type {boolean}
  16718. * @default true
  16719. */
  16720. this.lights = true;
  16721. /**
  16722. * The shininess of phong materials is by default inferred from the `shininess`
  16723. * property. This node property allows to overwrite the default
  16724. * and define the shininess with a node instead.
  16725. *
  16726. * If you don't want to overwrite the shininess but modify the existing
  16727. * value instead, use {@link materialShininess}.
  16728. *
  16729. * @type {?Node<float>}
  16730. * @default null
  16731. */
  16732. this.shininessNode = null;
  16733. /**
  16734. * The specular color of phong materials is by default inferred from the
  16735. * `specular` property. This node property allows to overwrite the default
  16736. * and define the specular color with a node instead.
  16737. *
  16738. * If you don't want to overwrite the specular color but modify the existing
  16739. * value instead, use {@link materialSpecular}.
  16740. *
  16741. * @type {?Node<vec3>}
  16742. * @default null
  16743. */
  16744. this.specularNode = null;
  16745. this.setDefaultValues( _defaultValues$7 );
  16746. this.setValues( parameters );
  16747. }
  16748. /**
  16749. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16750. * to implement the default environment mapping.
  16751. *
  16752. * @param {NodeBuilder} builder - The current node builder.
  16753. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16754. */
  16755. setupEnvironment( builder ) {
  16756. const envNode = super.setupEnvironment( builder );
  16757. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16758. }
  16759. /**
  16760. * Setups the lighting model.
  16761. *
  16762. * @return {PhongLightingModel} The lighting model.
  16763. */
  16764. setupLightingModel( /*builder*/ ) {
  16765. return new PhongLightingModel();
  16766. }
  16767. /**
  16768. * Setups the phong specific node variables.
  16769. *
  16770. * @param {NodeBuilder} builder - The current node builder.
  16771. */
  16772. setupVariants( /*builder*/ ) {
  16773. // SHININESS
  16774. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16775. shininess.assign( shininessNode );
  16776. // SPECULAR COLOR
  16777. const specularNode = this.specularNode || materialSpecular;
  16778. specularColor.assign( specularNode );
  16779. }
  16780. copy( source ) {
  16781. this.shininessNode = source.shininessNode;
  16782. this.specularNode = source.specularNode;
  16783. return super.copy( source );
  16784. }
  16785. }
  16786. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  16787. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  16788. return float( 0 );
  16789. }
  16790. const dxy = normalViewGeometry.dFdx().abs().max( normalViewGeometry.dFdy().abs() );
  16791. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  16792. return geometryRoughness;
  16793. } );
  16794. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  16795. const { roughness } = inputs;
  16796. const geometryRoughness = getGeometryRoughness();
  16797. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  16798. roughnessFactor = roughnessFactor.add( geometryRoughness );
  16799. roughnessFactor = roughnessFactor.min( 1.0 );
  16800. return roughnessFactor;
  16801. } );
  16802. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  16803. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  16804. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  16805. const a2 = alpha.pow2();
  16806. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  16807. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  16808. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  16809. } ).setLayout( {
  16810. name: 'V_GGX_SmithCorrelated',
  16811. type: 'float',
  16812. inputs: [
  16813. { name: 'alpha', type: 'float' },
  16814. { name: 'dotNL', type: 'float' },
  16815. { name: 'dotNV', type: 'float' }
  16816. ]
  16817. } ); // validated
  16818. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16819. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  16820. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  16821. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  16822. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  16823. } ).setLayout( {
  16824. name: 'V_GGX_SmithCorrelated_Anisotropic',
  16825. type: 'float',
  16826. inputs: [
  16827. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16828. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16829. { name: 'dotTV', type: 'float', qualifier: 'in' },
  16830. { name: 'dotBV', type: 'float', qualifier: 'in' },
  16831. { name: 'dotTL', type: 'float', qualifier: 'in' },
  16832. { name: 'dotBL', type: 'float', qualifier: 'in' },
  16833. { name: 'dotNV', type: 'float', qualifier: 'in' },
  16834. { name: 'dotNL', type: 'float', qualifier: 'in' }
  16835. ]
  16836. } );
  16837. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  16838. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  16839. // alpha is "roughness squared" in Disney’s reparameterization
  16840. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  16841. const a2 = alpha.pow2();
  16842. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  16843. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  16844. } ).setLayout( {
  16845. name: 'D_GGX',
  16846. type: 'float',
  16847. inputs: [
  16848. { name: 'alpha', type: 'float' },
  16849. { name: 'dotNH', type: 'float' }
  16850. ]
  16851. } ); // validated
  16852. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  16853. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16854. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  16855. const a2 = alphaT.mul( alphaB );
  16856. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  16857. const v2 = v.dot( v );
  16858. const w2 = a2.div( v2 );
  16859. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  16860. } ).setLayout( {
  16861. name: 'D_GGX_Anisotropic',
  16862. type: 'float',
  16863. inputs: [
  16864. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16865. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16866. { name: 'dotNH', type: 'float', qualifier: 'in' },
  16867. { name: 'dotTH', type: 'float', qualifier: 'in' },
  16868. { name: 'dotBH', type: 'float', qualifier: 'in' }
  16869. ]
  16870. } );
  16871. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  16872. const BRDF_GGX = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness, f, normalView: normalView$1 = normalView, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16873. const alpha = roughness.pow2(); // UE4's roughness
  16874. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16875. const dotNL = normalView$1.dot( lightDirection ).clamp();
  16876. const dotNV = normalView$1.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16877. const dotNH = normalView$1.dot( halfDir ).clamp();
  16878. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16879. let F = F_Schlick( { f0, f90, dotVH } );
  16880. let V, D;
  16881. if ( defined( USE_IRIDESCENCE ) ) {
  16882. F = iridescence.mix( F, f );
  16883. }
  16884. if ( defined( USE_ANISOTROPY ) ) {
  16885. const dotTL = anisotropyT.dot( lightDirection );
  16886. const dotTV = anisotropyT.dot( positionViewDirection );
  16887. const dotTH = anisotropyT.dot( halfDir );
  16888. const dotBL = anisotropyB.dot( lightDirection );
  16889. const dotBV = anisotropyB.dot( positionViewDirection );
  16890. const dotBH = anisotropyB.dot( halfDir );
  16891. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  16892. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  16893. } else {
  16894. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  16895. D = D_GGX( { alpha, dotNH } );
  16896. }
  16897. return F.mul( V ).mul( D );
  16898. } ); // validated
  16899. /**
  16900. * Precomputed DFG LUT for Image-Based Lighting
  16901. * Resolution: 16x16
  16902. * Samples: 4096 per texel
  16903. * Format: RG16F (2 half floats per texel: scale, bias)
  16904. */
  16905. const DATA = new Uint16Array( [
  16906. 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,
  16907. 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,
  16908. 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,
  16909. 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,
  16910. 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,
  16911. 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,
  16912. 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,
  16913. 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,
  16914. 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,
  16915. 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,
  16916. 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,
  16917. 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,
  16918. 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,
  16919. 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,
  16920. 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,
  16921. 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
  16922. ] );
  16923. let lut = null;
  16924. const DFGLUT = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  16925. if ( lut === null ) {
  16926. lut = new DataTexture( DATA, 16, 16, RGFormat, HalfFloatType );
  16927. lut.name = 'DFG_LUT';
  16928. lut.minFilter = LinearFilter;
  16929. lut.magFilter = LinearFilter;
  16930. lut.wrapS = ClampToEdgeWrapping;
  16931. lut.wrapT = ClampToEdgeWrapping;
  16932. lut.generateMipmaps = false;
  16933. lut.needsUpdate = true;
  16934. }
  16935. const uv = vec2( roughness, dotNV );
  16936. return texture( lut, uv ).rg;
  16937. } );
  16938. // GGX BRDF with multi-scattering energy compensation for direct lighting
  16939. // This provides more accurate energy conservation, especially for rough materials
  16940. // Based on "Practical Multiple Scattering Compensation for Microfacet Models"
  16941. // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf
  16942. const BRDF_GGX_Multiscatter = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness: _roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16943. // Single-scattering BRDF (standard GGX)
  16944. const singleScatter = BRDF_GGX( { lightDirection, f0, f90, roughness: _roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } );
  16945. // Multi-scattering compensation
  16946. const dotNL = normalView.dot( lightDirection ).clamp();
  16947. const dotNV = normalView.dot( positionViewDirection ).clamp();
  16948. // Precomputed DFG values for view and light directions
  16949. const dfgV = DFGLUT( { roughness: _roughness, dotNV } );
  16950. const dfgL = DFGLUT( { roughness: _roughness, dotNV: dotNL } );
  16951. // Single-scattering energy for view and light
  16952. const FssEss_V = f0.mul( dfgV.x ).add( f90.mul( dfgV.y ) );
  16953. const FssEss_L = f0.mul( dfgL.x ).add( f90.mul( dfgL.y ) );
  16954. const Ess_V = dfgV.x.add( dfgV.y );
  16955. const Ess_L = dfgL.x.add( dfgL.y );
  16956. // Energy lost to multiple scattering
  16957. const Ems_V = float( 1.0 ).sub( Ess_V );
  16958. const Ems_L = float( 1.0 ).sub( Ess_L );
  16959. // Average Fresnel reflectance
  16960. const Favg = f0.add( f0.oneMinus().mul( 0.047619 ) ); // 1/21
  16961. // Multiple scattering contribution
  16962. // Uses geometric mean of view and light contributions for better energy distribution
  16963. 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 ) );
  16964. // Energy compensation factor
  16965. const compensationFactor = Ems_V.mul( Ems_L );
  16966. const multiScatter = Fms.mul( compensationFactor );
  16967. return singleScatter.add( multiScatter );
  16968. } );
  16969. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  16970. const { dotNV, specularColor, specularF90, roughness } = inputs;
  16971. const fab = DFGLUT( { dotNV, roughness } );
  16972. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16973. } );
  16974. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  16975. const x = dotVH.oneMinus().saturate();
  16976. const x2 = x.mul( x );
  16977. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  16978. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  16979. } ).setLayout( {
  16980. name: 'Schlick_to_F0',
  16981. type: 'vec3',
  16982. inputs: [
  16983. { name: 'f', type: 'vec3' },
  16984. { name: 'f90', type: 'float' },
  16985. { name: 'dotVH', type: 'float' }
  16986. ]
  16987. } );
  16988. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16989. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  16990. const alpha = roughness.pow2();
  16991. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  16992. const invAlpha = float( 1.0 ).div( alpha );
  16993. const cos2h = dotNH.pow2();
  16994. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  16995. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  16996. } ).setLayout( {
  16997. name: 'D_Charlie',
  16998. type: 'float',
  16999. inputs: [
  17000. { name: 'roughness', type: 'float' },
  17001. { name: 'dotNH', type: 'float' }
  17002. ]
  17003. } );
  17004. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  17005. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  17006. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  17007. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  17008. } ).setLayout( {
  17009. name: 'V_Neubelt',
  17010. type: 'float',
  17011. inputs: [
  17012. { name: 'dotNV', type: 'float' },
  17013. { name: 'dotNL', type: 'float' }
  17014. ]
  17015. } );
  17016. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  17017. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  17018. const dotNL = normalView.dot( lightDirection ).clamp();
  17019. const dotNV = normalView.dot( positionViewDirection ).clamp();
  17020. const dotNH = normalView.dot( halfDir ).clamp();
  17021. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  17022. const V = V_Neubelt( { dotNV, dotNL } );
  17023. return sheen.mul( D ).mul( V );
  17024. } );
  17025. // Rect Area Light
  17026. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  17027. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  17028. // code: https://github.com/selfshadow/ltc_code/
  17029. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  17030. const LUT_SIZE = 64.0;
  17031. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  17032. const LUT_BIAS = 0.5 / LUT_SIZE;
  17033. const dotNV = N.dot( V ).saturate();
  17034. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  17035. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  17036. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  17037. return uv;
  17038. } ).setLayout( {
  17039. name: 'LTC_Uv',
  17040. type: 'vec2',
  17041. inputs: [
  17042. { name: 'N', type: 'vec3' },
  17043. { name: 'V', type: 'vec3' },
  17044. { name: 'roughness', type: 'float' }
  17045. ]
  17046. } );
  17047. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  17048. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  17049. // An approximation of the form factor of a horizon-clipped rectangle.
  17050. const l = f.length();
  17051. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  17052. } ).setLayout( {
  17053. name: 'LTC_ClippedSphereFormFactor',
  17054. type: 'float',
  17055. inputs: [
  17056. { name: 'f', type: 'vec3' }
  17057. ]
  17058. } );
  17059. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  17060. const x = v1.dot( v2 );
  17061. const y = x.abs().toVar();
  17062. // rational polynomial approximation to theta / sin( theta ) / 2PI
  17063. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  17064. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  17065. const v = a.div( b );
  17066. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  17067. return v1.cross( v2 ).mul( theta_sintheta );
  17068. } ).setLayout( {
  17069. name: 'LTC_EdgeVectorFormFactor',
  17070. type: 'vec3',
  17071. inputs: [
  17072. { name: 'v1', type: 'vec3' },
  17073. { name: 'v2', type: 'vec3' }
  17074. ]
  17075. } );
  17076. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  17077. // bail if point is on back side of plane of light
  17078. // assumes ccw winding order of light vertices
  17079. const v1 = p1.sub( p0 ).toVar();
  17080. const v2 = p3.sub( p0 ).toVar();
  17081. const lightNormal = v1.cross( v2 );
  17082. const result = vec3().toVar();
  17083. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  17084. // construct orthonormal basis around N
  17085. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  17086. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  17087. // compute transform
  17088. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  17089. // transform rect
  17090. // & project rect onto sphere
  17091. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  17092. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  17093. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  17094. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  17095. // calculate vector form factor
  17096. const vectorFormFactor = vec3( 0 ).toVar();
  17097. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  17098. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  17099. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  17100. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  17101. // adjust for horizon clipping
  17102. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  17103. } );
  17104. return result;
  17105. } ).setLayout( {
  17106. name: 'LTC_Evaluate',
  17107. type: 'vec3',
  17108. inputs: [
  17109. { name: 'N', type: 'vec3' },
  17110. { name: 'V', type: 'vec3' },
  17111. { name: 'P', type: 'vec3' },
  17112. { name: 'mInv', type: 'mat3' },
  17113. { name: 'p0', type: 'vec3' },
  17114. { name: 'p1', type: 'vec3' },
  17115. { name: 'p2', type: 'vec3' },
  17116. { name: 'p3', type: 'vec3' }
  17117. ]
  17118. } );
  17119. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  17120. // bail if point is on back side of plane of light
  17121. // assumes ccw winding order of light vertices
  17122. const v1 = p1.sub( p0 ).toVar();
  17123. const v2 = p3.sub( p0 ).toVar();
  17124. const lightNormal = v1.cross( v2 );
  17125. const result = vec3().toVar();
  17126. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  17127. // transform rect
  17128. // & project rect onto sphere
  17129. const coords0 = p0.sub( P ).normalize().toVar();
  17130. const coords1 = p1.sub( P ).normalize().toVar();
  17131. const coords2 = p2.sub( P ).normalize().toVar();
  17132. const coords3 = p3.sub( P ).normalize().toVar();
  17133. // calculate vector form factor
  17134. const vectorFormFactor = vec3( 0 ).toVar();
  17135. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  17136. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  17137. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  17138. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  17139. // adjust for horizon clipping
  17140. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  17141. } );
  17142. return result;
  17143. } ).setLayout( {
  17144. name: 'LTC_Evaluate',
  17145. type: 'vec3',
  17146. inputs: [
  17147. { name: 'P', type: 'vec3' },
  17148. { name: 'p0', type: 'vec3' },
  17149. { name: 'p1', type: 'vec3' },
  17150. { name: 'p2', type: 'vec3' },
  17151. { name: 'p3', type: 'vec3' }
  17152. ]
  17153. } );
  17154. // Mipped Bicubic Texture Filtering by N8
  17155. // https://www.shadertoy.com/view/Dl2SDW
  17156. const bC = 1.0 / 6.0;
  17157. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  17158. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  17159. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  17160. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  17161. const g0 = ( a ) => w0( a ).add( w1( a ) );
  17162. const g1 = ( a ) => w2( a ).add( w3( a ) );
  17163. // h0 and h1 are the two offset functions
  17164. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  17165. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  17166. const bicubic = ( textureNode, texelSize, lod ) => {
  17167. const uv = textureNode.uvNode;
  17168. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  17169. const iuv = floor( uvScaled );
  17170. const fuv = fract( uvScaled );
  17171. const g0x = g0( fuv.x );
  17172. const g1x = g1( fuv.x );
  17173. const h0x = h0( fuv.x );
  17174. const h1x = h1( fuv.x );
  17175. const h0y = h0( fuv.y );
  17176. const h1y = h1( fuv.y );
  17177. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  17178. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  17179. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  17180. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  17181. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  17182. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  17183. return a.add( b );
  17184. };
  17185. /**
  17186. * Applies mipped bicubic texture filtering to the given texture node.
  17187. *
  17188. * @tsl
  17189. * @function
  17190. * @param {TextureNode} textureNode - The texture node that should be filtered.
  17191. * @param {Node<float>} lodNode - Defines the LOD to sample from.
  17192. * @return {Node} The filtered texture sample.
  17193. */
  17194. const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => {
  17195. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  17196. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  17197. const fLodSizeInv = div( 1.0, fLodSize );
  17198. const cLodSizeInv = div( 1.0, cLodSize );
  17199. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  17200. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  17201. return fract( lodNode ).mix( fSample, cSample );
  17202. } );
  17203. /**
  17204. * Applies mipped bicubic texture filtering to the given texture node.
  17205. *
  17206. * @tsl
  17207. * @function
  17208. * @param {TextureNode} textureNode - The texture node that should be filtered.
  17209. * @param {Node<float>} [strength] - Defines the strength of the bicubic filtering.
  17210. * @return {Node} The filtered texture sample.
  17211. */
  17212. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => {
  17213. const lod = strength.mul( maxMipLevel( textureNode ) );
  17214. return textureBicubicLevel( textureNode, lod );
  17215. } );
  17216. //
  17217. // Transmission
  17218. //
  17219. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  17220. // Direction of refracted light.
  17221. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  17222. // Compute rotation-independent scaling of the model matrix.
  17223. const modelScale = vec3(
  17224. length( modelMatrix[ 0 ].xyz ),
  17225. length( modelMatrix[ 1 ].xyz ),
  17226. length( modelMatrix[ 2 ].xyz )
  17227. );
  17228. // The thickness is specified in local space.
  17229. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  17230. } ).setLayout( {
  17231. name: 'getVolumeTransmissionRay',
  17232. type: 'vec3',
  17233. inputs: [
  17234. { name: 'n', type: 'vec3' },
  17235. { name: 'v', type: 'vec3' },
  17236. { name: 'thickness', type: 'float' },
  17237. { name: 'ior', type: 'float' },
  17238. { name: 'modelMatrix', type: 'mat4' }
  17239. ]
  17240. } );
  17241. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  17242. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  17243. // an IOR of 1.5 results in the default amount of microfacet refraction.
  17244. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  17245. } ).setLayout( {
  17246. name: 'applyIorToRoughness',
  17247. type: 'float',
  17248. inputs: [
  17249. { name: 'roughness', type: 'float' },
  17250. { name: 'ior', type: 'float' }
  17251. ]
  17252. } );
  17253. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  17254. const viewportFrontSideTexture = /*@__PURE__*/ viewportOpaqueMipTexture();
  17255. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  17256. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  17257. const transmissionSample = vTexture.sample( fragCoord );
  17258. //const transmissionSample = viewportMipTexture( fragCoord );
  17259. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  17260. return textureBicubicLevel( transmissionSample, lod );
  17261. } );
  17262. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  17263. If( attenuationDistance.notEqual( 0 ), () => {
  17264. // Compute light attenuation using Beer's law.
  17265. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  17266. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  17267. return transmittance;
  17268. } );
  17269. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  17270. return vec3( 1.0 );
  17271. } ).setLayout( {
  17272. name: 'volumeAttenuation',
  17273. type: 'vec3',
  17274. inputs: [
  17275. { name: 'transmissionDistance', type: 'float' },
  17276. { name: 'attenuationColor', type: 'vec3' },
  17277. { name: 'attenuationDistance', type: 'float' }
  17278. ]
  17279. } );
  17280. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  17281. let transmittedLight, transmittance;
  17282. if ( dispersion ) {
  17283. transmittedLight = vec4().toVar();
  17284. transmittance = vec3().toVar();
  17285. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  17286. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  17287. Loop( { start: 0, end: 3 }, ( { i } ) => {
  17288. const ior = iors.element( i );
  17289. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  17290. const refractedRayExit = position.add( transmissionRay );
  17291. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  17292. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  17293. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  17294. refractionCoords.addAssign( 1.0 );
  17295. refractionCoords.divAssign( 2.0 );
  17296. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  17297. // Sample framebuffer to get pixel the refracted ray hits.
  17298. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  17299. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  17300. transmittedLight.a.addAssign( transmissionSample.a );
  17301. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  17302. } );
  17303. transmittedLight.a.divAssign( 3.0 );
  17304. } else {
  17305. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  17306. const refractedRayExit = position.add( transmissionRay );
  17307. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  17308. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  17309. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  17310. refractionCoords.addAssign( 1.0 );
  17311. refractionCoords.divAssign( 2.0 );
  17312. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  17313. // Sample framebuffer to get pixel the refracted ray hits.
  17314. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  17315. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  17316. }
  17317. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  17318. const dotNV = n.dot( v ).clamp();
  17319. // Get the specular component.
  17320. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  17321. dotNV,
  17322. specularColor,
  17323. specularF90,
  17324. roughness
  17325. } ) );
  17326. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  17327. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  17328. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  17329. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  17330. } );
  17331. //
  17332. // Iridescence
  17333. //
  17334. // XYZ to linear-sRGB color space
  17335. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  17336. 3.2404542, -0.969266, 0.0556434,
  17337. -1.5371385, 1.8760108, -0.2040259,
  17338. -0.4985314, 0.0415560, 1.0572252
  17339. );
  17340. // Assume air interface for top
  17341. // Note: We don't handle the case fresnel0 == 1
  17342. const Fresnel0ToIor = ( fresnel0 ) => {
  17343. const sqrtF0 = fresnel0.sqrt();
  17344. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  17345. };
  17346. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  17347. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  17348. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  17349. };
  17350. // Fresnel equations for dielectric/dielectric interfaces.
  17351. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  17352. // Evaluation XYZ sensitivity curves in Fourier space
  17353. const evalSensitivity = ( OPD, shift ) => {
  17354. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  17355. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  17356. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  17357. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  17358. 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() );
  17359. 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() );
  17360. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  17361. const rgb = XYZ_TO_REC709.mul( xyz );
  17362. return rgb;
  17363. };
  17364. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  17365. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  17366. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  17367. // Evaluate the cosTheta on the base layer (Snell law)
  17368. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  17369. // Handle TIR:
  17370. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  17371. If( cosTheta2Sq.lessThan( 0 ), () => {
  17372. return vec3( 1.0 );
  17373. } );
  17374. const cosTheta2 = cosTheta2Sq.sqrt();
  17375. // First interface
  17376. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  17377. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  17378. //const R21 = R12;
  17379. const T121 = R12.oneMinus();
  17380. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  17381. const phi21 = float( Math.PI ).sub( phi12 );
  17382. // Second interface
  17383. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  17384. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  17385. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  17386. const phi23 = vec3(
  17387. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  17388. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  17389. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  17390. );
  17391. // Phase shift
  17392. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  17393. const phi = vec3( phi21 ).add( phi23 );
  17394. // Compound terms
  17395. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  17396. const r123 = R123.sqrt();
  17397. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  17398. // Reflectance term for m = 0 (DC term amplitude)
  17399. const C0 = R12.add( Rs );
  17400. const I = C0.toVar();
  17401. // Reflectance term for m > 0 (pairs of diracs)
  17402. const Cm = Rs.sub( T121 ).toVar();
  17403. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  17404. Cm.mulAssign( r123 );
  17405. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  17406. I.addAssign( Cm.mul( Sm ) );
  17407. } );
  17408. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  17409. return I.max( vec3( 0.0 ) );
  17410. } ).setLayout( {
  17411. name: 'evalIridescence',
  17412. type: 'vec3',
  17413. inputs: [
  17414. { name: 'outsideIOR', type: 'float' },
  17415. { name: 'eta2', type: 'float' },
  17416. { name: 'cosTheta1', type: 'float' },
  17417. { name: 'thinFilmThickness', type: 'float' },
  17418. { name: 'baseF0', type: 'vec3' }
  17419. ]
  17420. } );
  17421. //
  17422. // Sheen
  17423. //
  17424. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  17425. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF".
  17426. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  17427. const dotNV = normal.dot( viewDir ).saturate();
  17428. const r2 = roughness.mul( roughness );
  17429. const rInv = roughness.add( 0.1 ).reciprocal();
  17430. const a = float( -1.9362 ).add( roughness.mul( 1.0678 ) ).add( r2.mul( 0.4573 ) ).sub( rInv.mul( 0.8469 ) );
  17431. const b = float( -0.6014 ).add( roughness.mul( 0.5538 ) ).sub( r2.mul( 0.4670 ) ).sub( rInv.mul( 0.1255 ) );
  17432. const DG = a.mul( dotNV ).add( b ).exp();
  17433. return DG.saturate();
  17434. } );
  17435. const clearcoatF0 = vec3( 0.04 );
  17436. const clearcoatF90 = float( 1 );
  17437. /**
  17438. * Represents the lighting model for a PBR material.
  17439. *
  17440. * @augments LightingModel
  17441. */
  17442. class PhysicalLightingModel extends LightingModel {
  17443. /**
  17444. * Constructs a new physical lighting model.
  17445. *
  17446. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  17447. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  17448. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  17449. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  17450. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  17451. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  17452. */
  17453. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  17454. super();
  17455. /**
  17456. * Whether clearcoat is supported or not.
  17457. *
  17458. * @type {boolean}
  17459. * @default false
  17460. */
  17461. this.clearcoat = clearcoat;
  17462. /**
  17463. * Whether sheen is supported or not.
  17464. *
  17465. * @type {boolean}
  17466. * @default false
  17467. */
  17468. this.sheen = sheen;
  17469. /**
  17470. * Whether iridescence is supported or not.
  17471. *
  17472. * @type {boolean}
  17473. * @default false
  17474. */
  17475. this.iridescence = iridescence;
  17476. /**
  17477. * Whether anisotropy is supported or not.
  17478. *
  17479. * @type {boolean}
  17480. * @default false
  17481. */
  17482. this.anisotropy = anisotropy;
  17483. /**
  17484. * Whether transmission is supported or not.
  17485. *
  17486. * @type {boolean}
  17487. * @default false
  17488. */
  17489. this.transmission = transmission;
  17490. /**
  17491. * Whether dispersion is supported or not.
  17492. *
  17493. * @type {boolean}
  17494. * @default false
  17495. */
  17496. this.dispersion = dispersion;
  17497. /**
  17498. * The clear coat radiance.
  17499. *
  17500. * @type {?Node}
  17501. * @default null
  17502. */
  17503. this.clearcoatRadiance = null;
  17504. /**
  17505. * The clear coat specular direct.
  17506. *
  17507. * @type {?Node}
  17508. * @default null
  17509. */
  17510. this.clearcoatSpecularDirect = null;
  17511. /**
  17512. * The clear coat specular indirect.
  17513. *
  17514. * @type {?Node}
  17515. * @default null
  17516. */
  17517. this.clearcoatSpecularIndirect = null;
  17518. /**
  17519. * The sheen specular direct.
  17520. *
  17521. * @type {?Node}
  17522. * @default null
  17523. */
  17524. this.sheenSpecularDirect = null;
  17525. /**
  17526. * The sheen specular indirect.
  17527. *
  17528. * @type {?Node}
  17529. * @default null
  17530. */
  17531. this.sheenSpecularIndirect = null;
  17532. /**
  17533. * The iridescence Fresnel.
  17534. *
  17535. * @type {?Node}
  17536. * @default null
  17537. */
  17538. this.iridescenceFresnel = null;
  17539. /**
  17540. * The iridescence F0.
  17541. *
  17542. * @type {?Node}
  17543. * @default null
  17544. */
  17545. this.iridescenceF0 = null;
  17546. /**
  17547. * The iridescence F0 dielectric.
  17548. *
  17549. * @type {?Node}
  17550. * @default null
  17551. */
  17552. this.iridescenceF0Dielectric = null;
  17553. /**
  17554. * The iridescence F0 metallic.
  17555. *
  17556. * @type {?Node}
  17557. * @default null
  17558. */
  17559. this.iridescenceF0Metallic = null;
  17560. }
  17561. /**
  17562. * Depending on what features are requested, the method prepares certain node variables
  17563. * which are later used for lighting computations.
  17564. *
  17565. * @param {NodeBuilder} builder - The current node builder.
  17566. */
  17567. start( builder ) {
  17568. if ( this.clearcoat === true ) {
  17569. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  17570. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  17571. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  17572. }
  17573. if ( this.sheen === true ) {
  17574. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  17575. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  17576. }
  17577. if ( this.iridescence === true ) {
  17578. const dotNVi = normalView.dot( positionViewDirection ).clamp();
  17579. const iridescenceFresnelDielectric = evalIridescence( {
  17580. outsideIOR: float( 1.0 ),
  17581. eta2: iridescenceIOR,
  17582. cosTheta1: dotNVi,
  17583. thinFilmThickness: iridescenceThickness,
  17584. baseF0: specularColor
  17585. } );
  17586. const iridescenceFresnelMetallic = evalIridescence( {
  17587. outsideIOR: float( 1.0 ),
  17588. eta2: iridescenceIOR,
  17589. cosTheta1: dotNVi,
  17590. thinFilmThickness: iridescenceThickness,
  17591. baseF0: diffuseColor.rgb
  17592. } );
  17593. this.iridescenceFresnel = mix( iridescenceFresnelDielectric, iridescenceFresnelMetallic, metalness );
  17594. this.iridescenceF0Dielectric = Schlick_to_F0( { f: iridescenceFresnelDielectric, f90: 1.0, dotVH: dotNVi } );
  17595. this.iridescenceF0Metallic = Schlick_to_F0( { f: iridescenceFresnelMetallic, f90: 1.0, dotVH: dotNVi } );
  17596. this.iridescenceF0 = mix( this.iridescenceF0Dielectric, this.iridescenceF0Metallic, metalness );
  17597. }
  17598. if ( this.transmission === true ) {
  17599. const position = positionWorld;
  17600. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  17601. const n = normalWorld;
  17602. const context = builder.context;
  17603. context.backdrop = getIBLVolumeRefraction(
  17604. n,
  17605. v,
  17606. roughness,
  17607. diffuseContribution,
  17608. specularColorBlended,
  17609. specularF90, // specularF90
  17610. position, // positionWorld
  17611. modelWorldMatrix, // modelMatrix
  17612. cameraViewMatrix, // viewMatrix
  17613. cameraProjectionMatrix, // projMatrix
  17614. ior,
  17615. thickness,
  17616. attenuationColor,
  17617. attenuationDistance,
  17618. this.dispersion ? dispersion : null
  17619. );
  17620. context.backdropAlpha = transmission;
  17621. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  17622. }
  17623. super.start( builder );
  17624. }
  17625. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  17626. // Approximates multi-scattering in order to preserve energy.
  17627. // http://www.jcgt.org/published/0008/01/03/
  17628. computeMultiscattering( singleScatter, multiScatter, specularF90, f0, iridescenceF0 = null ) {
  17629. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17630. const fab = DFGLUT( { roughness, dotNV } );
  17631. const Fr = iridescenceF0 ? iridescence.mix( f0, iridescenceF0 ) : f0;
  17632. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  17633. const Ess = fab.x.add( fab.y );
  17634. const Ems = Ess.oneMinus();
  17635. const Favg = Fr.add( Fr.oneMinus().mul( 0.047619 ) ); // 1/21
  17636. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  17637. singleScatter.addAssign( FssEss );
  17638. multiScatter.addAssign( Fms.mul( Ems ) );
  17639. }
  17640. /**
  17641. * Implements the direct light.
  17642. *
  17643. * @param {Object} lightData - The light data.
  17644. * @param {NodeBuilder} builder - The current node builder.
  17645. */
  17646. direct( { lightDirection, lightColor, reflectedLight }, /* builder */ ) {
  17647. const dotNL = normalView.dot( lightDirection ).clamp();
  17648. const irradiance = dotNL.mul( lightColor ).toVar();
  17649. if ( this.sheen === true ) {
  17650. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  17651. const sheenAlbedoV = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17652. const sheenAlbedoL = IBLSheenBRDF( { normal: normalView, viewDir: lightDirection, roughness: sheenRoughness } );
  17653. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedoV.max( sheenAlbedoL ) ).oneMinus();
  17654. irradiance.mulAssign( sheenEnergyComp );
  17655. }
  17656. if ( this.clearcoat === true ) {
  17657. const dotNLcc = clearcoatNormalView.dot( lightDirection ).clamp();
  17658. const ccIrradiance = dotNLcc.mul( lightColor );
  17659. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: clearcoatNormalView } ) ) );
  17660. }
  17661. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseContribution } ) ) );
  17662. 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 } ) ) );
  17663. }
  17664. /**
  17665. * This method is intended for implementing the direct light term for
  17666. * rect area light nodes.
  17667. *
  17668. * @param {Object} input - The input data.
  17669. * @param {NodeBuilder} builder - The current node builder.
  17670. */
  17671. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 }, /* builder */ ) {
  17672. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  17673. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  17674. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  17675. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  17676. const N = normalView;
  17677. const V = positionViewDirection;
  17678. const P = positionView.toVar();
  17679. const uv = LTC_Uv( { N, V, roughness } );
  17680. const t1 = ltc_1.sample( uv ).toVar();
  17681. const t2 = ltc_2.sample( uv ).toVar();
  17682. const mInv = mat3(
  17683. vec3( t1.x, 0, t1.y ),
  17684. vec3( 0, 1, 0 ),
  17685. vec3( t1.z, 0, t1.w )
  17686. ).toVar();
  17687. // LTC Fresnel Approximation by Stephen Hill
  17688. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  17689. const fresnel = specularColorBlended.mul( t2.x ).add( specularF90.sub( specularColorBlended ).mul( t2.y ) ).toVar();
  17690. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  17691. 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 } ) ) );
  17692. if ( this.clearcoat === true ) {
  17693. const Ncc = clearcoatNormalView;
  17694. const uvClearcoat = LTC_Uv( { N: Ncc, V, roughness: clearcoatRoughness } );
  17695. const t1Clearcoat = ltc_1.sample( uvClearcoat );
  17696. const t2Clearcoat = ltc_2.sample( uvClearcoat );
  17697. const mInvClearcoat = mat3(
  17698. vec3( t1Clearcoat.x, 0, t1Clearcoat.y ),
  17699. vec3( 0, 1, 0 ),
  17700. vec3( t1Clearcoat.z, 0, t1Clearcoat.w )
  17701. );
  17702. // LTC Fresnel Approximation for clearcoat
  17703. const fresnelClearcoat = clearcoatF0.mul( t2Clearcoat.x ).add( clearcoatF90.sub( clearcoatF0 ).mul( t2Clearcoat.y ) );
  17704. this.clearcoatSpecularDirect.addAssign( lightColor.mul( fresnelClearcoat ).mul( LTC_Evaluate( { N: Ncc, V, P, mInv: mInvClearcoat, p0, p1, p2, p3 } ) ) );
  17705. }
  17706. }
  17707. /**
  17708. * Implements the indirect lighting.
  17709. *
  17710. * @param {NodeBuilder} builder - The current node builder.
  17711. */
  17712. indirect( builder ) {
  17713. this.indirectDiffuse( builder );
  17714. this.indirectSpecular( builder );
  17715. this.ambientOcclusion( builder );
  17716. }
  17717. /**
  17718. * Implements the indirect diffuse term.
  17719. *
  17720. * @param {NodeBuilder} builder - The current node builder.
  17721. */
  17722. indirectDiffuse( builder ) {
  17723. const { irradiance, reflectedLight } = builder.context;
  17724. const diffuse = irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseContribution } ) ).toVar();
  17725. if ( this.sheen === true ) {
  17726. const sheenAlbedo = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17727. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedo ).oneMinus();
  17728. diffuse.mulAssign( sheenEnergyComp );
  17729. }
  17730. reflectedLight.indirectDiffuse.addAssign( diffuse );
  17731. }
  17732. /**
  17733. * Implements the indirect specular term.
  17734. *
  17735. * @param {NodeBuilder} builder - The current node builder.
  17736. */
  17737. indirectSpecular( builder ) {
  17738. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  17739. if ( this.sheen === true ) {
  17740. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  17741. sheen,
  17742. IBLSheenBRDF( {
  17743. normal: normalView,
  17744. viewDir: positionViewDirection,
  17745. roughness: sheenRoughness
  17746. } )
  17747. ) );
  17748. }
  17749. if ( this.clearcoat === true ) {
  17750. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17751. const clearcoatEnv = EnvironmentBRDF( {
  17752. dotNV: dotNVcc,
  17753. specularColor: clearcoatF0,
  17754. specularF90: clearcoatF90,
  17755. roughness: clearcoatRoughness
  17756. } );
  17757. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  17758. }
  17759. // Both indirect specular and indirect diffuse light accumulate here
  17760. // Compute multiscattering separately for dielectric and metallic, then mix
  17761. const singleScatteringDielectric = vec3().toVar( 'singleScatteringDielectric' );
  17762. const multiScatteringDielectric = vec3().toVar( 'multiScatteringDielectric' );
  17763. const singleScatteringMetallic = vec3().toVar( 'singleScatteringMetallic' );
  17764. const multiScatteringMetallic = vec3().toVar( 'multiScatteringMetallic' );
  17765. this.computeMultiscattering( singleScatteringDielectric, multiScatteringDielectric, specularF90, specularColor, this.iridescenceF0Dielectric );
  17766. this.computeMultiscattering( singleScatteringMetallic, multiScatteringMetallic, specularF90, diffuseColor.rgb, this.iridescenceF0Metallic );
  17767. // Mix based on metalness
  17768. const singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, metalness );
  17769. const multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, metalness );
  17770. // Diffuse energy conservation uses dielectric path
  17771. const totalScatteringDielectric = singleScatteringDielectric.add( multiScatteringDielectric );
  17772. const diffuse = diffuseContribution.mul( totalScatteringDielectric.oneMinus() );
  17773. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  17774. const indirectSpecular = radiance.mul( singleScattering ).add( multiScattering.mul( cosineWeightedIrradiance ) ).toVar();
  17775. const indirectDiffuse = diffuse.mul( cosineWeightedIrradiance ).toVar();
  17776. if ( this.sheen === true ) {
  17777. const sheenAlbedo = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17778. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedo ).oneMinus();
  17779. indirectSpecular.mulAssign( sheenEnergyComp );
  17780. indirectDiffuse.mulAssign( sheenEnergyComp );
  17781. }
  17782. reflectedLight.indirectSpecular.addAssign( indirectSpecular );
  17783. reflectedLight.indirectDiffuse.addAssign( indirectDiffuse );
  17784. }
  17785. /**
  17786. * Implements the ambient occlusion term.
  17787. *
  17788. * @param {NodeBuilder} builder - The current node builder.
  17789. */
  17790. ambientOcclusion( builder ) {
  17791. const { ambientOcclusion, reflectedLight } = builder.context;
  17792. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17793. const aoNV = dotNV.add( ambientOcclusion );
  17794. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  17795. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  17796. if ( this.clearcoat === true ) {
  17797. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  17798. }
  17799. if ( this.sheen === true ) {
  17800. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  17801. }
  17802. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  17803. reflectedLight.indirectSpecular.mulAssign( aoNode );
  17804. }
  17805. /**
  17806. * Used for final lighting accumulations depending on the requested features.
  17807. *
  17808. * @param {NodeBuilder} builder - The current node builder.
  17809. */
  17810. finish( { context } ) {
  17811. const { outgoingLight } = context;
  17812. if ( this.clearcoat === true ) {
  17813. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17814. const Fcc = F_Schlick( {
  17815. dotVH: dotNVcc,
  17816. f0: clearcoatF0,
  17817. f90: clearcoatF90
  17818. } );
  17819. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  17820. outgoingLight.assign( clearcoatLight );
  17821. }
  17822. if ( this.sheen === true ) {
  17823. const sheenLight = outgoingLight.add( this.sheenSpecularDirect, this.sheenSpecularIndirect.mul( 1.0 / Math.PI ) );
  17824. outgoingLight.assign( sheenLight );
  17825. }
  17826. }
  17827. }
  17828. // These defines must match with PMREMGenerator
  17829. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  17830. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  17831. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  17832. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  17833. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  17834. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  17835. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  17836. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  17837. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  17838. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  17839. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  17840. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  17841. // These shader functions convert between the UV coordinates of a single face of
  17842. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  17843. // sampling a textureCube (not generally normalized ).
  17844. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  17845. const absDirection = vec3( abs( direction ) ).toVar();
  17846. const face = float( -1 ).toVar();
  17847. If( absDirection.x.greaterThan( absDirection.z ), () => {
  17848. If( absDirection.x.greaterThan( absDirection.y ), () => {
  17849. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  17850. } ).Else( () => {
  17851. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17852. } );
  17853. } ).Else( () => {
  17854. If( absDirection.z.greaterThan( absDirection.y ), () => {
  17855. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  17856. } ).Else( () => {
  17857. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17858. } );
  17859. } );
  17860. return face;
  17861. } ).setLayout( {
  17862. name: 'getFace',
  17863. type: 'float',
  17864. inputs: [
  17865. { name: 'direction', type: 'vec3' }
  17866. ]
  17867. } );
  17868. // RH coordinate system; PMREM face-indexing convention
  17869. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  17870. const uv = vec2().toVar();
  17871. If( face.equal( 0.0 ), () => {
  17872. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  17873. } ).ElseIf( face.equal( 1.0 ), () => {
  17874. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  17875. } ).ElseIf( face.equal( 2.0 ), () => {
  17876. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  17877. } ).ElseIf( face.equal( 3.0 ), () => {
  17878. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  17879. } ).ElseIf( face.equal( 4.0 ), () => {
  17880. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  17881. } ).Else( () => {
  17882. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  17883. } );
  17884. return mul( 0.5, uv.add( 1.0 ) );
  17885. } ).setLayout( {
  17886. name: 'getUV',
  17887. type: 'vec2',
  17888. inputs: [
  17889. { name: 'direction', type: 'vec3' },
  17890. { name: 'face', type: 'float' }
  17891. ]
  17892. } );
  17893. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  17894. const mip = float( 0.0 ).toVar();
  17895. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  17896. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  17897. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  17898. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  17899. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  17900. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  17901. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  17902. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  17903. } ).Else( () => {
  17904. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  17905. } );
  17906. return mip;
  17907. } ).setLayout( {
  17908. name: 'roughnessToMip',
  17909. type: 'float',
  17910. inputs: [
  17911. { name: 'roughness', type: 'float' }
  17912. ]
  17913. } );
  17914. // RH coordinate system; PMREM face-indexing convention
  17915. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  17916. const uv = uv_immutable.toVar();
  17917. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  17918. const direction = vec3( uv, 1.0 ).toVar();
  17919. If( face.equal( 0.0 ), () => {
  17920. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  17921. } ).ElseIf( face.equal( 1.0 ), () => {
  17922. direction.assign( direction.xzy );
  17923. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  17924. } ).ElseIf( face.equal( 2.0 ), () => {
  17925. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  17926. } ).ElseIf( face.equal( 3.0 ), () => {
  17927. direction.assign( direction.zyx );
  17928. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  17929. } ).ElseIf( face.equal( 4.0 ), () => {
  17930. direction.assign( direction.xzy );
  17931. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  17932. } ).ElseIf( face.equal( 5.0 ), () => {
  17933. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  17934. } );
  17935. return direction;
  17936. } ).setLayout( {
  17937. name: 'getDirection',
  17938. type: 'vec3',
  17939. inputs: [
  17940. { name: 'uv', type: 'vec2' },
  17941. { name: 'face', type: 'float' }
  17942. ]
  17943. } );
  17944. //
  17945. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17946. const roughness = float( roughness_immutable );
  17947. const sampleDir = vec3( sampleDir_immutable );
  17948. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  17949. const mipF = fract( mip );
  17950. const mipInt = floor( mip );
  17951. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17952. If( mipF.notEqual( 0.0 ), () => {
  17953. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17954. color0.assign( mix( color0, color1, mipF ) );
  17955. } );
  17956. return color0;
  17957. } );
  17958. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17959. const mipInt = float( mipInt_immutable ).toVar();
  17960. const direction = vec3( direction_immutable );
  17961. const face = float( getFace( direction ) ).toVar();
  17962. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  17963. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  17964. const faceSize = float( exp2( mipInt ) ).toVar();
  17965. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  17966. If( face.greaterThan( 2.0 ), () => {
  17967. uv.y.addAssign( faceSize );
  17968. face.subAssign( 3.0 );
  17969. } );
  17970. uv.x.addAssign( face.mul( faceSize ) );
  17971. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  17972. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  17973. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  17974. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  17975. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  17976. } );
  17977. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17978. const cosTheta = cos( theta );
  17979. // Rodrigues' axis-angle rotation
  17980. const sampleDirection = outputDirection.mul( cosTheta )
  17981. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  17982. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  17983. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  17984. } );
  17985. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17986. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  17987. If( axis.equal( vec3( 0.0 ) ), () => {
  17988. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  17989. } );
  17990. axis.assign( normalize( axis ) );
  17991. const gl_FragColor = vec3().toVar();
  17992. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17993. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  17994. If( i.greaterThanEqual( samples ), () => {
  17995. Break();
  17996. } );
  17997. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  17998. 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 } ) ) );
  17999. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  18000. } );
  18001. return vec4( gl_FragColor, 1 );
  18002. } );
  18003. // GGX VNDF importance sampling functions
  18004. // Van der Corput radical inverse for generating quasi-random sequences
  18005. const radicalInverse_VdC = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  18006. const bits = uint( bits_immutable ).toVar();
  18007. bits.assign( bits.shiftLeft( uint( 16 ) ).bitOr( bits.shiftRight( uint( 16 ) ) ) );
  18008. bits.assign( bits.bitAnd( uint( 0x55555555 ) ).shiftLeft( uint( 1 ) ).bitOr( bits.bitAnd( uint( 0xAAAAAAAA ) ).shiftRight( uint( 1 ) ) ) );
  18009. bits.assign( bits.bitAnd( uint( 0x33333333 ) ).shiftLeft( uint( 2 ) ).bitOr( bits.bitAnd( uint( 0xCCCCCCCC ) ).shiftRight( uint( 2 ) ) ) );
  18010. bits.assign( bits.bitAnd( uint( 0x0F0F0F0F ) ).shiftLeft( uint( 4 ) ).bitOr( bits.bitAnd( uint( 0xF0F0F0F0 ) ).shiftRight( uint( 4 ) ) ) );
  18011. bits.assign( bits.bitAnd( uint( 0x00FF00FF ) ).shiftLeft( uint( 8 ) ).bitOr( bits.bitAnd( uint( 0xFF00FF00 ) ).shiftRight( uint( 8 ) ) ) );
  18012. return float( bits ).mul( 2.3283064365386963e-10 ); // / 0x100000000
  18013. } );
  18014. // Hammersley sequence for quasi-Monte Carlo sampling
  18015. const hammersley = /*@__PURE__*/ Fn( ( [ i, N ] ) => {
  18016. return vec2( float( i ).div( float( N ) ), radicalInverse_VdC( i ) );
  18017. } );
  18018. // GGX VNDF importance sampling (Eric Heitz 2018)
  18019. // "Sampling the GGX Distribution of Visible Normals"
  18020. // https://jcgt.org/published/0007/04/01/
  18021. const importanceSampleGGX_VNDF = /*@__PURE__*/ Fn( ( [ Xi, V, roughness ] ) => {
  18022. const alpha = roughness.mul( roughness ).toConst();
  18023. // Section 4.1: Orthonormal basis
  18024. const T1 = vec3( 1.0, 0.0, 0.0 ).toConst();
  18025. const T2 = cross( V, T1 ).toConst();
  18026. // Section 4.2: Parameterization of projected area
  18027. const r = sqrt( Xi.x ).toConst();
  18028. const phi = mul( 2.0, 3.14159265359 ).mul( Xi.y ).toConst();
  18029. const t1 = r.mul( cos( phi ) ).toConst();
  18030. const t2 = r.mul( sin( phi ) ).toVar();
  18031. const s = mul( 0.5, V.z.add( 1.0 ) ).toConst();
  18032. t2.assign( s.oneMinus().mul( sqrt( t1.mul( t1 ).oneMinus() ) ).add( s.mul( t2 ) ) );
  18033. // Section 4.3: Reprojection onto hemisphere
  18034. 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() ) ) ) );
  18035. // Section 3.4: Transform back to ellipsoid configuration
  18036. return normalize( vec3( alpha.mul( Nh.x ), alpha.mul( Nh.y ), max$1( 0.0, Nh.z ) ) );
  18037. } );
  18038. // GGX convolution using VNDF importance sampling
  18039. const ggxConvolution = /*@__PURE__*/ Fn( ( { roughness, mipInt, envMap, N_immutable, GGX_SAMPLES, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  18040. const N = vec3( N_immutable ).toVar();
  18041. const prefilteredColor = vec3( 0.0 ).toVar();
  18042. const totalWeight = float( 0.0 ).toVar();
  18043. // For very low roughness, just sample the environment directly
  18044. If( roughness.lessThan( 0.001 ), () => {
  18045. prefilteredColor.assign( bilinearCubeUV( envMap, N, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) );
  18046. } ).Else( () => {
  18047. // Tangent space basis for VNDF sampling
  18048. const up = select( abs( N.z ).lessThan( 0.999 ), vec3( 0.0, 0.0, 1.0 ), vec3( 1.0, 0.0, 0.0 ) );
  18049. const tangent = normalize( cross( up, N ) ).toVar();
  18050. const bitangent = cross( N, tangent ).toVar();
  18051. Loop( { start: uint( 0 ), end: GGX_SAMPLES }, ( { i } ) => {
  18052. const Xi = hammersley( i, GGX_SAMPLES );
  18053. // For PMREM, V = N, so in tangent space V is always (0, 0, 1)
  18054. const H_tangent = importanceSampleGGX_VNDF( Xi, vec3( 0.0, 0.0, 1.0 ), roughness );
  18055. // Transform H back to world space
  18056. const H = normalize( tangent.mul( H_tangent.x ).add( bitangent.mul( H_tangent.y ) ).add( N.mul( H_tangent.z ) ) );
  18057. const L = normalize( H.mul( dot( N, H ).mul( 2.0 ) ).sub( N ) );
  18058. const NdotL = max$1( dot( N, L ), 0.0 );
  18059. If( NdotL.greaterThan( 0.0 ), () => {
  18060. // Sample environment at fixed mip level
  18061. // VNDF importance sampling handles the distribution filtering
  18062. const sampleColor = bilinearCubeUV( envMap, L, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  18063. // Weight by NdotL for the split-sum approximation
  18064. // VNDF PDF naturally accounts for the visible microfacet distribution
  18065. prefilteredColor.addAssign( sampleColor.mul( NdotL ) );
  18066. totalWeight.addAssign( NdotL );
  18067. } );
  18068. } );
  18069. If( totalWeight.greaterThan( 0.0 ), () => {
  18070. prefilteredColor.assign( prefilteredColor.div( totalWeight ) );
  18071. } );
  18072. } );
  18073. return vec4( prefilteredColor, 1.0 );
  18074. } );
  18075. const LOD_MIN = 4;
  18076. // The standard deviations (radians) associated with the extra mips.
  18077. // Used for scene blur in fromScene() method.
  18078. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  18079. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  18080. // samples and exit early, but not recompile the shader.
  18081. // Used for scene blur in fromScene() method.
  18082. const MAX_SAMPLES = 20;
  18083. // GGX VNDF importance sampling configuration
  18084. const GGX_SAMPLES = 512;
  18085. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  18086. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  18087. const _clearColor$2 = /*@__PURE__*/ new Color();
  18088. let _oldTarget = null;
  18089. let _oldActiveCubeFace = 0;
  18090. let _oldActiveMipmapLevel = 0;
  18091. const _origin = /*@__PURE__*/ new Vector3();
  18092. // maps blur materials to their uniforms dictionary
  18093. const _uniformsMap = new WeakMap();
  18094. // WebGPU Face indices
  18095. const _faceLib = [
  18096. 3, 1, 5,
  18097. 0, 4, 2
  18098. ];
  18099. const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize();
  18100. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  18101. /**
  18102. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  18103. * (PMREM) from a cubeMap environment texture. This allows different levels of
  18104. * blur to be quickly accessed based on material roughness. It is packed into a
  18105. * special CubeUV format that allows us to perform custom interpolation so that
  18106. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  18107. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  18108. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  18109. * higher roughness levels. In this way we maintain resolution to smoothly
  18110. * interpolate diffuse lighting while limiting sampling computation.
  18111. *
  18112. * The prefiltering uses GGX VNDF (Visible Normal Distribution Function)
  18113. * importance sampling based on "Sampling the GGX Distribution of Visible Normals"
  18114. * (Heitz, 2018) to generate environment maps that accurately match the GGX BRDF
  18115. * used in material rendering for physically-based image-based lighting.
  18116. */
  18117. class PMREMGenerator {
  18118. /**
  18119. * Constructs a new PMREM generator.
  18120. *
  18121. * @param {Renderer} renderer - The renderer.
  18122. */
  18123. constructor( renderer ) {
  18124. this._renderer = renderer;
  18125. this._pingPongRenderTarget = null;
  18126. this._lodMax = 0;
  18127. this._cubeSize = 0;
  18128. this._sizeLods = [];
  18129. this._sigmas = [];
  18130. this._lodMeshes = [];
  18131. this._blurMaterial = null;
  18132. this._ggxMaterial = null;
  18133. this._cubemapMaterial = null;
  18134. this._equirectMaterial = null;
  18135. this._backgroundBox = null;
  18136. }
  18137. get _hasInitialized() {
  18138. return this._renderer.hasInitialized();
  18139. }
  18140. /**
  18141. * Generates a PMREM from a supplied Scene, which can be faster than using an
  18142. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  18143. * in radians to be applied to the scene before PMREM generation. Optional near
  18144. * and far planes ensure the scene is rendered in its entirety.
  18145. *
  18146. * @param {Scene} scene - The scene to be captured.
  18147. * @param {number} [sigma=0] - The blur radius in radians.
  18148. * @param {number} [near=0.1] - The near plane distance.
  18149. * @param {number} [far=100] - The far plane distance.
  18150. * @param {Object} [options={}] - The configuration options.
  18151. * @param {number} [options.size=256] - The texture size of the PMREM.
  18152. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  18153. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  18154. * @return {RenderTarget} The resulting PMREM.
  18155. * @see {@link PMREMGenerator#fromScene}
  18156. */
  18157. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  18158. const {
  18159. size = 256,
  18160. position = _origin,
  18161. renderTarget = null,
  18162. } = options;
  18163. this._setSize( size );
  18164. if ( this._hasInitialized === false ) {
  18165. warn( 'PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.' );
  18166. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  18167. options.renderTarget = cubeUVRenderTarget;
  18168. this.fromSceneAsync( scene, sigma, near, far, options );
  18169. return cubeUVRenderTarget;
  18170. }
  18171. _oldTarget = this._renderer.getRenderTarget();
  18172. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  18173. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  18174. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  18175. cubeUVRenderTarget.depthBuffer = true;
  18176. this._init( cubeUVRenderTarget );
  18177. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  18178. if ( sigma > 0 ) {
  18179. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  18180. }
  18181. this._applyPMREM( cubeUVRenderTarget );
  18182. this._cleanup( cubeUVRenderTarget );
  18183. return cubeUVRenderTarget;
  18184. }
  18185. /**
  18186. * Generates a PMREM from a supplied Scene, which can be faster than using an
  18187. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  18188. * in radians to be applied to the scene before PMREM generation. Optional near
  18189. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  18190. * is placed at the origin).
  18191. *
  18192. * @deprecated
  18193. * @param {Scene} scene - The scene to be captured.
  18194. * @param {number} [sigma=0] - The blur radius in radians.
  18195. * @param {number} [near=0.1] - The near plane distance.
  18196. * @param {number} [far=100] - The far plane distance.
  18197. * @param {Object} [options={}] - The configuration options.
  18198. * @param {number} [options.size=256] - The texture size of the PMREM.
  18199. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  18200. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  18201. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  18202. * @see {@link PMREMGenerator#fromScene}
  18203. */
  18204. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  18205. warnOnce( 'PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  18206. await this._renderer.init();
  18207. return this.fromScene( scene, sigma, near, far, options );
  18208. }
  18209. /**
  18210. * Generates a PMREM from an equirectangular texture, which can be either LDR
  18211. * or HDR. The ideal input image size is 1k (1024 x 512), as this matches best
  18212. * with the 256 x 256 cubemap output. The minimum supported input image size
  18213. * is 64 x 32.
  18214. *
  18215. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  18216. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  18217. * @return {RenderTarget} The resulting PMREM.
  18218. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  18219. */
  18220. fromEquirectangular( equirectangular, renderTarget = null ) {
  18221. if ( this._hasInitialized === false ) {
  18222. warn( 'PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" instead.' );
  18223. this._setSizeFromTexture( equirectangular );
  18224. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  18225. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  18226. return cubeUVRenderTarget;
  18227. }
  18228. return this._fromTexture( equirectangular, renderTarget );
  18229. }
  18230. /**
  18231. * Generates a PMREM from an equirectangular texture, which can be either LDR
  18232. * or HDR. The ideal input image size is 1k (1024 x 512),
  18233. * as this matches best with the 256 x 256 cubemap output.
  18234. *
  18235. * @deprecated
  18236. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  18237. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  18238. * @return {Promise<RenderTarget>} The resulting PMREM.
  18239. * @see {@link PMREMGenerator#fromEquirectangular}
  18240. */
  18241. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  18242. warnOnce( 'PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  18243. await this._renderer.init();
  18244. return this._fromTexture( equirectangular, renderTarget );
  18245. }
  18246. /**
  18247. * Generates a PMREM from an cubemap texture, which can be either LDR
  18248. * or HDR. The ideal input cube size is 256 x 256, as this matches best
  18249. * with the 256 x 256 cubemap output. The minimum supported input cube
  18250. * size is 16 x 16 per face.
  18251. *
  18252. * @param {Texture} cubemap - The cubemap texture to be converted.
  18253. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  18254. * @return {RenderTarget} The resulting PMREM.
  18255. * @see {@link PMREMGenerator#fromCubemapAsync}
  18256. */
  18257. fromCubemap( cubemap, renderTarget = null ) {
  18258. if ( this._hasInitialized === false ) {
  18259. warn( 'PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  18260. this._setSizeFromTexture( cubemap );
  18261. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  18262. this.fromCubemapAsync( cubemap, renderTarget );
  18263. return cubeUVRenderTarget;
  18264. }
  18265. return this._fromTexture( cubemap, renderTarget );
  18266. }
  18267. /**
  18268. * Generates a PMREM from an cubemap texture, which can be either LDR
  18269. * or HDR. The ideal input cube size is 256 x 256,
  18270. * with the 256 x 256 cubemap output.
  18271. *
  18272. * @deprecated
  18273. * @param {Texture} cubemap - The cubemap texture to be converted.
  18274. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  18275. * @return {Promise<RenderTarget>} The resulting PMREM.
  18276. * @see {@link PMREMGenerator#fromCubemap}
  18277. */
  18278. async fromCubemapAsync( cubemap, renderTarget = null ) {
  18279. warnOnce( 'PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  18280. await this._renderer.init();
  18281. return this._fromTexture( cubemap, renderTarget );
  18282. }
  18283. /**
  18284. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  18285. * your texture's network fetch for increased concurrency.
  18286. *
  18287. * @returns {Promise}
  18288. */
  18289. async compileCubemapShader() {
  18290. if ( this._cubemapMaterial === null ) {
  18291. this._cubemapMaterial = _getCubemapMaterial();
  18292. await this._compileMaterial( this._cubemapMaterial );
  18293. }
  18294. }
  18295. /**
  18296. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  18297. * your texture's network fetch for increased concurrency.
  18298. *
  18299. * @returns {Promise}
  18300. */
  18301. async compileEquirectangularShader() {
  18302. if ( this._equirectMaterial === null ) {
  18303. this._equirectMaterial = _getEquirectMaterial();
  18304. await this._compileMaterial( this._equirectMaterial );
  18305. }
  18306. }
  18307. /**
  18308. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  18309. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  18310. * one of them will cause any others to also become unusable.
  18311. */
  18312. dispose() {
  18313. this._dispose();
  18314. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  18315. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  18316. if ( this._backgroundBox !== null ) {
  18317. this._backgroundBox.geometry.dispose();
  18318. this._backgroundBox.material.dispose();
  18319. }
  18320. }
  18321. // private interface
  18322. _setSizeFromTexture( texture ) {
  18323. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  18324. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  18325. } else { // Equirectangular
  18326. this._setSize( texture.image.width / 4 );
  18327. }
  18328. }
  18329. _setSize( cubeSize ) {
  18330. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  18331. this._cubeSize = Math.pow( 2, this._lodMax );
  18332. }
  18333. _dispose() {
  18334. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  18335. if ( this._ggxMaterial !== null ) this._ggxMaterial.dispose();
  18336. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  18337. for ( let i = 0; i < this._lodMeshes.length; i ++ ) {
  18338. this._lodMeshes[ i ].geometry.dispose();
  18339. }
  18340. }
  18341. _cleanup( outputTarget ) {
  18342. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  18343. outputTarget.scissorTest = false;
  18344. this._setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  18345. }
  18346. _fromTexture( texture, renderTarget ) {
  18347. this._setSizeFromTexture( texture );
  18348. _oldTarget = this._renderer.getRenderTarget();
  18349. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  18350. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  18351. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  18352. this._init( cubeUVRenderTarget );
  18353. this._textureToCubeUV( texture, cubeUVRenderTarget );
  18354. this._applyPMREM( cubeUVRenderTarget );
  18355. this._cleanup( cubeUVRenderTarget );
  18356. return cubeUVRenderTarget;
  18357. }
  18358. _allocateTarget() {
  18359. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  18360. const height = 4 * this._cubeSize;
  18361. const cubeUVRenderTarget = _createRenderTarget( width, height );
  18362. return cubeUVRenderTarget;
  18363. }
  18364. _init( renderTarget ) {
  18365. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  18366. if ( this._pingPongRenderTarget !== null ) {
  18367. this._dispose();
  18368. }
  18369. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  18370. const { _lodMax } = this;
  18371. ( { lodMeshes: this._lodMeshes, sizeLods: this._sizeLods, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  18372. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  18373. this._ggxMaterial = _getGGXShader( _lodMax, renderTarget.width, renderTarget.height );
  18374. }
  18375. }
  18376. async _compileMaterial( material ) {
  18377. const mesh = new Mesh( new BufferGeometry(), material );
  18378. await this._renderer.compile( mesh, _flatCamera );
  18379. }
  18380. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  18381. const cubeCamera = _cubeCamera;
  18382. cubeCamera.near = near;
  18383. cubeCamera.far = far;
  18384. // px, py, pz, nx, ny, nz
  18385. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  18386. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  18387. const renderer = this._renderer;
  18388. const originalAutoClear = renderer.autoClear;
  18389. renderer.getClearColor( _clearColor$2 );
  18390. renderer.autoClear = false;
  18391. if ( this._backgroundBox === null ) {
  18392. this._backgroundBox = new Mesh(
  18393. new BoxGeometry(),
  18394. new MeshBasicMaterial( {
  18395. name: 'PMREM.Background',
  18396. side: BackSide,
  18397. depthWrite: false,
  18398. depthTest: false,
  18399. } )
  18400. );
  18401. }
  18402. const backgroundBox = this._backgroundBox;
  18403. const backgroundMaterial = backgroundBox.material;
  18404. let useSolidColor = false;
  18405. const background = scene.background;
  18406. if ( background ) {
  18407. if ( background.isColor ) {
  18408. backgroundMaterial.color.copy( background );
  18409. scene.background = null;
  18410. useSolidColor = true;
  18411. }
  18412. } else {
  18413. backgroundMaterial.color.copy( _clearColor$2 );
  18414. useSolidColor = true;
  18415. }
  18416. renderer.setRenderTarget( cubeUVRenderTarget );
  18417. renderer.clear();
  18418. if ( useSolidColor ) {
  18419. renderer.render( backgroundBox, cubeCamera );
  18420. }
  18421. for ( let i = 0; i < 6; i ++ ) {
  18422. const col = i % 3;
  18423. if ( col === 0 ) {
  18424. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18425. cubeCamera.position.set( position.x, position.y, position.z );
  18426. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  18427. } else if ( col === 1 ) {
  18428. cubeCamera.up.set( 0, 0, upSign[ i ] );
  18429. cubeCamera.position.set( position.x, position.y, position.z );
  18430. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  18431. } else {
  18432. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18433. cubeCamera.position.set( position.x, position.y, position.z );
  18434. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  18435. }
  18436. const size = this._cubeSize;
  18437. this._setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  18438. renderer.render( scene, cubeCamera );
  18439. }
  18440. renderer.autoClear = originalAutoClear;
  18441. scene.background = background;
  18442. }
  18443. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  18444. const renderer = this._renderer;
  18445. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  18446. if ( isCubeTexture ) {
  18447. if ( this._cubemapMaterial === null ) {
  18448. this._cubemapMaterial = _getCubemapMaterial( texture );
  18449. }
  18450. } else {
  18451. if ( this._equirectMaterial === null ) {
  18452. this._equirectMaterial = _getEquirectMaterial( texture );
  18453. }
  18454. }
  18455. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  18456. material.fragmentNode.value = texture;
  18457. const mesh = this._lodMeshes[ 0 ];
  18458. mesh.material = material;
  18459. const size = this._cubeSize;
  18460. this._setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  18461. renderer.setRenderTarget( cubeUVRenderTarget );
  18462. renderer.render( mesh, _flatCamera );
  18463. }
  18464. _applyPMREM( cubeUVRenderTarget ) {
  18465. const renderer = this._renderer;
  18466. const autoClear = renderer.autoClear;
  18467. renderer.autoClear = false;
  18468. const n = this._lodMeshes.length;
  18469. // Use GGX VNDF importance sampling
  18470. for ( let i = 1; i < n; i ++ ) {
  18471. this._applyGGXFilter( cubeUVRenderTarget, i - 1, i );
  18472. }
  18473. renderer.autoClear = autoClear;
  18474. }
  18475. /**
  18476. * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map.
  18477. * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the
  18478. * GGX BRDF for physically-based rendering. Reads from the previous LOD level and
  18479. * applies incremental roughness filtering to avoid over-blurring.
  18480. *
  18481. * @private
  18482. * @param {RenderTarget} cubeUVRenderTarget
  18483. * @param {number} lodIn - Source LOD level to read from
  18484. * @param {number} lodOut - Target LOD level to write to
  18485. */
  18486. _applyGGXFilter( cubeUVRenderTarget, lodIn, lodOut ) {
  18487. const renderer = this._renderer;
  18488. const pingPongRenderTarget = this._pingPongRenderTarget;
  18489. const ggxMaterial = this._ggxMaterial;
  18490. const ggxMesh = this._lodMeshes[ lodOut ];
  18491. ggxMesh.material = ggxMaterial;
  18492. const ggxUniforms = _uniformsMap.get( ggxMaterial );
  18493. // Calculate incremental roughness between LOD levels
  18494. const targetRoughness = lodOut / ( this._lodMeshes.length - 1 );
  18495. const sourceRoughness = lodIn / ( this._lodMeshes.length - 1 );
  18496. const incrementalRoughness = Math.sqrt( targetRoughness * targetRoughness - sourceRoughness * sourceRoughness );
  18497. // Apply blur strength mapping for better quality across the roughness range
  18498. const blurStrength = 0.0 + targetRoughness * 1.25;
  18499. const adjustedRoughness = incrementalRoughness * blurStrength;
  18500. // Calculate viewport position based on output LOD level
  18501. const { _lodMax } = this;
  18502. const outputSize = this._sizeLods[ lodOut ];
  18503. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  18504. const y = 4 * ( this._cubeSize - outputSize );
  18505. // Read from previous LOD with incremental roughness
  18506. cubeUVRenderTarget.texture.frame = ( cubeUVRenderTarget.texture.frame || 0 ) + 1;
  18507. ggxUniforms.envMap.value = cubeUVRenderTarget.texture;
  18508. ggxUniforms.roughness.value = adjustedRoughness;
  18509. ggxUniforms.mipInt.value = _lodMax - lodIn; // Sample from input LOD
  18510. this._setViewport( pingPongRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  18511. renderer.setRenderTarget( pingPongRenderTarget );
  18512. renderer.render( ggxMesh, _flatCamera );
  18513. // Copy from pingPong back to cubeUV (simple direct copy)
  18514. pingPongRenderTarget.texture.frame = ( pingPongRenderTarget.texture.frame || 0 ) + 1;
  18515. ggxUniforms.envMap.value = pingPongRenderTarget.texture;
  18516. ggxUniforms.roughness.value = 0.0; // Direct copy
  18517. ggxUniforms.mipInt.value = _lodMax - lodOut; // Read from the level we just wrote
  18518. this._setViewport( cubeUVRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  18519. renderer.setRenderTarget( cubeUVRenderTarget );
  18520. renderer.render( ggxMesh, _flatCamera );
  18521. }
  18522. /**
  18523. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  18524. * vertically and horizontally, but this breaks down on a cube. Here we apply
  18525. * the blur latitudinally (around the poles), and then longitudinally (towards
  18526. * the poles) to approximate the orthogonally-separable blur. It is least
  18527. * accurate at the poles, but still does a decent job.
  18528. *
  18529. * Used for initial scene blur in fromScene() method when sigma > 0.
  18530. *
  18531. * @private
  18532. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  18533. * @param {number} lodIn - The input level-of-detail.
  18534. * @param {number} lodOut - The output level-of-detail.
  18535. * @param {number} sigma - The blur radius in radians.
  18536. * @param {Vector3} [poleAxis] - The pole axis.
  18537. */
  18538. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  18539. const pingPongRenderTarget = this._pingPongRenderTarget;
  18540. this._halfBlur(
  18541. cubeUVRenderTarget,
  18542. pingPongRenderTarget,
  18543. lodIn,
  18544. lodOut,
  18545. sigma,
  18546. 'latitudinal',
  18547. poleAxis );
  18548. this._halfBlur(
  18549. pingPongRenderTarget,
  18550. cubeUVRenderTarget,
  18551. lodOut,
  18552. lodOut,
  18553. sigma,
  18554. 'longitudinal',
  18555. poleAxis );
  18556. }
  18557. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  18558. const renderer = this._renderer;
  18559. const blurMaterial = this._blurMaterial;
  18560. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  18561. error( 'blur direction must be either latitudinal or longitudinal!' );
  18562. }
  18563. // Number of standard deviations at which to cut off the discrete approximation.
  18564. const STANDARD_DEVIATIONS = 3;
  18565. const blurMesh = this._lodMeshes[ lodOut ];
  18566. blurMesh.material = blurMaterial;
  18567. const blurUniforms = _uniformsMap.get( blurMaterial );
  18568. const pixels = this._sizeLods[ lodIn ] - 1;
  18569. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  18570. const sigmaPixels = sigmaRadians / radiansPerPixel;
  18571. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  18572. if ( samples > MAX_SAMPLES ) {
  18573. warn( `sigmaRadians, ${
  18574. sigmaRadians}, is too large and will clip, as it requested ${
  18575. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  18576. }
  18577. const weights = [];
  18578. let sum = 0;
  18579. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  18580. const x = i / sigmaPixels;
  18581. const weight = Math.exp( - x * x / 2 );
  18582. weights.push( weight );
  18583. if ( i === 0 ) {
  18584. sum += weight;
  18585. } else if ( i < samples ) {
  18586. sum += 2 * weight;
  18587. }
  18588. }
  18589. for ( let i = 0; i < weights.length; i ++ ) {
  18590. weights[ i ] = weights[ i ] / sum;
  18591. }
  18592. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  18593. blurUniforms.envMap.value = targetIn.texture;
  18594. blurUniforms.samples.value = samples;
  18595. blurUniforms.weights.array = weights;
  18596. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  18597. if ( poleAxis ) {
  18598. blurUniforms.poleAxis.value = poleAxis;
  18599. }
  18600. const { _lodMax } = this;
  18601. blurUniforms.dTheta.value = radiansPerPixel;
  18602. blurUniforms.mipInt.value = _lodMax - lodIn;
  18603. const outputSize = this._sizeLods[ lodOut ];
  18604. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  18605. const y = 4 * ( this._cubeSize - outputSize );
  18606. this._setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  18607. renderer.setRenderTarget( targetOut );
  18608. renderer.render( blurMesh, _flatCamera );
  18609. }
  18610. _setViewport( target, x, y, width, height ) {
  18611. if ( this._renderer.isWebGLRenderer ) {
  18612. target.viewport.set( x, target.height - height - y, width, height );
  18613. target.scissor.set( x, target.height - height - y, width, height );
  18614. } else {
  18615. target.viewport.set( x, y, width, height );
  18616. target.scissor.set( x, y, width, height );
  18617. }
  18618. }
  18619. }
  18620. function _createPlanes( lodMax ) {
  18621. const sizeLods = [];
  18622. const sigmas = [];
  18623. const lodMeshes = [];
  18624. let lod = lodMax;
  18625. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  18626. for ( let i = 0; i < totalLods; i ++ ) {
  18627. const sizeLod = Math.pow( 2, lod );
  18628. sizeLods.push( sizeLod );
  18629. let sigma = 1.0 / sizeLod;
  18630. if ( i > lodMax - LOD_MIN ) {
  18631. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  18632. } else if ( i === 0 ) {
  18633. sigma = 0;
  18634. }
  18635. sigmas.push( sigma );
  18636. const texelSize = 1.0 / ( sizeLod - 2 );
  18637. const min = - texelSize;
  18638. const max = 1 + texelSize;
  18639. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  18640. const cubeFaces = 6;
  18641. const vertices = 6;
  18642. const positionSize = 3;
  18643. const uvSize = 2;
  18644. const faceIndexSize = 1;
  18645. const position = new Float32Array( positionSize * vertices * cubeFaces );
  18646. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  18647. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  18648. for ( let face = 0; face < cubeFaces; face ++ ) {
  18649. const x = ( face % 3 ) * 2 / 3 - 1;
  18650. const y = face > 2 ? 0 : -1;
  18651. const coordinates = [
  18652. x, y, 0,
  18653. x + 2 / 3, y, 0,
  18654. x + 2 / 3, y + 1, 0,
  18655. x, y, 0,
  18656. x + 2 / 3, y + 1, 0,
  18657. x, y + 1, 0
  18658. ];
  18659. const faceIdx = _faceLib[ face ];
  18660. position.set( coordinates, positionSize * vertices * faceIdx );
  18661. uv.set( uv1, uvSize * vertices * faceIdx );
  18662. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  18663. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  18664. }
  18665. const planes = new BufferGeometry();
  18666. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  18667. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  18668. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  18669. lodMeshes.push( new Mesh( planes, null ) );
  18670. if ( lod > LOD_MIN ) {
  18671. lod --;
  18672. }
  18673. }
  18674. return { lodMeshes, sizeLods, sigmas };
  18675. }
  18676. function _createRenderTarget( width, height ) {
  18677. const params = {
  18678. magFilter: LinearFilter,
  18679. minFilter: LinearFilter,
  18680. generateMipmaps: false,
  18681. type: HalfFloatType,
  18682. format: RGBAFormat,
  18683. colorSpace: LinearSRGBColorSpace,
  18684. //depthBuffer: false
  18685. };
  18686. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  18687. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  18688. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  18689. cubeUVRenderTarget.texture.isPMREMTexture = true;
  18690. cubeUVRenderTarget.scissorTest = true;
  18691. return cubeUVRenderTarget;
  18692. }
  18693. function _getMaterial( type ) {
  18694. const material = new NodeMaterial();
  18695. material.depthTest = false;
  18696. material.depthWrite = false;
  18697. material.blending = NoBlending;
  18698. material.name = `PMREM_${ type }`;
  18699. return material;
  18700. }
  18701. function _getBlurShader( lodMax, width, height ) {
  18702. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  18703. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  18704. const dTheta = uniform( 0 );
  18705. const n = float( MAX_SAMPLES );
  18706. const latitudinal = uniform( 0 ); // false, bool
  18707. const samples = uniform( 1 ); // int
  18708. const envMap = texture();
  18709. const mipInt = uniform( 0 ); // int
  18710. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18711. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18712. const CUBEUV_MAX_MIP = float( lodMax );
  18713. const materialUniforms = {
  18714. n,
  18715. latitudinal,
  18716. weights,
  18717. poleAxis,
  18718. outputDirection: _outputDirection,
  18719. dTheta,
  18720. samples,
  18721. envMap,
  18722. mipInt,
  18723. CUBEUV_TEXEL_WIDTH,
  18724. CUBEUV_TEXEL_HEIGHT,
  18725. CUBEUV_MAX_MIP
  18726. };
  18727. const material = _getMaterial( 'blur' );
  18728. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  18729. _uniformsMap.set( material, materialUniforms );
  18730. return material;
  18731. }
  18732. function _getGGXShader( lodMax, width, height ) {
  18733. const envMap = texture();
  18734. const roughness = uniform( 0 );
  18735. const mipInt = uniform( 0 );
  18736. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18737. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18738. const CUBEUV_MAX_MIP = float( lodMax );
  18739. const materialUniforms = {
  18740. envMap,
  18741. roughness,
  18742. mipInt,
  18743. CUBEUV_TEXEL_WIDTH,
  18744. CUBEUV_TEXEL_HEIGHT,
  18745. CUBEUV_MAX_MIP
  18746. };
  18747. const material = _getMaterial( 'ggx' );
  18748. material.fragmentNode = ggxConvolution( {
  18749. ...materialUniforms,
  18750. N_immutable: _outputDirection,
  18751. GGX_SAMPLES: uint( GGX_SAMPLES )
  18752. } );
  18753. _uniformsMap.set( material, materialUniforms );
  18754. return material;
  18755. }
  18756. function _getCubemapMaterial( envTexture ) {
  18757. const material = _getMaterial( 'cubemap' );
  18758. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  18759. return material;
  18760. }
  18761. function _getEquirectMaterial( envTexture ) {
  18762. const material = _getMaterial( 'equirect' );
  18763. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  18764. return material;
  18765. }
  18766. const _cache = new WeakMap();
  18767. /**
  18768. * Generates the cubeUV size based on the given image height.
  18769. *
  18770. * @private
  18771. * @param {number} imageHeight - The image height.
  18772. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  18773. */
  18774. function _generateCubeUVSize( imageHeight ) {
  18775. const maxMip = Math.log2( imageHeight ) - 2;
  18776. const texelHeight = 1.0 / imageHeight;
  18777. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  18778. return { texelWidth, texelHeight, maxMip };
  18779. }
  18780. /**
  18781. * Generates a PMREM from the given texture.
  18782. *
  18783. * @private
  18784. * @param {Texture} texture - The texture to create the PMREM for.
  18785. * @param {Renderer} renderer - The renderer.
  18786. * @param {PMREMGenerator} generator - The PMREM generator.
  18787. * @return {?Texture} The PMREM.
  18788. */
  18789. function _getPMREMFromTexture( texture, renderer, generator ) {
  18790. const cache = _getCache( renderer );
  18791. let cacheTexture = cache.get( texture );
  18792. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  18793. if ( pmremVersion !== texture.pmremVersion ) {
  18794. const image = texture.image;
  18795. if ( texture.isCubeTexture ) {
  18796. if ( isCubeMapReady( image ) ) {
  18797. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  18798. } else {
  18799. return null;
  18800. }
  18801. } else {
  18802. if ( isEquirectangularMapReady( image ) ) {
  18803. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  18804. } else {
  18805. return null;
  18806. }
  18807. }
  18808. cacheTexture.pmremVersion = texture.pmremVersion;
  18809. cache.set( texture, cacheTexture );
  18810. }
  18811. return cacheTexture.texture;
  18812. }
  18813. /**
  18814. * Returns a cache that stores generated PMREMs for the respective textures.
  18815. * A cache must be maintained per renderer since PMREMs are render target textures
  18816. * which can't be shared across render contexts.
  18817. *
  18818. * @private
  18819. * @param {Renderer} renderer - The renderer.
  18820. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  18821. */
  18822. function _getCache( renderer ) {
  18823. let rendererCache = _cache.get( renderer );
  18824. if ( rendererCache === undefined ) {
  18825. rendererCache = new WeakMap();
  18826. _cache.set( renderer, rendererCache );
  18827. }
  18828. return rendererCache;
  18829. }
  18830. /**
  18831. * This node represents a PMREM which is a special type of preprocessed
  18832. * environment map intended for PBR materials.
  18833. *
  18834. * ```js
  18835. * const material = new MeshStandardNodeMaterial();
  18836. * material.envNode = pmremTexture( envMap );
  18837. * ```
  18838. *
  18839. * @augments TempNode
  18840. */
  18841. class PMREMNode extends TempNode {
  18842. static get type() {
  18843. return 'PMREMNode';
  18844. }
  18845. /**
  18846. * Constructs a new function overloading node.
  18847. *
  18848. * @param {Texture} value - The input texture.
  18849. * @param {Node<vec2>} [uvNode=null] - The uv node.
  18850. * @param {Node<float>} [levelNode=null] - The level node.
  18851. */
  18852. constructor( value, uvNode = null, levelNode = null ) {
  18853. super( 'vec3' );
  18854. /**
  18855. * Reference to the input texture.
  18856. *
  18857. * @private
  18858. * @type {Texture}
  18859. */
  18860. this._value = value;
  18861. /**
  18862. * Reference to the generated PMREM.
  18863. *
  18864. * @private
  18865. * @type {Texture | null}
  18866. * @default null
  18867. */
  18868. this._pmrem = null;
  18869. /**
  18870. * The uv node.
  18871. *
  18872. * @type {Node<vec2>}
  18873. */
  18874. this.uvNode = uvNode;
  18875. /**
  18876. * The level node.
  18877. *
  18878. * @type {Node<float>}
  18879. */
  18880. this.levelNode = levelNode;
  18881. /**
  18882. * Reference to a PMREM generator.
  18883. *
  18884. * @private
  18885. * @type {?PMREMGenerator}
  18886. * @default null
  18887. */
  18888. this._generator = null;
  18889. const defaultTexture = new Texture();
  18890. defaultTexture.isRenderTargetTexture = true;
  18891. /**
  18892. * The texture node holding the generated PMREM.
  18893. *
  18894. * @private
  18895. * @type {TextureNode}
  18896. */
  18897. this._texture = texture( defaultTexture );
  18898. /**
  18899. * A uniform representing the PMREM's width.
  18900. *
  18901. * @private
  18902. * @type {UniformNode<float>}
  18903. */
  18904. this._width = uniform( 0 );
  18905. /**
  18906. * A uniform representing the PMREM's height.
  18907. *
  18908. * @private
  18909. * @type {UniformNode<float>}
  18910. */
  18911. this._height = uniform( 0 );
  18912. /**
  18913. * A uniform representing the PMREM's max Mip.
  18914. *
  18915. * @private
  18916. * @type {UniformNode<float>}
  18917. */
  18918. this._maxMip = uniform( 0 );
  18919. /**
  18920. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  18921. *
  18922. * @type {string}
  18923. * @default 'render'
  18924. */
  18925. this.updateBeforeType = NodeUpdateType.RENDER;
  18926. }
  18927. set value( value ) {
  18928. this._value = value;
  18929. this._pmrem = null;
  18930. }
  18931. /**
  18932. * The node's texture value.
  18933. *
  18934. * @type {Texture}
  18935. */
  18936. get value() {
  18937. return this._value;
  18938. }
  18939. /**
  18940. * Uses the given PMREM texture to update internal values.
  18941. *
  18942. * @param {Texture} texture - The PMREM texture.
  18943. */
  18944. updateFromTexture( texture ) {
  18945. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  18946. this._texture.value = texture;
  18947. this._width.value = cubeUVSize.texelWidth;
  18948. this._height.value = cubeUVSize.texelHeight;
  18949. this._maxMip.value = cubeUVSize.maxMip;
  18950. }
  18951. updateBefore( frame ) {
  18952. let pmrem = this._pmrem;
  18953. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  18954. const texture = this._value;
  18955. if ( pmremVersion !== texture.pmremVersion ) {
  18956. if ( texture.isPMREMTexture === true || texture.mapping === CubeUVReflectionMapping ) {
  18957. pmrem = texture;
  18958. } else {
  18959. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  18960. }
  18961. if ( pmrem !== null ) {
  18962. this._pmrem = pmrem;
  18963. this.updateFromTexture( pmrem );
  18964. }
  18965. }
  18966. }
  18967. setup( builder ) {
  18968. if ( this._generator === null ) {
  18969. this._generator = new PMREMGenerator( builder.renderer );
  18970. }
  18971. this.updateBefore( builder );
  18972. //
  18973. let uvNode = this.uvNode;
  18974. if ( uvNode === null && builder.context.getUV ) {
  18975. uvNode = builder.context.getUV( this, builder );
  18976. }
  18977. //
  18978. // PMREMGenerator renders into a render target with inverted Y, so its output needs the Y
  18979. // flip on sampling. Externally authored PMREMs follow the standard convention and don't.
  18980. uvNode = this._pmrem.isRenderTargetTexture
  18981. ? materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) )
  18982. : materialEnvRotation.mul( uvNode );
  18983. //
  18984. let levelNode = this.levelNode;
  18985. if ( levelNode === null && builder.context.getTextureLevel ) {
  18986. levelNode = builder.context.getTextureLevel( this );
  18987. }
  18988. //
  18989. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  18990. }
  18991. dispose() {
  18992. super.dispose();
  18993. if ( this._generator !== null ) this._generator.dispose();
  18994. }
  18995. }
  18996. /**
  18997. * Returns `true` if the given cube map image has been fully loaded.
  18998. *
  18999. * @private
  19000. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  19001. * @return {boolean} Whether the given cube map is ready or not.
  19002. */
  19003. function isCubeMapReady( image ) {
  19004. if ( image === null || image === undefined ) return false;
  19005. let count = 0;
  19006. const length = 6;
  19007. for ( let i = 0; i < length; i ++ ) {
  19008. if ( image[ i ] !== undefined ) count ++;
  19009. }
  19010. return count === length;
  19011. }
  19012. /**
  19013. * Returns `true` if the given equirectangular image has been fully loaded.
  19014. *
  19015. * @private
  19016. * @param {(Image|Object)} image - The equirectangular image.
  19017. * @return {boolean} Whether the given cube map is ready or not.
  19018. */
  19019. function isEquirectangularMapReady( image ) {
  19020. if ( image === null || image === undefined ) return false;
  19021. return image.height > 0;
  19022. }
  19023. /**
  19024. * TSL function for creating a PMREM node.
  19025. *
  19026. * @tsl
  19027. * @function
  19028. * @param {Texture} value - The input texture.
  19029. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  19030. * @param {?Node<float>} [levelNode=null] - The level node.
  19031. * @returns {PMREMNode}
  19032. */
  19033. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  19034. const _rendererCache = new WeakMap();
  19035. /**
  19036. * Represents a physical model for Image-based lighting (IBL). The environment
  19037. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  19038. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  19039. *
  19040. * @augments LightingNode
  19041. */
  19042. class EnvironmentNode extends LightingNode {
  19043. static get type() {
  19044. return 'EnvironmentNode';
  19045. }
  19046. /**
  19047. * Constructs a new environment node.
  19048. *
  19049. * @param {Node} [envNode=null] - A node representing the environment.
  19050. */
  19051. constructor( envNode = null ) {
  19052. super();
  19053. /**
  19054. * A node representing the environment.
  19055. *
  19056. * @type {?Node}
  19057. * @default null
  19058. */
  19059. this.envNode = envNode;
  19060. }
  19061. setup( builder ) {
  19062. const { material } = builder;
  19063. let envNode = this.envNode;
  19064. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  19065. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  19066. const cache = this._getPMREMNodeCache( builder.renderer );
  19067. let cacheEnvNode = cache.get( value );
  19068. if ( cacheEnvNode === undefined ) {
  19069. cacheEnvNode = pmremTexture( value );
  19070. cache.set( value, cacheEnvNode );
  19071. }
  19072. envNode = cacheEnvNode;
  19073. }
  19074. //
  19075. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  19076. const radianceNormalView = useAnisotropy ? bentNormalView : normalView;
  19077. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  19078. const irradiance = envNode.context( createIrradianceContext( normalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  19079. const isolateRadiance = isolate( radiance );
  19080. const isolateIrradiance = isolate( irradiance );
  19081. //
  19082. builder.context.radiance.addAssign( isolateRadiance );
  19083. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  19084. //
  19085. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  19086. if ( clearcoatRadiance ) {
  19087. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, clearcoatNormalView ) ).mul( materialEnvIntensity );
  19088. const isolateClearcoatRadiance = isolate( clearcoatRadianceContext );
  19089. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  19090. }
  19091. }
  19092. /**
  19093. * Returns the PMREM node cache of the current renderer.
  19094. *
  19095. * @private
  19096. * @param {Renderer} renderer - The current renderer.
  19097. * @return {WeakMap} The node cache.
  19098. */
  19099. _getPMREMNodeCache( renderer ) {
  19100. let pmremCache = _rendererCache.get( renderer );
  19101. if ( pmremCache === undefined ) {
  19102. pmremCache = new WeakMap();
  19103. _rendererCache.set( renderer, pmremCache );
  19104. }
  19105. return pmremCache;
  19106. }
  19107. }
  19108. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  19109. let reflectVec = null;
  19110. return {
  19111. getUV: () => {
  19112. if ( reflectVec === null ) {
  19113. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  19114. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  19115. reflectVec = pow4( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  19116. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  19117. }
  19118. return reflectVec;
  19119. },
  19120. getTextureLevel: () => {
  19121. return roughnessNode;
  19122. }
  19123. };
  19124. };
  19125. const createIrradianceContext = ( normalWorldNode ) => {
  19126. return {
  19127. getUV: () => {
  19128. return normalWorldNode;
  19129. },
  19130. getTextureLevel: () => {
  19131. return float( 1.0 );
  19132. }
  19133. };
  19134. };
  19135. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  19136. /**
  19137. * Node material version of {@link MeshStandardMaterial}.
  19138. *
  19139. * @augments NodeMaterial
  19140. */
  19141. class MeshStandardNodeMaterial extends NodeMaterial {
  19142. static get type() {
  19143. return 'MeshStandardNodeMaterial';
  19144. }
  19145. /**
  19146. * Constructs a new mesh standard node material.
  19147. *
  19148. * @param {Object} [parameters] - The configuration parameter.
  19149. */
  19150. constructor( parameters ) {
  19151. super();
  19152. /**
  19153. * This flag can be used for type testing.
  19154. *
  19155. * @type {boolean}
  19156. * @readonly
  19157. * @default true
  19158. */
  19159. this.isMeshStandardNodeMaterial = true;
  19160. /**
  19161. * Set to `true` because standard materials react on lights.
  19162. *
  19163. * @type {boolean}
  19164. * @default true
  19165. */
  19166. this.lights = true;
  19167. /**
  19168. * The emissive color of standard materials is by default inferred from the `emissive`,
  19169. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  19170. * overwrite the default and define the emissive color with a node instead.
  19171. *
  19172. * If you don't want to overwrite the emissive color but modify the existing
  19173. * value instead, use {@link materialEmissive}.
  19174. *
  19175. * @type {?Node<vec3>}
  19176. * @default null
  19177. */
  19178. this.emissiveNode = null;
  19179. /**
  19180. * The metalness of standard materials is by default inferred from the `metalness`,
  19181. * and `metalnessMap` properties. This node property allows to
  19182. * overwrite the default and define the metalness with a node instead.
  19183. *
  19184. * If you don't want to overwrite the metalness but modify the existing
  19185. * value instead, use {@link materialMetalness}.
  19186. *
  19187. * @type {?Node<float>}
  19188. * @default null
  19189. */
  19190. this.metalnessNode = null;
  19191. /**
  19192. * The roughness of standard materials is by default inferred from the `roughness`,
  19193. * and `roughnessMap` properties. This node property allows to
  19194. * overwrite the default and define the roughness with a node instead.
  19195. *
  19196. * If you don't want to overwrite the roughness but modify the existing
  19197. * value instead, use {@link materialRoughness}.
  19198. *
  19199. * @type {?Node<float>}
  19200. * @default null
  19201. */
  19202. this.roughnessNode = null;
  19203. this.setDefaultValues( _defaultValues$6 );
  19204. this.setValues( parameters );
  19205. }
  19206. /**
  19207. * Overwritten since this type of material uses {@link EnvironmentNode}
  19208. * to implement the PBR (PMREM based) environment mapping. Besides, the
  19209. * method honors `Scene.environment`.
  19210. *
  19211. * @param {NodeBuilder} builder - The current node builder.
  19212. * @return {?EnvironmentNode<vec3>} The environment node.
  19213. */
  19214. setupEnvironment( builder ) {
  19215. let envNode = super.setupEnvironment( builder );
  19216. if ( envNode === null && builder.environmentNode ) {
  19217. envNode = builder.environmentNode;
  19218. }
  19219. return envNode ? new EnvironmentNode( envNode ) : null;
  19220. }
  19221. /**
  19222. * Setups the lighting model.
  19223. *
  19224. * @return {PhysicalLightingModel} The lighting model.
  19225. */
  19226. setupLightingModel( /*builder*/ ) {
  19227. return new PhysicalLightingModel();
  19228. }
  19229. /**
  19230. * Setups the specular related node variables.
  19231. */
  19232. setupSpecular() {
  19233. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  19234. specularColor.assign( vec3( 0.04 ) );
  19235. specularColorBlended.assign( specularColorNode );
  19236. specularF90.assign( 1.0 );
  19237. }
  19238. /**
  19239. * Setups the standard specific node variables.
  19240. *
  19241. * @param {NodeBuilder} builder - The current node builder.
  19242. */
  19243. setupVariants() {
  19244. // METALNESS
  19245. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  19246. metalness.assign( metalnessNode );
  19247. // ROUGHNESS
  19248. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  19249. roughnessNode = getRoughness( { roughness: roughnessNode } );
  19250. roughness.assign( roughnessNode );
  19251. // SPECULAR COLOR
  19252. this.setupSpecular();
  19253. // DIFFUSE COLOR
  19254. diffuseContribution.assign( diffuseColor.rgb.mul( metalnessNode.oneMinus() ) );
  19255. }
  19256. copy( source ) {
  19257. this.emissiveNode = source.emissiveNode;
  19258. this.metalnessNode = source.metalnessNode;
  19259. this.roughnessNode = source.roughnessNode;
  19260. return super.copy( source );
  19261. }
  19262. }
  19263. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  19264. /**
  19265. * Node material version of {@link MeshPhysicalMaterial}.
  19266. *
  19267. * @augments MeshStandardNodeMaterial
  19268. */
  19269. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  19270. static get type() {
  19271. return 'MeshPhysicalNodeMaterial';
  19272. }
  19273. /**
  19274. * Constructs a new mesh physical node material.
  19275. *
  19276. * @param {Object} [parameters] - The configuration parameter.
  19277. */
  19278. constructor( parameters ) {
  19279. super();
  19280. /**
  19281. * This flag can be used for type testing.
  19282. *
  19283. * @type {boolean}
  19284. * @readonly
  19285. * @default true
  19286. */
  19287. this.isMeshPhysicalNodeMaterial = true;
  19288. /**
  19289. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  19290. * and `clearcoatMap` properties. This node property allows to overwrite the default
  19291. * and define the clearcoat with a node instead.
  19292. *
  19293. * If you don't want to overwrite the clearcoat but modify the existing
  19294. * value instead, use {@link materialClearcoat}.
  19295. *
  19296. * @type {?Node<float>}
  19297. * @default null
  19298. */
  19299. this.clearcoatNode = null;
  19300. /**
  19301. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  19302. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  19303. * and define the clearcoat roughness with a node instead.
  19304. *
  19305. * If you don't want to overwrite the clearcoat roughness but modify the existing
  19306. * value instead, use {@link materialClearcoatRoughness}.
  19307. *
  19308. * @type {?Node<float>}
  19309. * @default null
  19310. */
  19311. this.clearcoatRoughnessNode = null;
  19312. /**
  19313. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  19314. * property. This node property allows to overwrite the default
  19315. * and define the clearcoat normal with a node instead.
  19316. *
  19317. * If you don't want to overwrite the clearcoat normal but modify the existing
  19318. * value instead, use {@link materialClearcoatNormal}.
  19319. *
  19320. * @type {?Node<vec3>}
  19321. * @default null
  19322. */
  19323. this.clearcoatNormalNode = null;
  19324. /**
  19325. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  19326. * and `sheenColorMap` properties. This node property allows to overwrite the default
  19327. * and define the sheen with a node instead.
  19328. *
  19329. * If you don't want to overwrite the sheen but modify the existing
  19330. * value instead, use {@link materialSheen}.
  19331. *
  19332. * @type {?Node<vec3>}
  19333. * @default null
  19334. */
  19335. this.sheenNode = null;
  19336. /**
  19337. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  19338. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  19339. * and define the sheen roughness with a node instead.
  19340. *
  19341. * If you don't want to overwrite the sheen roughness but modify the existing
  19342. * value instead, use {@link materialSheenRoughness}.
  19343. *
  19344. * @type {?Node<float>}
  19345. * @default null
  19346. */
  19347. this.sheenRoughnessNode = null;
  19348. /**
  19349. * The iridescence of physical materials is by default inferred from the `iridescence`
  19350. * property. This node property allows to overwrite the default
  19351. * and define the iridescence with a node instead.
  19352. *
  19353. * If you don't want to overwrite the iridescence but modify the existing
  19354. * value instead, use {@link materialIridescence}.
  19355. *
  19356. * @type {?Node<float>}
  19357. * @default null
  19358. */
  19359. this.iridescenceNode = null;
  19360. /**
  19361. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  19362. * property. This node property allows to overwrite the default
  19363. * and define the iridescence IOR with a node instead.
  19364. *
  19365. * If you don't want to overwrite the iridescence IOR but modify the existing
  19366. * value instead, use {@link materialIridescenceIOR}.
  19367. *
  19368. * @type {?Node<float>}
  19369. * @default null
  19370. */
  19371. this.iridescenceIORNode = null;
  19372. /**
  19373. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  19374. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  19375. * and define the iridescence thickness with a node instead.
  19376. *
  19377. * If you don't want to overwrite the iridescence thickness but modify the existing
  19378. * value instead, use {@link materialIridescenceThickness}.
  19379. *
  19380. * @type {?Node<float>}
  19381. * @default null
  19382. */
  19383. this.iridescenceThicknessNode = null;
  19384. /**
  19385. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  19386. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  19387. * and define the specular intensity with a node instead.
  19388. *
  19389. * If you don't want to overwrite the specular intensity but modify the existing
  19390. * value instead, use {@link materialSpecularIntensity}.
  19391. *
  19392. * @type {?Node<float>}
  19393. * @default null
  19394. */
  19395. this.specularIntensityNode = null;
  19396. /**
  19397. * The specular color of physical materials is by default inferred from the `specularColor`
  19398. * and `specularColorMap` properties. This node property allows to overwrite the default
  19399. * and define the specular color with a node instead.
  19400. *
  19401. * If you don't want to overwrite the specular color but modify the existing
  19402. * value instead, use {@link materialSpecularColor}.
  19403. *
  19404. * @type {?Node<vec3>}
  19405. * @default null
  19406. */
  19407. this.specularColorNode = null;
  19408. /**
  19409. * The ior of physical materials is by default inferred from the `ior`
  19410. * property. This node property allows to overwrite the default
  19411. * and define the ior with a node instead.
  19412. *
  19413. * If you don't want to overwrite the ior but modify the existing
  19414. * value instead, use {@link materialIOR}.
  19415. *
  19416. * @type {?Node<float>}
  19417. * @default null
  19418. */
  19419. this.iorNode = null;
  19420. /**
  19421. * The transmission of physical materials is by default inferred from the `transmission` and
  19422. * `transmissionMap` properties. This node property allows to overwrite the default
  19423. * and define the transmission with a node instead.
  19424. *
  19425. * If you don't want to overwrite the transmission but modify the existing
  19426. * value instead, use {@link materialTransmission}.
  19427. *
  19428. * @type {?Node<float>}
  19429. * @default null
  19430. */
  19431. this.transmissionNode = null;
  19432. /**
  19433. * The thickness of physical materials is by default inferred from the `thickness` and
  19434. * `thicknessMap` properties. This node property allows to overwrite the default
  19435. * and define the thickness with a node instead.
  19436. *
  19437. * If you don't want to overwrite the thickness but modify the existing
  19438. * value instead, use {@link materialThickness}.
  19439. *
  19440. * @type {?Node<float>}
  19441. * @default null
  19442. */
  19443. this.thicknessNode = null;
  19444. /**
  19445. * The attenuation distance of physical materials is by default inferred from the
  19446. * `attenuationDistance` property. This node property allows to overwrite the default
  19447. * and define the attenuation distance with a node instead.
  19448. *
  19449. * If you don't want to overwrite the attenuation distance but modify the existing
  19450. * value instead, use {@link materialAttenuationDistance}.
  19451. *
  19452. * @type {?Node<float>}
  19453. * @default null
  19454. */
  19455. this.attenuationDistanceNode = null;
  19456. /**
  19457. * The attenuation color of physical materials is by default inferred from the
  19458. * `attenuationColor` property. This node property allows to overwrite the default
  19459. * and define the attenuation color with a node instead.
  19460. *
  19461. * If you don't want to overwrite the attenuation color but modify the existing
  19462. * value instead, use {@link materialAttenuationColor}.
  19463. *
  19464. * @type {?Node<vec3>}
  19465. * @default null
  19466. */
  19467. this.attenuationColorNode = null;
  19468. /**
  19469. * The dispersion of physical materials is by default inferred from the
  19470. * `dispersion` property. This node property allows to overwrite the default
  19471. * and define the dispersion with a node instead.
  19472. *
  19473. * If you don't want to overwrite the dispersion but modify the existing
  19474. * value instead, use {@link materialDispersion}.
  19475. *
  19476. * @type {?Node<float>}
  19477. * @default null
  19478. */
  19479. this.dispersionNode = null;
  19480. /**
  19481. * The anisotropy of physical materials is by default inferred from the
  19482. * `anisotropy` property. This node property allows to overwrite the default
  19483. * and define the anisotropy with a node instead.
  19484. *
  19485. * If you don't want to overwrite the anisotropy but modify the existing
  19486. * value instead, use {@link materialAnisotropy}.
  19487. *
  19488. * @type {?Node<float>}
  19489. * @default null
  19490. */
  19491. this.anisotropyNode = null;
  19492. this.setDefaultValues( _defaultValues$5 );
  19493. this.setValues( parameters );
  19494. }
  19495. /**
  19496. * Whether the lighting model should use clearcoat or not.
  19497. *
  19498. * @type {boolean}
  19499. * @default true
  19500. */
  19501. get useClearcoat() {
  19502. return this.clearcoat > 0 || this.clearcoatNode !== null;
  19503. }
  19504. /**
  19505. * Whether the lighting model should use iridescence or not.
  19506. *
  19507. * @type {boolean}
  19508. * @default true
  19509. */
  19510. get useIridescence() {
  19511. return this.iridescence > 0 || this.iridescenceNode !== null;
  19512. }
  19513. /**
  19514. * Whether the lighting model should use sheen or not.
  19515. *
  19516. * @type {boolean}
  19517. * @default true
  19518. */
  19519. get useSheen() {
  19520. return this.sheen > 0 || this.sheenNode !== null;
  19521. }
  19522. /**
  19523. * Whether the lighting model should use anisotropy or not.
  19524. *
  19525. * @type {boolean}
  19526. * @default true
  19527. */
  19528. get useAnisotropy() {
  19529. return this.anisotropy > 0 || this.anisotropyNode !== null;
  19530. }
  19531. /**
  19532. * Whether the lighting model should use transmission or not.
  19533. *
  19534. * @type {boolean}
  19535. * @default true
  19536. */
  19537. get useTransmission() {
  19538. return this.transmission > 0 || this.transmissionNode !== null;
  19539. }
  19540. /**
  19541. * Whether the lighting model should use dispersion or not.
  19542. *
  19543. * @type {boolean}
  19544. * @default true
  19545. */
  19546. get useDispersion() {
  19547. return this.dispersion > 0 || this.dispersionNode !== null;
  19548. }
  19549. /**
  19550. * Setups the specular related node variables.
  19551. */
  19552. setupSpecular() {
  19553. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  19554. ior.assign( iorNode );
  19555. specularColor.assign( min$1( pow2( ior.sub( 1.0 ).div( ior.add( 1.0 ) ) ).mul( materialSpecularColor ), vec3( 1.0 ) ).mul( materialSpecularIntensity ) );
  19556. specularColorBlended.assign( mix( specularColor, diffuseColor.rgb, metalness ) );
  19557. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  19558. }
  19559. /**
  19560. * Setups the lighting model.
  19561. *
  19562. * @return {PhysicalLightingModel} The lighting model.
  19563. */
  19564. setupLightingModel( /*builder*/ ) {
  19565. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  19566. }
  19567. /**
  19568. * Setups the physical specific node variables.
  19569. *
  19570. * @param {NodeBuilder} builder - The current node builder.
  19571. */
  19572. setupVariants( builder ) {
  19573. super.setupVariants( builder );
  19574. // CLEARCOAT
  19575. if ( this.useClearcoat ) {
  19576. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  19577. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  19578. clearcoat.assign( clearcoatNode );
  19579. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  19580. }
  19581. // SHEEN
  19582. if ( this.useSheen ) {
  19583. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  19584. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  19585. sheen.assign( sheenNode );
  19586. sheenRoughness.assign( sheenRoughnessNode );
  19587. }
  19588. // IRIDESCENCE
  19589. if ( this.useIridescence ) {
  19590. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  19591. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  19592. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  19593. iridescence.assign( iridescenceNode );
  19594. iridescenceIOR.assign( iridescenceIORNode );
  19595. iridescenceThickness.assign( iridescenceThicknessNode );
  19596. }
  19597. // ANISOTROPY
  19598. if ( this.useAnisotropy ) {
  19599. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  19600. anisotropy.assign( anisotropyV.length() );
  19601. If( anisotropy.equal( 0.0 ), () => {
  19602. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  19603. } ).Else( () => {
  19604. anisotropyV.divAssign( vec2( anisotropy ) );
  19605. anisotropy.assign( anisotropy.saturate() );
  19606. } );
  19607. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  19608. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  19609. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  19610. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  19611. }
  19612. // TRANSMISSION
  19613. if ( this.useTransmission ) {
  19614. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  19615. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  19616. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  19617. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  19618. transmission.assign( transmissionNode );
  19619. thickness.assign( thicknessNode );
  19620. attenuationDistance.assign( attenuationDistanceNode );
  19621. attenuationColor.assign( attenuationColorNode );
  19622. if ( this.useDispersion ) {
  19623. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  19624. dispersion.assign( dispersionNode );
  19625. }
  19626. }
  19627. }
  19628. /**
  19629. * Setups the clearcoat normal node.
  19630. *
  19631. * @return {Node<vec3>} The clearcoat normal.
  19632. */
  19633. setupClearcoatNormal() {
  19634. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  19635. }
  19636. setup( builder ) {
  19637. builder.context.setupClearcoatNormal = () => subBuild( this.setupClearcoatNormal( builder ), 'NORMAL', 'vec3' );
  19638. super.setup( builder );
  19639. }
  19640. copy( source ) {
  19641. this.clearcoatNode = source.clearcoatNode;
  19642. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  19643. this.clearcoatNormalNode = source.clearcoatNormalNode;
  19644. this.sheenNode = source.sheenNode;
  19645. this.sheenRoughnessNode = source.sheenRoughnessNode;
  19646. this.iridescenceNode = source.iridescenceNode;
  19647. this.iridescenceIORNode = source.iridescenceIORNode;
  19648. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  19649. this.specularIntensityNode = source.specularIntensityNode;
  19650. this.specularColorNode = source.specularColorNode;
  19651. this.iorNode = source.iorNode;
  19652. this.transmissionNode = source.transmissionNode;
  19653. this.thicknessNode = source.thicknessNode;
  19654. this.attenuationDistanceNode = source.attenuationDistanceNode;
  19655. this.attenuationColorNode = source.attenuationColorNode;
  19656. this.dispersionNode = source.dispersionNode;
  19657. this.anisotropyNode = source.anisotropyNode;
  19658. return super.copy( source );
  19659. }
  19660. }
  19661. /**
  19662. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  19663. *
  19664. * @augments PhysicalLightingModel
  19665. */
  19666. class SSSLightingModel extends PhysicalLightingModel {
  19667. /**
  19668. * Constructs a new physical lighting model.
  19669. *
  19670. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  19671. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  19672. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  19673. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  19674. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  19675. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  19676. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  19677. */
  19678. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  19679. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  19680. /**
  19681. * Whether the lighting model should use SSS or not.
  19682. *
  19683. * @type {boolean}
  19684. * @default false
  19685. */
  19686. this.useSSS = sss;
  19687. }
  19688. /**
  19689. * Extends the default implementation with a SSS term.
  19690. *
  19691. * 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/)
  19692. *
  19693. * @param {Object} input - The input data.
  19694. * @param {NodeBuilder} builder - The current node builder.
  19695. */
  19696. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  19697. if ( this.useSSS === true ) {
  19698. const material = builder.material;
  19699. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  19700. const scatteringHalf = lightDirection.add( normalView.mul( thicknessDistortionNode ) ).normalize();
  19701. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  19702. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  19703. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  19704. }
  19705. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  19706. }
  19707. }
  19708. /**
  19709. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  19710. * that implements a Subsurface scattering (SSS) term.
  19711. *
  19712. * @augments MeshPhysicalNodeMaterial
  19713. */
  19714. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  19715. static get type() {
  19716. return 'MeshSSSNodeMaterial';
  19717. }
  19718. /**
  19719. * Constructs a new mesh SSS node material.
  19720. *
  19721. * @param {Object} [parameters] - The configuration parameter.
  19722. */
  19723. constructor( parameters ) {
  19724. super( parameters );
  19725. /**
  19726. * Represents the thickness color.
  19727. *
  19728. * @type {?Node<vec3>}
  19729. * @default null
  19730. */
  19731. this.thicknessColorNode = null;
  19732. /**
  19733. * Represents the distortion factor.
  19734. *
  19735. * @type {?Node<float>}
  19736. */
  19737. this.thicknessDistortionNode = float( 0.1 );
  19738. /**
  19739. * Represents the thickness ambient factor.
  19740. *
  19741. * @type {?Node<float>}
  19742. */
  19743. this.thicknessAmbientNode = float( 0.0 );
  19744. /**
  19745. * Represents the thickness attenuation.
  19746. *
  19747. * @type {?Node<float>}
  19748. */
  19749. this.thicknessAttenuationNode = float( .1 );
  19750. /**
  19751. * Represents the thickness power.
  19752. *
  19753. * @type {?Node<float>}
  19754. */
  19755. this.thicknessPowerNode = float( 2.0 );
  19756. /**
  19757. * Represents the thickness scale.
  19758. *
  19759. * @type {?Node<float>}
  19760. */
  19761. this.thicknessScaleNode = float( 10.0 );
  19762. }
  19763. /**
  19764. * Whether the lighting model should use SSS or not.
  19765. *
  19766. * @type {boolean}
  19767. * @default true
  19768. */
  19769. get useSSS() {
  19770. return this.thicknessColorNode !== null;
  19771. }
  19772. /**
  19773. * Setups the lighting model.
  19774. *
  19775. * @return {SSSLightingModel} The lighting model.
  19776. */
  19777. setupLightingModel( /*builder*/ ) {
  19778. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  19779. }
  19780. copy( source ) {
  19781. this.thicknessColorNode = source.thicknessColorNode;
  19782. this.thicknessDistortionNode = source.thicknessDistortionNode;
  19783. this.thicknessAmbientNode = source.thicknessAmbientNode;
  19784. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  19785. this.thicknessPowerNode = source.thicknessPowerNode;
  19786. this.thicknessScaleNode = source.thicknessScaleNode;
  19787. return super.copy( source );
  19788. }
  19789. }
  19790. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  19791. // dotNL will be from -1.0 to 1.0
  19792. const dotNL = normal.dot( lightDirection );
  19793. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  19794. if ( builder.material.gradientMap ) {
  19795. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  19796. return vec3( gradientMap.r );
  19797. } else {
  19798. const fw = coord.fwidth().mul( 0.5 );
  19799. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  19800. }
  19801. } );
  19802. /**
  19803. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  19804. *
  19805. * @augments LightingModel
  19806. */
  19807. class ToonLightingModel extends LightingModel {
  19808. /**
  19809. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  19810. * reduced to a small number of discrete shades to create a comic-like, flat look.
  19811. *
  19812. * @param {Object} lightData - The light data.
  19813. * @param {NodeBuilder} builder - The current node builder.
  19814. */
  19815. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  19816. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  19817. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  19818. }
  19819. /**
  19820. * Implements the indirect lighting.
  19821. *
  19822. * @param {NodeBuilder} builder - The current node builder.
  19823. */
  19824. indirect( builder ) {
  19825. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  19826. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  19827. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  19828. }
  19829. }
  19830. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  19831. /**
  19832. * Node material version of {@link MeshToonMaterial}.
  19833. *
  19834. * @augments NodeMaterial
  19835. */
  19836. class MeshToonNodeMaterial extends NodeMaterial {
  19837. static get type() {
  19838. return 'MeshToonNodeMaterial';
  19839. }
  19840. /**
  19841. * Constructs a new mesh toon node material.
  19842. *
  19843. * @param {Object} [parameters] - The configuration parameter.
  19844. */
  19845. constructor( parameters ) {
  19846. super();
  19847. /**
  19848. * This flag can be used for type testing.
  19849. *
  19850. * @type {boolean}
  19851. * @readonly
  19852. * @default true
  19853. */
  19854. this.isMeshToonNodeMaterial = true;
  19855. /**
  19856. * Set to `true` because toon materials react on lights.
  19857. *
  19858. * @type {boolean}
  19859. * @default true
  19860. */
  19861. this.lights = true;
  19862. this.setDefaultValues( _defaultValues$4 );
  19863. this.setValues( parameters );
  19864. }
  19865. /**
  19866. * Setups the lighting model.
  19867. *
  19868. * @return {ToonLightingModel} The lighting model.
  19869. */
  19870. setupLightingModel( /*builder*/ ) {
  19871. return new ToonLightingModel();
  19872. }
  19873. }
  19874. /**
  19875. * TSL function for creating a matcap uv node.
  19876. *
  19877. * Can be used to compute texture coordinates for projecting a
  19878. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  19879. *
  19880. * @tsl
  19881. * @function
  19882. * @returns {Node<vec2>} The matcap UV coordinates.
  19883. */
  19884. const matcapUV = /*@__PURE__*/ Fn( () => {
  19885. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  19886. const y = positionViewDirection.cross( x );
  19887. return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  19888. } ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' );
  19889. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  19890. /**
  19891. * Node material version of {@link MeshMatcapMaterial}.
  19892. *
  19893. * @augments NodeMaterial
  19894. */
  19895. class MeshMatcapNodeMaterial extends NodeMaterial {
  19896. static get type() {
  19897. return 'MeshMatcapNodeMaterial';
  19898. }
  19899. /**
  19900. * Constructs a new mesh normal node material.
  19901. *
  19902. * @param {Object} [parameters] - The configuration parameter.
  19903. */
  19904. constructor( parameters ) {
  19905. super();
  19906. /**
  19907. * This flag can be used for type testing.
  19908. *
  19909. * @type {boolean}
  19910. * @readonly
  19911. * @default true
  19912. */
  19913. this.isMeshMatcapNodeMaterial = true;
  19914. this.setDefaultValues( _defaultValues$3 );
  19915. this.setValues( parameters );
  19916. }
  19917. /**
  19918. * Setups the matcap specific node variables.
  19919. *
  19920. * @param {NodeBuilder} builder - The current node builder.
  19921. */
  19922. setupVariants( builder ) {
  19923. const uv = matcapUV;
  19924. let matcapColor;
  19925. if ( builder.material.matcap ) {
  19926. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  19927. } else {
  19928. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  19929. }
  19930. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  19931. }
  19932. }
  19933. /**
  19934. * Applies a rotation to the given position node.
  19935. *
  19936. * @augments TempNode
  19937. */
  19938. class RotateNode extends TempNode {
  19939. static get type() {
  19940. return 'RotateNode';
  19941. }
  19942. /**
  19943. * Constructs a new rotate node.
  19944. *
  19945. * @param {Node} positionNode - The position node.
  19946. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  19947. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19948. */
  19949. constructor( positionNode, rotationNode ) {
  19950. super();
  19951. /**
  19952. * The position node.
  19953. *
  19954. * @type {Node}
  19955. */
  19956. this.positionNode = positionNode;
  19957. /**
  19958. * Represents the rotation that is applied to the position node.
  19959. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19960. *
  19961. * @type {Node}
  19962. */
  19963. this.rotationNode = rotationNode;
  19964. }
  19965. /**
  19966. * The type of the {@link RotateNode#positionNode} defines the node's type.
  19967. *
  19968. * @param {NodeBuilder} builder - The current node builder.
  19969. * @return {string} The node's type.
  19970. */
  19971. generateNodeType( builder ) {
  19972. return this.positionNode.getNodeType( builder );
  19973. }
  19974. setup( builder ) {
  19975. const { rotationNode, positionNode } = this;
  19976. const nodeType = this.getNodeType( builder );
  19977. if ( nodeType === 'vec2' ) {
  19978. const cosAngle = rotationNode.cos();
  19979. const sinAngle = rotationNode.sin();
  19980. const rotationMatrix = mat2(
  19981. cosAngle, sinAngle,
  19982. sinAngle.negate(), cosAngle
  19983. );
  19984. return rotationMatrix.mul( positionNode );
  19985. } else {
  19986. const rotation = rotationNode;
  19987. 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 ) );
  19988. 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 ) );
  19989. 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 ) );
  19990. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  19991. }
  19992. }
  19993. }
  19994. /**
  19995. * TSL function for creating a rotate node.
  19996. *
  19997. * @tsl
  19998. * @function
  19999. * @param {Node} positionNode - The position node.
  20000. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  20001. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  20002. * @returns {RotateNode}
  20003. */
  20004. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  20005. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  20006. /**
  20007. * Node material version of {@link SpriteMaterial}.
  20008. *
  20009. * @augments NodeMaterial
  20010. */
  20011. class SpriteNodeMaterial extends NodeMaterial {
  20012. static get type() {
  20013. return 'SpriteNodeMaterial';
  20014. }
  20015. /**
  20016. * Constructs a new sprite node material.
  20017. *
  20018. * @param {Object} [parameters] - The configuration parameter.
  20019. */
  20020. constructor( parameters ) {
  20021. super();
  20022. /**
  20023. * This flag can be used for type testing.
  20024. *
  20025. * @type {boolean}
  20026. * @readonly
  20027. * @default true
  20028. */
  20029. this.isSpriteNodeMaterial = true;
  20030. this._useSizeAttenuation = true;
  20031. /**
  20032. * This property makes it possible to define the position of the sprite with a
  20033. * node. That can be useful when the material is used with instanced rendering
  20034. * and node data are defined with an instanced attribute node:
  20035. * ```js
  20036. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  20037. * material.positionNode = instancedBufferAttribute( positionAttribute );
  20038. * ```
  20039. * Another possibility is to compute the instanced data with a compute shader:
  20040. * ```js
  20041. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  20042. * particleMaterial.positionNode = positionBuffer.toAttribute();
  20043. * ```
  20044. *
  20045. * @type {?Node<vec2>}
  20046. * @default null
  20047. */
  20048. this.positionNode = null;
  20049. /**
  20050. * The rotation of sprite materials is by default inferred from the `rotation`,
  20051. * property. This node property allows to overwrite the default and define
  20052. * the rotation with a node instead.
  20053. *
  20054. * If you don't want to overwrite the rotation but modify the existing
  20055. * value instead, use {@link materialRotation}.
  20056. *
  20057. * @type {?Node<float>}
  20058. * @default null
  20059. */
  20060. this.rotationNode = null;
  20061. /**
  20062. * This node property provides an additional way to scale sprites next to
  20063. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  20064. * is multiplied with the scale value of this node in the vertex shader.
  20065. *
  20066. * @type {?Node<vec2>}
  20067. * @default null
  20068. */
  20069. this.scaleNode = null;
  20070. /**
  20071. * In Sprites, the transparent property is enabled by default.
  20072. *
  20073. * @type {boolean}
  20074. * @default true
  20075. */
  20076. this.transparent = true;
  20077. this.setDefaultValues( _defaultValues$2 );
  20078. this.setValues( parameters );
  20079. }
  20080. /**
  20081. * Setups the position node in view space. This method implements
  20082. * the sprite specific vertex shader.
  20083. *
  20084. * @param {NodeBuilder} builder - The current node builder.
  20085. * @return {Node<vec3>} The position in view space.
  20086. */
  20087. setupPositionView( builder ) {
  20088. const { object, camera } = builder;
  20089. const { positionNode, rotationNode, scaleNode, sizeAttenuation } = this;
  20090. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  20091. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  20092. if ( scaleNode !== null ) {
  20093. scale = scale.mul( vec2( scaleNode ) );
  20094. }
  20095. if ( camera.isPerspectiveCamera && sizeAttenuation === false ) {
  20096. scale = scale.mul( mvPosition.z.negate() );
  20097. }
  20098. let alignedPosition = positionGeometry.xy;
  20099. if ( object.center && object.center.isVector2 === true ) {
  20100. const center = reference$1( 'center', 'vec2', object );
  20101. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  20102. }
  20103. alignedPosition = alignedPosition.mul( scale );
  20104. const rotation = float( rotationNode || materialRotation );
  20105. const rotatedPosition = rotate( alignedPosition, rotation );
  20106. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  20107. }
  20108. copy( source ) {
  20109. this.positionNode = source.positionNode;
  20110. this.rotationNode = source.rotationNode;
  20111. this.scaleNode = source.scaleNode;
  20112. return super.copy( source );
  20113. }
  20114. /**
  20115. * Whether to use size attenuation or not.
  20116. *
  20117. * @type {boolean}
  20118. * @default true
  20119. */
  20120. get sizeAttenuation() {
  20121. return this._useSizeAttenuation;
  20122. }
  20123. set sizeAttenuation( value ) {
  20124. if ( this._useSizeAttenuation !== value ) {
  20125. this._useSizeAttenuation = value;
  20126. this.needsUpdate = true;
  20127. }
  20128. }
  20129. }
  20130. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  20131. const _size$4 = /*@__PURE__*/ new Vector2();
  20132. /**
  20133. * Node material version of {@link PointsMaterial}.
  20134. *
  20135. * This material can be used in two ways:
  20136. *
  20137. * - By rendering point primitives with {@link Points}. Since WebGPU only supports point primitives
  20138. * with a pixel size of `1`, it's not possible to define a size.
  20139. *
  20140. * ```js
  20141. * const pointCloud = new THREE.Points( geometry, new THREE.PointsNodeMaterial() );
  20142. * ```
  20143. *
  20144. * - By rendering point primitives with {@link Sprites}. In this case, size is honored,
  20145. * see {@link PointsNodeMaterial#sizeNode}.
  20146. *
  20147. * ```js
  20148. * const instancedPoints = new THREE.Sprite( new THREE.PointsNodeMaterial( { positionNode: instancedBufferAttribute( positionAttribute ) } ) );
  20149. * ```
  20150. *
  20151. * @augments SpriteNodeMaterial
  20152. */
  20153. class PointsNodeMaterial extends SpriteNodeMaterial {
  20154. static get type() {
  20155. return 'PointsNodeMaterial';
  20156. }
  20157. /**
  20158. * Constructs a new points node material.
  20159. *
  20160. * @param {Object} [parameters] - The configuration parameter.
  20161. */
  20162. constructor( parameters ) {
  20163. super();
  20164. /**
  20165. * This node property provides an additional way to set the point size.
  20166. *
  20167. * Note that WebGPU only supports point primitives with 1 pixel size. Consequently,
  20168. * this node has no effect when the material is used with {@link Points} and a WebGPU
  20169. * backend. If an application wants to render points with a size larger than 1 pixel,
  20170. * the material should be used with {@link Sprite} and instancing.
  20171. *
  20172. * @type {?Node<vec2>}
  20173. * @default null
  20174. */
  20175. this.sizeNode = null;
  20176. /**
  20177. * This flag can be used for type testing.
  20178. *
  20179. * @type {boolean}
  20180. * @readonly
  20181. * @default true
  20182. */
  20183. this.isPointsNodeMaterial = true;
  20184. this.setDefaultValues( _defaultValues$1 );
  20185. this.setValues( parameters );
  20186. }
  20187. setupPositionView() {
  20188. const { positionNode } = this;
  20189. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  20190. }
  20191. setupVertexSprite( builder ) {
  20192. const { material, camera } = builder;
  20193. const { rotationNode, scaleNode, sizeNode, sizeAttenuation } = this;
  20194. let mvp = super.setupVertex( builder );
  20195. // skip further processing if the material is not a node material
  20196. if ( material.isNodeMaterial !== true ) {
  20197. return mvp;
  20198. }
  20199. // point size
  20200. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  20201. pointSize = pointSize.mul( screenDPR );
  20202. // size attenuation
  20203. if ( camera.isPerspectiveCamera && sizeAttenuation === true ) {
  20204. // follow WebGLRenderer's implementation, and scale by half the canvas height in logical units
  20205. pointSize = pointSize.mul( scale.div( positionView.z.negate() ) );
  20206. }
  20207. // scale
  20208. if ( scaleNode && scaleNode.isNode ) {
  20209. pointSize = pointSize.mul( vec2( scaleNode ) );
  20210. }
  20211. // compute offset
  20212. let offset = positionGeometry.xy;
  20213. // apply rotation
  20214. if ( rotationNode && rotationNode.isNode ) {
  20215. const rotation = float( rotationNode );
  20216. offset = rotate( offset, rotation );
  20217. }
  20218. // account for point size
  20219. offset = offset.mul( pointSize );
  20220. // scale by viewport size
  20221. offset = offset.div( viewportSize.div( 2 ) );
  20222. // compensate for the perspective divide
  20223. offset = offset.mul( mvp.w );
  20224. // add offset
  20225. mvp = mvp.add( vec4( offset, 0, 0 ) );
  20226. return mvp;
  20227. }
  20228. setupVertex( builder ) {
  20229. if ( builder.object.isPoints ) {
  20230. return super.setupVertex( builder );
  20231. } else {
  20232. return this.setupVertexSprite( builder );
  20233. }
  20234. }
  20235. /**
  20236. * Whether alpha to coverage should be used or not.
  20237. *
  20238. * @type {boolean}
  20239. * @default true
  20240. */
  20241. get alphaToCoverage() {
  20242. return this._useAlphaToCoverage;
  20243. }
  20244. set alphaToCoverage( value ) {
  20245. if ( this._useAlphaToCoverage !== value ) {
  20246. this._useAlphaToCoverage = value;
  20247. this.needsUpdate = true;
  20248. }
  20249. }
  20250. }
  20251. const scale = /*@__PURE__*/ uniform( 1 ).onFrameUpdate( function ( { renderer } ) {
  20252. const size = renderer.getSize( _size$4 ); // logical units
  20253. this.value = 0.5 * size.y;
  20254. } );
  20255. /**
  20256. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  20257. *
  20258. * @augments LightingModel
  20259. */
  20260. class ShadowMaskModel extends LightingModel {
  20261. /**
  20262. * Constructs a new shadow mask model.
  20263. */
  20264. constructor() {
  20265. super();
  20266. /**
  20267. * The shadow mask node.
  20268. *
  20269. * @type {Node}
  20270. */
  20271. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  20272. }
  20273. /**
  20274. * Only used to save the shadow mask.
  20275. *
  20276. * @param {Object} input - The input data.
  20277. */
  20278. direct( { lightNode } ) {
  20279. if ( lightNode.shadowNode !== null ) {
  20280. this.shadowNode.mulAssign( lightNode.shadowNode );
  20281. }
  20282. }
  20283. /**
  20284. * Uses the shadow mask to produce the final color.
  20285. *
  20286. * @param {NodeBuilder} builder - The current node builder.
  20287. */
  20288. finish( { context } ) {
  20289. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  20290. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  20291. }
  20292. }
  20293. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  20294. /**
  20295. * Node material version of {@link ShadowMaterial}.
  20296. *
  20297. * @augments NodeMaterial
  20298. */
  20299. class ShadowNodeMaterial extends NodeMaterial {
  20300. static get type() {
  20301. return 'ShadowNodeMaterial';
  20302. }
  20303. /**
  20304. * Constructs a new shadow node material.
  20305. *
  20306. * @param {Object} [parameters] - The configuration parameter.
  20307. */
  20308. constructor( parameters ) {
  20309. super();
  20310. /**
  20311. * This flag can be used for type testing.
  20312. *
  20313. * @type {boolean}
  20314. * @readonly
  20315. * @default true
  20316. */
  20317. this.isShadowNodeMaterial = true;
  20318. /**
  20319. * Set to `true` because so it's possible to implement
  20320. * the shadow mask effect.
  20321. *
  20322. * @type {boolean}
  20323. * @default true
  20324. */
  20325. this.lights = true;
  20326. /**
  20327. * Overwritten since shadow materials are transparent
  20328. * by default.
  20329. *
  20330. * @type {boolean}
  20331. * @default true
  20332. */
  20333. this.transparent = true;
  20334. this.setDefaultValues( _defaultValues );
  20335. this.setValues( parameters );
  20336. }
  20337. /**
  20338. * Setups the lighting model.
  20339. *
  20340. * @return {ShadowMaskModel} The lighting model.
  20341. */
  20342. setupLightingModel( /*builder*/ ) {
  20343. return new ShadowMaskModel();
  20344. }
  20345. }
  20346. const scatteringDensity = property( 'vec3' );
  20347. const linearDepthRay = property( 'vec3' );
  20348. const outgoingRayLight = property( 'vec3' );
  20349. /**
  20350. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  20351. * This model calculates the scattering and transmittance of light through a volumetric medium.
  20352. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  20353. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  20354. *
  20355. * @augments LightingModel
  20356. */
  20357. class VolumetricLightingModel extends LightingModel {
  20358. constructor() {
  20359. super();
  20360. }
  20361. start( builder ) {
  20362. const { material } = builder;
  20363. const startPos = property( 'vec3' );
  20364. const endPos = property( 'vec3' );
  20365. // This approach dynamically changes the direction of the ray,
  20366. // 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.
  20367. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  20368. startPos.assign( cameraPosition );
  20369. endPos.assign( positionWorld );
  20370. } ).Else( () => {
  20371. startPos.assign( positionWorld );
  20372. endPos.assign( cameraPosition );
  20373. } );
  20374. //
  20375. const viewVector = endPos.sub( startPos );
  20376. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  20377. const stepSize = viewVector.length().div( steps ).toVar();
  20378. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  20379. const distTravelled = float( 0.0 ).toVar();
  20380. const transmittance = vec3( 1 ).toVar();
  20381. if ( material.offsetNode ) {
  20382. // reduce banding
  20383. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  20384. }
  20385. Loop( steps, () => {
  20386. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  20387. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  20388. if ( material.depthNode !== null ) {
  20389. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  20390. builder.context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  20391. }
  20392. builder.context.positionWorld = positionRay;
  20393. builder.context.shadowPositionWorld = positionRay;
  20394. builder.context.positionView = positionViewRay;
  20395. scatteringDensity.assign( 0 );
  20396. let scatteringNode;
  20397. if ( material.scatteringNode ) {
  20398. scatteringNode = material.scatteringNode( {
  20399. positionRay
  20400. } );
  20401. }
  20402. super.start( builder );
  20403. if ( scatteringNode ) {
  20404. scatteringDensity.mulAssign( scatteringNode );
  20405. }
  20406. // beer's law
  20407. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  20408. transmittance.mulAssign( falloff );
  20409. // move along the ray
  20410. distTravelled.addAssign( stepSize );
  20411. } );
  20412. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  20413. }
  20414. scatteringLight( lightColor, builder ) {
  20415. const sceneDepthNode = builder.context.sceneDepthNode;
  20416. if ( sceneDepthNode ) {
  20417. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  20418. scatteringDensity.addAssign( lightColor );
  20419. } );
  20420. } else {
  20421. scatteringDensity.addAssign( lightColor );
  20422. }
  20423. }
  20424. direct( { lightNode, lightColor }, builder ) {
  20425. // Ignore lights with infinite distance
  20426. if ( lightNode.light.distance === undefined ) return;
  20427. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  20428. const directLight = lightColor.xyz.toVar();
  20429. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  20430. this.scatteringLight( directLight, builder );
  20431. }
  20432. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  20433. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  20434. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  20435. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  20436. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  20437. const P = builder.context.positionView;
  20438. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  20439. this.scatteringLight( directLight, builder );
  20440. }
  20441. finish( builder ) {
  20442. builder.context.outgoingLight.assign( outgoingRayLight );
  20443. }
  20444. }
  20445. /**
  20446. * Volume node material.
  20447. *
  20448. * @augments NodeMaterial
  20449. */
  20450. class VolumeNodeMaterial extends NodeMaterial {
  20451. static get type() {
  20452. return 'VolumeNodeMaterial';
  20453. }
  20454. /**
  20455. * Constructs a new volume node material.
  20456. *
  20457. * @param {Object} [parameters] - The configuration parameter.
  20458. */
  20459. constructor( parameters ) {
  20460. super();
  20461. /**
  20462. * This flag can be used for type testing.
  20463. *
  20464. * @type {boolean}
  20465. * @readonly
  20466. * @default true
  20467. */
  20468. this.isVolumeNodeMaterial = true;
  20469. /**
  20470. * Number of steps used for raymarching.
  20471. *
  20472. * @type {number}
  20473. * @default 25
  20474. */
  20475. this.steps = 25;
  20476. /**
  20477. * Offsets the distance a ray has been traveled through a volume.
  20478. * Can be used to implement dithering to reduce banding.
  20479. *
  20480. * @type {Node<float>}
  20481. * @default null
  20482. */
  20483. this.offsetNode = null;
  20484. /**
  20485. * Node used for scattering calculations.
  20486. *
  20487. * @type {Function|FunctionNode<vec4>}
  20488. * @default null
  20489. */
  20490. this.scatteringNode = null;
  20491. this.lights = true;
  20492. this.transparent = true;
  20493. this.side = BackSide;
  20494. this.depthTest = false;
  20495. this.depthWrite = false;
  20496. this.setValues( parameters );
  20497. }
  20498. setupLightingModel() {
  20499. return new VolumetricLightingModel();
  20500. }
  20501. }
  20502. /**
  20503. * This module manages the internal animation loop of the renderer.
  20504. *
  20505. * @private
  20506. */
  20507. class Animation {
  20508. /**
  20509. * Constructs a new animation loop management component.
  20510. *
  20511. * @param {Renderer} renderer - A reference to the main renderer.
  20512. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  20513. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20514. */
  20515. constructor( renderer, nodes, info ) {
  20516. /**
  20517. * A reference to the main renderer.
  20518. *
  20519. * @type {Renderer}
  20520. */
  20521. this.renderer = renderer;
  20522. /**
  20523. * Renderer component for managing nodes related logic.
  20524. *
  20525. * @type {NodeManager}
  20526. */
  20527. this.nodes = nodes;
  20528. /**
  20529. * Renderer component for managing metrics and monitoring data.
  20530. *
  20531. * @type {Info}
  20532. */
  20533. this.info = info;
  20534. /**
  20535. * A reference to the context from `requestAnimationFrame()` can
  20536. * be called (usually `window`).
  20537. *
  20538. * @type {?(Window|XRSession)}
  20539. */
  20540. this._context = typeof self !== 'undefined' ? self : null;
  20541. /**
  20542. * The user-defined animation loop.
  20543. *
  20544. * @type {?Function}
  20545. * @default null
  20546. */
  20547. this._animationLoop = null;
  20548. /**
  20549. * The requestId which is returned from the `requestAnimationFrame()` call.
  20550. * Can be used to cancel the stop the animation loop.
  20551. *
  20552. * @type {?number}
  20553. * @default null
  20554. */
  20555. this._requestId = null;
  20556. }
  20557. /**
  20558. * Starts the internal animation loop.
  20559. */
  20560. start() {
  20561. const update = ( time, xrFrame ) => {
  20562. this._requestId = this._context.requestAnimationFrame( update );
  20563. if ( this.info.autoReset === true ) this.info.reset();
  20564. this.nodes.nodeFrame.update();
  20565. this.info.frame = this.nodes.nodeFrame.frameId;
  20566. this.renderer._inspector.begin();
  20567. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  20568. this.renderer._inspector.finish();
  20569. };
  20570. update();
  20571. }
  20572. /**
  20573. * Stops the internal animation loop.
  20574. */
  20575. stop() {
  20576. if ( this._context !== null ) this._context.cancelAnimationFrame( this._requestId );
  20577. this._requestId = null;
  20578. }
  20579. /**
  20580. * Returns the user-level animation loop.
  20581. *
  20582. * @return {?Function} The animation loop.
  20583. */
  20584. getAnimationLoop() {
  20585. return this._animationLoop;
  20586. }
  20587. /**
  20588. * Defines the user-level animation loop.
  20589. *
  20590. * @param {?Function} callback - The animation loop.
  20591. */
  20592. setAnimationLoop( callback ) {
  20593. this._animationLoop = callback;
  20594. }
  20595. /**
  20596. * Returns the animation context.
  20597. *
  20598. * @return {Window|XRSession} The animation context.
  20599. */
  20600. getContext() {
  20601. return this._context;
  20602. }
  20603. /**
  20604. * Defines the context in which `requestAnimationFrame()` is executed.
  20605. *
  20606. * @param {Window|XRSession} context - The context to set.
  20607. */
  20608. setContext( context ) {
  20609. this._context = context;
  20610. }
  20611. /**
  20612. * Frees all internal resources and stops the animation loop.
  20613. */
  20614. dispose() {
  20615. this.stop();
  20616. }
  20617. }
  20618. /**
  20619. * Data structure for the renderer. It allows defining values
  20620. * with chained, hierarchical keys. Keys are meant to be
  20621. * objects since the module internally works with Weak Maps
  20622. * for performance reasons.
  20623. *
  20624. * @private
  20625. */
  20626. class ChainMap {
  20627. /**
  20628. * Constructs a new Chain Map.
  20629. */
  20630. constructor() {
  20631. /**
  20632. * A map of Weak Maps by their key length.
  20633. *
  20634. * @type {Object<number, WeakMap>}
  20635. */
  20636. this.weakMaps = {};
  20637. }
  20638. /**
  20639. * Returns the Weak Map for the given keys.
  20640. *
  20641. * @param {Array<Object>} keys - List of keys.
  20642. * @return {WeakMap} The weak map.
  20643. */
  20644. _getWeakMap( keys ) {
  20645. const length = keys.length;
  20646. let weakMap = this.weakMaps[ length ];
  20647. if ( weakMap === undefined ) {
  20648. weakMap = new WeakMap();
  20649. this.weakMaps[ length ] = weakMap;
  20650. }
  20651. return weakMap;
  20652. }
  20653. /**
  20654. * Returns the value for the given array of keys.
  20655. *
  20656. * @param {Array<Object>} keys - List of keys.
  20657. * @return {any} The value. Returns `undefined` if no value was found.
  20658. */
  20659. get( keys ) {
  20660. let map = this._getWeakMap( keys );
  20661. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20662. map = map.get( keys[ i ] );
  20663. if ( map === undefined ) return undefined;
  20664. }
  20665. return map.get( keys[ keys.length - 1 ] );
  20666. }
  20667. /**
  20668. * Sets the value for the given keys.
  20669. *
  20670. * @param {Array<Object>} keys - List of keys.
  20671. * @param {any} value - The value to set.
  20672. * @return {ChainMap} A reference to this Chain Map.
  20673. */
  20674. set( keys, value ) {
  20675. let map = this._getWeakMap( keys );
  20676. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20677. const key = keys[ i ];
  20678. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  20679. map = map.get( key );
  20680. }
  20681. map.set( keys[ keys.length - 1 ], value );
  20682. return this;
  20683. }
  20684. /**
  20685. * Deletes a value for the given keys.
  20686. *
  20687. * @param {Array<Object>} keys - The keys.
  20688. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  20689. */
  20690. delete( keys ) {
  20691. let map = this._getWeakMap( keys );
  20692. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20693. map = map.get( keys[ i ] );
  20694. if ( map === undefined ) return false;
  20695. }
  20696. return map.delete( keys[ keys.length - 1 ] );
  20697. }
  20698. }
  20699. let _id$a = 0;
  20700. function getKeys( obj ) {
  20701. const keys = Object.keys( obj );
  20702. let proto = Object.getPrototypeOf( obj );
  20703. while ( proto ) {
  20704. const descriptors = Object.getOwnPropertyDescriptors( proto );
  20705. for ( const key in descriptors ) {
  20706. if ( descriptors[ key ] !== undefined ) {
  20707. const descriptor = descriptors[ key ];
  20708. if ( descriptor && typeof descriptor.get === 'function' ) {
  20709. keys.push( key );
  20710. }
  20711. }
  20712. }
  20713. proto = Object.getPrototypeOf( proto );
  20714. }
  20715. return keys;
  20716. }
  20717. /**
  20718. * A render object is the renderer's representation of single entity that gets drawn
  20719. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  20720. * scene since render objects also depend from the used material, the current render context
  20721. * and the current scene's lighting.
  20722. *
  20723. * In general, the basic process of the renderer is:
  20724. *
  20725. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  20726. * - Process the render lists by calling one or more render commands for each render item.
  20727. * - For each render command, request a render object and perform the draw.
  20728. *
  20729. * The module provides an interface to get data required for the draw command like the actual
  20730. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  20731. * creating render objects should only be done when necessary.
  20732. *
  20733. * @private
  20734. */
  20735. class RenderObject {
  20736. /**
  20737. * Constructs a new render object.
  20738. *
  20739. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  20740. * @param {Geometries} geometries - Renderer component for managing geometries.
  20741. * @param {Renderer} renderer - The renderer.
  20742. * @param {Object3D} object - The 3D object.
  20743. * @param {Material} material - The 3D object's material.
  20744. * @param {Scene} scene - The scene the 3D object belongs to.
  20745. * @param {Camera} camera - The camera the object should be rendered with.
  20746. * @param {LightsNode} lightsNode - The lights node.
  20747. * @param {RenderContext} renderContext - The render context.
  20748. * @param {ClippingContext} clippingContext - The clipping context.
  20749. */
  20750. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  20751. this.id = _id$a ++;
  20752. /**
  20753. * Renderer component for managing nodes related logic.
  20754. *
  20755. * @type {NodeManager}
  20756. * @private
  20757. */
  20758. this._nodes = nodes;
  20759. /**
  20760. * Renderer component for managing geometries.
  20761. *
  20762. * @type {Geometries}
  20763. * @private
  20764. */
  20765. this._geometries = geometries;
  20766. /**
  20767. * The renderer.
  20768. *
  20769. * @type {Renderer}
  20770. */
  20771. this.renderer = renderer;
  20772. /**
  20773. * The 3D object.
  20774. *
  20775. * @type {Object3D}
  20776. */
  20777. this.object = object;
  20778. /**
  20779. * The 3D object's material.
  20780. *
  20781. * @type {Material}
  20782. */
  20783. this.material = material;
  20784. /**
  20785. * The scene the 3D object belongs to.
  20786. *
  20787. * @type {Scene}
  20788. */
  20789. this.scene = scene;
  20790. /**
  20791. * The camera the 3D object should be rendered with.
  20792. *
  20793. * @type {Camera}
  20794. */
  20795. this.camera = camera;
  20796. /**
  20797. * The lights node.
  20798. *
  20799. * @type {LightsNode}
  20800. */
  20801. this.lightsNode = lightsNode;
  20802. /**
  20803. * The render context.
  20804. *
  20805. * @type {RenderContext}
  20806. */
  20807. this.context = renderContext;
  20808. /**
  20809. * The 3D object's geometry.
  20810. *
  20811. * @type {BufferGeometry}
  20812. */
  20813. this.geometry = object.geometry;
  20814. /**
  20815. * The render object's version.
  20816. *
  20817. * @type {number}
  20818. */
  20819. this.version = material.version;
  20820. /**
  20821. * The draw range of the geometry.
  20822. *
  20823. * @type {?Object}
  20824. * @default null
  20825. */
  20826. this.drawRange = null;
  20827. /**
  20828. * An array holding the buffer attributes
  20829. * of the render object. This entails attribute
  20830. * definitions on geometry and node level.
  20831. *
  20832. * @type {?Array<BufferAttribute>}
  20833. * @default null
  20834. */
  20835. this.attributes = null;
  20836. /**
  20837. * An object holding the version of the
  20838. * attributes. The keys are the attribute names
  20839. * and the values are the attribute versions.
  20840. *
  20841. * @type {?Object<string, number>}
  20842. * @default null
  20843. */
  20844. this.attributesId = null;
  20845. /**
  20846. * A reference to a render pipeline the render
  20847. * object is processed with.
  20848. *
  20849. * @type {RenderPipeline}
  20850. * @default null
  20851. */
  20852. this.pipeline = null;
  20853. /**
  20854. * Only relevant for objects using
  20855. * multiple materials. This represents a group entry
  20856. * from the respective `BufferGeometry`.
  20857. *
  20858. * @type {?{start: number, count: number}}
  20859. * @default null
  20860. */
  20861. this.group = null;
  20862. /**
  20863. * An array holding the vertex buffers which can
  20864. * be buffer attributes but also interleaved buffers.
  20865. *
  20866. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  20867. * @default null
  20868. */
  20869. this.vertexBuffers = null;
  20870. /**
  20871. * The parameters for the draw command.
  20872. *
  20873. * @type {?Object}
  20874. * @default null
  20875. */
  20876. this.drawParams = null;
  20877. /**
  20878. * If this render object is used inside a render bundle,
  20879. * this property points to the respective bundle group.
  20880. *
  20881. * @type {?BundleGroup}
  20882. * @default null
  20883. */
  20884. this.bundle = null;
  20885. /**
  20886. * The clipping context.
  20887. *
  20888. * @type {ClippingContext}
  20889. */
  20890. this.clippingContext = clippingContext;
  20891. /**
  20892. * The clipping context's cache key.
  20893. *
  20894. * @type {string}
  20895. */
  20896. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  20897. /**
  20898. * The initial node cache key.
  20899. *
  20900. * @type {number}
  20901. */
  20902. this.initialNodesCacheKey = this.getDynamicCacheKey();
  20903. /**
  20904. * The initial cache key.
  20905. *
  20906. * @type {number}
  20907. */
  20908. this.initialCacheKey = this.getCacheKey();
  20909. /**
  20910. * The node builder state.
  20911. *
  20912. * @type {?NodeBuilderState}
  20913. * @private
  20914. * @default null
  20915. */
  20916. this._nodeBuilderState = null;
  20917. /**
  20918. * An array of bindings.
  20919. *
  20920. * @type {?Array<BindGroup>}
  20921. * @private
  20922. * @default null
  20923. */
  20924. this._bindings = null;
  20925. /**
  20926. * Reference to the node material observer.
  20927. *
  20928. * @type {?NodeMaterialObserver}
  20929. * @private
  20930. * @default null
  20931. */
  20932. this._monitor = null;
  20933. /**
  20934. * An event listener which is defined by `RenderObjects`. It performs
  20935. * clean up tasks when `dispose()` on this render object.
  20936. *
  20937. * @method
  20938. */
  20939. this.onDispose = null;
  20940. /**
  20941. * This flag can be used for type testing.
  20942. *
  20943. * @type {boolean}
  20944. * @readonly
  20945. * @default true
  20946. */
  20947. this.isRenderObject = true;
  20948. /**
  20949. * An event listener which is executed when `dispose()` is called on
  20950. * the material of this render object.
  20951. *
  20952. * @method
  20953. */
  20954. this.onMaterialDispose = () => {
  20955. this.dispose();
  20956. };
  20957. /**
  20958. * An event listener which is executed when `dispose()` is called on
  20959. * the geometry of this render object.
  20960. *
  20961. * @method
  20962. */
  20963. this.onGeometryDispose = () => {
  20964. // clear geometry cache attributes
  20965. this.attributes = null;
  20966. this.attributesId = null;
  20967. };
  20968. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  20969. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  20970. }
  20971. /**
  20972. * Updates the clipping context.
  20973. *
  20974. * @param {ClippingContext} context - The clipping context to set.
  20975. */
  20976. updateClipping( context ) {
  20977. this.clippingContext = context;
  20978. }
  20979. /**
  20980. * Whether the clipping requires an update or not.
  20981. *
  20982. * @type {boolean}
  20983. * @readonly
  20984. */
  20985. get clippingNeedsUpdate() {
  20986. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  20987. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  20988. return true;
  20989. }
  20990. /**
  20991. * The number of clipping planes defined in context of hardware clipping.
  20992. *
  20993. * @type {number}
  20994. * @readonly
  20995. */
  20996. get hardwareClippingPlanes() {
  20997. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  20998. }
  20999. /**
  21000. * Returns the node builder state of this render object.
  21001. *
  21002. * @return {NodeBuilderState} The node builder state.
  21003. */
  21004. getNodeBuilderState() {
  21005. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  21006. }
  21007. /**
  21008. * Returns the node material observer of this render object.
  21009. *
  21010. * @return {NodeMaterialObserver} The node material observer.
  21011. */
  21012. getMonitor() {
  21013. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  21014. }
  21015. /**
  21016. * Returns an array of bind groups of this render object.
  21017. *
  21018. * @return {Array<BindGroup>} The bindings.
  21019. */
  21020. getBindings() {
  21021. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  21022. }
  21023. /**
  21024. * Returns a binding group by group name of this render object.
  21025. *
  21026. * @param {string} name - The name of the binding group.
  21027. * @return {?BindGroup} The bindings.
  21028. */
  21029. getBindingGroup( name ) {
  21030. for ( const bindingGroup of this.getBindings() ) {
  21031. if ( bindingGroup.name === name ) {
  21032. return bindingGroup;
  21033. }
  21034. }
  21035. }
  21036. /**
  21037. * Returns the index of the render object's geometry.
  21038. *
  21039. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  21040. */
  21041. getIndex() {
  21042. return this._geometries.getIndex( this );
  21043. }
  21044. /**
  21045. * Returns the indirect buffer attribute.
  21046. *
  21047. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  21048. */
  21049. getIndirect() {
  21050. return this._geometries.getIndirect( this );
  21051. }
  21052. /**
  21053. * Returns the byte offset into the indirect attribute buffer.
  21054. *
  21055. * @return {number|Array<number>} The byte offset into the indirect attribute buffer.
  21056. */
  21057. getIndirectOffset() {
  21058. return this._geometries.getIndirectOffset( this );
  21059. }
  21060. /**
  21061. * Returns an array that acts as a key for identifying the render object in a chain map.
  21062. *
  21063. * @return {Array<Object>} An array with object references.
  21064. */
  21065. getChainArray() {
  21066. return [ this.object, this.material, this.context, this.lightsNode ];
  21067. }
  21068. /**
  21069. * This method is used when the geometry of a 3D object has been exchanged and the
  21070. * respective render object now requires an update.
  21071. *
  21072. * @param {BufferGeometry} geometry - The geometry to set.
  21073. */
  21074. setGeometry( geometry ) {
  21075. this.geometry = geometry;
  21076. this.attributes = null;
  21077. this.attributesId = null;
  21078. }
  21079. /**
  21080. * Returns the buffer attributes of the render object. The returned array holds
  21081. * attribute definitions on geometry and node level.
  21082. *
  21083. * @return {Array<BufferAttribute>} An array with buffer attributes.
  21084. */
  21085. getAttributes() {
  21086. if ( this.attributes !== null ) return this.attributes;
  21087. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  21088. const geometry = this.geometry;
  21089. const attributes = [];
  21090. const vertexBuffers = new Set();
  21091. const attributesId = {};
  21092. for ( const nodeAttribute of nodeAttributes ) {
  21093. let attribute;
  21094. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  21095. // node attribute
  21096. attribute = nodeAttribute.node.attribute;
  21097. } else {
  21098. // geometry attribute
  21099. attribute = geometry.getAttribute( nodeAttribute.name );
  21100. if ( attribute !== undefined ) {
  21101. attributesId[ nodeAttribute.name ] = attribute.id;
  21102. }
  21103. }
  21104. if ( attribute === undefined ) continue;
  21105. attributes.push( attribute );
  21106. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  21107. vertexBuffers.add( bufferAttribute );
  21108. }
  21109. this.attributes = attributes;
  21110. this.attributesId = attributesId;
  21111. this.vertexBuffers = Array.from( vertexBuffers.values() );
  21112. return attributes;
  21113. }
  21114. /**
  21115. * Returns the vertex buffers of the render object.
  21116. *
  21117. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  21118. */
  21119. getVertexBuffers() {
  21120. if ( this.vertexBuffers === null ) this.getAttributes();
  21121. return this.vertexBuffers;
  21122. }
  21123. /**
  21124. * Returns the draw parameters for the render object.
  21125. *
  21126. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  21127. */
  21128. getDrawParameters() {
  21129. const { object, material, geometry, group, drawRange } = this;
  21130. const drawParams = this.drawParams || ( this.drawParams = {
  21131. vertexCount: 0,
  21132. firstVertex: 0,
  21133. instanceCount: 0,
  21134. firstInstance: 0
  21135. } );
  21136. const index = this.getIndex();
  21137. const hasIndex = ( index !== null );
  21138. let instanceCount = 1;
  21139. if ( geometry.isInstancedBufferGeometry === true ) {
  21140. instanceCount = geometry.instanceCount;
  21141. } else if ( object.count !== undefined ) {
  21142. instanceCount = Math.max( 0, object.count );
  21143. }
  21144. if ( instanceCount === 0 ) return null;
  21145. drawParams.instanceCount = instanceCount;
  21146. if ( object.isBatchedMesh === true ) return drawParams;
  21147. let rangeFactor = 1;
  21148. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  21149. rangeFactor = 2;
  21150. }
  21151. let firstVertex = drawRange.start * rangeFactor;
  21152. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  21153. if ( group !== null ) {
  21154. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  21155. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  21156. }
  21157. const position = geometry.attributes.position;
  21158. let itemCount = Infinity;
  21159. if ( hasIndex ) {
  21160. itemCount = index.count;
  21161. } else if ( position !== undefined && position !== null ) {
  21162. itemCount = position.count;
  21163. }
  21164. firstVertex = Math.max( firstVertex, 0 );
  21165. lastVertex = Math.min( lastVertex, itemCount );
  21166. const count = lastVertex - firstVertex;
  21167. if ( count < 0 || count === Infinity ) return null;
  21168. drawParams.vertexCount = count;
  21169. drawParams.firstVertex = firstVertex;
  21170. return drawParams;
  21171. }
  21172. /**
  21173. * Returns the render object's geometry cache key.
  21174. *
  21175. * The geometry cache key is part of the material cache key.
  21176. *
  21177. * @return {string} The geometry cache key.
  21178. */
  21179. getGeometryCacheKey() {
  21180. const { geometry } = this;
  21181. let cacheKey = '';
  21182. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  21183. const attribute = geometry.attributes[ name ];
  21184. cacheKey += name + ',';
  21185. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  21186. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  21187. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  21188. if ( attribute.normalized ) cacheKey += 'n,';
  21189. }
  21190. // structural equality isn't sufficient for morph targets since the
  21191. // data are maintained in textures. only if the targets are all equal
  21192. // the texture and thus the instance of `MorphNode` can be shared.
  21193. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  21194. const targets = geometry.morphAttributes[ name ];
  21195. cacheKey += 'morph-' + name + ',';
  21196. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  21197. const attribute = targets[ i ];
  21198. cacheKey += attribute.id + ',';
  21199. }
  21200. }
  21201. if ( geometry.index ) {
  21202. cacheKey += 'index,';
  21203. }
  21204. return cacheKey;
  21205. }
  21206. /**
  21207. * Returns the render object's material cache key.
  21208. *
  21209. * The material cache key is part of the render object cache key.
  21210. *
  21211. * @return {number} The material cache key.
  21212. */
  21213. getMaterialCacheKey() {
  21214. const { object, material, renderer } = this;
  21215. let cacheKey = material.customProgramCacheKey();
  21216. for ( const property of getKeys( material ) ) {
  21217. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  21218. const value = material[ property ];
  21219. let valueKey;
  21220. if ( value !== null ) {
  21221. // some material values require a formatting
  21222. const type = typeof value;
  21223. if ( type === 'number' ) {
  21224. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  21225. } else if ( type === 'object' ) {
  21226. valueKey = '{';
  21227. if ( value.isTexture ) {
  21228. valueKey += value.mapping;
  21229. // WebGPU must honor the sampler data because they are part of the bindings
  21230. if ( renderer.backend.isWebGPUBackend === true ) {
  21231. valueKey += value.magFilter;
  21232. valueKey += value.minFilter;
  21233. valueKey += value.wrapS;
  21234. valueKey += value.wrapT;
  21235. valueKey += value.wrapR;
  21236. }
  21237. }
  21238. valueKey += '}';
  21239. } else {
  21240. valueKey = String( value );
  21241. }
  21242. } else {
  21243. valueKey = String( value );
  21244. }
  21245. cacheKey += /*property + ':' +*/ valueKey + ',';
  21246. }
  21247. cacheKey += this.clippingContextCacheKey + ',';
  21248. if ( object.geometry ) {
  21249. cacheKey += this.getGeometryCacheKey();
  21250. }
  21251. if ( object.skeleton ) {
  21252. cacheKey += object.skeleton.bones.length + ',';
  21253. }
  21254. if ( object.isBatchedMesh ) {
  21255. cacheKey += object._matricesTexture.uuid + ',';
  21256. if ( object._colorsTexture !== null ) {
  21257. cacheKey += object._colorsTexture.uuid + ',';
  21258. }
  21259. }
  21260. if ( object.isInstancedMesh || object.count > 1 || Array.isArray( object.morphTargetInfluences ) ) {
  21261. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  21262. cacheKey += object.uuid + ',';
  21263. }
  21264. cacheKey += this.context.id + ',';
  21265. cacheKey += object.receiveShadow + ',';
  21266. return hashString( cacheKey );
  21267. }
  21268. /**
  21269. * Whether the geometry requires an update or not.
  21270. *
  21271. * @type {boolean}
  21272. * @readonly
  21273. */
  21274. get needsGeometryUpdate() {
  21275. if ( this.geometry.id !== this.object.geometry.id ) return true;
  21276. if ( this.attributes !== null ) {
  21277. const attributesId = this.attributesId;
  21278. for ( const name in attributesId ) {
  21279. const attribute = this.geometry.getAttribute( name );
  21280. if ( attribute === undefined || attributesId[ name ] !== attribute.id ) {
  21281. return true;
  21282. }
  21283. }
  21284. }
  21285. return false;
  21286. }
  21287. /**
  21288. * Whether the render object requires an update or not.
  21289. *
  21290. * Note: There are two distinct places where render objects are checked for an update.
  21291. *
  21292. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  21293. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  21294. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  21295. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  21296. * a need for a refresh due to material, geometry or object related value changes.
  21297. *
  21298. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  21299. * that performs the 'needsUpdate' check.
  21300. *
  21301. * @type {boolean}
  21302. * @readonly
  21303. */
  21304. get needsUpdate() {
  21305. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  21306. }
  21307. /**
  21308. * Returns the dynamic cache key which represents a key that is computed per draw command.
  21309. *
  21310. * @return {number} The cache key.
  21311. */
  21312. getDynamicCacheKey() {
  21313. let cacheKey = 0;
  21314. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  21315. // the renderer is inside a shadow pass.
  21316. if ( this.material.isShadowPassMaterial !== true ) {
  21317. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  21318. }
  21319. if ( this.camera.isArrayCamera ) {
  21320. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  21321. }
  21322. if ( this.object.receiveShadow ) {
  21323. cacheKey = hash$1( cacheKey, 1 );
  21324. }
  21325. cacheKey = hash$1( cacheKey, this.renderer.contextNode.id, this.renderer.contextNode.version );
  21326. return cacheKey;
  21327. }
  21328. /**
  21329. * Returns the render object's cache key.
  21330. *
  21331. * @return {number} The cache key.
  21332. */
  21333. getCacheKey() {
  21334. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  21335. }
  21336. /**
  21337. * Frees internal resources.
  21338. */
  21339. dispose() {
  21340. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  21341. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  21342. this.onDispose();
  21343. }
  21344. }
  21345. const _chainKeys$3 = [];
  21346. /**
  21347. * This module manages the render objects of the renderer.
  21348. *
  21349. * @private
  21350. */
  21351. class RenderObjects {
  21352. /**
  21353. * Constructs a new render object management component.
  21354. *
  21355. * @param {Renderer} renderer - The renderer.
  21356. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  21357. * @param {Geometries} geometries - Renderer component for managing geometries.
  21358. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  21359. * @param {Bindings} bindings - Renderer component for managing bindings.
  21360. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21361. */
  21362. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  21363. /**
  21364. * The renderer.
  21365. *
  21366. * @type {Renderer}
  21367. */
  21368. this.renderer = renderer;
  21369. /**
  21370. * Renderer component for managing nodes related logic.
  21371. *
  21372. * @type {NodeManager}
  21373. */
  21374. this.nodes = nodes;
  21375. /**
  21376. * Renderer component for managing geometries.
  21377. *
  21378. * @type {Geometries}
  21379. */
  21380. this.geometries = geometries;
  21381. /**
  21382. * Renderer component for managing pipelines.
  21383. *
  21384. * @type {Pipelines}
  21385. */
  21386. this.pipelines = pipelines;
  21387. /**
  21388. * Renderer component for managing bindings.
  21389. *
  21390. * @type {Bindings}
  21391. */
  21392. this.bindings = bindings;
  21393. /**
  21394. * Renderer component for managing metrics and monitoring data.
  21395. *
  21396. * @type {Info}
  21397. */
  21398. this.info = info;
  21399. /**
  21400. * A dictionary that manages render contexts in chain maps
  21401. * for each pass ID.
  21402. *
  21403. * @type {Object<string,ChainMap>}
  21404. */
  21405. this.chainMaps = {};
  21406. }
  21407. /**
  21408. * Returns a render object for the given object and state data.
  21409. *
  21410. * @param {Object3D} object - The 3D object.
  21411. * @param {Material} material - The 3D object's material.
  21412. * @param {Scene} scene - The scene the 3D object belongs to.
  21413. * @param {Camera} camera - The camera the 3D object should be rendered with.
  21414. * @param {LightsNode} lightsNode - The lights node.
  21415. * @param {RenderContext} renderContext - The render context.
  21416. * @param {ClippingContext} clippingContext - The clipping context.
  21417. * @param {string} [passId] - An optional ID for identifying the pass.
  21418. * @return {RenderObject} The render object.
  21419. */
  21420. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  21421. const chainMap = this.getChainMap( passId );
  21422. // set chain keys
  21423. _chainKeys$3[ 0 ] = object;
  21424. _chainKeys$3[ 1 ] = material;
  21425. _chainKeys$3[ 2 ] = renderContext;
  21426. _chainKeys$3[ 3 ] = lightsNode;
  21427. //
  21428. let renderObject = chainMap.get( _chainKeys$3 );
  21429. if ( renderObject === undefined ) {
  21430. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  21431. chainMap.set( _chainKeys$3, renderObject );
  21432. } else {
  21433. // update references
  21434. renderObject.camera = camera;
  21435. //
  21436. renderObject.updateClipping( clippingContext );
  21437. if ( renderObject.needsGeometryUpdate ) {
  21438. renderObject.setGeometry( object.geometry );
  21439. }
  21440. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  21441. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  21442. renderObject.dispose();
  21443. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  21444. } else {
  21445. renderObject.version = material.version;
  21446. }
  21447. }
  21448. }
  21449. // reset chain array
  21450. _chainKeys$3[ 0 ] = null;
  21451. _chainKeys$3[ 1 ] = null;
  21452. _chainKeys$3[ 2 ] = null;
  21453. _chainKeys$3[ 3 ] = null;
  21454. //
  21455. return renderObject;
  21456. }
  21457. /**
  21458. * Returns a chain map for the given pass ID.
  21459. *
  21460. * @param {string} [passId='default'] - The pass ID.
  21461. * @return {ChainMap} The chain map.
  21462. */
  21463. getChainMap( passId = 'default' ) {
  21464. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  21465. }
  21466. /**
  21467. * Frees internal resources.
  21468. */
  21469. dispose() {
  21470. this.chainMaps = {};
  21471. }
  21472. /**
  21473. * Factory method for creating render objects with the given list of parameters.
  21474. *
  21475. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  21476. * @param {Geometries} geometries - Renderer component for managing geometries.
  21477. * @param {Renderer} renderer - The renderer.
  21478. * @param {Object3D} object - The 3D object.
  21479. * @param {Material} material - The object's material.
  21480. * @param {Scene} scene - The scene the 3D object belongs to.
  21481. * @param {Camera} camera - The camera the object should be rendered with.
  21482. * @param {LightsNode} lightsNode - The lights node.
  21483. * @param {RenderContext} renderContext - The render context.
  21484. * @param {ClippingContext} clippingContext - The clipping context.
  21485. * @param {string} [passId] - An optional ID for identifying the pass.
  21486. * @return {RenderObject} The render object.
  21487. */
  21488. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  21489. const chainMap = this.getChainMap( passId );
  21490. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  21491. renderObject.onDispose = () => {
  21492. this.pipelines.delete( renderObject );
  21493. this.bindings.deleteForRender( renderObject );
  21494. this.nodes.delete( renderObject );
  21495. chainMap.delete( renderObject.getChainArray() );
  21496. };
  21497. return renderObject;
  21498. }
  21499. }
  21500. /**
  21501. * Data structure for the renderer. It is intended to manage
  21502. * data of objects in dictionaries.
  21503. *
  21504. * @private
  21505. */
  21506. class DataMap {
  21507. /**
  21508. * Constructs a new data map.
  21509. */
  21510. constructor() {
  21511. /**
  21512. * `DataMap` internally uses a weak map
  21513. * to manage its data.
  21514. *
  21515. * @type {WeakMap<Object, Object>}
  21516. */
  21517. this.data = new WeakMap();
  21518. }
  21519. /**
  21520. * Returns the dictionary for the given object.
  21521. *
  21522. * @param {Object} object - The object.
  21523. * @return {Object} The dictionary.
  21524. */
  21525. get( object ) {
  21526. let map = this.data.get( object );
  21527. if ( map === undefined ) {
  21528. map = {};
  21529. this.data.set( object, map );
  21530. }
  21531. return map;
  21532. }
  21533. /**
  21534. * Deletes the dictionary for the given object.
  21535. *
  21536. * @param {Object} object - The object.
  21537. * @return {?Object} The deleted dictionary.
  21538. */
  21539. delete( object ) {
  21540. let map = null;
  21541. if ( this.data.has( object ) ) {
  21542. map = this.data.get( object );
  21543. this.data.delete( object );
  21544. }
  21545. return map;
  21546. }
  21547. /**
  21548. * Returns `true` if the given object has a dictionary defined.
  21549. *
  21550. * @param {Object} object - The object to test.
  21551. * @return {boolean} Whether a dictionary is defined or not.
  21552. */
  21553. has( object ) {
  21554. return this.data.has( object );
  21555. }
  21556. /**
  21557. * Frees internal resources.
  21558. */
  21559. dispose() {
  21560. this.data = new WeakMap();
  21561. }
  21562. }
  21563. const AttributeType = {
  21564. VERTEX: 1,
  21565. INDEX: 2,
  21566. STORAGE: 3,
  21567. INDIRECT: 4
  21568. };
  21569. // size of a chunk in bytes (STD140 layout)
  21570. const GPU_CHUNK_BYTES = 16;
  21571. // @TODO: Move to src/constants.js
  21572. const BlendColorFactor = 211;
  21573. const OneMinusBlendColorFactor = 212;
  21574. /**
  21575. * This renderer module manages geometry attributes.
  21576. *
  21577. * @private
  21578. * @augments DataMap
  21579. */
  21580. class Attributes extends DataMap {
  21581. /**
  21582. * Constructs a new attribute management component.
  21583. *
  21584. * @param {Backend} backend - The renderer's backend.
  21585. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21586. */
  21587. constructor( backend, info ) {
  21588. super();
  21589. /**
  21590. * The renderer's backend.
  21591. *
  21592. * @type {Backend}
  21593. */
  21594. this.backend = backend;
  21595. /**
  21596. * Renderer component for managing metrics and monitoring data.
  21597. *
  21598. * @type {Info}
  21599. */
  21600. this.info = info;
  21601. }
  21602. /**
  21603. * Deletes the data for the given attribute.
  21604. *
  21605. * @param {BufferAttribute} attribute - The attribute.
  21606. * @return {?Object} The deleted attribute data.
  21607. */
  21608. delete( attribute ) {
  21609. const attributeData = super.delete( attribute );
  21610. if ( attributeData !== null ) {
  21611. this.backend.destroyAttribute( attribute );
  21612. this.info.destroyAttribute( attribute );
  21613. }
  21614. return attributeData;
  21615. }
  21616. /**
  21617. * Updates the given attribute. This method creates attribute buffers
  21618. * for new attributes and updates data for existing ones.
  21619. *
  21620. * @param {BufferAttribute} attribute - The attribute to update.
  21621. * @param {number} type - The attribute type.
  21622. */
  21623. update( attribute, type ) {
  21624. const data = this.get( attribute );
  21625. if ( data.version === undefined ) {
  21626. if ( type === AttributeType.VERTEX ) {
  21627. this.backend.createAttribute( attribute );
  21628. this.info.createAttribute( attribute );
  21629. } else if ( type === AttributeType.INDEX ) {
  21630. this.backend.createIndexAttribute( attribute );
  21631. this.info.createIndexAttribute( attribute );
  21632. } else if ( type === AttributeType.STORAGE ) {
  21633. this.backend.createStorageAttribute( attribute );
  21634. this.info.createStorageAttribute( attribute );
  21635. } else if ( type === AttributeType.INDIRECT ) {
  21636. this.backend.createIndirectStorageAttribute( attribute );
  21637. this.info.createIndirectStorageAttribute( attribute );
  21638. }
  21639. data.version = this._getBufferAttribute( attribute ).version;
  21640. } else {
  21641. const bufferAttribute = this._getBufferAttribute( attribute );
  21642. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  21643. this.backend.updateAttribute( attribute );
  21644. data.version = bufferAttribute.version;
  21645. }
  21646. }
  21647. }
  21648. /**
  21649. * Utility method for handling interleaved buffer attributes correctly.
  21650. * To process them, their `InterleavedBuffer` is returned.
  21651. *
  21652. * @param {BufferAttribute} attribute - The attribute.
  21653. * @return {BufferAttribute|InterleavedBuffer}
  21654. */
  21655. _getBufferAttribute( attribute ) {
  21656. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  21657. return attribute;
  21658. }
  21659. }
  21660. /**
  21661. * Returns the wireframe version for the given geometry.
  21662. *
  21663. * @private
  21664. * @function
  21665. * @param {BufferGeometry} geometry - The geometry.
  21666. * @return {number} The version.
  21667. */
  21668. function getWireframeVersion( geometry ) {
  21669. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  21670. }
  21671. /**
  21672. * Returns the wireframe ID for the given geometry.
  21673. *
  21674. * @private
  21675. * @function
  21676. * @param {BufferGeometry} geometry - The geometry.
  21677. * @return {number} The ID.
  21678. */
  21679. function getWireframeId( geometry ) {
  21680. return ( geometry.index !== null ) ? geometry.index.id : geometry.attributes.position.id;
  21681. }
  21682. /**
  21683. * Returns a wireframe index attribute for the given geometry.
  21684. *
  21685. * @private
  21686. * @function
  21687. * @param {BufferGeometry} geometry - The geometry.
  21688. * @return {BufferAttribute} The wireframe index attribute.
  21689. */
  21690. function getWireframeIndex( geometry ) {
  21691. const indices = [];
  21692. const geometryIndex = geometry.index;
  21693. const geometryPosition = geometry.attributes.position;
  21694. if ( geometryIndex !== null ) {
  21695. const array = geometryIndex.array;
  21696. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  21697. const a = array[ i + 0 ];
  21698. const b = array[ i + 1 ];
  21699. const c = array[ i + 2 ];
  21700. indices.push( a, b, b, c, c, a );
  21701. }
  21702. } else {
  21703. const array = geometryPosition.array;
  21704. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  21705. const a = i + 0;
  21706. const b = i + 1;
  21707. const c = i + 2;
  21708. indices.push( a, b, b, c, c, a );
  21709. }
  21710. }
  21711. const attribute = new ( geometryPosition.count >= 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  21712. attribute.version = getWireframeVersion( geometry );
  21713. attribute.__id = getWireframeId( geometry );
  21714. return attribute;
  21715. }
  21716. /**
  21717. * This renderer module manages geometries.
  21718. *
  21719. * @private
  21720. * @augments DataMap
  21721. */
  21722. class Geometries extends DataMap {
  21723. /**
  21724. * Constructs a new geometry management component.
  21725. *
  21726. * @param {Attributes} attributes - Renderer component for managing attributes.
  21727. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21728. */
  21729. constructor( attributes, info ) {
  21730. super();
  21731. /**
  21732. * Renderer component for managing attributes.
  21733. *
  21734. * @type {Attributes}
  21735. */
  21736. this.attributes = attributes;
  21737. /**
  21738. * Renderer component for managing metrics and monitoring data.
  21739. *
  21740. * @type {Info}
  21741. */
  21742. this.info = info;
  21743. /**
  21744. * Weak Map for managing attributes for wireframe rendering.
  21745. *
  21746. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  21747. */
  21748. this.wireframes = new WeakMap();
  21749. /**
  21750. * This Weak Map is used to make sure buffer attributes are
  21751. * updated only once per render call.
  21752. *
  21753. * @type {WeakMap<BufferAttribute,number>}
  21754. */
  21755. this.attributeCall = new WeakMap();
  21756. /**
  21757. * Stores the event listeners attached to geometries.
  21758. *
  21759. * @private
  21760. * @type {Map<BufferGeometry,Function>}
  21761. */
  21762. this._geometryDisposeListeners = new Map();
  21763. }
  21764. /**
  21765. * Returns `true` if the given render object has an initialized geometry.
  21766. *
  21767. * @param {RenderObject} renderObject - The render object.
  21768. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  21769. */
  21770. has( renderObject ) {
  21771. const geometry = renderObject.geometry;
  21772. return super.has( geometry ) && this.get( geometry ).initialized === true;
  21773. }
  21774. /**
  21775. * Prepares the geometry of the given render object for rendering.
  21776. *
  21777. * @param {RenderObject} renderObject - The render object.
  21778. */
  21779. updateForRender( renderObject ) {
  21780. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  21781. this.updateAttributes( renderObject );
  21782. }
  21783. /**
  21784. * Initializes the geometry of the given render object.
  21785. *
  21786. * @param {RenderObject} renderObject - The render object.
  21787. */
  21788. initGeometry( renderObject ) {
  21789. const geometry = renderObject.geometry;
  21790. const geometryData = this.get( geometry );
  21791. geometryData.initialized = true;
  21792. this.info.memory.geometries ++;
  21793. const onDispose = () => {
  21794. this.info.memory.geometries --;
  21795. const index = geometry.index;
  21796. const geometryAttributes = renderObject.getAttributes();
  21797. if ( index !== null ) {
  21798. this.attributes.delete( index );
  21799. }
  21800. for ( const geometryAttribute of geometryAttributes ) {
  21801. this.attributes.delete( geometryAttribute );
  21802. }
  21803. const wireframeAttribute = this.wireframes.get( geometry );
  21804. if ( wireframeAttribute !== undefined ) {
  21805. this.attributes.delete( wireframeAttribute );
  21806. }
  21807. geometry.removeEventListener( 'dispose', onDispose );
  21808. this._geometryDisposeListeners.delete( geometry );
  21809. };
  21810. geometry.addEventListener( 'dispose', onDispose );
  21811. // see #31798 why tracking separate remove listeners is required right now
  21812. // TODO: Re-evaluate how onDispose() is managed in this component
  21813. this._geometryDisposeListeners.set( geometry, onDispose );
  21814. }
  21815. /**
  21816. * Updates the geometry attributes of the given render object.
  21817. *
  21818. * @param {RenderObject} renderObject - The render object.
  21819. */
  21820. updateAttributes( renderObject ) {
  21821. // attributes
  21822. const attributes = renderObject.getAttributes();
  21823. for ( const attribute of attributes ) {
  21824. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  21825. this.updateAttribute( attribute, AttributeType.STORAGE );
  21826. } else {
  21827. this.updateAttribute( attribute, AttributeType.VERTEX );
  21828. }
  21829. }
  21830. // indexes
  21831. const index = this.getIndex( renderObject );
  21832. if ( index !== null ) {
  21833. this.updateAttribute( index, AttributeType.INDEX );
  21834. }
  21835. // indirect
  21836. const indirect = renderObject.geometry.indirect;
  21837. if ( indirect !== null ) {
  21838. this.updateAttribute( indirect, AttributeType.INDIRECT );
  21839. }
  21840. }
  21841. /**
  21842. * Updates the given attribute.
  21843. *
  21844. * @param {BufferAttribute} attribute - The attribute to update.
  21845. * @param {number} type - The attribute type.
  21846. */
  21847. updateAttribute( attribute, type ) {
  21848. const callId = this.info.render.calls;
  21849. if ( ! attribute.isInterleavedBufferAttribute ) {
  21850. if ( this.attributeCall.get( attribute ) !== callId ) {
  21851. this.attributes.update( attribute, type );
  21852. this.attributeCall.set( attribute, callId );
  21853. }
  21854. } else {
  21855. if ( this.attributeCall.get( attribute ) === undefined ) {
  21856. this.attributes.update( attribute, type );
  21857. this.attributeCall.set( attribute, callId );
  21858. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  21859. this.attributes.update( attribute, type );
  21860. this.attributeCall.set( attribute.data, callId );
  21861. this.attributeCall.set( attribute, callId );
  21862. }
  21863. }
  21864. }
  21865. /**
  21866. * Returns the indirect buffer attribute of the given render object.
  21867. *
  21868. * @param {RenderObject} renderObject - The render object.
  21869. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  21870. */
  21871. getIndirect( renderObject ) {
  21872. return renderObject.geometry.indirect;
  21873. }
  21874. /**
  21875. * Returns the byte offset into the indirect attribute buffer of the given render object.
  21876. *
  21877. * @param {RenderObject} renderObject - The render object.
  21878. * @return {number} The byte offset into the indirect attribute buffer.
  21879. */
  21880. getIndirectOffset( renderObject ) {
  21881. return renderObject.geometry.indirectOffset;
  21882. }
  21883. /**
  21884. * Returns the index of the given render object's geometry. This is implemented
  21885. * in a method to return a wireframe index if necessary.
  21886. *
  21887. * @param {RenderObject} renderObject - The render object.
  21888. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  21889. */
  21890. getIndex( renderObject ) {
  21891. const { geometry, material } = renderObject;
  21892. let index = geometry.index;
  21893. if ( material.wireframe === true ) {
  21894. const wireframes = this.wireframes;
  21895. let wireframeAttribute = wireframes.get( geometry );
  21896. if ( wireframeAttribute === undefined ) {
  21897. wireframeAttribute = getWireframeIndex( geometry );
  21898. wireframes.set( geometry, wireframeAttribute );
  21899. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) || wireframeAttribute.__id !== getWireframeId( geometry ) ) {
  21900. this.attributes.delete( wireframeAttribute );
  21901. wireframeAttribute = getWireframeIndex( geometry );
  21902. wireframes.set( geometry, wireframeAttribute );
  21903. }
  21904. index = wireframeAttribute;
  21905. }
  21906. return index;
  21907. }
  21908. dispose() {
  21909. for ( const [ geometry, onDispose ] of this._geometryDisposeListeners.entries() ) {
  21910. geometry.removeEventListener( 'dispose', onDispose );
  21911. }
  21912. this._geometryDisposeListeners.clear();
  21913. }
  21914. }
  21915. /**
  21916. * This renderer module provides a series of statistical information
  21917. * about the GPU memory and the rendering process. Useful for debugging
  21918. * and monitoring.
  21919. */
  21920. class Info {
  21921. /**
  21922. * Constructs a new info component.
  21923. */
  21924. constructor() {
  21925. /**
  21926. * Whether frame related metrics should automatically
  21927. * be resetted or not. This property should be set to `false`
  21928. * by apps which manage their own animation loop. They must
  21929. * then call `renderer.info.reset()` once per frame manually.
  21930. *
  21931. * @type {boolean}
  21932. * @default true
  21933. */
  21934. this.autoReset = true;
  21935. /**
  21936. * The current frame ID. This ID is managed
  21937. * by `NodeFrame`.
  21938. *
  21939. * @type {number}
  21940. * @readonly
  21941. * @default 0
  21942. */
  21943. this.frame = 0;
  21944. /**
  21945. * The number of render calls since the
  21946. * app has been started.
  21947. *
  21948. * @type {number}
  21949. * @readonly
  21950. * @default 0
  21951. */
  21952. this.calls = 0;
  21953. /**
  21954. * Render related metrics.
  21955. *
  21956. * @type {Object}
  21957. * @readonly
  21958. * @property {number} calls - The number of render calls since the app has been started.
  21959. * @property {number} frameCalls - The number of render calls of the current frame.
  21960. * @property {number} drawCalls - The number of draw calls of the current frame.
  21961. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  21962. * @property {number} points - The number of rendered point primitives of the current frame.
  21963. * @property {number} lines - The number of rendered line primitives of the current frame.
  21964. * @property {number} timestamp - The timestamp of the frame.
  21965. */
  21966. this.render = {
  21967. calls: 0,
  21968. frameCalls: 0,
  21969. drawCalls: 0,
  21970. triangles: 0,
  21971. points: 0,
  21972. lines: 0,
  21973. timestamp: 0,
  21974. };
  21975. /**
  21976. * Compute related metrics.
  21977. *
  21978. * @type {Object}
  21979. * @readonly
  21980. * @property {number} calls - The number of compute calls since the app has been started.
  21981. * @property {number} frameCalls - The number of compute calls of the current frame.
  21982. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  21983. */
  21984. this.compute = {
  21985. calls: 0,
  21986. frameCalls: 0,
  21987. timestamp: 0
  21988. };
  21989. /**
  21990. * Memory related metrics.
  21991. *
  21992. * @type {Object}
  21993. * @readonly
  21994. * @property {number} attributes - The number of active attributes.
  21995. * @property {number} attributesSize - The memory size of active attributes in bytes.
  21996. * @property {number} geometries - The number of active geometries.
  21997. * @property {number} indexAttributes - The number of active index attributes.
  21998. * @property {number} indexAttributesSize - The memory size of active index attributes in bytes.
  21999. * @property {number} indirectStorageAttributes - The number of active indirect storage attributes.
  22000. * @property {number} indirectStorageAttributesSize - The memory size of active indirect storage attributes in bytes.
  22001. * @property {number} programs - The number of active programs.
  22002. * @property {number} programsSize - The memory size of active programs in bytes.
  22003. * @property {number} readbackBuffers - The number of active readback buffers.
  22004. * @property {number} readbackBuffersSize - The memory size of active readback buffers in bytes.
  22005. * @property {number} renderTargets - The number of active renderTargets.
  22006. * @property {number} storageAttributes - The number of active storage attributes.
  22007. * @property {number} storageAttributesSize - The memory size of active storage attributes in bytes.
  22008. * @property {number} textures - The number of active textures.
  22009. * @property {number} texturesSize - The memory size of active textures in bytes.
  22010. * @property {number} uniformBuffers - The number of active uniform buffers.
  22011. * @property {number} uniformBuffersSize - The memory size of active uniform buffers in bytes.
  22012. * @property {number} total - The total memory size in bytes.
  22013. */
  22014. this.memory = {
  22015. attributes: 0,
  22016. attributesSize: 0,
  22017. geometries: 0,
  22018. indexAttributes: 0,
  22019. indexAttributesSize: 0,
  22020. indirectStorageAttributes: 0,
  22021. indirectStorageAttributesSize: 0,
  22022. programs: 0,
  22023. programsSize: 0,
  22024. readbackBuffers: 0,
  22025. readbackBuffersSize: 0,
  22026. renderTargets: 0,
  22027. storageAttributes: 0,
  22028. storageAttributesSize: 0,
  22029. textures: 0,
  22030. texturesSize: 0,
  22031. uniformBuffers: 0,
  22032. uniformBuffersSize: 0,
  22033. total: 0
  22034. };
  22035. /**
  22036. * Map for storing calculated byte sizes of tracked objects.
  22037. *
  22038. * @type {Map<Object, number>}
  22039. * @private
  22040. */
  22041. this.memoryMap = new Map();
  22042. }
  22043. /**
  22044. * This method should be executed per draw call and updates the corresponding metrics.
  22045. *
  22046. * @param {Object3D} object - The 3D object that is going to be rendered.
  22047. * @param {number} count - The vertex or index count.
  22048. * @param {number} instanceCount - The instance count.
  22049. */
  22050. update( object, count, instanceCount ) {
  22051. this.render.drawCalls ++;
  22052. if ( object.isMesh || object.isSprite ) {
  22053. this.render.triangles += instanceCount * ( count / 3 );
  22054. } else if ( object.isPoints ) {
  22055. this.render.points += instanceCount * count;
  22056. } else if ( object.isLineSegments ) {
  22057. this.render.lines += instanceCount * ( count / 2 );
  22058. } else if ( object.isLine ) {
  22059. this.render.lines += instanceCount * ( count - 1 );
  22060. } else {
  22061. error( 'WebGPUInfo: Unknown object type.' );
  22062. }
  22063. }
  22064. /**
  22065. * Resets frame related metrics.
  22066. */
  22067. reset() {
  22068. this.render.drawCalls = 0;
  22069. this.render.frameCalls = 0;
  22070. this.compute.frameCalls = 0;
  22071. this.render.triangles = 0;
  22072. this.render.points = 0;
  22073. this.render.lines = 0;
  22074. }
  22075. /**
  22076. * Performs a complete reset of the object.
  22077. */
  22078. dispose() {
  22079. this.reset();
  22080. this.calls = 0;
  22081. this.render.calls = 0;
  22082. this.compute.calls = 0;
  22083. this.render.timestamp = 0;
  22084. this.compute.timestamp = 0;
  22085. for ( const prop in this.memory ) {
  22086. this.memory[ prop ] = 0;
  22087. }
  22088. this.memoryMap.clear();
  22089. }
  22090. /**
  22091. * Tracks texture memory explicitly, updating counts and byte tracking.
  22092. *
  22093. * @param {Texture} texture
  22094. */
  22095. createTexture( texture ) {
  22096. const size = this._getTextureMemorySize( texture );
  22097. this.memoryMap.set( texture, size );
  22098. this.memory.textures ++;
  22099. this.memory.total += size;
  22100. this.memory.texturesSize += size;
  22101. }
  22102. /**
  22103. * Tracks texture memory explicitly, updating counts and byte tracking.
  22104. *
  22105. * @param {Texture} texture
  22106. */
  22107. destroyTexture( texture ) {
  22108. const size = this.memoryMap.get( texture ) || 0;
  22109. this.memoryMap.delete( texture );
  22110. this.memory.textures --;
  22111. this.memory.total -= size;
  22112. this.memory.texturesSize -= size;
  22113. }
  22114. /**
  22115. * Tracks attribute memory explicitly, updating counts and byte tracking.
  22116. *
  22117. * @param {BufferAttribute} attribute
  22118. * @param {string} type - type of attribute
  22119. * @private
  22120. */
  22121. _createAttribute( attribute, type ) {
  22122. const size = this._getAttributeMemorySize( attribute );
  22123. this.memoryMap.set( attribute, { size, type } );
  22124. this.memory[ type ] ++;
  22125. this.memory.total += size;
  22126. this.memory[ type + 'Size' ] += size;
  22127. }
  22128. /**
  22129. * Tracks a regular attribute memory explicitly.
  22130. *
  22131. * @param {BufferAttribute} attribute - The attribute to track.
  22132. */
  22133. createAttribute( attribute ) {
  22134. this._createAttribute( attribute, 'attributes' );
  22135. }
  22136. /**
  22137. * Tracks an index attribute memory explicitly.
  22138. *
  22139. * @param {BufferAttribute} attribute - The index attribute to track.
  22140. */
  22141. createIndexAttribute( attribute ) {
  22142. this._createAttribute( attribute, 'indexAttributes' );
  22143. }
  22144. /**
  22145. * Tracks a storage attribute memory explicitly.
  22146. *
  22147. * @param {BufferAttribute} attribute - The storage attribute to track.
  22148. */
  22149. createStorageAttribute( attribute ) {
  22150. this._createAttribute( attribute, 'storageAttributes' );
  22151. }
  22152. /**
  22153. * Tracks an indirect storage attribute memory explicitly.
  22154. *
  22155. * @param {BufferAttribute} attribute - The indirect storage attribute to track.
  22156. */
  22157. createIndirectStorageAttribute( attribute ) {
  22158. this._createAttribute( attribute, 'indirectStorageAttributes' );
  22159. }
  22160. /**
  22161. * Tracks attribute memory explicitly, updating counts and byte tracking.
  22162. *
  22163. * @param {BufferAttribute} attribute
  22164. */
  22165. destroyAttribute( attribute ) {
  22166. const data = this.memoryMap.get( attribute );
  22167. if ( data ) {
  22168. this.memoryMap.delete( attribute );
  22169. this.memory[ data.type ] --;
  22170. this.memory.total -= data.size;
  22171. this.memory[ data.type + 'Size' ] -= data.size;
  22172. }
  22173. }
  22174. /**
  22175. * Tracks a readback buffer memory explicitly.
  22176. *
  22177. * @param {ReadbackBuffer} readbackBuffer - The readback buffer to track.
  22178. */
  22179. createReadbackBuffer( readbackBuffer ) {
  22180. const maxByteLength = readbackBuffer.maxByteLength;
  22181. this.memoryMap.set( readbackBuffer, { size: maxByteLength, type: 'readbackBuffers' } );
  22182. this.memory.readbackBuffers ++;
  22183. this.memory.total += maxByteLength;
  22184. this.memory.readbackBuffersSize += maxByteLength;
  22185. }
  22186. /**
  22187. * Tracks a readback buffer memory explicitly.
  22188. *
  22189. * @param {ReadbackBuffer} readbackBuffer - The readback buffer to track.
  22190. */
  22191. destroyReadbackBuffer( readbackBuffer ) {
  22192. const { size } = this.memoryMap.get( readbackBuffer );
  22193. this.memoryMap.delete( readbackBuffer );
  22194. this.memory.readbackBuffers --;
  22195. this.memory.total -= size;
  22196. this.memory.readbackBuffersSize -= size;
  22197. }
  22198. /**
  22199. * Tracks a uniform buffer memory explicitly.
  22200. *
  22201. * @param {UniformBuffer} uniformBuffer - The uniform buffer to track.
  22202. */
  22203. createUniformBuffer( uniformBuffer ) {
  22204. const size = uniformBuffer.byteLength;
  22205. this.memoryMap.set( uniformBuffer, { size, type: 'uniformBuffers' } );
  22206. this.memory.uniformBuffers ++;
  22207. this.memory.total += size;
  22208. this.memory.uniformBuffersSize += size;
  22209. }
  22210. /**
  22211. * Tracks a uniform buffer memory explicitly.
  22212. *
  22213. * @param {UniformBuffer} uniformBuffer - The uniform buffer to track.
  22214. */
  22215. destroyUniformBuffer( uniformBuffer ) {
  22216. const data = this.memoryMap.get( uniformBuffer );
  22217. if ( data ) {
  22218. this.memoryMap.delete( uniformBuffer );
  22219. this.memory.uniformBuffers --;
  22220. this.memory.total -= data.size;
  22221. this.memory.uniformBuffersSize -= data.size;
  22222. }
  22223. }
  22224. /**
  22225. * Tracks program memory explicitly, updating counts and byte tracking.
  22226. *
  22227. * @param {ProgrammableStage} program - The program to track.
  22228. */
  22229. createProgram( program ) {
  22230. const size = program.code.length; // Approx size
  22231. this.memoryMap.set( program, size );
  22232. this.memory.programs ++;
  22233. this.memory.total += size;
  22234. this.memory.programsSize += size;
  22235. }
  22236. /**
  22237. * Tracks program memory explicitly, updating counts and byte tracking.
  22238. *
  22239. * @param {Object} program - The program to track.
  22240. */
  22241. destroyProgram( program ) {
  22242. const size = this.memoryMap.get( program ) || 0;
  22243. this.memoryMap.delete( program );
  22244. this.memory.programs --;
  22245. this.memory.total -= size;
  22246. this.memory.programsSize -= size;
  22247. }
  22248. /**
  22249. * Calculates the memory size of a texture in bytes.
  22250. *
  22251. * @param {Texture} texture - The texture to calculate the size for.
  22252. * @return {number} The calculated size in bytes.
  22253. * @private
  22254. */
  22255. _getTextureMemorySize( texture ) {
  22256. if ( texture.isCompressedTexture ) {
  22257. return 1; // Fallback estimate since exact format decompressed isn't readily available without format maps
  22258. }
  22259. let bytesPerChannel = 1;
  22260. if ( texture.type === ByteType || texture.type === UnsignedByteType ) bytesPerChannel = 1;
  22261. else if ( texture.type === ShortType || texture.type === UnsignedShortType || texture.type === HalfFloatType ) bytesPerChannel = 2;
  22262. else if ( texture.type === IntType || texture.type === UnsignedIntType || texture.type === FloatType ) bytesPerChannel = 4;
  22263. let channels = 4; // RGBA default
  22264. if ( texture.format === AlphaFormat || texture.format === RedFormat || texture.format === RedIntegerFormat || texture.format === DepthFormat || texture.format === DepthStencilFormat ) channels = 1;
  22265. else if ( texture.format === RGFormat || texture.format === RGIntegerFormat ) channels = 2;
  22266. else if ( texture.format === RGBFormat || texture.format === RGBIntegerFormat ) channels = 3;
  22267. let bytesPerPixel = bytesPerChannel * channels;
  22268. // Packed overrides
  22269. if ( texture.type === UnsignedShort4444Type || texture.type === UnsignedShort5551Type ) bytesPerPixel = 2;
  22270. else if ( texture.type === UnsignedInt248Type || texture.type === UnsignedInt5999Type || texture.type === UnsignedInt101111Type ) bytesPerPixel = 4;
  22271. const width = texture.width || 1;
  22272. const height = texture.height || 1;
  22273. const depth = texture.isCubeTexture ? 6 : ( texture.depth || 1 );
  22274. let size = width * height * depth * bytesPerPixel;
  22275. const mipmaps = texture.mipmaps;
  22276. if ( mipmaps && mipmaps.length > 0 ) {
  22277. let mipmapSize = 0;
  22278. for ( let i = 0; i < mipmaps.length; i ++ ) {
  22279. const mipmap = mipmaps[ i ];
  22280. if ( mipmap.data ) {
  22281. mipmapSize += mipmap.data.byteLength;
  22282. } else {
  22283. const mipWidth = mipmap.width || Math.max( 1, width >> i );
  22284. const mipHeight = mipmap.height || Math.max( 1, height >> i );
  22285. mipmapSize += mipWidth * mipHeight * depth * bytesPerPixel;
  22286. }
  22287. }
  22288. size += mipmapSize;
  22289. } else if ( texture.generateMipmaps ) {
  22290. size = size * 1.333; // MiP chain approximation
  22291. }
  22292. return Math.round( size );
  22293. }
  22294. /**
  22295. * Calculates the memory size of an attribute in bytes.
  22296. *
  22297. * @param {BufferAttribute} attribute - The attribute to calculate the size for.
  22298. * @return {number} The calculated size in bytes.
  22299. * @private
  22300. */
  22301. _getAttributeMemorySize( attribute ) {
  22302. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  22303. if ( attribute.array ) {
  22304. return attribute.array.byteLength;
  22305. } else if ( attribute.count && attribute.itemSize ) {
  22306. return attribute.count * attribute.itemSize * 4; // Assume Float32
  22307. }
  22308. return 0;
  22309. }
  22310. }
  22311. /**
  22312. * Abstract class for representing pipelines.
  22313. *
  22314. * @private
  22315. * @abstract
  22316. */
  22317. class Pipeline {
  22318. /**
  22319. * Constructs a new pipeline.
  22320. *
  22321. * @param {string} cacheKey - The pipeline's cache key.
  22322. */
  22323. constructor( cacheKey ) {
  22324. /**
  22325. * The pipeline's cache key.
  22326. *
  22327. * @type {string}
  22328. */
  22329. this.cacheKey = cacheKey;
  22330. /**
  22331. * How often the pipeline is currently in use.
  22332. *
  22333. * @type {number}
  22334. * @default 0
  22335. */
  22336. this.usedTimes = 0;
  22337. }
  22338. }
  22339. /**
  22340. * Class for representing render pipelines.
  22341. *
  22342. * @private
  22343. * @augments Pipeline
  22344. */
  22345. class RenderObjectPipeline extends Pipeline {
  22346. /**
  22347. * Constructs a new render object pipeline.
  22348. *
  22349. * @param {string} cacheKey - The pipeline's cache key.
  22350. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  22351. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  22352. */
  22353. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  22354. super( cacheKey );
  22355. /**
  22356. * The pipeline's vertex shader.
  22357. *
  22358. * @type {ProgrammableStage}
  22359. */
  22360. this.vertexProgram = vertexProgram;
  22361. /**
  22362. * The pipeline's fragment shader.
  22363. *
  22364. * @type {ProgrammableStage}
  22365. */
  22366. this.fragmentProgram = fragmentProgram;
  22367. }
  22368. }
  22369. /**
  22370. * Class for representing compute pipelines.
  22371. *
  22372. * @private
  22373. * @augments Pipeline
  22374. */
  22375. class ComputePipeline extends Pipeline {
  22376. /**
  22377. * Constructs a new compute pipeline.
  22378. *
  22379. * @param {string} cacheKey - The pipeline's cache key.
  22380. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  22381. */
  22382. constructor( cacheKey, computeProgram ) {
  22383. super( cacheKey );
  22384. /**
  22385. * The pipeline's compute shader.
  22386. *
  22387. * @type {ProgrammableStage}
  22388. */
  22389. this.computeProgram = computeProgram;
  22390. /**
  22391. * This flag can be used for type testing.
  22392. *
  22393. * @type {boolean}
  22394. * @readonly
  22395. * @default true
  22396. */
  22397. this.isComputePipeline = true;
  22398. }
  22399. }
  22400. let _id$9 = 0;
  22401. /**
  22402. * Class for representing programmable stages which are vertex,
  22403. * fragment or compute shaders. Unlike fixed-function states (like blending),
  22404. * they represent the programmable part of a pipeline.
  22405. *
  22406. * @private
  22407. */
  22408. class ProgrammableStage {
  22409. /**
  22410. * Constructs a new programmable stage.
  22411. *
  22412. * @param {string} code - The shader code.
  22413. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  22414. * @param {string} name - The name of the shader.
  22415. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  22416. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  22417. */
  22418. constructor( code, stage, name, transforms = null, attributes = null ) {
  22419. /**
  22420. * The id of the programmable stage.
  22421. *
  22422. * @type {number}
  22423. */
  22424. this.id = _id$9 ++;
  22425. /**
  22426. * The shader code.
  22427. *
  22428. * @type {string}
  22429. */
  22430. this.code = code;
  22431. /**
  22432. * The type of stage.
  22433. *
  22434. * @type {string}
  22435. */
  22436. this.stage = stage;
  22437. /**
  22438. * The name of the stage.
  22439. * This is used for debugging purposes.
  22440. *
  22441. * @type {string}
  22442. */
  22443. this.name = name;
  22444. /**
  22445. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  22446. *
  22447. * @type {?Array<Object>}
  22448. */
  22449. this.transforms = transforms;
  22450. /**
  22451. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  22452. *
  22453. * @type {?Array<Object>}
  22454. */
  22455. this.attributes = attributes;
  22456. /**
  22457. * How often the programmable stage is currently in use.
  22458. *
  22459. * @type {number}
  22460. * @default 0
  22461. */
  22462. this.usedTimes = 0;
  22463. }
  22464. }
  22465. /**
  22466. * This renderer module manages the pipelines of the renderer.
  22467. *
  22468. * @private
  22469. * @augments DataMap
  22470. */
  22471. class Pipelines extends DataMap {
  22472. /**
  22473. * Constructs a new pipeline management component.
  22474. *
  22475. * @param {Backend} backend - The renderer's backend.
  22476. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  22477. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22478. */
  22479. constructor( backend, nodes, info ) {
  22480. super();
  22481. /**
  22482. * The renderer's backend.
  22483. *
  22484. * @type {Backend}
  22485. */
  22486. this.backend = backend;
  22487. /**
  22488. * Renderer component for managing nodes related logic.
  22489. *
  22490. * @type {NodeManager}
  22491. */
  22492. this.nodes = nodes;
  22493. /**
  22494. * Renderer component for managing metrics and monitoring data.
  22495. *
  22496. * @type {Info}
  22497. */
  22498. this.info = info;
  22499. /**
  22500. * A references to the bindings management component.
  22501. * This reference will be set inside the `Bindings`
  22502. * constructor.
  22503. *
  22504. * @type {?Bindings}
  22505. * @default null
  22506. */
  22507. this.bindings = null;
  22508. /**
  22509. * Internal cache for maintaining pipelines.
  22510. * The key of the map is a cache key, the value the pipeline.
  22511. *
  22512. * @type {Map<string,Pipeline>}
  22513. */
  22514. this.caches = new Map();
  22515. /**
  22516. * This dictionary maintains for each shader stage type (vertex,
  22517. * fragment and compute) the programmable stage objects which
  22518. * represent the actual shader code.
  22519. *
  22520. * @type {Object<string,Map<string, ProgrammableStage>>}
  22521. */
  22522. this.programs = {
  22523. vertex: new Map(),
  22524. fragment: new Map(),
  22525. compute: new Map()
  22526. };
  22527. }
  22528. /**
  22529. * Returns a compute pipeline for the given compute node.
  22530. *
  22531. * @param {Node} computeNode - The compute node.
  22532. * @param {Array<BindGroup>} bindings - The bindings.
  22533. * @return {ComputePipeline} The compute pipeline.
  22534. */
  22535. getForCompute( computeNode, bindings ) {
  22536. const { backend } = this;
  22537. const data = this.get( computeNode );
  22538. if ( this._needsComputeUpdate( computeNode ) ) {
  22539. const previousPipeline = data.pipeline;
  22540. if ( previousPipeline ) {
  22541. previousPipeline.usedTimes --;
  22542. previousPipeline.computeProgram.usedTimes --;
  22543. }
  22544. // get shader
  22545. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  22546. // programmable stage
  22547. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  22548. if ( stageCompute === undefined ) {
  22549. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  22550. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  22551. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  22552. backend.createProgram( stageCompute );
  22553. this.info.createProgram( stageCompute );
  22554. }
  22555. // determine compute pipeline
  22556. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  22557. let pipeline = this.caches.get( cacheKey );
  22558. if ( pipeline === undefined ) {
  22559. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  22560. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  22561. }
  22562. // keep track of all used times
  22563. pipeline.usedTimes ++;
  22564. stageCompute.usedTimes ++;
  22565. //
  22566. data.version = computeNode.version;
  22567. data.pipeline = pipeline;
  22568. }
  22569. return data.pipeline;
  22570. }
  22571. /**
  22572. * Returns a render pipeline for the given render object.
  22573. *
  22574. * @param {RenderObject} renderObject - The render object.
  22575. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  22576. * @return {RenderObjectPipeline} The render pipeline.
  22577. */
  22578. getForRender( renderObject, promises = null ) {
  22579. const { backend } = this;
  22580. const data = this.get( renderObject );
  22581. if ( this._needsRenderUpdate( renderObject ) ) {
  22582. const previousPipeline = data.pipeline;
  22583. if ( previousPipeline ) {
  22584. previousPipeline.usedTimes --;
  22585. previousPipeline.vertexProgram.usedTimes --;
  22586. previousPipeline.fragmentProgram.usedTimes --;
  22587. }
  22588. // get shader
  22589. const nodeBuilderState = renderObject.getNodeBuilderState();
  22590. const name = renderObject.material ? renderObject.material.name : '';
  22591. // programmable stages
  22592. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  22593. if ( stageVertex === undefined ) {
  22594. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  22595. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  22596. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  22597. backend.createProgram( stageVertex );
  22598. this.info.createProgram( stageVertex );
  22599. }
  22600. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  22601. if ( stageFragment === undefined ) {
  22602. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  22603. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  22604. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  22605. backend.createProgram( stageFragment );
  22606. this.info.createProgram( stageFragment );
  22607. }
  22608. // determine render pipeline
  22609. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22610. let pipeline = this.caches.get( cacheKey );
  22611. if ( pipeline === undefined ) {
  22612. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  22613. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  22614. } else {
  22615. renderObject.pipeline = pipeline;
  22616. }
  22617. // keep track of all used times
  22618. pipeline.usedTimes ++;
  22619. stageVertex.usedTimes ++;
  22620. stageFragment.usedTimes ++;
  22621. //
  22622. data.pipeline = pipeline;
  22623. }
  22624. return data.pipeline;
  22625. }
  22626. /**
  22627. * Checks if the render pipeline for the given render object is ready for drawing.
  22628. * Returns false if the GPU pipeline is still being compiled asynchronously.
  22629. *
  22630. * @param {RenderObject} renderObject - The render object.
  22631. * @return {boolean} True if the pipeline is ready for drawing.
  22632. */
  22633. isReady( renderObject ) {
  22634. const data = this.get( renderObject );
  22635. const pipeline = data.pipeline;
  22636. if ( pipeline === undefined ) return false;
  22637. const pipelineData = this.backend.get( pipeline );
  22638. return pipelineData.pipeline !== undefined && pipelineData.pipeline !== null;
  22639. }
  22640. /**
  22641. * Deletes the pipeline for the given render object.
  22642. *
  22643. * @param {RenderObject} object - The render object.
  22644. * @return {?Object} The deleted dictionary.
  22645. */
  22646. delete( object ) {
  22647. const pipeline = this.get( object ).pipeline;
  22648. if ( pipeline ) {
  22649. // pipeline
  22650. pipeline.usedTimes --;
  22651. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  22652. // programs
  22653. if ( pipeline.isComputePipeline ) {
  22654. pipeline.computeProgram.usedTimes --;
  22655. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  22656. } else {
  22657. pipeline.fragmentProgram.usedTimes --;
  22658. pipeline.vertexProgram.usedTimes --;
  22659. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  22660. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  22661. }
  22662. }
  22663. return super.delete( object );
  22664. }
  22665. /**
  22666. * Frees internal resources.
  22667. */
  22668. dispose() {
  22669. super.dispose();
  22670. this.caches = new Map();
  22671. this.programs = {
  22672. vertex: new Map(),
  22673. fragment: new Map(),
  22674. compute: new Map()
  22675. };
  22676. }
  22677. /**
  22678. * Updates the pipeline for the given render object.
  22679. *
  22680. * @param {RenderObject} renderObject - The render object.
  22681. */
  22682. updateForRender( renderObject ) {
  22683. this.getForRender( renderObject );
  22684. }
  22685. /**
  22686. * Returns a compute pipeline for the given parameters.
  22687. *
  22688. * @private
  22689. * @param {Node} computeNode - The compute node.
  22690. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  22691. * @param {string} cacheKey - The cache key.
  22692. * @param {Array<BindGroup>} bindings - The bindings.
  22693. * @return {ComputePipeline} The compute pipeline.
  22694. */
  22695. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  22696. // check for existing pipeline
  22697. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  22698. let pipeline = this.caches.get( cacheKey );
  22699. if ( pipeline === undefined ) {
  22700. pipeline = new ComputePipeline( cacheKey, stageCompute );
  22701. this.caches.set( cacheKey, pipeline );
  22702. this.backend.createComputePipeline( pipeline, bindings );
  22703. }
  22704. return pipeline;
  22705. }
  22706. /**
  22707. * Returns a render pipeline for the given parameters.
  22708. *
  22709. * @private
  22710. * @param {RenderObject} renderObject - The render object.
  22711. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  22712. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  22713. * @param {string} cacheKey - The cache key.
  22714. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  22715. * @return {RenderObjectPipeline} The render pipeline.
  22716. */
  22717. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  22718. // check for existing pipeline
  22719. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22720. let pipeline = this.caches.get( cacheKey );
  22721. if ( pipeline === undefined ) {
  22722. pipeline = new RenderObjectPipeline( cacheKey, stageVertex, stageFragment );
  22723. this.caches.set( cacheKey, pipeline );
  22724. renderObject.pipeline = pipeline;
  22725. // The `promises` array is `null` by default and only set to an empty array when
  22726. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  22727. // pending promises that resolve when the render pipelines are ready for rendering.
  22728. this.backend.createRenderPipeline( renderObject, promises );
  22729. }
  22730. return pipeline;
  22731. }
  22732. /**
  22733. * Computes a cache key representing a compute pipeline.
  22734. *
  22735. * @private
  22736. * @param {Node} computeNode - The compute node.
  22737. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  22738. * @return {string} The cache key.
  22739. */
  22740. _getComputeCacheKey( computeNode, stageCompute ) {
  22741. return computeNode.id + ',' + stageCompute.id;
  22742. }
  22743. /**
  22744. * Computes a cache key representing a render pipeline.
  22745. *
  22746. * @private
  22747. * @param {RenderObject} renderObject - The render object.
  22748. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  22749. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  22750. * @return {string} The cache key.
  22751. */
  22752. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  22753. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  22754. }
  22755. /**
  22756. * Releases the given pipeline.
  22757. *
  22758. * @private
  22759. * @param {Pipeline} pipeline - The pipeline to release.
  22760. */
  22761. _releasePipeline( pipeline ) {
  22762. this.caches.delete( pipeline.cacheKey );
  22763. }
  22764. /**
  22765. * Releases the shader program.
  22766. *
  22767. * @private
  22768. * @param {Object} program - The shader program to release.
  22769. */
  22770. _releaseProgram( program ) {
  22771. const code = program.code;
  22772. const stage = program.stage;
  22773. this.programs[ stage ].delete( code );
  22774. this.info.destroyProgram( program );
  22775. }
  22776. /**
  22777. * Returns `true` if the compute pipeline for the given compute node requires an update.
  22778. *
  22779. * @private
  22780. * @param {Node} computeNode - The compute node.
  22781. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  22782. */
  22783. _needsComputeUpdate( computeNode ) {
  22784. const data = this.get( computeNode );
  22785. return data.pipeline === undefined || data.version !== computeNode.version;
  22786. }
  22787. /**
  22788. * Returns `true` if the render pipeline for the given render object requires an update.
  22789. *
  22790. * @private
  22791. * @param {RenderObject} renderObject - The render object.
  22792. * @return {boolean} Whether the render object for the given render object requires an update or not.
  22793. */
  22794. _needsRenderUpdate( renderObject ) {
  22795. const data = this.get( renderObject );
  22796. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  22797. }
  22798. }
  22799. /**
  22800. * This renderer module manages the bindings of the renderer.
  22801. *
  22802. * @private
  22803. * @augments DataMap
  22804. */
  22805. class Bindings extends DataMap {
  22806. /**
  22807. * Constructs a new bindings management component.
  22808. *
  22809. * @param {Backend} backend - The renderer's backend.
  22810. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  22811. * @param {Textures} textures - Renderer component for managing textures.
  22812. * @param {Attributes} attributes - Renderer component for managing attributes.
  22813. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  22814. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22815. */
  22816. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  22817. super();
  22818. /**
  22819. * The renderer's backend.
  22820. *
  22821. * @type {Backend}
  22822. */
  22823. this.backend = backend;
  22824. /**
  22825. * Renderer component for managing textures.
  22826. *
  22827. * @type {Textures}
  22828. */
  22829. this.textures = textures;
  22830. /**
  22831. * Renderer component for managing pipelines.
  22832. *
  22833. * @type {Pipelines}
  22834. */
  22835. this.pipelines = pipelines;
  22836. /**
  22837. * Renderer component for managing attributes.
  22838. *
  22839. * @type {Attributes}
  22840. */
  22841. this.attributes = attributes;
  22842. /**
  22843. * Renderer component for managing nodes related logic.
  22844. *
  22845. * @type {NodeManager}
  22846. */
  22847. this.nodes = nodes;
  22848. /**
  22849. * Renderer component for managing metrics and monitoring data.
  22850. *
  22851. * @type {Info}
  22852. */
  22853. this.info = info;
  22854. this.pipelines.bindings = this; // assign bindings to pipelines
  22855. }
  22856. /**
  22857. * Returns the bind groups for the given render object.
  22858. *
  22859. * @param {RenderObject} renderObject - The render object.
  22860. * @return {Array<BindGroup>} The bind groups.
  22861. */
  22862. getForRender( renderObject ) {
  22863. const bindings = renderObject.getBindings();
  22864. const renderObjectData = this.get( renderObject );
  22865. if ( renderObjectData.initialized !== true ) {
  22866. // bind groups are created once per object
  22867. this._createBindings( bindings );
  22868. renderObjectData.initialized = true;
  22869. }
  22870. return bindings;
  22871. }
  22872. /**
  22873. * Returns the bind groups for the given compute node.
  22874. *
  22875. * @param {Node} computeNode - The compute node.
  22876. * @return {Array<BindGroup>} The bind groups.
  22877. */
  22878. getForCompute( computeNode ) {
  22879. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  22880. const computeNodeData = this.get( computeNode );
  22881. if ( computeNodeData.initialized !== true || computeNodeData.bindings !== bindings ) {
  22882. // bind groups are created once per compute node version
  22883. if ( computeNodeData.bindings !== undefined ) {
  22884. this._destroyBindings( computeNodeData.bindings );
  22885. }
  22886. this._createBindings( bindings );
  22887. computeNodeData.initialized = true;
  22888. computeNodeData.bindings = bindings;
  22889. }
  22890. return bindings;
  22891. }
  22892. /**
  22893. * Updates the bindings for the given compute node.
  22894. *
  22895. * @param {Node} computeNode - The compute node.
  22896. */
  22897. updateForCompute( computeNode ) {
  22898. this._updateBindings( this.getForCompute( computeNode ) );
  22899. }
  22900. /**
  22901. * Updates the bindings for the given render object.
  22902. *
  22903. * @param {RenderObject} renderObject - The render object.
  22904. */
  22905. updateForRender( renderObject ) {
  22906. this._updateBindings( this.getForRender( renderObject ) );
  22907. }
  22908. /**
  22909. * Deletes the bindings for the given compute node.
  22910. *
  22911. * @param {Node} computeNode - The compute node.
  22912. */
  22913. deleteForCompute( computeNode ) {
  22914. const computeNodeData = this.get( computeNode );
  22915. const bindings = computeNodeData.bindings || this.nodes.getForCompute( computeNode ).bindings;
  22916. this._destroyBindings( bindings );
  22917. this.delete( computeNode );
  22918. }
  22919. /**
  22920. * Deletes the bindings for the given renderObject node.
  22921. *
  22922. * @param {RenderObject} renderObject - The renderObject.
  22923. */
  22924. deleteForRender( renderObject ) {
  22925. const bindings = renderObject.getBindings();
  22926. this._destroyBindings( bindings );
  22927. this.delete( renderObject );
  22928. }
  22929. /**
  22930. * Creates the bindings for the given array of bindings.
  22931. *
  22932. * @param {Array<BindGroup>} bindings - The bind groups.
  22933. */
  22934. _createBindings( bindings ) {
  22935. for ( const bindGroup of bindings ) {
  22936. // binding group
  22937. const groupData = this.get( bindGroup );
  22938. if ( groupData.bindGroup === undefined ) {
  22939. // initialize
  22940. for ( const binding of bindGroup.bindings ) {
  22941. if ( binding.isUniformBuffer ) {
  22942. this.backend.createUniformBuffer( binding );
  22943. this.info.createUniformBuffer( binding );
  22944. } else if ( binding.isSampledTexture ) {
  22945. this.textures.updateTexture( binding.texture );
  22946. } else if ( binding.isSampler ) {
  22947. this.textures.updateSampler( binding.texture, binding.textureNode );
  22948. } else if ( binding.isStorageBuffer ) {
  22949. const attribute = binding.attribute;
  22950. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  22951. this.attributes.update( attribute, attributeType );
  22952. }
  22953. }
  22954. // each object defines an array of bindings (ubos, textures, samplers etc.)
  22955. this.backend.createBindings( bindGroup, bindings, 0 );
  22956. groupData.bindGroup = bindGroup;
  22957. groupData.usedTimes = 1;
  22958. } else {
  22959. groupData.usedTimes ++;
  22960. }
  22961. }
  22962. }
  22963. /**
  22964. * Deletes the given array of bindings.
  22965. *
  22966. * @param {Array<BindGroup>} bindings - The bind groups.
  22967. */
  22968. _destroyBindings( bindings ) {
  22969. for ( const bindGroup of bindings ) {
  22970. const groupData = this.get( bindGroup );
  22971. groupData.usedTimes --;
  22972. if ( groupData.usedTimes === 0 ) {
  22973. for ( const binding of bindGroup.bindings ) {
  22974. if ( binding.isUniformBuffer ) {
  22975. this.backend.destroyUniformBuffer( binding );
  22976. this.info.destroyUniformBuffer( binding );
  22977. // release arrays
  22978. binding.release();
  22979. }
  22980. }
  22981. this.backend.deleteBindGroupData( bindGroup );
  22982. this.delete( bindGroup );
  22983. }
  22984. }
  22985. }
  22986. /**
  22987. * Updates the given array of bindings.
  22988. *
  22989. * @param {Array<BindGroup>} bindings - The bind groups.
  22990. */
  22991. _updateBindings( bindings ) {
  22992. for ( const bindGroup of bindings ) {
  22993. this._update( bindGroup, bindings );
  22994. }
  22995. }
  22996. /**
  22997. * Updates the given bind group.
  22998. *
  22999. * @param {BindGroup} bindGroup - The bind group to update.
  23000. * @param {Array<BindGroup>} bindings - The bind groups.
  23001. */
  23002. _update( bindGroup, bindings ) {
  23003. const { backend } = this;
  23004. let needsBindingsUpdate = false;
  23005. let cacheBindings = true;
  23006. let cacheIndex = 0;
  23007. let version = 0;
  23008. // iterate over all bindings and check if buffer updates or a new binding group is required
  23009. for ( const binding of bindGroup.bindings ) {
  23010. const updatedGroup = this.nodes.updateGroup( binding );
  23011. // every uniforms group is a uniform buffer. So if no update is required,
  23012. // we move one with the next binding. Otherwise the next if block will update the group.
  23013. if ( updatedGroup === false ) continue;
  23014. //
  23015. if ( binding.isStorageBuffer ) {
  23016. const attribute = binding.attribute;
  23017. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  23018. const bindingData = backend.get( binding );
  23019. this.attributes.update( attribute, attributeType );
  23020. if ( bindingData.attribute !== attribute ) {
  23021. bindingData.attribute = attribute;
  23022. needsBindingsUpdate = true;
  23023. }
  23024. }
  23025. if ( binding.isUniformBuffer ) {
  23026. const updated = binding.update();
  23027. if ( updated ) {
  23028. backend.updateBinding( binding );
  23029. }
  23030. } else if ( binding.isSampledTexture ) {
  23031. const updated = binding.update();
  23032. // get the texture data after the update, to sync the texture reference from node
  23033. const texture = binding.texture;
  23034. const texturesTextureData = this.textures.get( texture );
  23035. if ( updated ) {
  23036. // version: update the texture data or create a new one
  23037. this.textures.updateTexture( texture );
  23038. // generation: update the bindings if the binding refers to a different texture object
  23039. if ( binding.generation !== texturesTextureData.generation ) {
  23040. binding.generation = texturesTextureData.generation;
  23041. needsBindingsUpdate = true;
  23042. }
  23043. // keep track which bind groups refer to the current texture (this is needed for dispose)
  23044. texturesTextureData.bindGroups.add( bindGroup );
  23045. }
  23046. const textureData = backend.get( texture );
  23047. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  23048. cacheBindings = false;
  23049. } else {
  23050. cacheIndex = cacheIndex * 10 + texture.id;
  23051. version += texture.version;
  23052. }
  23053. if ( texture.isStorageTexture === true && texture.mipmapsAutoUpdate === true ) {
  23054. const textureData = this.get( texture );
  23055. if ( binding.store === true ) {
  23056. textureData.needsMipmap = true;
  23057. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  23058. this.backend.generateMipmaps( texture );
  23059. textureData.needsMipmap = false;
  23060. }
  23061. }
  23062. } else if ( binding.isSampler ) {
  23063. const updated = binding.update();
  23064. if ( updated ) {
  23065. const samplerKey = this.textures.updateSampler( binding.texture, binding.textureNode );
  23066. if ( binding.samplerKey !== samplerKey ) {
  23067. binding.samplerKey = samplerKey;
  23068. needsBindingsUpdate = true;
  23069. }
  23070. }
  23071. }
  23072. if ( binding.isBuffer && binding.updateRanges.length > 0 ) {
  23073. binding.clearUpdateRanges();
  23074. }
  23075. }
  23076. if ( needsBindingsUpdate === true ) {
  23077. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  23078. }
  23079. }
  23080. }
  23081. /**
  23082. * Default sorting function for opaque render items.
  23083. *
  23084. * @private
  23085. * @function
  23086. * @param {Object} a - The first render item.
  23087. * @param {Object} b - The second render item.
  23088. * @return {number} A numeric value which defines the sort order.
  23089. */
  23090. function painterSortStable( a, b ) {
  23091. if ( a.groupOrder !== b.groupOrder ) {
  23092. return a.groupOrder - b.groupOrder;
  23093. } else if ( a.renderOrder !== b.renderOrder ) {
  23094. return a.renderOrder - b.renderOrder;
  23095. } else if ( a.z !== b.z ) {
  23096. return a.z - b.z;
  23097. } else {
  23098. return a.id - b.id;
  23099. }
  23100. }
  23101. /**
  23102. * Default sorting function for transparent render items.
  23103. *
  23104. * @private
  23105. * @function
  23106. * @param {Object} a - The first render item.
  23107. * @param {Object} b - The second render item.
  23108. * @return {number} A numeric value which defines the sort order.
  23109. */
  23110. function reversePainterSortStable( a, b ) {
  23111. if ( a.groupOrder !== b.groupOrder ) {
  23112. return a.groupOrder - b.groupOrder;
  23113. } else if ( a.renderOrder !== b.renderOrder ) {
  23114. return a.renderOrder - b.renderOrder;
  23115. } else if ( a.z !== b.z ) {
  23116. return b.z - a.z;
  23117. } else {
  23118. return a.id - b.id;
  23119. }
  23120. }
  23121. /**
  23122. * Returns `true` if the given transparent material requires a double pass.
  23123. *
  23124. * @private
  23125. * @function
  23126. * @param {Material} material - The transparent material.
  23127. * @return {boolean} Whether the given material requires a double pass or not.
  23128. */
  23129. function needsDoublePass( material ) {
  23130. const hasTransmission = material.transmission > 0 || ( material.transmissionNode && material.transmissionNode.isNode );
  23131. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  23132. }
  23133. /**
  23134. * When the renderer analyzes the scene at the beginning of a render call,
  23135. * it stores 3D object for further processing in render lists. Depending on the
  23136. * properties of a 3D objects (like their transformation or material state), the
  23137. * objects are maintained in ordered lists for the actual rendering.
  23138. *
  23139. * Render lists are unique per scene and camera combination.
  23140. *
  23141. * @private
  23142. * @augments Pipeline
  23143. */
  23144. class RenderList {
  23145. /**
  23146. * Constructs a render list.
  23147. *
  23148. * @param {Lighting} lighting - The lighting management component.
  23149. * @param {Scene} scene - The scene.
  23150. * @param {Camera} camera - The camera the scene is rendered with.
  23151. */
  23152. constructor( lighting, scene, camera ) {
  23153. /**
  23154. * 3D objects are transformed into render items and stored in this array.
  23155. *
  23156. * @type {Array<Object>}
  23157. */
  23158. this.renderItems = [];
  23159. /**
  23160. * The current render items index.
  23161. *
  23162. * @type {number}
  23163. * @default 0
  23164. */
  23165. this.renderItemsIndex = 0;
  23166. /**
  23167. * A list with opaque render items.
  23168. *
  23169. * @type {Array<Object>}
  23170. */
  23171. this.opaque = [];
  23172. /**
  23173. * A list with transparent render items which require
  23174. * double pass rendering (e.g. transmissive objects).
  23175. *
  23176. * @type {Array<Object>}
  23177. */
  23178. this.transparentDoublePass = [];
  23179. /**
  23180. * A list with transparent render items.
  23181. *
  23182. * @type {Array<Object>}
  23183. */
  23184. this.transparent = [];
  23185. /**
  23186. * A list with transparent render bundle data.
  23187. *
  23188. * @type {Array<Object>}
  23189. */
  23190. this.bundles = [];
  23191. /**
  23192. * The render list's lights node. This node is later
  23193. * relevant for the actual analytical light nodes which
  23194. * compute the scene's lighting in the shader.
  23195. *
  23196. * @type {LightsNode}
  23197. */
  23198. this.lightsNode = lighting.getNode( scene, camera );
  23199. /**
  23200. * The scene's lights stored in an array. This array
  23201. * is used to setup the lights node.
  23202. *
  23203. * @type {Array<Light>}
  23204. */
  23205. this.lightsArray = [];
  23206. /**
  23207. * The scene.
  23208. *
  23209. * @type {Scene}
  23210. */
  23211. this.scene = scene;
  23212. /**
  23213. * The camera the scene is rendered with.
  23214. *
  23215. * @type {Camera}
  23216. */
  23217. this.camera = camera;
  23218. /**
  23219. * How many objects perform occlusion query tests.
  23220. *
  23221. * @type {number}
  23222. * @default 0
  23223. */
  23224. this.occlusionQueryCount = 0;
  23225. }
  23226. /**
  23227. * This method is called right at the beginning of a render call
  23228. * before the scene is analyzed. It prepares the internal data
  23229. * structures for the upcoming render lists generation.
  23230. *
  23231. * @return {RenderList} A reference to this render list.
  23232. */
  23233. begin() {
  23234. this.renderItemsIndex = 0;
  23235. this.opaque.length = 0;
  23236. this.transparentDoublePass.length = 0;
  23237. this.transparent.length = 0;
  23238. this.bundles.length = 0;
  23239. this.lightsArray.length = 0;
  23240. this.occlusionQueryCount = 0;
  23241. return this;
  23242. }
  23243. /**
  23244. * Returns a render item for the giving render item state. The state is defined
  23245. * by a series of object-related parameters.
  23246. *
  23247. * The method avoids object creation by holding render items and reusing them in
  23248. * subsequent render calls (just with different property values).
  23249. *
  23250. * @param {Object3D} object - The 3D object.
  23251. * @param {BufferGeometry} geometry - The 3D object's geometry.
  23252. * @param {Material} material - The 3D object's material.
  23253. * @param {number} groupOrder - The current group order.
  23254. * @param {number} z - Th 3D object's depth value (z value in clip space).
  23255. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  23256. * @param {ClippingContext} clippingContext - The current clipping context.
  23257. * @return {Object} The render item.
  23258. */
  23259. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  23260. let renderItem = this.renderItems[ this.renderItemsIndex ];
  23261. if ( renderItem === undefined ) {
  23262. renderItem = {
  23263. id: object.id,
  23264. object: object,
  23265. geometry: geometry,
  23266. material: material,
  23267. groupOrder: groupOrder,
  23268. renderOrder: object.renderOrder,
  23269. z: z,
  23270. group: group,
  23271. clippingContext: clippingContext
  23272. };
  23273. this.renderItems[ this.renderItemsIndex ] = renderItem;
  23274. } else {
  23275. renderItem.id = object.id;
  23276. renderItem.object = object;
  23277. renderItem.geometry = geometry;
  23278. renderItem.material = material;
  23279. renderItem.groupOrder = groupOrder;
  23280. renderItem.renderOrder = object.renderOrder;
  23281. renderItem.z = z;
  23282. renderItem.group = group;
  23283. renderItem.clippingContext = clippingContext;
  23284. }
  23285. this.renderItemsIndex ++;
  23286. return renderItem;
  23287. }
  23288. /**
  23289. * Pushes the given object as a render item to the internal render lists.
  23290. * The selected lists depend on the object properties.
  23291. *
  23292. * @param {Object3D} object - The 3D object.
  23293. * @param {BufferGeometry} geometry - The 3D object's geometry.
  23294. * @param {Material} material - The 3D object's material.
  23295. * @param {number} groupOrder - The current group order.
  23296. * @param {number} z - Th 3D object's depth value (z value in clip space).
  23297. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  23298. * @param {ClippingContext} clippingContext - The current clipping context.
  23299. */
  23300. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  23301. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  23302. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  23303. if ( material.transparent === true || material.transmission > 0 ||
  23304. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  23305. ( material.backdropNode && material.backdropNode.isNode ) ) {
  23306. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  23307. this.transparent.push( renderItem );
  23308. } else {
  23309. this.opaque.push( renderItem );
  23310. }
  23311. }
  23312. /**
  23313. * Inserts the given object as a render item at the start of the internal render lists.
  23314. * The selected lists depend on the object properties.
  23315. *
  23316. * @param {Object3D} object - The 3D object.
  23317. * @param {BufferGeometry} geometry - The 3D object's geometry.
  23318. * @param {Material} material - The 3D object's material.
  23319. * @param {number} groupOrder - The current group order.
  23320. * @param {number} z - Th 3D object's depth value (z value in clip space).
  23321. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  23322. * @param {ClippingContext} clippingContext - The current clipping context.
  23323. */
  23324. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  23325. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  23326. if ( material.transparent === true || material.transmission > 0 ||
  23327. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  23328. ( material.backdropNode && material.backdropNode.isNode ) ) {
  23329. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  23330. this.transparent.unshift( renderItem );
  23331. } else {
  23332. this.opaque.unshift( renderItem );
  23333. }
  23334. }
  23335. /**
  23336. * Pushes render bundle group data into the render list.
  23337. *
  23338. * @param {Object} group - Bundle group data.
  23339. */
  23340. pushBundle( group ) {
  23341. this.bundles.push( group );
  23342. }
  23343. /**
  23344. * Pushes a light into the render list.
  23345. *
  23346. * @param {Light} light - The light.
  23347. */
  23348. pushLight( light ) {
  23349. this.lightsArray.push( light );
  23350. }
  23351. /**
  23352. * Sorts the internal render lists.
  23353. *
  23354. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  23355. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  23356. */
  23357. sort( customOpaqueSort, customTransparentSort ) {
  23358. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  23359. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  23360. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  23361. }
  23362. /**
  23363. * This method performs finalizing tasks right after the render lists
  23364. * have been generated.
  23365. */
  23366. finish() {
  23367. // update lights
  23368. this.lightsNode.setLights( this.lightsArray );
  23369. // Clear references from inactive renderItems in the list
  23370. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  23371. const renderItem = this.renderItems[ i ];
  23372. if ( renderItem.id === null ) break;
  23373. renderItem.id = null;
  23374. renderItem.object = null;
  23375. renderItem.geometry = null;
  23376. renderItem.material = null;
  23377. renderItem.groupOrder = null;
  23378. renderItem.renderOrder = null;
  23379. renderItem.z = null;
  23380. renderItem.group = null;
  23381. renderItem.clippingContext = null;
  23382. }
  23383. }
  23384. }
  23385. const _chainKeys$2 = [];
  23386. /**
  23387. * This renderer module manages the render lists which are unique
  23388. * per scene and camera combination.
  23389. *
  23390. * @private
  23391. */
  23392. class RenderLists {
  23393. /**
  23394. * Constructs a render lists management component.
  23395. *
  23396. * @param {Lighting} lighting - The lighting management component.
  23397. */
  23398. constructor( lighting ) {
  23399. /**
  23400. * The lighting management component.
  23401. *
  23402. * @type {Lighting}
  23403. */
  23404. this.lighting = lighting;
  23405. /**
  23406. * The internal chain map which holds the render lists.
  23407. *
  23408. * @type {ChainMap}
  23409. */
  23410. this.lists = new ChainMap();
  23411. }
  23412. /**
  23413. * Returns a render list for the given scene and camera.
  23414. *
  23415. * @param {Scene} scene - The scene.
  23416. * @param {Camera} camera - The camera.
  23417. * @return {RenderList} The render list.
  23418. */
  23419. get( scene, camera ) {
  23420. const lists = this.lists;
  23421. _chainKeys$2[ 0 ] = scene;
  23422. _chainKeys$2[ 1 ] = camera;
  23423. let list = lists.get( _chainKeys$2 );
  23424. if ( list === undefined ) {
  23425. list = new RenderList( this.lighting, scene, camera );
  23426. lists.set( _chainKeys$2, list );
  23427. }
  23428. _chainKeys$2[ 0 ] = null;
  23429. _chainKeys$2[ 1 ] = null;
  23430. return list;
  23431. }
  23432. /**
  23433. * Frees all internal resources.
  23434. */
  23435. dispose() {
  23436. this.lists = new ChainMap();
  23437. }
  23438. }
  23439. let _id$8 = 0;
  23440. /**
  23441. * Any render or compute command is executed in a specific context that defines
  23442. * the state of the renderer and its backend. Typical examples for such context
  23443. * data are the current clear values or data from the active framebuffer. This
  23444. * module is used to represent these contexts as objects.
  23445. *
  23446. * @private
  23447. */
  23448. class RenderContext {
  23449. /**
  23450. * Constructs a new render context.
  23451. */
  23452. constructor() {
  23453. /**
  23454. * The context's ID.
  23455. *
  23456. * @type {number}
  23457. */
  23458. this.id = _id$8 ++;
  23459. /**
  23460. * The MRT configuration.
  23461. *
  23462. * @type {?MRTNode}
  23463. * @default null
  23464. */
  23465. this.mrt = null;
  23466. /**
  23467. * Whether the current active framebuffer has a color attachment.
  23468. *
  23469. * @type {boolean}
  23470. * @default true
  23471. */
  23472. this.color = true;
  23473. /**
  23474. * Whether the color attachment should be cleared or not.
  23475. *
  23476. * @type {boolean}
  23477. * @default true
  23478. */
  23479. this.clearColor = true;
  23480. /**
  23481. * The clear color value.
  23482. *
  23483. * @type {Object}
  23484. * @default true
  23485. */
  23486. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  23487. /**
  23488. * Whether the current active framebuffer has a depth attachment.
  23489. *
  23490. * @type {boolean}
  23491. * @default true
  23492. */
  23493. this.depth = true;
  23494. /**
  23495. * Whether the depth attachment should be cleared or not.
  23496. *
  23497. * @type {boolean}
  23498. * @default true
  23499. */
  23500. this.clearDepth = true;
  23501. /**
  23502. * The clear depth value.
  23503. *
  23504. * @type {number}
  23505. * @default 1
  23506. */
  23507. this.clearDepthValue = 1;
  23508. /**
  23509. * Whether the current active framebuffer has a stencil attachment.
  23510. *
  23511. * @type {boolean}
  23512. * @default false
  23513. */
  23514. this.stencil = false;
  23515. /**
  23516. * Whether the stencil attachment should be cleared or not.
  23517. *
  23518. * @type {boolean}
  23519. * @default true
  23520. */
  23521. this.clearStencil = true;
  23522. /**
  23523. * The clear stencil value.
  23524. *
  23525. * @type {number}
  23526. * @default 1
  23527. */
  23528. this.clearStencilValue = 1;
  23529. /**
  23530. * By default the viewport encloses the entire framebuffer If a smaller
  23531. * viewport is manually defined, this property is to `true` by the renderer.
  23532. *
  23533. * @type {boolean}
  23534. * @default false
  23535. */
  23536. this.viewport = false;
  23537. /**
  23538. * The viewport value. This value is in physical pixels meaning it incorporates
  23539. * the renderer's pixel ratio. The viewport property of render targets or
  23540. * the renderer is in logical pixels.
  23541. *
  23542. * @type {Vector4}
  23543. */
  23544. this.viewportValue = new Vector4();
  23545. /**
  23546. * When the scissor test is active and scissor rectangle smaller than the
  23547. * framebuffers dimensions, this property is to `true` by the renderer.
  23548. *
  23549. * @type {boolean}
  23550. * @default false
  23551. */
  23552. this.scissor = false;
  23553. /**
  23554. * The scissor rectangle.
  23555. *
  23556. * @type {Vector4}
  23557. */
  23558. this.scissorValue = new Vector4();
  23559. /**
  23560. * The active render target.
  23561. *
  23562. * @type {?RenderTarget}
  23563. * @default null
  23564. */
  23565. this.renderTarget = null;
  23566. /**
  23567. * The textures of the active render target.
  23568. * `null` when no render target is set.
  23569. *
  23570. * @type {?Array<Texture>}
  23571. * @default null
  23572. */
  23573. this.textures = null;
  23574. /**
  23575. * The depth texture of the active render target.
  23576. * `null` when no render target is set.
  23577. *
  23578. * @type {?DepthTexture}
  23579. * @default null
  23580. */
  23581. this.depthTexture = null;
  23582. /**
  23583. * The active cube face.
  23584. *
  23585. * @type {number}
  23586. * @default 0
  23587. */
  23588. this.activeCubeFace = 0;
  23589. /**
  23590. * The active mipmap level.
  23591. *
  23592. * @type {number}
  23593. * @default 0
  23594. */
  23595. this.activeMipmapLevel = 0;
  23596. /**
  23597. * The number of MSAA samples. This value is always `1` when
  23598. * MSAA isn't used.
  23599. *
  23600. * @type {number}
  23601. * @default 1
  23602. */
  23603. this.sampleCount = 1;
  23604. /**
  23605. * The active render target's width in physical pixels.
  23606. *
  23607. * @type {number}
  23608. * @default 0
  23609. */
  23610. this.width = 0;
  23611. /**
  23612. * The active render target's height in physical pixels.
  23613. *
  23614. * @type {number}
  23615. * @default 0
  23616. */
  23617. this.height = 0;
  23618. /**
  23619. * The occlusion query count.
  23620. *
  23621. * @type {number}
  23622. * @default 0
  23623. */
  23624. this.occlusionQueryCount = 0;
  23625. /**
  23626. * The current clipping context.
  23627. *
  23628. * @type {?ClippingContext}
  23629. * @default null
  23630. */
  23631. this.clippingContext = null;
  23632. /**
  23633. * The current camera.
  23634. *
  23635. * @type {?Camera}
  23636. * @default null
  23637. */
  23638. this.camera = null;
  23639. /**
  23640. * This flag can be used for type testing.
  23641. *
  23642. * @type {boolean}
  23643. * @readonly
  23644. * @default true
  23645. */
  23646. this.isRenderContext = true;
  23647. }
  23648. /**
  23649. * Returns the cache key of this render context.
  23650. *
  23651. * @return {number} The cache key.
  23652. */
  23653. getCacheKey() {
  23654. return getCacheKey( this );
  23655. }
  23656. }
  23657. /**
  23658. * Computes a cache key for the given render context. This key
  23659. * should identify the render target state so it is possible to
  23660. * configure the correct attachments in the respective backend.
  23661. *
  23662. * @param {RenderContext} renderContext - The render context.
  23663. * @return {number} The cache key.
  23664. */
  23665. function getCacheKey( renderContext ) {
  23666. const { textures, activeCubeFace, activeMipmapLevel } = renderContext;
  23667. const values = [ activeCubeFace, activeMipmapLevel ];
  23668. for ( const texture of textures ) {
  23669. values.push( texture.id );
  23670. }
  23671. return hashArray( values );
  23672. }
  23673. /**
  23674. * This module manages the render contexts of the renderer.
  23675. *
  23676. * @private
  23677. */
  23678. class RenderContexts {
  23679. /**
  23680. * Constructs a new render context management component.
  23681. *
  23682. * @param {Renderer} renderer - The renderer.
  23683. */
  23684. constructor( renderer ) {
  23685. /**
  23686. * The renderer.
  23687. *
  23688. * @type {Renderer}
  23689. */
  23690. this.renderer = renderer;
  23691. /**
  23692. * A dictionary that manages render contexts.
  23693. *
  23694. * @type {Object<string,RenderContext>}
  23695. */
  23696. this._renderContexts = {};
  23697. }
  23698. /**
  23699. * Returns a render context for the given scene, camera and render target.
  23700. *
  23701. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  23702. * @param {?MRTNode} [mrt=null] - The MRT configuration
  23703. * @param {?number} [callDepth=0] - The call depth of the renderer.
  23704. * @return {RenderContext} The render context.
  23705. */
  23706. get( renderTarget = null, mrt = null, callDepth = 0 ) {
  23707. //
  23708. let attachmentState;
  23709. if ( renderTarget === null ) {
  23710. attachmentState = 'default';
  23711. } else {
  23712. const format = renderTarget.texture.format;
  23713. const type = renderTarget.texture.type;
  23714. const count = renderTarget.textures.length;
  23715. attachmentState = `${ count }:${ format }:${ type }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  23716. }
  23717. //
  23718. const mrtState = ( mrt !== null ) ? mrt.id : 'default';
  23719. //
  23720. const renderStateKey = attachmentState + '-' + mrtState + '-' + callDepth;
  23721. let renderState = this._renderContexts[ renderStateKey ];
  23722. if ( renderState === undefined ) {
  23723. renderState = new RenderContext();
  23724. renderState.mrt = mrt;
  23725. this._renderContexts[ renderStateKey ] = renderState;
  23726. }
  23727. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  23728. renderState.clearDepthValue = this.renderer.getClearDepth();
  23729. renderState.clearStencilValue = this.renderer.getClearStencil();
  23730. return renderState;
  23731. }
  23732. /**
  23733. * Frees internal resources.
  23734. */
  23735. dispose() {
  23736. this._renderContexts = {};
  23737. }
  23738. }
  23739. const _size$3 = /*@__PURE__*/ new Vector3();
  23740. /**
  23741. * This module manages the textures of the renderer.
  23742. *
  23743. * @private
  23744. * @augments DataMap
  23745. */
  23746. class Textures extends DataMap {
  23747. /**
  23748. * Constructs a new texture management component.
  23749. *
  23750. * @param {Renderer} renderer - The renderer.
  23751. * @param {Backend} backend - The renderer's backend.
  23752. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  23753. */
  23754. constructor( renderer, backend, info ) {
  23755. super();
  23756. /**
  23757. * The renderer.
  23758. *
  23759. * @type {Renderer}
  23760. */
  23761. this.renderer = renderer;
  23762. /**
  23763. * The backend.
  23764. *
  23765. * @type {Backend}
  23766. */
  23767. this.backend = backend;
  23768. /**
  23769. * Renderer component for managing metrics and monitoring data.
  23770. *
  23771. * @type {Info}
  23772. */
  23773. this.info = info;
  23774. /**
  23775. * A set of HTMLTextures that need paint updates.
  23776. *
  23777. * @type {Set<HTMLTexture>}
  23778. */
  23779. this._htmlTextures = new Set();
  23780. }
  23781. /**
  23782. * Updates the given render target. Based on the given render target configuration,
  23783. * it updates the texture states representing the attachments of the framebuffer.
  23784. *
  23785. * @param {RenderTarget} renderTarget - The render target to update.
  23786. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  23787. */
  23788. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  23789. const renderTargetData = this.get( renderTarget );
  23790. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  23791. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  23792. const textures = renderTarget.textures;
  23793. const size = this.getSize( textures[ 0 ] );
  23794. const mipWidth = size.width >> activeMipmapLevel;
  23795. const mipHeight = size.height >> activeMipmapLevel;
  23796. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  23797. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  23798. let textureNeedsUpdate = false;
  23799. const hasArrayDepthTexture = depthTexture !== undefined && depthTexture.image !== undefined && depthTexture.image.depth > 1;
  23800. const useArrayDepth = size.depth > 1 && ( renderTarget.useArrayDepthTexture || renderTarget.multiview || hasArrayDepthTexture );
  23801. if ( depthTexture === undefined && useDepthTexture ) {
  23802. depthTexture = new DepthTexture();
  23803. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  23804. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  23805. depthTexture.image.width = mipWidth;
  23806. depthTexture.image.height = mipHeight;
  23807. depthTexture.image.depth = size.depth;
  23808. depthTexture.renderTarget = renderTarget;
  23809. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  23810. }
  23811. if ( depthTexture ) {
  23812. depthTexture.isArrayTexture = useArrayDepth;
  23813. }
  23814. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  23815. textureNeedsUpdate = true;
  23816. if ( depthTexture ) {
  23817. depthTexture.needsUpdate = true;
  23818. depthTexture.image.width = mipWidth;
  23819. depthTexture.image.height = mipHeight;
  23820. depthTexture.image.depth = useArrayDepth ? size.depth : 1;
  23821. }
  23822. }
  23823. renderTargetData.width = size.width;
  23824. renderTargetData.height = size.height;
  23825. renderTargetData.textures = textures;
  23826. renderTargetData.depthTexture = depthTexture || null;
  23827. renderTargetData.depth = renderTarget.depthBuffer;
  23828. renderTargetData.stencil = renderTarget.stencilBuffer;
  23829. renderTargetData.renderTarget = renderTarget;
  23830. if ( renderTargetData.sampleCount !== sampleCount ) {
  23831. textureNeedsUpdate = true;
  23832. if ( depthTexture ) {
  23833. depthTexture.needsUpdate = true;
  23834. }
  23835. renderTargetData.sampleCount = sampleCount;
  23836. }
  23837. //
  23838. const options = { sampleCount };
  23839. // XR render targets require no texture updates
  23840. if ( renderTarget.isXRRenderTarget !== true ) {
  23841. for ( let i = 0; i < textures.length; i ++ ) {
  23842. const texture = textures[ i ];
  23843. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  23844. this.updateTexture( texture, options );
  23845. }
  23846. if ( depthTexture ) {
  23847. this.updateTexture( depthTexture, options );
  23848. }
  23849. }
  23850. // dispose handler
  23851. if ( renderTargetData.initialized !== true ) {
  23852. renderTargetData.initialized = true;
  23853. this.info.memory.renderTargets ++;
  23854. // dispose
  23855. renderTargetData.onDispose = () => {
  23856. this._destroyRenderTarget( renderTarget );
  23857. };
  23858. renderTarget.addEventListener( 'dispose', renderTargetData.onDispose );
  23859. }
  23860. }
  23861. /**
  23862. * Updates the given texture. Depending on the texture state, this method
  23863. * triggers the upload of texture data to the GPU memory. If the texture data are
  23864. * not yet ready for the upload, it uses default texture data for as a placeholder.
  23865. *
  23866. * @param {Texture} texture - The texture to update.
  23867. * @param {Object} [options={}] - The options.
  23868. */
  23869. updateTexture( texture, options = {} ) {
  23870. const textureData = this.get( texture );
  23871. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  23872. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  23873. const backend = this.backend;
  23874. if ( isRenderTarget && textureData.initialized === true ) {
  23875. // it's an update
  23876. backend.destroyTexture( texture );
  23877. }
  23878. //
  23879. if ( texture.isFramebufferTexture ) {
  23880. const renderTarget = this.renderer.getRenderTarget();
  23881. if ( renderTarget ) {
  23882. texture.type = renderTarget.texture.type;
  23883. } else {
  23884. texture.type = UnsignedByteType;
  23885. }
  23886. }
  23887. // Ensure HTMLTexture elements are in the canvas before measuring size.
  23888. if ( texture.isHTMLTexture && texture.image ) {
  23889. const canvas = this.renderer.domElement;
  23890. if ( 'requestPaint' in canvas ) {
  23891. if ( ! canvas.hasAttribute( 'layoutsubtree' ) ) {
  23892. canvas.setAttribute( 'layoutsubtree', 'true' );
  23893. }
  23894. if ( texture.image.parentNode !== canvas ) {
  23895. canvas.appendChild( texture.image );
  23896. }
  23897. // Set up shared paint callback for all HTMLTextures.
  23898. if ( this._htmlTextures.size === 0 ) {
  23899. const htmlTextures = this._htmlTextures;
  23900. canvas.onpaint = ( event ) => {
  23901. const changed = event && event.changedElements;
  23902. for ( const t of htmlTextures ) {
  23903. if ( ! changed || changed.includes( t.image ) ) {
  23904. t.needsUpdate = true;
  23905. }
  23906. }
  23907. };
  23908. }
  23909. this._htmlTextures.add( texture );
  23910. }
  23911. }
  23912. //
  23913. const { width, height, depth } = this.getSize( texture );
  23914. options.width = width;
  23915. options.height = height;
  23916. options.depth = depth;
  23917. options.needsMipmaps = this.needsMipmaps( texture );
  23918. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  23919. // TODO: Uniformly handle mipmap definitions
  23920. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  23921. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  23922. if ( texture.isCubeTexture && texture.mipmaps.length > 0 ) options.levels ++;
  23923. //
  23924. if ( isRenderTarget || texture.isStorageTexture === true || texture.isExternalTexture === true ) {
  23925. backend.createTexture( texture, options );
  23926. textureData.generation = texture.version;
  23927. } else {
  23928. if ( texture.version > 0 ) {
  23929. const image = texture.image;
  23930. if ( image === undefined ) {
  23931. warn( 'Renderer: Texture marked for update but image is undefined.' );
  23932. } else if ( image.complete === false ) {
  23933. warn( 'Renderer: Texture marked for update but image is incomplete.' );
  23934. } else {
  23935. if ( texture.images ) {
  23936. const images = [];
  23937. for ( const image of texture.images ) {
  23938. images.push( image );
  23939. }
  23940. options.images = images;
  23941. } else {
  23942. options.image = image;
  23943. }
  23944. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  23945. backend.createTexture( texture, options );
  23946. textureData.isDefaultTexture = false;
  23947. textureData.generation = texture.version;
  23948. }
  23949. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  23950. const skipAutoGeneration = texture.isStorageTexture === true && texture.mipmapsAutoUpdate === false;
  23951. if ( options.needsMipmaps && texture.mipmaps.length === 0 && ! skipAutoGeneration ) {
  23952. backend.generateMipmaps( texture );
  23953. }
  23954. if ( texture.onUpdate ) texture.onUpdate( texture );
  23955. }
  23956. } else {
  23957. // async update
  23958. backend.createDefaultTexture( texture );
  23959. textureData.isDefaultTexture = true;
  23960. textureData.generation = texture.version;
  23961. }
  23962. }
  23963. // dispose handler
  23964. if ( textureData.initialized !== true ) {
  23965. textureData.initialized = true;
  23966. textureData.generation = texture.version;
  23967. textureData.bindGroups = new Set();
  23968. //
  23969. this.info.createTexture( texture );
  23970. //
  23971. if ( texture.isVideoTexture && ColorManagement.enabled === true && ColorManagement.getTransfer( texture.colorSpace ) !== SRGBTransfer ) {
  23972. warn( 'WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace.' );
  23973. }
  23974. // dispose
  23975. textureData.onDispose = () => {
  23976. this._destroyTexture( texture );
  23977. };
  23978. texture.addEventListener( 'dispose', textureData.onDispose );
  23979. }
  23980. //
  23981. textureData.version = texture.version;
  23982. }
  23983. /**
  23984. * Updates the sampler for the given texture. This method has no effect
  23985. * for the WebGL backend since it has no concept of samplers. Texture
  23986. * parameters are configured with the `texParameter()` command for each
  23987. * texture.
  23988. *
  23989. * In WebGPU, samplers are objects like textures and it's possible to share
  23990. * them when the texture parameters match.
  23991. *
  23992. * @param {Texture} texture - The texture to update the sampler for.
  23993. * @param {TextureNode} textureNode - The texture node to update the sampler with.
  23994. * @return {string} The current sampler key.
  23995. */
  23996. updateSampler( texture, textureNode ) {
  23997. return this.backend.updateSampler( texture, textureNode );
  23998. }
  23999. /**
  24000. * Computes the size of the given texture and writes the result
  24001. * into the target vector. This vector is also returned by the
  24002. * method.
  24003. *
  24004. * If no texture data are available for the compute yet, the method
  24005. * returns default size values.
  24006. *
  24007. * @param {Texture} texture - The texture to compute the size for.
  24008. * @param {Vector3} target - The target vector.
  24009. * @return {Vector3} The target vector.
  24010. */
  24011. getSize( texture, target = _size$3 ) {
  24012. let image = texture.images ? texture.images[ 0 ] : texture.image;
  24013. if ( image ) {
  24014. if ( image.image !== undefined ) image = image.image;
  24015. if ( texture.isHTMLTexture ) {
  24016. target.width = image.offsetWidth || 1;
  24017. target.height = image.offsetHeight || 1;
  24018. target.depth = 1;
  24019. } else if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( image instanceof HTMLVideoElement ) ) {
  24020. target.width = image.videoWidth || 1;
  24021. target.height = image.videoHeight || 1;
  24022. target.depth = 1;
  24023. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( image instanceof VideoFrame ) ) {
  24024. target.width = image.displayWidth || 1;
  24025. target.height = image.displayHeight || 1;
  24026. target.depth = 1;
  24027. } else {
  24028. target.width = image.width || 1;
  24029. target.height = image.height || 1;
  24030. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  24031. }
  24032. } else {
  24033. target.width = target.height = target.depth = 1;
  24034. }
  24035. return target;
  24036. }
  24037. /**
  24038. * Computes the number of mipmap levels for the given texture.
  24039. *
  24040. * @param {Texture} texture - The texture.
  24041. * @param {number} width - The texture's width.
  24042. * @param {number} height - The texture's height.
  24043. * @return {number} The number of mipmap levels.
  24044. */
  24045. getMipLevels( texture, width, height ) {
  24046. let mipLevelCount;
  24047. if ( texture.mipmaps.length > 0 ) {
  24048. mipLevelCount = texture.mipmaps.length;
  24049. } else {
  24050. if ( texture.isCompressedTexture === true ) {
  24051. // it is not possible to compute mipmaps for compressed textures. So
  24052. // when no mipmaps are defined in "texture.mipmaps", force a texture
  24053. // level of 1
  24054. mipLevelCount = 1;
  24055. } else {
  24056. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  24057. }
  24058. }
  24059. return mipLevelCount;
  24060. }
  24061. /**
  24062. * Returns `true` if the given texture makes use of mipmapping.
  24063. *
  24064. * @param {Texture} texture - The texture.
  24065. * @return {boolean} Whether mipmaps are required or not.
  24066. */
  24067. needsMipmaps( texture ) {
  24068. return texture.generateMipmaps === true || texture.mipmaps.length > 0;
  24069. }
  24070. /**
  24071. * Frees internal resources when the given render target isn't
  24072. * required anymore.
  24073. *
  24074. * @param {RenderTarget} renderTarget - The render target to destroy.
  24075. */
  24076. _destroyRenderTarget( renderTarget ) {
  24077. if ( this.has( renderTarget ) === true ) {
  24078. const renderTargetData = this.get( renderTarget );
  24079. const textures = renderTargetData.textures;
  24080. const depthTexture = renderTargetData.depthTexture;
  24081. //
  24082. renderTarget.removeEventListener( 'dispose', renderTargetData.onDispose );
  24083. //
  24084. for ( let i = 0; i < textures.length; i ++ ) {
  24085. this._destroyTexture( textures[ i ] );
  24086. }
  24087. if ( depthTexture ) {
  24088. this._destroyTexture( depthTexture );
  24089. }
  24090. this.delete( renderTarget );
  24091. this.backend.delete( renderTarget );
  24092. this.info.memory.renderTargets --;
  24093. }
  24094. }
  24095. /**
  24096. * Frees internal resource when the given texture isn't
  24097. * required anymore.
  24098. *
  24099. * @param {Texture} texture - The texture to destroy.
  24100. */
  24101. _destroyTexture( texture ) {
  24102. if ( this.has( texture ) === true ) {
  24103. const textureData = this.get( texture );
  24104. //
  24105. texture.removeEventListener( 'dispose', textureData.onDispose );
  24106. // if a texture is not ready for use, it falls back to a default texture so it's possible
  24107. // to use it for rendering. If a texture in this state is disposed, it's important to
  24108. // not destroy/delete the underlying GPU texture object since it is cached and shared with
  24109. // other textures.
  24110. const isDefaultTexture = textureData.isDefaultTexture;
  24111. this.backend.destroyTexture( texture, isDefaultTexture );
  24112. // delete cached bind groups so they don't point to destroyed textures
  24113. if ( textureData.bindGroups ) {
  24114. for ( const bindGroup of textureData.bindGroups ) {
  24115. const bindingsData = this.backend.get( bindGroup );
  24116. bindingsData.groups = undefined;
  24117. bindingsData.versions = undefined;
  24118. // go through all bindings and if one points to the destroyed texture, trigger dispose as well
  24119. for ( const binding of bindGroup.bindings ) {
  24120. if ( binding.isSampler && binding.texture === texture ) {
  24121. binding.reset();
  24122. }
  24123. }
  24124. }
  24125. }
  24126. this._htmlTextures.delete( texture );
  24127. this.delete( texture );
  24128. this.info.destroyTexture( texture );
  24129. }
  24130. }
  24131. }
  24132. /**
  24133. * A four-component version of {@link Color} which is internally
  24134. * used by the renderer to represents clear color with alpha as
  24135. * one object.
  24136. *
  24137. * @private
  24138. * @augments Color
  24139. */
  24140. class Color4 extends Color {
  24141. /**
  24142. * Constructs a new four-component color.
  24143. * You can also pass a single THREE.Color, hex or
  24144. * string argument to this constructor.
  24145. *
  24146. * @param {number|string} [r=1] - The red value.
  24147. * @param {number} [g=1] - The green value.
  24148. * @param {number} [b=1] - The blue value.
  24149. * @param {number} [a=1] - The alpha value.
  24150. */
  24151. constructor( r, g, b, a = 1 ) {
  24152. super( r, g, b );
  24153. this.a = a;
  24154. }
  24155. /**
  24156. * Overwrites the default to honor alpha.
  24157. * You can also pass a single THREE.Color, hex or
  24158. * string argument to this method.
  24159. *
  24160. * @param {number|string|Color} r - The red value.
  24161. * @param {number} [g] - The green value.
  24162. * @param {number} [b] - The blue value.
  24163. * @param {number} [a=1] - The alpha value.
  24164. * @return {Color4} A reference to this object.
  24165. */
  24166. set( r, g, b, a = 1 ) {
  24167. this.a = a;
  24168. return super.set( r, g, b );
  24169. }
  24170. /**
  24171. * Overwrites the default to honor alpha.
  24172. *
  24173. * @param {Color4} color - The color to copy.
  24174. * @return {Color4} A reference to this object.
  24175. */
  24176. copy( color ) {
  24177. if ( color.a !== undefined ) this.a = color.a;
  24178. return super.copy( color );
  24179. }
  24180. /**
  24181. * Overwrites the default to honor alpha.
  24182. *
  24183. * @return {Color4} The cloned color.
  24184. */
  24185. clone() {
  24186. return new this.constructor( this.r, this.g, this.b, this.a );
  24187. }
  24188. }
  24189. /**
  24190. * Special version of {@link PropertyNode} which is used for parameters.
  24191. *
  24192. * @augments PropertyNode
  24193. */
  24194. class ParameterNode extends PropertyNode {
  24195. static get type() {
  24196. return 'ParameterNode';
  24197. }
  24198. /**
  24199. * Constructs a new parameter node.
  24200. *
  24201. * @param {string} nodeType - The type of the node.
  24202. * @param {?string} [name=null] - The name of the parameter in the shader.
  24203. */
  24204. constructor( nodeType, name = null ) {
  24205. super( nodeType, name );
  24206. /**
  24207. * This flag can be used for type testing.
  24208. *
  24209. * @type {boolean}
  24210. * @readonly
  24211. * @default true
  24212. */
  24213. this.isParameterNode = true;
  24214. }
  24215. /**
  24216. * Gets the type of a member variable in the parameter node.
  24217. *
  24218. * @param {NodeBuilder} builder - The node builder.
  24219. * @param {string} name - The name of the member variable.
  24220. * @returns {string}
  24221. */
  24222. getMemberType( builder, name ) {
  24223. const type = this.getNodeType( builder );
  24224. const struct = builder.getStructTypeNode( type );
  24225. let memberType;
  24226. if ( struct !== null ) {
  24227. memberType = struct.getMemberType( builder, name );
  24228. } else {
  24229. error( `TSL: Member "${ name }" not found in struct "${ type }".`, new StackTrace() );
  24230. memberType = 'float';
  24231. }
  24232. return memberType;
  24233. }
  24234. getHash() {
  24235. return String( this.id );
  24236. }
  24237. generate() {
  24238. return this.name;
  24239. }
  24240. }
  24241. /**
  24242. * TSL function for creating a parameter node.
  24243. *
  24244. * @tsl
  24245. * @function
  24246. * @param {string} type - The type of the node.
  24247. * @param {?string} name - The name of the parameter in the shader.
  24248. * @returns {ParameterNode}
  24249. */
  24250. const parameter = ( type, name ) => new ParameterNode( type, name );
  24251. /**
  24252. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  24253. * They are usually needed in cases like `If`, `Else`.
  24254. *
  24255. * @augments Node
  24256. */
  24257. class StackNode extends Node {
  24258. static get type() {
  24259. return 'StackNode';
  24260. }
  24261. /**
  24262. * Constructs a new stack node.
  24263. *
  24264. * @param {?StackNode} [parent=null] - The parent stack node.
  24265. */
  24266. constructor( parent = null ) {
  24267. super();
  24268. /**
  24269. * List of nodes.
  24270. *
  24271. * @type {Array<Node>}
  24272. */
  24273. this.nodes = [];
  24274. /**
  24275. * The output node.
  24276. *
  24277. * @type {?Node}
  24278. * @default null
  24279. */
  24280. this.outputNode = null;
  24281. /**
  24282. * The parent stack node.
  24283. *
  24284. * @type {?StackNode}
  24285. * @default null
  24286. */
  24287. this.parent = parent;
  24288. /**
  24289. * The current conditional node.
  24290. *
  24291. * @private
  24292. * @type {ConditionalNode}
  24293. * @default null
  24294. */
  24295. this._currentCond = null;
  24296. /**
  24297. * The expression node. Only
  24298. * relevant for Switch/Case.
  24299. *
  24300. * @private
  24301. * @type {Node}
  24302. * @default null
  24303. */
  24304. this._expressionNode = null;
  24305. /**
  24306. * The current node being processed.
  24307. *
  24308. * @private
  24309. * @type {Node}
  24310. * @default null
  24311. */
  24312. this._currentNode = null;
  24313. /**
  24314. * Stores additional data for nodes that are added to the stack.
  24315. *
  24316. * @private
  24317. * @type {Map<Node, {delta: number}>}
  24318. */
  24319. this._nodeDataLibrary = new Map();
  24320. /**
  24321. * This flag can be used for type testing.
  24322. *
  24323. * @type {boolean}
  24324. * @readonly
  24325. * @default true
  24326. */
  24327. this.isStackNode = true;
  24328. }
  24329. getElementType( builder ) {
  24330. return this.outputNode ? this.outputNode.getElementType( builder ) : 'void';
  24331. }
  24332. generateNodeType( builder ) {
  24333. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  24334. }
  24335. getMemberType( builder, name ) {
  24336. return this.outputNode ? this.outputNode.getMemberType( builder, name ) : 'void';
  24337. }
  24338. /**
  24339. * Adds a node to this stack.
  24340. *
  24341. * @param {Node} node - The node to add.
  24342. * @param {number} [index=-1] - The index of the node. If not specified, the node will be added to the end of the stack.
  24343. * @return {StackNode} A reference to this stack node.
  24344. */
  24345. addToStack( node, index = -1 ) {
  24346. if ( node.isNode !== true ) {
  24347. error( 'TSL: Invalid node added to stack.', new StackTrace() );
  24348. return this;
  24349. }
  24350. if ( index === -1 ) {
  24351. if ( this._currentNode ) {
  24352. let nodeData = this._nodeDataLibrary.get( this._currentNode );
  24353. if ( nodeData === undefined ) {
  24354. nodeData = {
  24355. delta: 0
  24356. };
  24357. this._nodeDataLibrary.set( this._currentNode, nodeData );
  24358. }
  24359. nodeData.delta ++;
  24360. index = this.nodes.indexOf( this._currentNode ) + nodeData.delta;
  24361. } else {
  24362. index = this.nodes.length;
  24363. }
  24364. }
  24365. this.nodes.splice( index, 0, node );
  24366. return this;
  24367. }
  24368. /**
  24369. * Adds a node to the stack before the current node.
  24370. *
  24371. * @param {Node} node - The node to add.
  24372. * @return {StackNode} A reference to this stack node.
  24373. */
  24374. addToStackBefore( node ) {
  24375. const index = this._currentNode ? this.nodes.indexOf( this._currentNode ) : 0;
  24376. return this.addToStack( node, index );
  24377. }
  24378. /**
  24379. * Represent an `if` statement in TSL.
  24380. *
  24381. * @param {Node} boolNode - Represents the condition.
  24382. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  24383. * @return {StackNode} A reference to this stack node.
  24384. */
  24385. If( boolNode, method ) {
  24386. const methodNode = new ShaderNode( method );
  24387. this._currentCond = select( boolNode, methodNode );
  24388. return this.addToStack( this._currentCond );
  24389. }
  24390. /**
  24391. * Represent an `elseif` statement in TSL.
  24392. *
  24393. * @param {Node} boolNode - Represents the condition.
  24394. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  24395. * @return {StackNode} A reference to this stack node.
  24396. */
  24397. ElseIf( boolNode, method ) {
  24398. const methodNode = new ShaderNode( method );
  24399. const ifNode = select( boolNode, methodNode );
  24400. this._currentCond.elseNode = ifNode;
  24401. this._currentCond = ifNode;
  24402. return this;
  24403. }
  24404. /**
  24405. * Represent an `else` statement in TSL.
  24406. *
  24407. * @param {Function} method - TSL code which is executed in the `else` case.
  24408. * @return {StackNode} A reference to this stack node.
  24409. */
  24410. Else( method ) {
  24411. this._currentCond.elseNode = new ShaderNode( method );
  24412. return this;
  24413. }
  24414. /**
  24415. * Represents a `switch` statement in TSL.
  24416. *
  24417. * @param {any} expression - Represents the expression.
  24418. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  24419. * @return {StackNode} A reference to this stack node.
  24420. */
  24421. Switch( expression ) {
  24422. this._expressionNode = nodeObject( expression );
  24423. return this;
  24424. }
  24425. /**
  24426. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  24427. * The last parameter must be the callback method that should be executed in the `true` case.
  24428. *
  24429. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  24430. * @return {StackNode} A reference to this stack node.
  24431. */
  24432. Case( ...params ) {
  24433. const caseNodes = [];
  24434. // extract case nodes from the parameter list
  24435. if ( params.length >= 2 ) {
  24436. for ( let i = 0; i < params.length - 1; i ++ ) {
  24437. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  24438. }
  24439. } else {
  24440. error( 'TSL: Invalid parameter length. Case() requires at least two parameters.', new StackTrace() );
  24441. }
  24442. // extract method
  24443. const method = params[ params.length - 1 ];
  24444. const methodNode = new ShaderNode( method );
  24445. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  24446. let caseNode = caseNodes[ 0 ];
  24447. for ( let i = 1; i < caseNodes.length; i ++ ) {
  24448. caseNode = caseNode.or( caseNodes[ i ] );
  24449. }
  24450. // build condition
  24451. const condNode = select( caseNode, methodNode );
  24452. if ( this._currentCond === null ) {
  24453. this._currentCond = condNode;
  24454. return this.addToStack( this._currentCond );
  24455. } else {
  24456. this._currentCond.elseNode = condNode;
  24457. this._currentCond = condNode;
  24458. return this;
  24459. }
  24460. }
  24461. /**
  24462. * Represents the default code block of a Switch/Case statement.
  24463. *
  24464. * @param {Function} method - TSL code which is executed in the `else` case.
  24465. * @return {StackNode} A reference to this stack node.
  24466. */
  24467. Default( method ) {
  24468. this.Else( method );
  24469. return this;
  24470. }
  24471. setup( builder ) {
  24472. const nodeProperties = builder.getNodeProperties( this );
  24473. let index = 0;
  24474. for ( const childNode of this.getChildren() ) {
  24475. if ( childNode.isVarNode && childNode.isIntent( builder ) ) {
  24476. if ( childNode.isAssign( builder ) !== true ) {
  24477. continue;
  24478. }
  24479. }
  24480. nodeProperties[ 'node' + index ++ ] = childNode;
  24481. }
  24482. // return a outputNode if exists or null
  24483. return nodeProperties.outputNode || null;
  24484. }
  24485. build( builder, ...params ) {
  24486. const previousStack = getCurrentStack();
  24487. const buildStage = builder.buildStage;
  24488. setCurrentStack( this );
  24489. builder.setActiveStack( this );
  24490. //
  24491. for ( let i = 0; i < this.nodes.length; i ++ ) {
  24492. const node = this.nodes[ i ];
  24493. const previousNode = this._currentNode;
  24494. this._currentNode = node;
  24495. if ( node.isVarNode && node.isIntent( builder ) ) {
  24496. if ( node.isAssign( builder ) !== true ) {
  24497. continue;
  24498. }
  24499. }
  24500. if ( buildStage === 'setup' ) {
  24501. node.build( builder );
  24502. } else if ( buildStage === 'analyze' ) {
  24503. node.build( builder, this );
  24504. } else if ( buildStage === 'generate' ) {
  24505. const stages = builder.getDataFromNode( node, 'any' ).stages;
  24506. const parents = stages && stages[ builder.shaderStage ];
  24507. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  24508. continue; // skip var nodes that are only used in .toVarying()
  24509. }
  24510. node.build( builder, 'void' );
  24511. }
  24512. this._currentNode = previousNode;
  24513. }
  24514. //
  24515. let result;
  24516. if ( this.outputNode ) {
  24517. const buildResult = this.outputNode.build( builder, ...params );
  24518. if ( builder.buildStage !== 'generate' || this.outputNode.getNodeType( builder ) !== 'void' ) {
  24519. result = buildResult;
  24520. }
  24521. } else {
  24522. result = super.build( builder, ...params );
  24523. }
  24524. setCurrentStack( previousStack );
  24525. builder.removeActiveStack( this );
  24526. return result;
  24527. }
  24528. }
  24529. /**
  24530. * TSL function for creating a stack node.
  24531. *
  24532. * @tsl
  24533. * @function
  24534. * @param {?StackNode} [parent=null] - The parent stack node.
  24535. * @returns {StackNode}
  24536. */
  24537. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  24538. /**
  24539. * Generates a layout for struct members.
  24540. * This function takes an object representing struct members and returns an array of member layouts.
  24541. * Each member layout includes the member's name, type, and whether it is atomic.
  24542. *
  24543. * @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.
  24544. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  24545. */
  24546. function getMembersLayout( members ) {
  24547. return Object.entries( members ).map( ( [ name, value ] ) => {
  24548. if ( typeof value === 'string' ) {
  24549. return { name, type: value, atomic: false };
  24550. }
  24551. return { name, type: value.type, atomic: value.atomic || false };
  24552. } );
  24553. }
  24554. /**
  24555. * Represents a struct type node in the node-based system.
  24556. * This class is used to define and manage the layout and types of struct members.
  24557. * It extends the base Node class and provides methods to get the length of the struct,
  24558. * retrieve member types, and generate the struct type for a builder.
  24559. *
  24560. * @augments Node
  24561. */
  24562. class StructTypeNode extends Node {
  24563. static get type() {
  24564. return 'StructTypeNode';
  24565. }
  24566. /**
  24567. * Creates an instance of StructTypeNode.
  24568. *
  24569. * @param {Object} membersLayout - The layout of the members for the struct.
  24570. * @param {?string} [name=null] - The optional name of the struct.
  24571. */
  24572. constructor( membersLayout, name = null ) {
  24573. super( 'struct' );
  24574. /**
  24575. * The layout of the members for the struct
  24576. *
  24577. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  24578. */
  24579. this.membersLayout = getMembersLayout( membersLayout );
  24580. /**
  24581. * The name of the struct.
  24582. *
  24583. * @type {?string}
  24584. * @default null
  24585. */
  24586. this.name = name;
  24587. /**
  24588. * This flag can be used for type testing.
  24589. *
  24590. * @type {boolean}
  24591. * @readonly
  24592. * @default true
  24593. */
  24594. this.isStructLayoutNode = true;
  24595. }
  24596. /**
  24597. * Returns the length of the struct.
  24598. * The length is calculated by summing the lengths of the struct's members.
  24599. *
  24600. * @returns {number} The length of the struct.
  24601. */
  24602. getLength() {
  24603. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  24604. let maxAlignment = 1; // maximum alignment value in this struct
  24605. let offset = 0; // global buffer offset in 4 byte elements
  24606. for ( const member of this.membersLayout ) {
  24607. const type = member.type;
  24608. const itemSize = getMemoryLengthFromType( type );
  24609. const alignment = getAlignmentFromType( type ) / BYTES_PER_ELEMENT;
  24610. maxAlignment = Math.max( maxAlignment, alignment );
  24611. const chunkOffset = offset % maxAlignment; // offset in the current chunk of maxAlignment elements
  24612. const overhang = chunkOffset % alignment; // distance from the last aligned offset
  24613. if ( overhang !== 0 ) {
  24614. offset += alignment - overhang; // move to next aligned offset
  24615. }
  24616. offset += itemSize;
  24617. }
  24618. return ( Math.ceil( offset / maxAlignment ) * maxAlignment ); // ensure length is a multiple of maxAlignment
  24619. }
  24620. getMemberType( builder, name ) {
  24621. const member = this.membersLayout.find( m => m.name === name );
  24622. return member ? member.type : 'void';
  24623. }
  24624. generateNodeType( builder ) {
  24625. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  24626. return structType.name;
  24627. }
  24628. setup( builder ) {
  24629. builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  24630. builder.addInclude( this );
  24631. }
  24632. generate( builder ) {
  24633. return this.getNodeType( builder );
  24634. }
  24635. }
  24636. /**
  24637. * StructNode allows to create custom structures with multiple members.
  24638. * This can also be used to define structures in attribute and uniform data.
  24639. *
  24640. * ```js
  24641. * // Define a custom struct
  24642. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  24643. *
  24644. * // Create a new instance of the struct
  24645. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  24646. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  24647. *
  24648. * // Access the struct members
  24649. * const min = bb.get( 'min' );
  24650. *
  24651. * // Assign a new value to a member
  24652. * min.assign( vec3() );
  24653. * ```
  24654. * @augments Node
  24655. */
  24656. class StructNode extends Node {
  24657. static get type() {
  24658. return 'StructNode';
  24659. }
  24660. constructor( structTypeNode, values ) {
  24661. super( 'vec3' );
  24662. this.structTypeNode = structTypeNode;
  24663. this.values = values;
  24664. this.isStructNode = true;
  24665. }
  24666. generateNodeType( builder ) {
  24667. return this.structTypeNode.getNodeType( builder );
  24668. }
  24669. getMemberType( builder, name ) {
  24670. return this.structTypeNode.getMemberType( builder, name );
  24671. }
  24672. _getChildren() {
  24673. // Ensure struct type is the last child for correct code generation order
  24674. const children = super._getChildren();
  24675. const structTypeProperty = children.find( child => child.childNode === this.structTypeNode );
  24676. children.splice( children.indexOf( structTypeProperty ), 1 );
  24677. children.push( structTypeProperty );
  24678. return children;
  24679. }
  24680. generate( builder ) {
  24681. const nodeVar = builder.getVarFromNode( this );
  24682. const structType = nodeVar.type;
  24683. const propertyName = builder.getPropertyName( nodeVar );
  24684. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structTypeNode.membersLayout, this.values ) }`, this );
  24685. return nodeVar.name;
  24686. }
  24687. }
  24688. /**
  24689. * TSL function for creating a struct node.
  24690. *
  24691. * @tsl
  24692. * @function
  24693. * @param {Object} membersLayout - The layout of the struct members.
  24694. * @param {?string} [name=null] - The name of the struct.
  24695. * @returns {Function} The struct function.
  24696. */
  24697. const struct = ( membersLayout, name = null ) => {
  24698. const structLayout = new StructTypeNode( membersLayout, name );
  24699. const struct = ( ...params ) => {
  24700. let values = null;
  24701. if ( params.length > 0 ) {
  24702. if ( params[ 0 ].isNode ) {
  24703. values = {};
  24704. const names = Object.keys( membersLayout );
  24705. for ( let i = 0; i < params.length; i ++ ) {
  24706. values[ names[ i ] ] = params[ i ];
  24707. }
  24708. } else {
  24709. values = params[ 0 ];
  24710. }
  24711. }
  24712. return new StructNode( structLayout, values );
  24713. };
  24714. struct.layout = structLayout;
  24715. struct.isStruct = true;
  24716. return struct;
  24717. };
  24718. /**
  24719. * This node can be used to define multiple outputs in a shader programs.
  24720. *
  24721. * @augments Node
  24722. */
  24723. class OutputStructNode extends Node {
  24724. static get type() {
  24725. return 'OutputStructNode';
  24726. }
  24727. /**
  24728. * Constructs a new output struct node. The constructor can be invoked with an
  24729. * arbitrary number of nodes representing the members.
  24730. *
  24731. * @param {...Node} members - A parameter list of nodes.
  24732. */
  24733. constructor( ...members ) {
  24734. super();
  24735. /**
  24736. * An array of nodes which defines the output.
  24737. *
  24738. * @type {Array<Node>}
  24739. */
  24740. this.members = members;
  24741. /**
  24742. * This flag can be used for type testing.
  24743. *
  24744. * @type {boolean}
  24745. * @readonly
  24746. * @default true
  24747. */
  24748. this.isOutputStructNode = true;
  24749. }
  24750. generateNodeType( /*builder*/ ) {
  24751. return 'OutputType';
  24752. }
  24753. generate( builder ) {
  24754. const nodeData = builder.getDataFromNode( this );
  24755. if ( nodeData.membersLayout === undefined ) {
  24756. const members = this.members;
  24757. const membersLayout = [];
  24758. for ( let i = 0; i < members.length; i ++ ) {
  24759. const name = 'm' + i;
  24760. const type = members[ i ].getNodeType( builder );
  24761. membersLayout.push( { name, type, index: i } );
  24762. }
  24763. nodeData.membersLayout = membersLayout;
  24764. nodeData.structType = builder.getOutputStructTypeFromNode( this, nodeData.membersLayout );
  24765. }
  24766. //
  24767. const propertyName = builder.getOutputStructName();
  24768. const members = this.members;
  24769. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  24770. for ( let i = 0; i < members.length; i ++ ) {
  24771. const snippet = members[ i ].build( builder );
  24772. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  24773. }
  24774. return propertyName;
  24775. }
  24776. }
  24777. /**
  24778. * TSL function for creating an output struct node.
  24779. *
  24780. * @tsl
  24781. * @function
  24782. * @param {...Node} members - A parameter list of nodes.
  24783. * @returns {OutputStructNode}
  24784. */
  24785. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  24786. /**
  24787. * Represents blending configuration.
  24788. *
  24789. * This class encapsulates all blending-related properties that control how
  24790. * a material's colors are combined with the colors already in the frame buffer.
  24791. */
  24792. class BlendMode {
  24793. /**
  24794. * Constructs a new blending configuration.
  24795. *
  24796. * @param {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending|MaterialBlending)} [blending=NormalBlending] - The blending mode.
  24797. */
  24798. constructor( blending = NormalBlending ) {
  24799. /**
  24800. * Defines the blending type.
  24801. *
  24802. * It must be set to `CustomBlending` if custom blending properties like
  24803. * {@link BlendMode#blendSrc}, {@link BlendMode#blendDst} or {@link BlendMode#blendEquation}
  24804. * should have any effect.
  24805. *
  24806. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending|MaterialBlending)}
  24807. * @default NormalBlending
  24808. */
  24809. this.blending = blending;
  24810. /**
  24811. * Defines the blending source factor.
  24812. *
  24813. * This determines how the source (incoming) fragment color is factored before being added
  24814. * to the destination (existing) fragment color in the frame buffer.
  24815. *
  24816. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  24817. * @default SrcAlphaFactor
  24818. */
  24819. this.blendSrc = SrcAlphaFactor;
  24820. /**
  24821. * Defines the blending destination factor.
  24822. *
  24823. * This determines how the destination (existing) fragment color in the frame buffer
  24824. * is factored before being combined with the source (incoming) fragment color.
  24825. *
  24826. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  24827. * @default OneMinusSrcAlphaFactor
  24828. */
  24829. this.blendDst = OneMinusSrcAlphaFactor;
  24830. /**
  24831. * Defines the blending equation.
  24832. *
  24833. * This determines how the source and destination colors are combined.
  24834. *
  24835. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  24836. * @default AddEquation
  24837. */
  24838. this.blendEquation = AddEquation;
  24839. /**
  24840. * Defines the blending source alpha factor.
  24841. *
  24842. * When set, this allows separate control of the alpha channel's source blending factor.
  24843. * If `null`, {@link BlendMode#blendSrc} is used for the alpha channel as well.
  24844. *
  24845. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  24846. * @default null
  24847. */
  24848. this.blendSrcAlpha = null;
  24849. /**
  24850. * Defines the blending destination alpha factor.
  24851. *
  24852. * When set, this allows separate control of the alpha channel's destination blending factor.
  24853. * If `null`, {@link BlendMode#blendDst} is used for the alpha channel as well.
  24854. *
  24855. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  24856. * @default null
  24857. */
  24858. this.blendDstAlpha = null;
  24859. /**
  24860. * Defines the blending equation of the alpha channel.
  24861. *
  24862. * When set, this allows separate control of the alpha channel's blending equation.
  24863. * If `null`, {@link BlendMode#blendEquation} is used for the alpha channel as well.
  24864. *
  24865. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  24866. * @default null
  24867. */
  24868. this.blendEquationAlpha = null;
  24869. /**
  24870. * Defines whether to premultiply the alpha (transparency) value.
  24871. *
  24872. * If `true`, the RGB color of the texture or material is multiplied by its alpha value.
  24873. * This is useful for transparent textures/materials where the color data
  24874. * should already include the transparency information.
  24875. *
  24876. * @type {boolean}
  24877. * @default false
  24878. */
  24879. this.premultiplyAlpha = false;
  24880. }
  24881. /**
  24882. * Copies the blending properties from the given source to this instance.
  24883. *
  24884. * @param {BlendMode} source - The blending configuration to copy from.
  24885. * @return {BlendMode} A reference to this instance.
  24886. */
  24887. copy( source ) {
  24888. this.blending = source.blending;
  24889. this.blendSrc = source.blendSrc;
  24890. this.blendDst = source.blendDst;
  24891. this.blendEquation = source.blendEquation;
  24892. this.blendSrcAlpha = source.blendSrcAlpha;
  24893. this.blendDstAlpha = source.blendDstAlpha;
  24894. this.blendEquationAlpha = source.blendEquationAlpha;
  24895. this.premultiplyAlpha = source.premultiplyAlpha;
  24896. return this;
  24897. }
  24898. /**
  24899. * Returns a clone of this blending configuration.
  24900. *
  24901. * @return {BlendMode} A new Blending instance with the same properties.
  24902. */
  24903. clone() {
  24904. return new this.constructor().copy( this );
  24905. }
  24906. }
  24907. // Predefined blend modes for MRT nodes.
  24908. const _noBlending = /**@__PURE__*/ new BlendMode( NoBlending );
  24909. const _materialBlending = /**@__PURE__*/ new BlendMode( MaterialBlending );
  24910. /**
  24911. * Returns the MRT texture index for the given name.
  24912. *
  24913. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  24914. * @param {string} name - The name of the MRT texture which index is requested.
  24915. * @return {number} The texture index.
  24916. */
  24917. function getTextureIndex( textures, name ) {
  24918. for ( let i = 0; i < textures.length; i ++ ) {
  24919. if ( textures[ i ].name === name ) {
  24920. return i;
  24921. }
  24922. }
  24923. return -1;
  24924. }
  24925. /**
  24926. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  24927. * post-processing is shown below:
  24928. * ```js
  24929. * const mrtNode = mrt( {
  24930. * output: output,
  24931. * normal: normalView
  24932. * } ) ;
  24933. * ```
  24934. * The MRT output is defined as a dictionary.
  24935. *
  24936. * @augments OutputStructNode
  24937. */
  24938. class MRTNode extends OutputStructNode {
  24939. static get type() {
  24940. return 'MRTNode';
  24941. }
  24942. /**
  24943. * Constructs a new output struct node.
  24944. *
  24945. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  24946. */
  24947. constructor( outputNodes ) {
  24948. super();
  24949. /**
  24950. * A dictionary representing the MRT outputs. The key
  24951. * is the name of the output, the value the node which produces
  24952. * the output result.
  24953. *
  24954. * @type {Object<string, Node>}
  24955. */
  24956. this.outputNodes = outputNodes;
  24957. /**
  24958. * A dictionary storing the blend modes for each output.
  24959. *
  24960. * @type {Object<string, BlendMode>}
  24961. */
  24962. this.blendModes = {
  24963. output: _materialBlending
  24964. };
  24965. /**
  24966. * This flag can be used for type testing.
  24967. *
  24968. * @type {boolean}
  24969. * @readonly
  24970. * @default true
  24971. */
  24972. this.isMRTNode = true;
  24973. }
  24974. /**
  24975. * Sets the blend mode for the given output name.
  24976. *
  24977. * @param {string} name - The name of the output.
  24978. * @param {BlendMode} blend - The blending mode.
  24979. * @return {MRTNode} The current MRT node.
  24980. */
  24981. setBlendMode( name, blend ) {
  24982. this.blendModes[ name ] = blend;
  24983. return this;
  24984. }
  24985. /**
  24986. * Returns the blend mode for the given output name.
  24987. *
  24988. * @param {string} name - The name of the output.
  24989. * @return {BlendMode} The blend mode.
  24990. */
  24991. getBlendMode( name ) {
  24992. return this.blendModes[ name ] || _noBlending;
  24993. }
  24994. /**
  24995. * Returns `true` if the MRT node has an output with the given name.
  24996. *
  24997. * @param {string} name - The name of the output.
  24998. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  24999. */
  25000. has( name ) {
  25001. return this.outputNodes[ name ] !== undefined;
  25002. }
  25003. /**
  25004. * Returns the output node for the given name.
  25005. *
  25006. * @param {string} name - The name of the output.
  25007. * @return {Node} The output node.
  25008. */
  25009. get( name ) {
  25010. return this.outputNodes[ name ];
  25011. }
  25012. /**
  25013. * Merges the outputs of the given MRT node with the outputs of this node.
  25014. *
  25015. * @param {MRTNode} mrtNode - The MRT to merge.
  25016. * @return {MRTNode} A new MRT node with merged outputs..
  25017. */
  25018. merge( mrtNode ) {
  25019. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  25020. const blendings = { ...this.blendModes, ...mrtNode.blendModes };
  25021. const mrtTarget = mrt( outputs );
  25022. mrtTarget.blendings = blendings;
  25023. return mrtTarget;
  25024. }
  25025. setup( builder ) {
  25026. const outputNodes = this.outputNodes;
  25027. const mrt = builder.renderer.getRenderTarget();
  25028. const members = [];
  25029. const textures = mrt.textures;
  25030. for ( const name in outputNodes ) {
  25031. const index = getTextureIndex( textures, name );
  25032. members[ index ] = vec4( outputNodes[ name ] );
  25033. }
  25034. this.members = members;
  25035. return super.setup( builder );
  25036. }
  25037. }
  25038. /**
  25039. * TSL function for creating a MRT node.
  25040. *
  25041. * @tsl
  25042. * @function
  25043. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  25044. * @returns {MRTNode}
  25045. */
  25046. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  25047. /**
  25048. * This node represents an operation that reinterprets the bit representation of a value
  25049. * in one type as a value in another type.
  25050. *
  25051. * @augments TempNode
  25052. */
  25053. class BitcastNode extends TempNode {
  25054. static get type() {
  25055. return 'BitcastNode';
  25056. }
  25057. /**
  25058. * Constructs a new bitcast node.
  25059. *
  25060. * @param {Node} valueNode - The value to convert.
  25061. * @param {string} conversionType - The type to convert to.
  25062. * @param {?string} [inputType = null] - The expected input data type of the bitcast operation.
  25063. */
  25064. constructor( valueNode, conversionType, inputType = null ) {
  25065. super();
  25066. /**
  25067. * The data to bitcast to a new type.
  25068. *
  25069. * @type {Node}
  25070. */
  25071. this.valueNode = valueNode;
  25072. /**
  25073. * The type the value will be converted to.
  25074. *
  25075. * @type {string}
  25076. */
  25077. this.conversionType = conversionType;
  25078. /**
  25079. * The expected input data type of the bitcast operation.
  25080. *
  25081. *
  25082. * @type {string}
  25083. * @default null
  25084. */
  25085. this.inputType = inputType;
  25086. /**
  25087. * This flag can be used for type testing.
  25088. *
  25089. * @type {boolean}
  25090. * @readonly
  25091. * @default true
  25092. */
  25093. this.isBitcastNode = true;
  25094. }
  25095. generateNodeType( builder ) {
  25096. // GLSL aliasing
  25097. if ( this.inputType !== null ) {
  25098. const valueType = this.valueNode.getNodeType( builder );
  25099. const valueLength = builder.getTypeLength( valueType );
  25100. return builder.getTypeFromLength( valueLength, this.conversionType );
  25101. }
  25102. return this.conversionType;
  25103. }
  25104. generate( builder ) {
  25105. const type = this.getNodeType( builder );
  25106. let inputType = '';
  25107. if ( this.inputType !== null ) {
  25108. const valueType = this.valueNode.getNodeType( builder );
  25109. const valueTypeLength = builder.getTypeLength( valueType );
  25110. inputType = valueTypeLength === 1 ? this.inputType : builder.changeComponentType( valueType, this.inputType );
  25111. } else {
  25112. inputType = this.valueNode.getNodeType( builder );
  25113. }
  25114. return `${ builder.getBitcastMethod( type, inputType ) }( ${ this.valueNode.build( builder, inputType ) } )`;
  25115. }
  25116. }
  25117. /**
  25118. * Reinterpret the bit representation of a value in one type as a value in another type.
  25119. *
  25120. * @tsl
  25121. * @function
  25122. * @param {Node | number} x - The parameter.
  25123. * @param {string} y - The new type.
  25124. * @returns {Node}
  25125. */
  25126. const bitcast = /*@__PURE__*/ nodeProxyIntent( BitcastNode ).setParameterLength( 2 );
  25127. /**
  25128. * Bitcasts a float or a vector of floats to a corresponding integer type with the same element size.
  25129. *
  25130. * @tsl
  25131. * @function
  25132. * @param {Node<float>} value - The float or vector of floats to bitcast.
  25133. * @returns {BitcastNode}
  25134. */
  25135. const floatBitsToInt = ( value ) => new BitcastNode( value, 'int', 'float' );
  25136. /**
  25137. * Bitcasts a float or a vector of floats to a corresponding unsigned integer type with the same element size.
  25138. *
  25139. * @tsl
  25140. * @function
  25141. * @param {Node<float>} value - The float or vector of floats to bitcast.
  25142. * @returns {BitcastNode}
  25143. */
  25144. const floatBitsToUint = ( value ) => new BitcastNode( value, 'uint', 'float' );
  25145. /**
  25146. * Bitcasts an integer or a vector of integers to a corresponding float type with the same element size.
  25147. *
  25148. * @tsl
  25149. * @function
  25150. * @param {Node<int>} value - The integer or vector of integers to bitcast.
  25151. * @returns {BitcastNode}
  25152. */
  25153. const intBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'int' );
  25154. /**
  25155. * Bitcast an unsigned integer or a vector of unsigned integers to a corresponding float type with the same element size.
  25156. *
  25157. * @tsl
  25158. * @function
  25159. * @param {Node<uint>} value - The unsigned integer or vector of unsigned integers to bitcast.
  25160. * @returns {BitcastNode}
  25161. */
  25162. const uintBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'uint' );
  25163. const registeredBitcountFunctions = {};
  25164. /**
  25165. * This node represents an operation that counts the bits of a piece of shader data.
  25166. *
  25167. * @augments MathNode
  25168. */
  25169. class BitcountNode extends MathNode {
  25170. static get type() {
  25171. return 'BitcountNode';
  25172. }
  25173. /**
  25174. * Constructs a new math node.
  25175. *
  25176. * @param {'countTrailingZeros'|'countLeadingZeros'|'countOneBits'} method - The method name.
  25177. * @param {Node} aNode - The first input.
  25178. */
  25179. constructor( method, aNode ) {
  25180. super( method, aNode );
  25181. /**
  25182. * This flag can be used for type testing.
  25183. *
  25184. * @type {boolean}
  25185. * @readonly
  25186. * @default true
  25187. */
  25188. this.isBitcountNode = true;
  25189. }
  25190. /**
  25191. * Casts the input value of the function to an integer if necessary.
  25192. *
  25193. * @private
  25194. * @param {Node<uint>|Node<int>} inputNode - The input value.
  25195. * @param {Node<uint>} outputNode - The output value.
  25196. * @param {string} elementType - The type of the input value.
  25197. */
  25198. _resolveElementType( inputNode, outputNode, elementType ) {
  25199. if ( elementType === 'int' ) {
  25200. outputNode.assign( bitcast( inputNode, 'uint' ) );
  25201. } else {
  25202. outputNode.assign( inputNode );
  25203. }
  25204. }
  25205. _returnDataNode( inputType ) {
  25206. switch ( inputType ) {
  25207. case 'uint': {
  25208. return uint;
  25209. }
  25210. case 'int': {
  25211. return int;
  25212. }
  25213. case 'uvec2': {
  25214. return uvec2;
  25215. }
  25216. case 'uvec3': {
  25217. return uvec3;
  25218. }
  25219. case 'uvec4': {
  25220. return uvec4;
  25221. }
  25222. case 'ivec2': {
  25223. return ivec2;
  25224. }
  25225. case 'ivec3': {
  25226. return ivec3;
  25227. }
  25228. case 'ivec4': {
  25229. return ivec4;
  25230. }
  25231. }
  25232. }
  25233. /**
  25234. * Creates and registers a reusable GLSL function that emulates the behavior of countTrailingZeros.
  25235. *
  25236. * @private
  25237. * @param {string} method - The name of the function to create.
  25238. * @param {string} elementType - The type of the input value.
  25239. * @returns {Function} - The generated function
  25240. */
  25241. _createTrailingZerosBaseLayout( method, elementType ) {
  25242. const outputConvertNode = this._returnDataNode( elementType );
  25243. const fnDef = Fn( ( [ value ] ) => {
  25244. const v = uint( 0.0 );
  25245. this._resolveElementType( value, v, elementType );
  25246. const f = float( v.bitAnd( negate( v ) ) );
  25247. const uintBits = floatBitsToUint( f );
  25248. const numTrailingZeros = ( uintBits.shiftRight( 23 ) ).sub( 127 );
  25249. return outputConvertNode( numTrailingZeros );
  25250. } ).setLayout( {
  25251. name: method,
  25252. type: elementType,
  25253. inputs: [
  25254. { name: 'value', type: elementType }
  25255. ]
  25256. } );
  25257. return fnDef;
  25258. }
  25259. /**
  25260. * Creates and registers a reusable GLSL function that emulates the behavior of countLeadingZeros.
  25261. *
  25262. * @private
  25263. * @param {string} method - The name of the function to create.
  25264. * @param {string} elementType - The type of the input value.
  25265. * @returns {Function} - The generated function
  25266. */
  25267. _createLeadingZerosBaseLayout( method, elementType ) {
  25268. const outputConvertNode = this._returnDataNode( elementType );
  25269. const fnDef = Fn( ( [ value ] ) => {
  25270. If( value.equal( uint( 0 ) ), () => {
  25271. return uint( 32 );
  25272. } );
  25273. const v = uint( 0 );
  25274. const n = uint( 0 );
  25275. this._resolveElementType( value, v, elementType );
  25276. If( v.shiftRight( 16 ).equal( 0 ), () => {
  25277. n.addAssign( 16 );
  25278. v.shiftLeftAssign( 16 );
  25279. } );
  25280. If( v.shiftRight( 24 ).equal( 0 ), () => {
  25281. n.addAssign( 8 );
  25282. v.shiftLeftAssign( 8 );
  25283. } );
  25284. If( v.shiftRight( 28 ).equal( 0 ), () => {
  25285. n.addAssign( 4 );
  25286. v.shiftLeftAssign( 4 );
  25287. } );
  25288. If( v.shiftRight( 30 ).equal( 0 ), () => {
  25289. n.addAssign( 2 );
  25290. v.shiftLeftAssign( 2 );
  25291. } );
  25292. If( v.shiftRight( 31 ).equal( 0 ), () => {
  25293. n.addAssign( 1 );
  25294. } );
  25295. return outputConvertNode( n );
  25296. } ).setLayout( {
  25297. name: method,
  25298. type: elementType,
  25299. inputs: [
  25300. { name: 'value', type: elementType }
  25301. ]
  25302. } );
  25303. return fnDef;
  25304. }
  25305. /**
  25306. * Creates and registers a reusable GLSL function that emulates the behavior of countOneBits.
  25307. *
  25308. * @private
  25309. * @param {string} method - The name of the function to create.
  25310. * @param {string} elementType - The type of the input value.
  25311. * @returns {Function} - The generated function
  25312. */
  25313. _createOneBitsBaseLayout( method, elementType ) {
  25314. const outputConvertNode = this._returnDataNode( elementType );
  25315. const fnDef = Fn( ( [ value ] ) => {
  25316. const v = uint( 0.0 );
  25317. this._resolveElementType( value, v, elementType );
  25318. v.assign( v.sub( v.shiftRight( uint( 1 ) ).bitAnd( uint( 0x55555555 ) ) ) );
  25319. v.assign( v.bitAnd( uint( 0x33333333 ) ).add( v.shiftRight( uint( 2 ) ).bitAnd( uint( 0x33333333 ) ) ) );
  25320. const numBits = v.add( v.shiftRight( uint( 4 ) ) ).bitAnd( uint( 0xF0F0F0F ) ).mul( uint( 0x1010101 ) ).shiftRight( uint( 24 ) );
  25321. return outputConvertNode( numBits );
  25322. } ).setLayout( {
  25323. name: method,
  25324. type: elementType,
  25325. inputs: [
  25326. { name: 'value', type: elementType }
  25327. ]
  25328. } );
  25329. return fnDef;
  25330. }
  25331. /**
  25332. * Creates and registers a reusable GLSL function that emulates the behavior of the specified bitcount function.
  25333. * including considerations for component-wise bitcounts on vector type inputs.
  25334. *
  25335. * @private
  25336. * @param {string} method - The name of the function to create.
  25337. * @param {string} inputType - The type of the input value.
  25338. * @param {number} typeLength - The vec length of the input value.
  25339. * @param {Function} baseFn - The base function that operates on an individual component of the vector.
  25340. * @returns {Function} - The alias function for the specified bitcount method.
  25341. */
  25342. _createMainLayout( method, inputType, typeLength, baseFn ) {
  25343. const outputConvertNode = this._returnDataNode( inputType );
  25344. const fnDef = Fn( ( [ value ] ) => {
  25345. if ( typeLength === 1 ) {
  25346. return outputConvertNode( baseFn( value ) );
  25347. } else {
  25348. const vec = outputConvertNode( 0 );
  25349. const components = [ 'x', 'y', 'z', 'w' ];
  25350. for ( let i = 0; i < typeLength; i ++ ) {
  25351. const component = components[ i ];
  25352. vec[ component ].assign( baseFn( value[ component ] ) );
  25353. }
  25354. return vec;
  25355. }
  25356. } ).setLayout( {
  25357. name: method,
  25358. type: inputType,
  25359. inputs: [
  25360. { name: 'value', type: inputType }
  25361. ]
  25362. } );
  25363. return fnDef;
  25364. }
  25365. setup( builder ) {
  25366. const { method, aNode } = this;
  25367. const { renderer } = builder;
  25368. if ( renderer.backend.isWebGPUBackend ) {
  25369. // use built-in WGSL functions for WebGPU
  25370. return super.setup( builder );
  25371. }
  25372. const inputType = this.getInputType( builder );
  25373. const elementType = builder.getElementType( inputType );
  25374. const typeLength = builder.getTypeLength( inputType );
  25375. const baseMethod = `${method}_base_${elementType}`;
  25376. const newMethod = `${method}_${inputType}`;
  25377. let baseFn = registeredBitcountFunctions[ baseMethod ];
  25378. if ( baseFn === undefined ) {
  25379. switch ( method ) {
  25380. case BitcountNode.COUNT_LEADING_ZEROS: {
  25381. baseFn = this._createLeadingZerosBaseLayout( baseMethod, elementType );
  25382. break;
  25383. }
  25384. case BitcountNode.COUNT_TRAILING_ZEROS: {
  25385. baseFn = this._createTrailingZerosBaseLayout( baseMethod, elementType );
  25386. break;
  25387. }
  25388. case BitcountNode.COUNT_ONE_BITS: {
  25389. baseFn = this._createOneBitsBaseLayout( baseMethod, elementType );
  25390. break;
  25391. }
  25392. }
  25393. registeredBitcountFunctions[ baseMethod ] = baseFn;
  25394. }
  25395. let fn = registeredBitcountFunctions[ newMethod ];
  25396. if ( fn === undefined ) {
  25397. fn = this._createMainLayout( newMethod, inputType, typeLength, baseFn );
  25398. registeredBitcountFunctions[ newMethod ] = fn;
  25399. }
  25400. const output = Fn( () => {
  25401. return fn(
  25402. aNode,
  25403. );
  25404. } );
  25405. return output();
  25406. }
  25407. }
  25408. BitcountNode.COUNT_TRAILING_ZEROS = 'countTrailingZeros';
  25409. BitcountNode.COUNT_LEADING_ZEROS = 'countLeadingZeros';
  25410. BitcountNode.COUNT_ONE_BITS = 'countOneBits';
  25411. /**
  25412. * Finds the number of consecutive 0 bits from the least significant bit of the input value,
  25413. * which is also the index of the least significant bit of the input value.
  25414. *
  25415. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  25416. *
  25417. * @tsl
  25418. * @function
  25419. * @param {Node | number} x - The input value.
  25420. * @returns {Node}
  25421. */
  25422. const countTrailingZeros = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_TRAILING_ZEROS ).setParameterLength( 1 );
  25423. /**
  25424. * Finds the number of consecutive 0 bits starting from the most significant bit of the input value.
  25425. *
  25426. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  25427. *
  25428. * @tsl
  25429. * @function
  25430. * @param {Node | number} x - The input value.
  25431. * @returns {Node}
  25432. */
  25433. const countLeadingZeros = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_LEADING_ZEROS ).setParameterLength( 1 );
  25434. /**
  25435. * Finds the number of '1' bits set in the input value
  25436. *
  25437. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  25438. *
  25439. * @tsl
  25440. * @function
  25441. * @returns {Node}
  25442. */
  25443. const countOneBits = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_ONE_BITS ).setParameterLength( 1 );
  25444. /**
  25445. * Generates a hash value in the range `[0, 1]` from the given seed.
  25446. *
  25447. * @tsl
  25448. * @function
  25449. * @param {Node<float>} seed - The seed.
  25450. * @return {Node<float>} The hash value.
  25451. */
  25452. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  25453. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  25454. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  25455. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  25456. const result = word.shiftRight( 22 ).bitXor( word );
  25457. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  25458. } );
  25459. /**
  25460. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  25461. * The corners are mapped to `0` and the center to `1`.
  25462. * Reference: {@link https://iquilezles.org/articles/functions/}.
  25463. *
  25464. * @tsl
  25465. * @function
  25466. * @param {Node<float>} x - The value to remap.
  25467. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  25468. * @return {Node<float>} The remapped value.
  25469. */
  25470. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  25471. /**
  25472. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  25473. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  25474. * Reference: {@link https://iquilezles.org/articles/functions/}.
  25475. *
  25476. * @tsl
  25477. * @function
  25478. * @param {Node<float>} x - The value to remap.
  25479. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  25480. * @return {Node<float>} The remapped value.
  25481. */
  25482. 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 ) );
  25483. /**
  25484. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  25485. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  25486. * Reference: {@link https://iquilezles.org/articles/functions/}.
  25487. *
  25488. * @tsl
  25489. * @function
  25490. * @param {Node<float>} x - The value to remap.
  25491. * @param {Node<float>} a - First control parameter.
  25492. * @param {Node<float>} b - Second control parameter.
  25493. * @return {Node<float>} The remapped value.
  25494. */
  25495. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  25496. /**
  25497. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  25498. * Reference: {@link https://iquilezles.org/articles/functions/}.
  25499. *
  25500. * @tsl
  25501. * @function
  25502. * @param {Node<float>} x - The value to compute the sin for.
  25503. * @param {Node<float>} k - Controls the amount of bounces.
  25504. * @return {Node<float>} The result value.
  25505. */
  25506. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  25507. /**
  25508. * This node represents an operation that packs floating-point values of a vector into an unsigned 32-bit integer
  25509. *
  25510. * @augments TempNode
  25511. */
  25512. class PackFloatNode extends TempNode {
  25513. static get type() {
  25514. return 'PackFloatNode';
  25515. }
  25516. /**
  25517. *
  25518. * @param {'snorm' | 'unorm' | 'float16'} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  25519. * @param {Node} vectorNode - The vector node to be packed
  25520. */
  25521. constructor( encoding, vectorNode ) {
  25522. super();
  25523. /**
  25524. * The vector to be packed.
  25525. *
  25526. * @type {Node}
  25527. */
  25528. this.vectorNode = vectorNode;
  25529. /**
  25530. * The numeric encoding.
  25531. *
  25532. * @type {string}
  25533. */
  25534. this.encoding = encoding;
  25535. /**
  25536. * This flag can be used for type testing.
  25537. *
  25538. * @type {boolean}
  25539. * @readonly
  25540. * @default true
  25541. */
  25542. this.isPackFloatNode = true;
  25543. }
  25544. generateNodeType() {
  25545. return 'uint';
  25546. }
  25547. generate( builder ) {
  25548. const inputType = this.vectorNode.getNodeType( builder );
  25549. return `${ builder.getFloatPackingMethod( this.encoding ) }(${ this.vectorNode.build( builder, inputType )})`;
  25550. }
  25551. }
  25552. /**
  25553. * Converts each component of the normalized float to 16-bit integer values. The results are packed into a single unsigned integer.
  25554. * round(clamp(c, -1, +1) * 32767.0)
  25555. *
  25556. * @tsl
  25557. * @function
  25558. * @param {Node<vec2>} value - The 2-component vector to be packed
  25559. * @returns {Node}
  25560. */
  25561. const packSnorm2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'snorm' ).setParameterLength( 1 );
  25562. /**
  25563. * Converts each component of the normalized float to 16-bit integer values. The results are packed into a single unsigned integer.
  25564. * round(clamp(c, 0, +1) * 65535.0)
  25565. *
  25566. * @tsl
  25567. * @function
  25568. * @param {Node<vec2>} value - The 2-component vector to be packed
  25569. * @returns {Node}
  25570. */
  25571. const packUnorm2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'unorm' ).setParameterLength( 1 );
  25572. /**
  25573. * Converts each component of the vec2 to 16-bit floating-point values. The results are packed into a single unsigned integer.
  25574. *
  25575. * @tsl
  25576. * @function
  25577. * @param {Node<vec2>} value - The 2-component vector to be packed
  25578. * @returns {Node}
  25579. */
  25580. const packHalf2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'float16' ).setParameterLength( 1 );
  25581. /**
  25582. * This node represents an operation that unpacks values from a 32-bit unsigned integer, reinterpreting the results as a floating-point vector
  25583. *
  25584. * @augments TempNode
  25585. */
  25586. class UnpackFloatNode extends TempNode {
  25587. static get type() {
  25588. return 'UnpackFloatNode';
  25589. }
  25590. /**
  25591. *
  25592. * @param {'snorm' | 'unorm' | 'float16'} encoding - The numeric encoding that describes how the integer values are mapped to the float range
  25593. * @param {Node} uintNode - The uint node to be unpacked
  25594. */
  25595. constructor( encoding, uintNode ) {
  25596. super();
  25597. /**
  25598. * The unsigned integer to be unpacked.
  25599. *
  25600. * @type {Node}
  25601. */
  25602. this.uintNode = uintNode;
  25603. /**
  25604. * The numeric encoding.
  25605. *
  25606. * @type {string}
  25607. */
  25608. this.encoding = encoding;
  25609. /**
  25610. * This flag can be used for type testing.
  25611. *
  25612. * @type {boolean}
  25613. * @readonly
  25614. * @default true
  25615. */
  25616. this.isUnpackFloatNode = true;
  25617. }
  25618. generateNodeType() {
  25619. return 'vec2';
  25620. }
  25621. generate( builder ) {
  25622. const inputType = this.uintNode.getNodeType( builder );
  25623. return `${ builder.getFloatUnpackingMethod( this.encoding ) }(${ this.uintNode.build( builder, inputType )})`;
  25624. }
  25625. }
  25626. /**
  25627. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as normalized signed integers. Returns a vec2 with both values.
  25628. *
  25629. * @tsl
  25630. * @function
  25631. * @param {Node<uint>} value - The unsigned integer to be unpacked
  25632. * @returns {Node}
  25633. */
  25634. const unpackSnorm2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'snorm' ).setParameterLength( 1 );
  25635. /**
  25636. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as normalized unsigned integers. Returns a vec2 with both values.
  25637. *
  25638. * @tsl
  25639. * @function
  25640. * @param {Node<uint>} value - The unsigned integer to be unpacked
  25641. * @returns {Node}
  25642. */
  25643. const unpackUnorm2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'unorm' ).setParameterLength( 1 );
  25644. /**
  25645. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as 16-bit floating-point numbers. Returns a vec2 with both values.
  25646. *
  25647. * @tsl
  25648. * @function
  25649. * @param {Node<uint>} value - The unsigned integer to be unpacked
  25650. * @returns {Node}
  25651. */
  25652. const unpackHalf2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'float16' ).setParameterLength( 1 );
  25653. // https://github.com/cabbibo/glsl-tri-noise-3d
  25654. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  25655. return x.fract().sub( .5 ).abs();
  25656. } ).setLayout( {
  25657. name: 'tri',
  25658. type: 'float',
  25659. inputs: [
  25660. { name: 'x', type: 'float' }
  25661. ]
  25662. } );
  25663. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  25664. 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. ) ) ) ) );
  25665. } ).setLayout( {
  25666. name: 'tri3',
  25667. type: 'vec3',
  25668. inputs: [
  25669. { name: 'p', type: 'vec3' }
  25670. ]
  25671. } );
  25672. /**
  25673. * Generates a noise value from the given position, speed and time parameters.
  25674. *
  25675. * @tsl
  25676. * @function
  25677. * @param {Node<vec3>} position - The position.
  25678. * @param {Node<float>} speed - The speed.
  25679. * @param {Node<float>} time - The time.
  25680. * @return {Node<float>} The generated noise.
  25681. */
  25682. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  25683. const p = vec3( position ).toVar();
  25684. const z = float( 1.4 ).toVar();
  25685. const rz = float( 0.0 ).toVar();
  25686. const bp = vec3( p ).toVar();
  25687. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  25688. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  25689. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  25690. bp.mulAssign( 1.8 );
  25691. z.mulAssign( 1.5 );
  25692. p.mulAssign( 1.2 );
  25693. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  25694. rz.addAssign( t.div( z ) );
  25695. bp.addAssign( 0.14 );
  25696. } );
  25697. return rz;
  25698. } ).setLayout( {
  25699. name: 'triNoise3D',
  25700. type: 'float',
  25701. inputs: [
  25702. { name: 'position', type: 'vec3' },
  25703. { name: 'speed', type: 'float' },
  25704. { name: 'time', type: 'float' }
  25705. ]
  25706. } );
  25707. /**
  25708. * This class allows to define multiple overloaded versions
  25709. * of the same function. Depending on the parameters of the function
  25710. * call, the node picks the best-fit overloaded version.
  25711. *
  25712. * @augments Node
  25713. */
  25714. class FunctionOverloadingNode extends Node {
  25715. static get type() {
  25716. return 'FunctionOverloadingNode';
  25717. }
  25718. /**
  25719. * Constructs a new function overloading node.
  25720. *
  25721. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  25722. * @param {...Node} parametersNodes - A list of parameter nodes.
  25723. */
  25724. constructor( functionNodes = [], ...parametersNodes ) {
  25725. super();
  25726. /**
  25727. * Array of `Fn` function definitions.
  25728. *
  25729. * @type {Array<Function>}
  25730. */
  25731. this.functionNodes = functionNodes;
  25732. /**
  25733. * A list of parameter nodes.
  25734. *
  25735. * @type {Array<Node>}
  25736. */
  25737. this.parametersNodes = parametersNodes;
  25738. /**
  25739. * The selected overloaded function call.
  25740. *
  25741. * @private
  25742. * @type {ShaderCallNodeInternal}
  25743. */
  25744. this._candidateFn = null;
  25745. /**
  25746. * This node is marked as global.
  25747. *
  25748. * @type {boolean}
  25749. * @default true
  25750. */
  25751. this.global = true;
  25752. }
  25753. /**
  25754. * This method is overwritten since the node type is inferred from
  25755. * the function's return type.
  25756. *
  25757. * @param {NodeBuilder} builder - The current node builder.
  25758. * @return {string} The node type.
  25759. */
  25760. generateNodeType( builder ) {
  25761. const candidateFn = this.getCandidateFn( builder );
  25762. return candidateFn.shaderNode.layout.type;
  25763. }
  25764. /**
  25765. * Returns the candidate function for the current parameters.
  25766. *
  25767. * @param {NodeBuilder} builder - The current node builder.
  25768. * @return {FunctionNode} The candidate function.
  25769. */
  25770. getCandidateFn( builder ) {
  25771. const params = this.parametersNodes;
  25772. let candidateFn = this._candidateFn;
  25773. if ( candidateFn === null ) {
  25774. let bestCandidateFn = null;
  25775. let bestScore = -1;
  25776. for ( const functionNode of this.functionNodes ) {
  25777. const shaderNode = functionNode.shaderNode;
  25778. const layout = shaderNode.layout;
  25779. if ( layout === null ) {
  25780. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  25781. }
  25782. const inputs = layout.inputs;
  25783. if ( params.length === inputs.length ) {
  25784. let currentScore = 0;
  25785. for ( let i = 0; i < params.length; i ++ ) {
  25786. const param = params[ i ];
  25787. const input = inputs[ i ];
  25788. if ( param.getNodeType( builder ) === input.type ) {
  25789. currentScore ++;
  25790. }
  25791. }
  25792. if ( currentScore > bestScore ) {
  25793. bestCandidateFn = functionNode;
  25794. bestScore = currentScore;
  25795. }
  25796. }
  25797. }
  25798. this._candidateFn = candidateFn = bestCandidateFn;
  25799. }
  25800. return candidateFn;
  25801. }
  25802. /**
  25803. * Sets up the node for the current parameters.
  25804. *
  25805. * @param {NodeBuilder} builder - The current node builder.
  25806. * @return {Node} The setup node.
  25807. */
  25808. setup( builder ) {
  25809. const candidateFn = this.getCandidateFn( builder );
  25810. return candidateFn( ...this.parametersNodes );
  25811. }
  25812. }
  25813. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  25814. /**
  25815. * TSL function for creating a function overloading node.
  25816. *
  25817. * @tsl
  25818. * @function
  25819. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  25820. * @returns {FunctionOverloadingNode}
  25821. */
  25822. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  25823. /**
  25824. * Represents the elapsed time in seconds.
  25825. *
  25826. * @tsl
  25827. * @type {UniformNode<float>}
  25828. */
  25829. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  25830. /**
  25831. * Represents the delta time in seconds.
  25832. *
  25833. * @tsl
  25834. * @type {UniformNode<float>}
  25835. */
  25836. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  25837. /**
  25838. * Represents the current frame ID.
  25839. *
  25840. * @tsl
  25841. * @type {UniformNode<uint>}
  25842. */
  25843. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  25844. /**
  25845. * Generates a sine wave oscillation based on a timer.
  25846. *
  25847. * @tsl
  25848. * @function
  25849. * @param {Node<float>} t - The timer to generate the oscillation with.
  25850. * @return {Node<float>} The oscillation node.
  25851. */
  25852. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  25853. /**
  25854. * Generates a square wave oscillation based on a timer.
  25855. *
  25856. * @tsl
  25857. * @function
  25858. * @param {Node<float>} t - The timer to generate the oscillation with.
  25859. * @return {Node<float>} The oscillation node.
  25860. */
  25861. const oscSquare = ( t = time ) => t.fract().round();
  25862. /**
  25863. * Generates a triangle wave oscillation based on a timer.
  25864. *
  25865. * @tsl
  25866. * @function
  25867. * @param {Node<float>} t - The timer to generate the oscillation with.
  25868. * @return {Node<float>} The oscillation node.
  25869. */
  25870. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  25871. /**
  25872. * Generates a sawtooth wave oscillation based on a timer.
  25873. *
  25874. * @tsl
  25875. * @function
  25876. * @param {Node<float>} t - The timer to generate the oscillation with.
  25877. * @return {Node<float>} The oscillation node.
  25878. */
  25879. const oscSawtooth = ( t = time ) => t.fract();
  25880. /**
  25881. * Replaces the default UV coordinates used in texture lookups.
  25882. *
  25883. * ```js
  25884. *material.contextNode = replaceDefaultUV( ( textureNode ) => {
  25885. *
  25886. * // ...
  25887. * return customUVCoordinates;
  25888. *
  25889. *} );
  25890. *```
  25891. *
  25892. * @tsl
  25893. * @function
  25894. * @param {function(Node):Node<vec2>|Node<vec2>} callback - A callback that receives the texture node
  25895. * and must return the new uv coordinates.
  25896. * @param {Node} [node=null] - An optional node to which the context will be applied.
  25897. * @return {ContextNode} A context node that replaces the default UV coordinates.
  25898. */
  25899. function replaceDefaultUV( callback, node = null ) {
  25900. const getUV = typeof callback === 'function' ? callback : () => callback;
  25901. return context( node, { getUV } );
  25902. }
  25903. /**
  25904. * Rotates the given uv coordinates around a center point
  25905. *
  25906. * @tsl
  25907. * @function
  25908. * @param {Node<vec2>} uv - The uv coordinates.
  25909. * @param {Node<float>} rotation - The rotation defined in radians.
  25910. * @param {Node<vec2>} center - The center of rotation
  25911. * @return {Node<vec2>} The rotated uv coordinates.
  25912. */
  25913. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  25914. return rotate( uv.sub( center ), rotation ).add( center );
  25915. } );
  25916. /**
  25917. * Applies a spherical warping effect to the given uv coordinates.
  25918. *
  25919. * @tsl
  25920. * @function
  25921. * @param {Node<vec2>} uv - The uv coordinates.
  25922. * @param {Node<float>} strength - The strength of the effect.
  25923. * @param {Node<vec2>} center - The center point
  25924. * @return {Node<vec2>} The updated uv coordinates.
  25925. */
  25926. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  25927. const delta = uv.sub( center );
  25928. const delta2 = delta.dot( delta );
  25929. const delta4 = delta2.mul( delta2 );
  25930. const deltaOffset = delta4.mul( strength );
  25931. return uv.add( delta.mul( deltaOffset ) );
  25932. } );
  25933. /**
  25934. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  25935. * oriented always towards the camera.
  25936. *
  25937. * ```js
  25938. * material.vertexNode = billboarding();
  25939. * ```
  25940. *
  25941. * @tsl
  25942. * @function
  25943. * @param {Object} config - The configuration object.
  25944. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  25945. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  25946. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  25947. * @return {Node<vec3>} The updated vertex position in clip space.
  25948. */
  25949. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  25950. let worldMatrix;
  25951. if ( position !== null ) {
  25952. worldMatrix = modelWorldMatrix.toVar();
  25953. worldMatrix[ 3 ][ 0 ] = position.x;
  25954. worldMatrix[ 3 ][ 1 ] = position.y;
  25955. worldMatrix[ 3 ][ 2 ] = position.z;
  25956. } else {
  25957. worldMatrix = modelWorldMatrix;
  25958. }
  25959. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  25960. if ( defined( horizontal ) ) {
  25961. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  25962. modelViewMatrix[ 0 ][ 1 ] = 0;
  25963. modelViewMatrix[ 0 ][ 2 ] = 0;
  25964. }
  25965. if ( defined( vertical ) ) {
  25966. modelViewMatrix[ 1 ][ 0 ] = 0;
  25967. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  25968. modelViewMatrix[ 1 ][ 2 ] = 0;
  25969. }
  25970. modelViewMatrix[ 2 ][ 0 ] = 0;
  25971. modelViewMatrix[ 2 ][ 1 ] = 0;
  25972. modelViewMatrix[ 2 ][ 2 ] = 1;
  25973. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  25974. } );
  25975. /**
  25976. * A special version of a screen uv function that involves a depth comparison
  25977. * when computing the final uvs. The function mitigates visual errors when
  25978. * using viewport texture nodes for refraction purposes. Without this function
  25979. * objects in front of a refractive surface might appear on the refractive surface
  25980. * which is incorrect.
  25981. *
  25982. * @tsl
  25983. * @function
  25984. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  25985. * @return {Node<vec2>} The update uv coordinates.
  25986. */
  25987. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  25988. const depth = linearDepth();
  25989. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  25990. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  25991. return finalUV;
  25992. } );
  25993. /**
  25994. * TSL function for computing texture coordinates for animated sprite sheets.
  25995. *
  25996. * ```js
  25997. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  25998. *
  25999. * material.colorNode = texture( spriteSheet, uvNode );
  26000. * ```
  26001. *
  26002. * @tsl
  26003. * @function
  26004. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  26005. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  26006. * @param {?Node<float>} [frameNode=float(0)] - The node that defines the current frame/sprite.
  26007. * @returns {Node<vec2>}
  26008. */
  26009. const spritesheetUV = /*@__PURE__*/ Fn( ( [ countNode, uvNode = uv$1(), frameNode = float( 0 ) ] ) => {
  26010. const width = countNode.x;
  26011. const height = countNode.y;
  26012. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  26013. const column = frameNum.mod( width );
  26014. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  26015. const scale = countNode.reciprocal();
  26016. const uvFrameOffset = vec2( column, row );
  26017. return uvNode.add( uvFrameOffset ).mul( scale );
  26018. } );
  26019. /**
  26020. * TSL function for creating a triplanar textures node.
  26021. *
  26022. * Can be used for triplanar texture mapping.
  26023. *
  26024. * ```js
  26025. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  26026. * ```
  26027. *
  26028. * @tsl
  26029. * @function
  26030. * @param {Node} textureXNode - First texture node.
  26031. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  26032. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  26033. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  26034. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  26035. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  26036. * @returns {Node<vec4>}
  26037. */
  26038. const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => {
  26039. // Reference: https://github.com/keijiro/StandardTriplanar
  26040. // Blending factor of triplanar mapping
  26041. let bf = normalNode.abs().normalize();
  26042. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  26043. // Triplanar mapping
  26044. const tx = positionNode.yz.mul( scaleNode );
  26045. const ty = positionNode.zx.mul( scaleNode );
  26046. const tz = positionNode.xy.mul( scaleNode );
  26047. // Base color
  26048. const textureX = textureXNode.value;
  26049. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  26050. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  26051. const cx = texture( textureX, tx ).mul( bf.x );
  26052. const cy = texture( textureY, ty ).mul( bf.y );
  26053. const cz = texture( textureZ, tz ).mul( bf.z );
  26054. return add( cx, cy, cz );
  26055. } );
  26056. /**
  26057. * TSL function for creating a triplanar textures node.
  26058. *
  26059. * @tsl
  26060. * @function
  26061. * @param {Node} textureXNode - First texture node.
  26062. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  26063. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  26064. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  26065. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  26066. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  26067. * @returns {Node<vec4>}
  26068. */
  26069. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  26070. const _reflectorPlane = new Plane();
  26071. const _normal = new Vector3();
  26072. const _reflectorWorldPosition = new Vector3();
  26073. const _cameraWorldPosition = new Vector3();
  26074. const _rotationMatrix = new Matrix4();
  26075. const _lookAtPosition = new Vector3( 0, 0, -1 );
  26076. const clipPlane = new Vector4();
  26077. const _view = new Vector3();
  26078. const _target = new Vector3();
  26079. const _q = new Vector4();
  26080. const _size$2 = new Vector2();
  26081. const _defaultRT = new RenderTarget();
  26082. const _defaultUV = screenUV.flipX();
  26083. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  26084. let _inReflector = false;
  26085. /**
  26086. * This node can be used to implement mirror-like flat reflective surfaces.
  26087. *
  26088. * ```js
  26089. * const groundReflector = reflector();
  26090. * material.colorNode = groundReflector;
  26091. *
  26092. * const plane = new Mesh( geometry, material );
  26093. * plane.add( groundReflector.target );
  26094. * ```
  26095. *
  26096. * @augments TextureNode
  26097. */
  26098. class ReflectorNode extends TextureNode {
  26099. static get type() {
  26100. return 'ReflectorNode';
  26101. }
  26102. /**
  26103. * Constructs a new reflector node.
  26104. *
  26105. * @param {Object} [parameters={}] - An object holding configuration parameters.
  26106. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  26107. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  26108. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  26109. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  26110. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  26111. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  26112. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  26113. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  26114. */
  26115. constructor( parameters = {} ) {
  26116. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  26117. /**
  26118. * A reference to the internal reflector base node which holds the actual implementation.
  26119. *
  26120. * @private
  26121. * @type {ReflectorBaseNode}
  26122. * @default ReflectorBaseNode
  26123. */
  26124. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  26125. /**
  26126. * A reference to the internal depth node.
  26127. *
  26128. * @private
  26129. * @type {?Node}
  26130. * @default null
  26131. */
  26132. this._depthNode = null;
  26133. this.setUpdateMatrix( false );
  26134. }
  26135. /**
  26136. * A reference to the internal reflector node.
  26137. *
  26138. * @type {ReflectorBaseNode}
  26139. */
  26140. get reflector() {
  26141. return this._reflectorBaseNode;
  26142. }
  26143. /**
  26144. * A reference to 3D object the reflector is linked to.
  26145. *
  26146. * @type {Object3D}
  26147. */
  26148. get target() {
  26149. return this._reflectorBaseNode.target;
  26150. }
  26151. /**
  26152. * Returns a node representing the mirror's depth. That can be used
  26153. * to implement more advanced reflection effects like distance attenuation.
  26154. *
  26155. * @return {Node} The depth node.
  26156. */
  26157. getDepthNode() {
  26158. if ( this._depthNode === null ) {
  26159. if ( this._reflectorBaseNode.depth !== true ) {
  26160. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  26161. }
  26162. this._depthNode = new ReflectorNode( {
  26163. defaultTexture: _defaultRT.depthTexture,
  26164. reflector: this._reflectorBaseNode
  26165. } );
  26166. }
  26167. return this._depthNode;
  26168. }
  26169. setup( builder ) {
  26170. // ignore if used in post-processing
  26171. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  26172. return super.setup( builder );
  26173. }
  26174. clone() {
  26175. const newNode = new this.constructor( this.reflectorNode );
  26176. newNode.uvNode = this.uvNode;
  26177. newNode.levelNode = this.levelNode;
  26178. newNode.biasNode = this.biasNode;
  26179. newNode.sampler = this.sampler;
  26180. newNode.depthNode = this.depthNode;
  26181. newNode.compareNode = this.compareNode;
  26182. newNode.gradNode = this.gradNode;
  26183. newNode.gatherNode = this.gatherNode;
  26184. newNode.offsetNode = this.offsetNode;
  26185. newNode._reflectorBaseNode = this._reflectorBaseNode;
  26186. return newNode;
  26187. }
  26188. /**
  26189. * Frees internal resources. Should be called when the node is no longer in use.
  26190. */
  26191. dispose() {
  26192. super.dispose();
  26193. this._reflectorBaseNode.dispose();
  26194. }
  26195. }
  26196. /**
  26197. * Holds the actual implementation of the reflector.
  26198. *
  26199. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  26200. * in `ReflectorNode`, see #29619.
  26201. *
  26202. * @private
  26203. * @augments Node
  26204. */
  26205. class ReflectorBaseNode extends Node {
  26206. static get type() {
  26207. return 'ReflectorBaseNode';
  26208. }
  26209. /**
  26210. * Constructs a new reflector base node.
  26211. *
  26212. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  26213. * @param {Object} [parameters={}] - An object holding configuration parameters.
  26214. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  26215. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  26216. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  26217. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  26218. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  26219. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  26220. */
  26221. constructor( textureNode, parameters = {} ) {
  26222. super();
  26223. const {
  26224. target = new Object3D(),
  26225. resolutionScale = 1,
  26226. generateMipmaps = false,
  26227. bounces = true,
  26228. depth = false,
  26229. samples = 0
  26230. } = parameters;
  26231. /**
  26232. * Represents the rendered reflections as a texture node.
  26233. *
  26234. * @type {TextureNode}
  26235. */
  26236. this.textureNode = textureNode;
  26237. /**
  26238. * The 3D object the reflector is linked to.
  26239. *
  26240. * @type {Object3D}
  26241. * @default {new Object3D()}
  26242. */
  26243. this.target = target;
  26244. /**
  26245. * The resolution scale.
  26246. *
  26247. * @type {number}
  26248. * @default {1}
  26249. */
  26250. this.resolutionScale = resolutionScale;
  26251. if ( parameters.resolution !== undefined ) {
  26252. warnOnce( 'ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".' ); // @deprecated r180
  26253. this.resolutionScale = parameters.resolution;
  26254. }
  26255. /**
  26256. * Whether mipmaps should be generated or not.
  26257. *
  26258. * @type {boolean}
  26259. * @default {false}
  26260. */
  26261. this.generateMipmaps = generateMipmaps;
  26262. /**
  26263. * Whether reflectors can render other reflector nodes or not.
  26264. *
  26265. * @type {boolean}
  26266. * @default {true}
  26267. */
  26268. this.bounces = bounces;
  26269. /**
  26270. * Whether depth data should be generated or not.
  26271. *
  26272. * @type {boolean}
  26273. * @default {false}
  26274. */
  26275. this.depth = depth;
  26276. /**
  26277. * The number of anti-aliasing samples for the render-target
  26278. *
  26279. * @type {number}
  26280. * @default {0}
  26281. */
  26282. this.samples = samples;
  26283. /**
  26284. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  26285. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  26286. *
  26287. * @type {string}
  26288. * @default 'render'
  26289. */
  26290. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  26291. /**
  26292. * Weak map for managing virtual cameras.
  26293. *
  26294. * @type {WeakMap<Camera, Camera>}
  26295. */
  26296. this.virtualCameras = new WeakMap();
  26297. /**
  26298. * Weak map for managing render targets.
  26299. *
  26300. * @type {Map<Camera, RenderTarget>}
  26301. */
  26302. this.renderTargets = new Map();
  26303. /**
  26304. * Force render even if reflector is facing away from camera.
  26305. *
  26306. * @type {boolean}
  26307. * @default {false}
  26308. */
  26309. this.forceUpdate = false;
  26310. /**
  26311. * Whether the reflector has been rendered or not.
  26312. *
  26313. * When the reflector is facing away from the camera,
  26314. * this flag is set to `false` and the texture will be empty(black).
  26315. *
  26316. * @type {boolean}
  26317. * @default {false}
  26318. */
  26319. this.hasOutput = false;
  26320. }
  26321. /**
  26322. * Updates the resolution of the internal render target.
  26323. *
  26324. * @private
  26325. * @param {RenderTarget} renderTarget - The render target to resize.
  26326. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  26327. */
  26328. _updateResolution( renderTarget, renderer ) {
  26329. const resolution = this.resolutionScale;
  26330. renderer.getDrawingBufferSize( _size$2 );
  26331. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  26332. }
  26333. setup( builder ) {
  26334. this._updateResolution( _defaultRT, builder.renderer );
  26335. return super.setup( builder );
  26336. }
  26337. /**
  26338. * Frees internal resources. Should be called when the node is no longer in use.
  26339. */
  26340. dispose() {
  26341. super.dispose();
  26342. for ( const renderTarget of this.renderTargets.values() ) {
  26343. renderTarget.dispose();
  26344. }
  26345. }
  26346. /**
  26347. * Returns a virtual camera for the given camera. The virtual camera is used to
  26348. * render the scene from the reflector's view so correct reflections can be produced.
  26349. *
  26350. * @param {Camera} camera - The scene's camera.
  26351. * @return {Camera} The corresponding virtual camera.
  26352. */
  26353. getVirtualCamera( camera ) {
  26354. let virtualCamera = this.virtualCameras.get( camera );
  26355. if ( virtualCamera === undefined ) {
  26356. virtualCamera = camera.clone();
  26357. this.virtualCameras.set( camera, virtualCamera );
  26358. }
  26359. return virtualCamera;
  26360. }
  26361. /**
  26362. * Returns a render target for the given camera. The reflections are rendered
  26363. * into this render target.
  26364. *
  26365. * @param {Camera} camera - The scene's camera.
  26366. * @return {RenderTarget} The render target.
  26367. */
  26368. getRenderTarget( camera ) {
  26369. let renderTarget = this.renderTargets.get( camera );
  26370. if ( renderTarget === undefined ) {
  26371. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType, samples: this.samples } );
  26372. if ( this.generateMipmaps === true ) {
  26373. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  26374. renderTarget.texture.generateMipmaps = true;
  26375. }
  26376. if ( this.depth === true ) {
  26377. renderTarget.depthTexture = new DepthTexture();
  26378. }
  26379. this.renderTargets.set( camera, renderTarget );
  26380. }
  26381. return renderTarget;
  26382. }
  26383. updateBefore( frame ) {
  26384. if ( this.bounces === false && _inReflector ) return false;
  26385. _inReflector = true;
  26386. const { scene, camera, renderer, material } = frame;
  26387. const { target } = this;
  26388. const virtualCamera = this.getVirtualCamera( camera );
  26389. const renderTarget = this.getRenderTarget( virtualCamera );
  26390. renderer.getDrawingBufferSize( _size$2 );
  26391. this._updateResolution( renderTarget, renderer );
  26392. //
  26393. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  26394. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  26395. _rotationMatrix.extractRotation( target.matrixWorld );
  26396. _normal.set( 0, 0, 1 );
  26397. _normal.applyMatrix4( _rotationMatrix );
  26398. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  26399. // Avoid rendering when reflector is facing away unless forcing an update
  26400. const isFacingAway = _view.dot( _normal ) > 0;
  26401. let needsClear = false;
  26402. if ( isFacingAway === true && this.forceUpdate === false ) {
  26403. if ( this.hasOutput === false ) {
  26404. _inReflector = false;
  26405. return;
  26406. }
  26407. needsClear = true;
  26408. }
  26409. _view.reflect( _normal ).negate();
  26410. _view.add( _reflectorWorldPosition );
  26411. _rotationMatrix.extractRotation( camera.matrixWorld );
  26412. _lookAtPosition.set( 0, 0, -1 );
  26413. _lookAtPosition.applyMatrix4( _rotationMatrix );
  26414. _lookAtPosition.add( _cameraWorldPosition );
  26415. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  26416. _target.reflect( _normal ).negate();
  26417. _target.add( _reflectorWorldPosition );
  26418. //
  26419. virtualCamera.coordinateSystem = camera.coordinateSystem;
  26420. virtualCamera.position.copy( _view );
  26421. virtualCamera.up.set( 0, 1, 0 );
  26422. virtualCamera.up.applyMatrix4( _rotationMatrix );
  26423. virtualCamera.up.reflect( _normal );
  26424. virtualCamera.lookAt( _target );
  26425. virtualCamera.near = camera.near;
  26426. virtualCamera.far = camera.far;
  26427. virtualCamera.updateMatrixWorld();
  26428. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  26429. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  26430. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  26431. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  26432. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  26433. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  26434. const projectionMatrix = virtualCamera.projectionMatrix;
  26435. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  26436. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  26437. _q.z = -1;
  26438. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  26439. // Calculate the scaled plane vector
  26440. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  26441. const clipBias = 0;
  26442. // Replacing the third row of the projection matrix
  26443. projectionMatrix.elements[ 2 ] = clipPlane.x;
  26444. projectionMatrix.elements[ 6 ] = clipPlane.y;
  26445. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  26446. projectionMatrix.elements[ 14 ] = clipPlane.w;
  26447. //
  26448. this.textureNode.value = renderTarget.texture;
  26449. if ( this.depth === true ) {
  26450. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  26451. }
  26452. material.visible = false;
  26453. const currentRenderTarget = renderer.getRenderTarget();
  26454. const currentMRT = renderer.getMRT();
  26455. const currentAutoClear = renderer.autoClear;
  26456. renderer.setMRT( null );
  26457. renderer.setRenderTarget( renderTarget );
  26458. renderer.autoClear = true;
  26459. const previousName = scene.name;
  26460. scene.name = ( scene.name || 'Scene' ) + ' [ Reflector ]'; // TODO: Add bounce index
  26461. if ( needsClear ) {
  26462. renderer.clear();
  26463. this.hasOutput = false;
  26464. } else {
  26465. renderer.render( scene, virtualCamera );
  26466. this.hasOutput = true;
  26467. }
  26468. scene.name = previousName;
  26469. renderer.setMRT( currentMRT );
  26470. renderer.setRenderTarget( currentRenderTarget );
  26471. renderer.autoClear = currentAutoClear;
  26472. material.visible = true;
  26473. _inReflector = false;
  26474. this.forceUpdate = false;
  26475. }
  26476. /**
  26477. * The resolution scale.
  26478. *
  26479. * @deprecated
  26480. * @type {number}
  26481. * @default {1}
  26482. */
  26483. get resolution() {
  26484. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  26485. return this.resolutionScale;
  26486. }
  26487. set resolution( value ) {
  26488. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  26489. this.resolutionScale = value;
  26490. }
  26491. }
  26492. /**
  26493. * TSL function for creating a reflector node.
  26494. *
  26495. * @tsl
  26496. * @function
  26497. * @param {Object} [parameters={}] - An object holding configuration parameters.
  26498. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  26499. * @param {number} [parameters.resolution=1] - The resolution scale.
  26500. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  26501. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  26502. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  26503. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  26504. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  26505. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  26506. * @returns {ReflectorNode}
  26507. */
  26508. const reflector = ( parameters ) => new ReflectorNode( parameters );
  26509. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  26510. /**
  26511. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  26512. *
  26513. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  26514. *
  26515. * @private
  26516. * @augments BufferGeometry
  26517. */
  26518. class QuadGeometry extends BufferGeometry {
  26519. /**
  26520. * Constructs a new quad geometry.
  26521. *
  26522. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  26523. */
  26524. constructor( flipY = false ) {
  26525. super();
  26526. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  26527. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  26528. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  26529. }
  26530. }
  26531. const _geometry = /*@__PURE__*/ new QuadGeometry();
  26532. /**
  26533. * This module is a helper for passes which need to render a full
  26534. * screen effect which is quite common in context of post processing.
  26535. *
  26536. * The intended usage is to reuse a single quad mesh for rendering
  26537. * subsequent passes by just reassigning the `material` reference.
  26538. *
  26539. * Note: This module can only be used with `WebGPURenderer`.
  26540. *
  26541. * @augments Mesh
  26542. */
  26543. class QuadMesh extends Mesh {
  26544. /**
  26545. * Constructs a new quad mesh.
  26546. *
  26547. * @param {?Material} [material=null] - The material to render the quad mesh with.
  26548. */
  26549. constructor( material = null ) {
  26550. super( _geometry, material );
  26551. /**
  26552. * The camera to render the quad mesh with.
  26553. *
  26554. * @type {OrthographicCamera}
  26555. * @readonly
  26556. */
  26557. this.camera = _camera;
  26558. /**
  26559. * This flag can be used for type testing.
  26560. *
  26561. * @type {boolean}
  26562. * @readonly
  26563. * @default true
  26564. */
  26565. this.isQuadMesh = true;
  26566. }
  26567. /**
  26568. * Async version of `render()`.
  26569. *
  26570. * @async
  26571. * @deprecated
  26572. * @param {Renderer} renderer - The renderer.
  26573. * @return {Promise} A Promise that resolves when the render has been finished.
  26574. */
  26575. async renderAsync( renderer ) {
  26576. warnOnce( 'QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  26577. await renderer.init();
  26578. renderer.render( this, _camera );
  26579. }
  26580. /**
  26581. * Renders the quad mesh
  26582. *
  26583. * @param {Renderer} renderer - The renderer.
  26584. */
  26585. render( renderer ) {
  26586. renderer.render( this, _camera );
  26587. }
  26588. }
  26589. const _size$1 = /*@__PURE__*/ new Vector2();
  26590. /**
  26591. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  26592. * This module is especially relevant in context of post processing where certain nodes require
  26593. * texture input for their effects. With the helper function `convertToTexture()` which is based
  26594. * on this module, the node system can automatically ensure texture input if required.
  26595. *
  26596. * @augments TextureNode
  26597. */
  26598. class RTTNode extends TextureNode {
  26599. static get type() {
  26600. return 'RTTNode';
  26601. }
  26602. /**
  26603. * Constructs a new RTT node.
  26604. *
  26605. * @param {Node} node - The node to render a texture with.
  26606. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  26607. * @param {?number} [height=null] - The height of the internal render target.
  26608. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  26609. */
  26610. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  26611. const renderTarget = new RenderTarget( width, height, options );
  26612. super( renderTarget.texture, uv$1() );
  26613. /**
  26614. * This flag can be used for type testing.
  26615. *
  26616. * @type {boolean}
  26617. * @readonly
  26618. * @default true
  26619. */
  26620. this.isRTTNode = true;
  26621. /**
  26622. * The node to render a texture with.
  26623. *
  26624. * @type {Node}
  26625. */
  26626. this.node = node;
  26627. /**
  26628. * The width of the internal render target.
  26629. * If not width is applied, the render target is automatically resized.
  26630. *
  26631. * @type {?number}
  26632. * @default null
  26633. */
  26634. this.width = width;
  26635. /**
  26636. * The height of the internal render target.
  26637. *
  26638. * @type {?number}
  26639. * @default null
  26640. */
  26641. this.height = height;
  26642. /**
  26643. * The pixel ratio
  26644. *
  26645. * @type {number}
  26646. * @default 1
  26647. */
  26648. this.pixelRatio = 1;
  26649. /**
  26650. * The render target
  26651. *
  26652. * @type {RenderTarget}
  26653. */
  26654. this.renderTarget = renderTarget;
  26655. /**
  26656. * Whether the texture requires an update or not.
  26657. *
  26658. * @type {boolean}
  26659. * @default true
  26660. */
  26661. this.textureNeedsUpdate = true;
  26662. /**
  26663. * Whether the texture should automatically be updated or not.
  26664. *
  26665. * @type {boolean}
  26666. * @default true
  26667. */
  26668. this.autoUpdate = true;
  26669. /**
  26670. * The node which is used with the quad mesh for RTT.
  26671. *
  26672. * @private
  26673. * @type {Node}
  26674. * @default null
  26675. */
  26676. this._rttNode = null;
  26677. /**
  26678. * The internal quad mesh for RTT.
  26679. *
  26680. * @private
  26681. * @type {QuadMesh}
  26682. */
  26683. this._quadMesh = new QuadMesh( new NodeMaterial() );
  26684. /**
  26685. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  26686. * the texture once per render in its {@link RTTNode#updateBefore} method.
  26687. *
  26688. * @type {string}
  26689. * @default 'render'
  26690. */
  26691. this.updateBeforeType = NodeUpdateType.RENDER;
  26692. }
  26693. /**
  26694. * Whether the internal render target should automatically be resized or not.
  26695. *
  26696. * @type {boolean}
  26697. * @readonly
  26698. * @default true
  26699. */
  26700. get autoResize() {
  26701. return this.width === null;
  26702. }
  26703. setup( builder ) {
  26704. this._rttNode = this.node.context( builder.getSharedContext() );
  26705. this._quadMesh.material.name = 'RTT';
  26706. this._quadMesh.material.needsUpdate = true;
  26707. return super.setup( builder );
  26708. }
  26709. /**
  26710. * Sets the size of the internal render target
  26711. *
  26712. * @param {number} width - The width to set.
  26713. * @param {number} height - The width to set.
  26714. */
  26715. setSize( width, height ) {
  26716. this.width = width;
  26717. this.height = height;
  26718. const effectiveWidth = width * this.pixelRatio;
  26719. const effectiveHeight = height * this.pixelRatio;
  26720. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  26721. this.textureNeedsUpdate = true;
  26722. }
  26723. /**
  26724. * Sets the pixel ratio. This will also resize the render target.
  26725. *
  26726. * @param {number} pixelRatio - The pixel ratio to set.
  26727. */
  26728. setPixelRatio( pixelRatio ) {
  26729. this.pixelRatio = pixelRatio;
  26730. this.setSize( this.width, this.height );
  26731. }
  26732. updateBefore( { renderer } ) {
  26733. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  26734. this.textureNeedsUpdate = false;
  26735. //
  26736. if ( this.autoResize === true ) {
  26737. const pixelRatio = renderer.getPixelRatio();
  26738. const size = renderer.getSize( _size$1 );
  26739. const effectiveWidth = Math.floor( size.width * pixelRatio );
  26740. const effectiveHeight = Math.floor( size.height * pixelRatio );
  26741. if ( effectiveWidth !== this.renderTarget.width || effectiveHeight !== this.renderTarget.height ) {
  26742. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  26743. this.textureNeedsUpdate = true;
  26744. }
  26745. }
  26746. //
  26747. let name = 'RTT';
  26748. if ( this.node.name ) {
  26749. name = this.node.name + ' [ ' + name + ' ]';
  26750. }
  26751. this._quadMesh.material.fragmentNode = this._rttNode;
  26752. this._quadMesh.name = name;
  26753. //
  26754. const currentRenderTarget = renderer.getRenderTarget();
  26755. renderer.setRenderTarget( this.renderTarget );
  26756. this._quadMesh.render( renderer );
  26757. renderer.setRenderTarget( currentRenderTarget );
  26758. }
  26759. clone() {
  26760. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  26761. newNode.sampler = this.sampler;
  26762. newNode.referenceNode = this;
  26763. return newNode;
  26764. }
  26765. }
  26766. /**
  26767. * TSL function for creating a RTT node.
  26768. *
  26769. * @tsl
  26770. * @function
  26771. * @param {Node} node - The node to render a texture with.
  26772. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  26773. * @param {?number} [height=null] - The height of the internal render target.
  26774. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  26775. * @returns {RTTNode}
  26776. */
  26777. const rtt = ( node, ...params ) => new RTTNode( nodeObject( node ), ...params );
  26778. /**
  26779. * TSL function for converting nodes to textures nodes.
  26780. *
  26781. * @tsl
  26782. * @function
  26783. * @param {Node} node - The node to render a texture with.
  26784. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  26785. * @param {?number} [height=null] - The height of the internal render target.
  26786. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  26787. * @returns {RTTNode}
  26788. */
  26789. const convertToTexture = ( node, ...params ) => {
  26790. if ( node.isSampleNode || node.isTextureNode ) return node;
  26791. if ( node.isPassNode ) return node.getTextureNode();
  26792. return rtt( node, ...params );
  26793. };
  26794. /**
  26795. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  26796. * depth value and the camera's inverse projection matrix.
  26797. *
  26798. * @tsl
  26799. * @function
  26800. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  26801. * @param {Node<float>} depth - The fragment's depth value.
  26802. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  26803. * @return {Node<vec3>} The fragments position in view space.
  26804. */
  26805. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  26806. let clipSpacePosition;
  26807. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  26808. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  26809. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  26810. } else {
  26811. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  26812. }
  26813. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  26814. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  26815. } );
  26816. /**
  26817. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  26818. * and the camera's projection matrix
  26819. *
  26820. * @tsl
  26821. * @function
  26822. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  26823. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  26824. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  26825. */
  26826. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  26827. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  26828. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  26829. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  26830. } );
  26831. /**
  26832. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  26833. * target is available or if flat surface normals are required.
  26834. *
  26835. * @tsl
  26836. * @function
  26837. * @param {Node<vec2>} uv - The texture coordinate.
  26838. * @param {DepthTexture} depthTexture - The depth texture.
  26839. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  26840. * @return {Node<vec3>} The computed normal vector.
  26841. */
  26842. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  26843. const size = textureSize( textureLoad( depthTexture ) );
  26844. const p = ivec2( uv.mul( size ) ).toVar();
  26845. const c0 = textureLoad( depthTexture, p ).toVar();
  26846. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  26847. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  26848. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  26849. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  26850. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  26851. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  26852. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  26853. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  26854. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  26855. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  26856. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  26857. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  26858. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  26859. 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 ) ) );
  26860. 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 ) ) );
  26861. return normalize( cross( dpdx, dpdy ) );
  26862. } );
  26863. /**
  26864. * Interleaved Gradient Noise (IGN) from Jimenez 2014.
  26865. *
  26866. * IGN has "low discrepancy" resulting in evenly distributed samples. It's superior compared to
  26867. * default white noise, blue noise or Bayer.
  26868. *
  26869. * References:
  26870. * - {@link https://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare/}
  26871. * - {@link https://blog.demofox.org/2022/01/01/interleaved-gradient-noise-a-different-kind-of-low-discrepancy-sequence/}
  26872. *
  26873. * @tsl
  26874. * @function
  26875. * @param {Node<vec2>} position - The input position, usually screen coordinates.
  26876. * @return {Node<float>} The noise value.
  26877. */
  26878. const interleavedGradientNoise = Fn( ( [ position ] ) => {
  26879. return fract( float( 52.9829189 ).mul( fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) ) );
  26880. } ).setLayout( {
  26881. name: 'interleavedGradientNoise',
  26882. type: 'float',
  26883. inputs: [
  26884. { name: 'position', type: 'vec2' }
  26885. ]
  26886. } );
  26887. /**
  26888. * Vogel disk sampling for uniform circular distribution.
  26889. *
  26890. * This function generates sample points distributed uniformly on a disk using the golden angle,
  26891. * resulting in an efficient low-discrepancy sequence for sampling. The rotation parameter (phi)
  26892. * allows randomizing the pattern per-pixel when combined with IGN.
  26893. *
  26894. * @tsl
  26895. * @function
  26896. * @param {Node<int>} sampleIndex - The index of the current sample (0-based).
  26897. * @param {Node<int>} samplesCount - The total number of samples.
  26898. * @param {Node<float>} phi - Rotation angle in radians (typically from IGN * 2π).
  26899. * @return {Node<vec2>} A 2D point on the unit disk.
  26900. */
  26901. const vogelDiskSample = Fn( ( [ sampleIndex, samplesCount, phi ] ) => {
  26902. const goldenAngle = float( 2.399963229728653 ); // 2π * (2 - φ) where φ is golden ratio
  26903. const r = sqrt( float( sampleIndex ).add( 0.5 ).div( float( samplesCount ) ) );
  26904. const theta = float( sampleIndex ).mul( goldenAngle ).add( phi );
  26905. return vec2( cos( theta ), sin( theta ) ).mul( r );
  26906. } ).setLayout( {
  26907. name: 'vogelDiskSample',
  26908. type: 'vec2',
  26909. inputs: [
  26910. { name: 'sampleIndex', type: 'int' },
  26911. { name: 'samplesCount', type: 'int' },
  26912. { name: 'phi', type: 'float' }
  26913. ]
  26914. } );
  26915. /**
  26916. * Class representing a node that samples a value using a provided callback function.
  26917. *
  26918. * @extends Node
  26919. */
  26920. class SampleNode extends Node {
  26921. /**
  26922. * Returns the type of the node.
  26923. *
  26924. * @type {string}
  26925. * @readonly
  26926. * @static
  26927. */
  26928. static get type() {
  26929. return 'SampleNode';
  26930. }
  26931. /**
  26932. * Creates an instance of SampleNode.
  26933. *
  26934. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  26935. * @param {?Node<vec2>} [uvNode=null] - The UV node to be used in the texture sampling.
  26936. */
  26937. constructor( callback, uvNode = null ) {
  26938. super();
  26939. this.callback = callback;
  26940. /**
  26941. * Represents the texture coordinates.
  26942. *
  26943. * @type {?Node<vec2|vec3>}
  26944. * @default null
  26945. */
  26946. this.uvNode = uvNode;
  26947. /**
  26948. * This flag can be used for type testing.
  26949. *
  26950. * @type {boolean}
  26951. * @readonly
  26952. * @default true
  26953. */
  26954. this.isSampleNode = true;
  26955. }
  26956. /**
  26957. * Sets up the node by sampling with the default UV accessor.
  26958. *
  26959. * @returns {Node} The result of the callback function when called with the UV node.
  26960. */
  26961. setup() {
  26962. return this.sample( uv$1() );
  26963. }
  26964. /**
  26965. * Calls the callback function with the provided UV node.
  26966. *
  26967. * @param {Node<vec2>} uv - The UV node or value to be passed to the callback.
  26968. * @returns {Node} The result of the callback function.
  26969. */
  26970. sample( uv ) {
  26971. return this.callback( uv );
  26972. }
  26973. }
  26974. /**
  26975. * Helper function to create a SampleNode wrapped as a node object.
  26976. *
  26977. * @function
  26978. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  26979. * @param {?Node<vec2>} [uv=null] - The UV node to be used in the texture sampling.
  26980. * @returns {SampleNode} The created SampleNode instance wrapped as a node object.
  26981. */
  26982. const sample = ( callback, uv = null ) => new SampleNode( callback, nodeObject( uv ) );
  26983. /**
  26984. * EventNode is a node that executes a callback during specific update phases.
  26985. *
  26986. * @augments Node
  26987. */
  26988. class EventNode extends Node {
  26989. static get type() {
  26990. return 'EventNode';
  26991. }
  26992. /**
  26993. * Creates an EventNode.
  26994. *
  26995. * @param {string} eventType - The type of event
  26996. * @param {Function} callback - The callback to execute on update.
  26997. */
  26998. constructor( eventType, callback ) {
  26999. super( 'void' );
  27000. this.eventType = eventType;
  27001. this.callback = callback;
  27002. if ( eventType === EventNode.OBJECT ) {
  27003. this.updateType = NodeUpdateType.OBJECT;
  27004. } else if ( eventType === EventNode.MATERIAL ) {
  27005. this.updateType = NodeUpdateType.RENDER;
  27006. } else if ( eventType === EventNode.FRAME ) {
  27007. this.updateType = NodeUpdateType.FRAME;
  27008. } else if ( eventType === EventNode.BEFORE_OBJECT ) {
  27009. this.updateBeforeType = NodeUpdateType.OBJECT;
  27010. } else if ( eventType === EventNode.BEFORE_MATERIAL ) {
  27011. this.updateBeforeType = NodeUpdateType.RENDER;
  27012. } else if ( eventType === EventNode.BEFORE_FRAME ) {
  27013. this.updateBeforeType = NodeUpdateType.FRAME;
  27014. }
  27015. }
  27016. update( frame ) {
  27017. this.callback( frame );
  27018. }
  27019. updateBefore( frame ) {
  27020. this.callback( frame );
  27021. }
  27022. }
  27023. EventNode.OBJECT = 'object';
  27024. EventNode.MATERIAL = 'material';
  27025. EventNode.FRAME = 'frame';
  27026. EventNode.BEFORE_OBJECT = 'beforeObject';
  27027. EventNode.BEFORE_MATERIAL = 'beforeMaterial';
  27028. EventNode.BEFORE_FRAME = 'beforeFrame';
  27029. /**
  27030. * Helper to create an EventNode and add it to the stack.
  27031. *
  27032. * @param {string} type - The event type.
  27033. * @param {Function} callback - The callback function.
  27034. * @returns {EventNode}
  27035. */
  27036. const createEvent = ( type, callback ) => new EventNode( type, callback ).toStack();
  27037. /**
  27038. * Creates an event that triggers a function every time an object (Mesh|Sprite) is rendered.
  27039. *
  27040. * 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.
  27041. *
  27042. * @param {Function} callback - The callback function.
  27043. * @returns {EventNode}
  27044. */
  27045. const OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback );
  27046. /**
  27047. * Creates an event that triggers a function when the first object that uses the material is rendered.
  27048. *
  27049. * 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.
  27050. *
  27051. * @param {Function} callback - The callback function.
  27052. * @returns {EventNode}
  27053. */
  27054. const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback );
  27055. /**
  27056. * Creates an event that triggers a function every frame.
  27057. *
  27058. * 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.
  27059. *
  27060. * @param {Function} callback - The callback function.
  27061. * @returns {EventNode}
  27062. */
  27063. const OnFrameUpdate = ( callback ) => createEvent( EventNode.FRAME, callback );
  27064. /**
  27065. * Creates an event that triggers a function before an object (Mesh|Sprite) is updated.
  27066. *
  27067. * 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.
  27068. *
  27069. * @param {Function} callback - The callback function.
  27070. * @returns {EventNode}
  27071. */
  27072. const OnBeforeObjectUpdate = ( callback ) => createEvent( EventNode.BEFORE_OBJECT, callback );
  27073. /**
  27074. * Creates an event that triggers a function before the material is updated.
  27075. *
  27076. * 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.
  27077. *
  27078. * @param {Function} callback - The callback function.
  27079. * @returns {EventNode}
  27080. */
  27081. const OnBeforeMaterialUpdate = ( callback ) => createEvent( EventNode.BEFORE_MATERIAL, callback );
  27082. /**
  27083. * Creates an event that triggers a function before every frame.
  27084. *
  27085. * 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.
  27086. *
  27087. * @param {Function} callback - The callback function.
  27088. * @returns {EventNode}
  27089. */
  27090. const OnBeforeFrameUpdate = ( callback ) => createEvent( EventNode.BEFORE_FRAME, callback );
  27091. /**
  27092. * This special type of instanced buffer attribute is intended for compute shaders.
  27093. * In earlier three.js versions it was only possible to update attribute data
  27094. * on the CPU via JavaScript and then upload the data to the GPU. With the
  27095. * new material system and renderer it is now possible to use compute shaders
  27096. * to compute the data for an attribute more efficiently on the GPU.
  27097. *
  27098. * The idea is to create an instance of this class and provide it as an input
  27099. * to {@link StorageBufferNode}.
  27100. *
  27101. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  27102. *
  27103. * @augments InstancedBufferAttribute
  27104. */
  27105. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  27106. /**
  27107. * Constructs a new storage instanced buffer attribute.
  27108. *
  27109. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  27110. * The subsequent parameters are then obsolete.
  27111. * @param {number} itemSize - The item size.
  27112. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  27113. */
  27114. constructor( count, itemSize, typeClass = Float32Array ) {
  27115. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  27116. super( array, itemSize );
  27117. /**
  27118. * This flag can be used for type testing.
  27119. *
  27120. * @type {boolean}
  27121. * @readonly
  27122. * @default true
  27123. */
  27124. this.isStorageInstancedBufferAttribute = true;
  27125. }
  27126. }
  27127. /**
  27128. * This special type of buffer attribute is intended for compute shaders.
  27129. * In earlier three.js versions it was only possible to update attribute data
  27130. * on the CPU via JavaScript and then upload the data to the GPU. With the
  27131. * new material system and renderer it is now possible to use compute shaders
  27132. * to compute the data for an attribute more efficiently on the GPU.
  27133. *
  27134. * The idea is to create an instance of this class and provide it as an input
  27135. * to {@link StorageBufferNode}.
  27136. *
  27137. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  27138. *
  27139. * @augments BufferAttribute
  27140. */
  27141. class StorageBufferAttribute extends BufferAttribute {
  27142. /**
  27143. * Constructs a new storage buffer attribute.
  27144. *
  27145. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  27146. * The subsequent parameters are then obsolete.
  27147. * @param {number} itemSize - The item size.
  27148. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  27149. */
  27150. constructor( count, itemSize, typeClass = Float32Array ) {
  27151. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  27152. super( array, itemSize );
  27153. /**
  27154. * This flag can be used for type testing.
  27155. *
  27156. * @type {boolean}
  27157. * @readonly
  27158. * @default true
  27159. */
  27160. this.isStorageBufferAttribute = true;
  27161. }
  27162. }
  27163. /**
  27164. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  27165. *
  27166. * @tsl
  27167. * @function
  27168. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  27169. * @param {string|Struct} [type='float'] - The data type.
  27170. * @returns {StorageBufferNode}
  27171. */
  27172. const attributeArray = ( count, type = 'float' ) => {
  27173. let itemSize, typedArray;
  27174. if ( type.isStruct === true ) {
  27175. itemSize = type.layout.getLength();
  27176. typedArray = getTypedArrayFromType( 'float' );
  27177. } else {
  27178. itemSize = getLengthFromType( type );
  27179. typedArray = getTypedArrayFromType( type );
  27180. }
  27181. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  27182. const node = storage( buffer, type, count );
  27183. return node;
  27184. };
  27185. /**
  27186. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  27187. *
  27188. * @tsl
  27189. * @function
  27190. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  27191. * @param {string|Struct} [type='float'] - The data type.
  27192. * @returns {StorageBufferNode}
  27193. */
  27194. const instancedArray = ( count, type = 'float' ) => {
  27195. let itemSize, typedArray;
  27196. if ( type.isStruct === true ) {
  27197. itemSize = type.layout.getLength();
  27198. typedArray = getTypedArrayFromType( 'float' );
  27199. } else {
  27200. itemSize = getLengthFromType( type );
  27201. typedArray = getTypedArrayFromType( type );
  27202. }
  27203. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  27204. const node = storage( buffer, type, buffer.count );
  27205. return node;
  27206. };
  27207. /**
  27208. * A node for representing the uv coordinates of points.
  27209. *
  27210. * Can only be used with a WebGL backend. In WebGPU, point
  27211. * primitives always have the size of one pixel and can thus
  27212. * can't be used as sprite-like objects that display textures.
  27213. *
  27214. * @augments Node
  27215. */
  27216. class PointUVNode extends Node {
  27217. static get type() {
  27218. return 'PointUVNode';
  27219. }
  27220. /**
  27221. * Constructs a new point uv node.
  27222. */
  27223. constructor() {
  27224. super( 'vec2' );
  27225. /**
  27226. * This flag can be used for type testing.
  27227. *
  27228. * @type {boolean}
  27229. * @readonly
  27230. * @default true
  27231. */
  27232. this.isPointUVNode = true;
  27233. }
  27234. generate( /*builder*/ ) {
  27235. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  27236. }
  27237. }
  27238. /**
  27239. * TSL object that represents the uv coordinates of points.
  27240. *
  27241. * @tsl
  27242. * @type {PointUVNode}
  27243. */
  27244. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  27245. const _m1 = /*@__PURE__*/ new Matrix4();
  27246. /**
  27247. * TSL object that represents the scene's background blurriness.
  27248. *
  27249. * @tsl
  27250. * @type {Node<float>}
  27251. */
  27252. const backgroundBlurriness = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( { scene } ) => scene.backgroundBlurriness );
  27253. /**
  27254. * TSL object that represents the scene's background intensity.
  27255. *
  27256. * @tsl
  27257. * @type {Node<float>}
  27258. */
  27259. const backgroundIntensity = /*@__PURE__*/ uniform( 1 ).setGroup( renderGroup ).onRenderUpdate( ( { scene } ) => scene.backgroundIntensity );
  27260. /**
  27261. * TSL object that represents the scene's background rotation.
  27262. *
  27263. * @tsl
  27264. * @type {Node<mat4>}
  27265. */
  27266. const backgroundRotation = /*@__PURE__*/ uniform( new Matrix4() ).setGroup( renderGroup ).onRenderUpdate( ( { scene } ) => {
  27267. const background = scene.background;
  27268. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  27269. // note: since the matrix is orthonormal, we can use the more-efficient transpose() in lieu of invert()
  27270. _m1.makeRotationFromEuler( scene.backgroundRotation ).transpose();
  27271. } else {
  27272. _m1.identity();
  27273. }
  27274. return _m1;
  27275. } );
  27276. /**
  27277. * This special version of a texture node can be used to
  27278. * write data into a storage texture with a compute shader.
  27279. *
  27280. * ```js
  27281. * const storageTexture = new THREE.StorageTexture( width, height );
  27282. *
  27283. * const computeTexture = Fn( ( { storageTexture } ) => {
  27284. *
  27285. * const posX = instanceIndex.mod( width );
  27286. * const posY = instanceIndex.div( width );
  27287. * const indexUV = uvec2( posX, posY );
  27288. *
  27289. * // generate RGB values
  27290. *
  27291. * const r = 1;
  27292. * const g = 1;
  27293. * const b = 1;
  27294. *
  27295. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  27296. *
  27297. * } );
  27298. *
  27299. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  27300. * renderer.computeAsync( computeNode );
  27301. * ```
  27302. *
  27303. * This node can only be used with a WebGPU backend.
  27304. *
  27305. * @augments TextureNode
  27306. */
  27307. class StorageTextureNode extends TextureNode {
  27308. static get type() {
  27309. return 'StorageTextureNode';
  27310. }
  27311. /**
  27312. * Constructs a new storage texture node.
  27313. *
  27314. * @param {StorageTexture} value - The storage texture.
  27315. * @param {Node<vec2|vec3>} uvNode - The uv node.
  27316. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  27317. */
  27318. constructor( value, uvNode, storeNode = null ) {
  27319. super( value, uvNode );
  27320. /**
  27321. * The value node that should be stored in the texture.
  27322. *
  27323. * @type {?Node}
  27324. * @default null
  27325. */
  27326. this.storeNode = storeNode;
  27327. /**
  27328. * The mip level to write to for storage textures.
  27329. *
  27330. * @type {number}
  27331. * @default 0
  27332. */
  27333. this.mipLevel = 0;
  27334. /**
  27335. * This flag can be used for type testing.
  27336. *
  27337. * @type {boolean}
  27338. * @readonly
  27339. * @default true
  27340. */
  27341. this.isStorageTextureNode = true;
  27342. /**
  27343. * The access type of the texture node.
  27344. *
  27345. * @type {string}
  27346. * @default 'writeOnly'
  27347. */
  27348. this.access = NodeAccess.WRITE_ONLY;
  27349. }
  27350. /**
  27351. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  27352. *
  27353. * @param {NodeBuilder} builder - The current node builder.
  27354. * @return {string} The input type.
  27355. */
  27356. getInputType( /*builder*/ ) {
  27357. return 'storageTexture';
  27358. }
  27359. setup( builder ) {
  27360. super.setup( builder );
  27361. const properties = builder.getNodeProperties( this );
  27362. properties.storeNode = this.storeNode;
  27363. return properties;
  27364. }
  27365. /**
  27366. * Defines the node access.
  27367. *
  27368. * @param {string} value - The node access.
  27369. * @return {StorageTextureNode} A reference to this node.
  27370. */
  27371. setAccess( value ) {
  27372. this.access = value;
  27373. return this;
  27374. }
  27375. /**
  27376. * Sets the mip level to write to.
  27377. *
  27378. * @param {number} level - The mip level.
  27379. * @return {StorageTextureNode} A reference to this node.
  27380. */
  27381. setMipLevel( level ) {
  27382. this.mipLevel = level;
  27383. return this;
  27384. }
  27385. /**
  27386. * Generates the code snippet of the storage node. If no `storeNode`
  27387. * is defined, the texture node is generated as normal texture.
  27388. *
  27389. * @param {NodeBuilder} builder - The current node builder.
  27390. * @param {string} output - The current output.
  27391. * @return {string} The generated code snippet.
  27392. */
  27393. generate( builder, output ) {
  27394. if ( this.storeNode !== null ) {
  27395. this.generateStore( builder );
  27396. return '';
  27397. }
  27398. return super.generate( builder, output );
  27399. }
  27400. /**
  27401. * Generates the snippet for the storage texture.
  27402. *
  27403. * @param {NodeBuilder} builder - The current node builder.
  27404. * @param {string} textureProperty - The texture property.
  27405. * @param {string} uvSnippet - The uv snippet.
  27406. * @param {?string} levelSnippet - The level snippet.
  27407. * @param {?string} biasSnippet - The bias snippet.
  27408. * @param {?string} depthSnippet - The depth snippet.
  27409. * @param {?string} compareSnippet - The compare snippet.
  27410. * @param {?Array<string>} gradSnippet - The grad snippet.
  27411. * @param {?string} offsetSnippet - The offset snippet.
  27412. * @return {string} The generated code snippet.
  27413. */
  27414. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet ) {
  27415. const texture = this.value;
  27416. return builder.generateStorageTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  27417. }
  27418. /**
  27419. * Convenience method for configuring a read/write node access.
  27420. *
  27421. * @return {StorageTextureNode} A reference to this node.
  27422. */
  27423. toReadWrite() {
  27424. return this.setAccess( NodeAccess.READ_WRITE );
  27425. }
  27426. /**
  27427. * Convenience method for configuring a read-only node access.
  27428. *
  27429. * @return {StorageTextureNode} A reference to this node.
  27430. */
  27431. toReadOnly() {
  27432. return this.setAccess( NodeAccess.READ_ONLY );
  27433. }
  27434. /**
  27435. * Convenience method for configuring a write-only node access.
  27436. *
  27437. * @return {StorageTextureNode} A reference to this node.
  27438. */
  27439. toWriteOnly() {
  27440. return this.setAccess( NodeAccess.WRITE_ONLY );
  27441. }
  27442. /**
  27443. * Generates the code snippet of the storage texture node.
  27444. *
  27445. * @param {NodeBuilder} builder - The current node builder.
  27446. */
  27447. generateStore( builder ) {
  27448. const properties = builder.getNodeProperties( this );
  27449. const { uvNode, storeNode, depthNode } = properties;
  27450. const textureProperty = super.generate( builder, 'property' );
  27451. const uvSnippet = uvNode.build( builder, this.value.is3DTexture === true ? 'uvec3' : 'uvec2' );
  27452. const storeSnippet = storeNode.build( builder, 'vec4' );
  27453. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  27454. const snippet = builder.generateTextureStore( this.value, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  27455. builder.addLineFlowCode( snippet, this );
  27456. }
  27457. clone() {
  27458. const newNode = super.clone();
  27459. newNode.storeNode = this.storeNode;
  27460. newNode.mipLevel = this.mipLevel;
  27461. newNode.access = this.access;
  27462. return newNode;
  27463. }
  27464. }
  27465. /**
  27466. * TSL function for creating a storage texture node.
  27467. *
  27468. * @tsl
  27469. * @function
  27470. * @param {StorageTexture} value - The storage texture.
  27471. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  27472. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  27473. * @returns {StorageTextureNode}
  27474. */
  27475. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  27476. /**
  27477. * TODO: Explain difference to `storageTexture()`.
  27478. *
  27479. * @tsl
  27480. * @function
  27481. * @param {StorageTexture} value - The storage texture.
  27482. * @param {Node<vec2|vec3>} uvNode - The uv node.
  27483. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  27484. * @returns {StorageTextureNode}
  27485. */
  27486. const textureStore = ( value, uvNode, storeNode ) => {
  27487. let node;
  27488. if ( value.isStorageTextureNode === true ) {
  27489. // Derive new storage texture node from existing one
  27490. node = value.clone();
  27491. node.uvNode = uvNode;
  27492. node.storeNode = storeNode;
  27493. } else {
  27494. node = storageTexture( value, uvNode, storeNode );
  27495. }
  27496. if ( storeNode !== null ) node.toStack();
  27497. return node;
  27498. };
  27499. const normal = Fn( ( { texture, uv } ) => {
  27500. const epsilon = 0.0001;
  27501. const ret = vec3().toVar();
  27502. If( uv.x.lessThan( epsilon ), () => {
  27503. ret.assign( vec3( 1, 0, 0 ) );
  27504. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  27505. ret.assign( vec3( 0, 1, 0 ) );
  27506. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  27507. ret.assign( vec3( 0, 0, 1 ) );
  27508. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  27509. ret.assign( vec3( -1, 0, 0 ) );
  27510. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  27511. ret.assign( vec3( 0, -1, 0 ) );
  27512. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  27513. ret.assign( vec3( 0, 0, -1 ) );
  27514. } ).Else( () => {
  27515. const step = 0.01;
  27516. 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 );
  27517. 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 );
  27518. 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 );
  27519. ret.assign( vec3( x, y, z ) );
  27520. } );
  27521. return ret.normalize();
  27522. } );
  27523. /**
  27524. * This type of uniform node represents a 3D texture.
  27525. *
  27526. * @augments TextureNode
  27527. */
  27528. class Texture3DNode extends TextureNode {
  27529. static get type() {
  27530. return 'Texture3DNode';
  27531. }
  27532. /**
  27533. * Constructs a new 3D texture node.
  27534. *
  27535. * @param {Data3DTexture} value - The 3D texture.
  27536. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  27537. * @param {?Node<int>} [levelNode=null] - The level node.
  27538. */
  27539. constructor( value, uvNode = null, levelNode = null ) {
  27540. super( value, uvNode, levelNode );
  27541. /**
  27542. * This flag can be used for type testing.
  27543. *
  27544. * @type {boolean}
  27545. * @readonly
  27546. * @default true
  27547. */
  27548. this.isTexture3DNode = true;
  27549. }
  27550. /**
  27551. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  27552. *
  27553. * @param {NodeBuilder} builder - The current node builder.
  27554. * @return {string} The input type.
  27555. */
  27556. getInputType( /*builder*/ ) {
  27557. return 'texture3D';
  27558. }
  27559. /**
  27560. * Returns a default uv node which is in context of 3D textures a three-dimensional
  27561. * uv node.
  27562. *
  27563. * @return {Node<vec3>} The default uv node.
  27564. */
  27565. getDefaultUV() {
  27566. return vec3( 0.5, 0.5, 0.5 );
  27567. }
  27568. /**
  27569. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  27570. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  27571. *
  27572. * @param {boolean} value - The update toggle.
  27573. */
  27574. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  27575. /**
  27576. * Generates the uv code snippet.
  27577. *
  27578. * @param {NodeBuilder} builder - The current node builder.
  27579. * @param {Node} uvNode - The uv node to generate code for.
  27580. * @return {string} The generated code snippet.
  27581. */
  27582. generateUV( builder, uvNode ) {
  27583. return uvNode.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  27584. }
  27585. /**
  27586. * Generates the offset code snippet.
  27587. *
  27588. * @param {NodeBuilder} builder - The current node builder.
  27589. * @param {Node} offsetNode - The offset node to generate code for.
  27590. * @return {string} The generated code snippet.
  27591. */
  27592. generateOffset( builder, offsetNode ) {
  27593. return offsetNode.build( builder, 'ivec3' );
  27594. }
  27595. /**
  27596. * Computes the normal for the given uv. These texture coordiantes represent a
  27597. * position inside the 3D texture. Unlike geometric normals, this normal
  27598. * represents a slope or gradient of scalar data inside the 3D texture.
  27599. *
  27600. * @param {Node<vec3>} uvNode - The uv node that defines a position in the 3D texture.
  27601. * @return {Node<vec3>} The normal representing the slope/gradient in the data.
  27602. */
  27603. normal( uvNode ) {
  27604. return normal( { texture: this, uv: uvNode } );
  27605. }
  27606. }
  27607. /**
  27608. * TSL function for creating a 3D texture node.
  27609. *
  27610. * @tsl
  27611. * @function
  27612. * @param {Data3DTexture} value - The 3D texture.
  27613. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  27614. * @param {?Node<int>} [levelNode=null] - The level node.
  27615. * @returns {Texture3DNode}
  27616. */
  27617. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  27618. /**
  27619. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  27620. *
  27621. * @tsl
  27622. * @function
  27623. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  27624. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  27625. * @param {?Node<int>} [levelNode=null] - The level node.
  27626. * @param {?Node<float>} [biasNode=null] - The bias node.
  27627. * @returns {TextureNode}
  27628. */
  27629. const texture3DLoad = ( ...params ) => texture3D( ...params ).setSampler( false );
  27630. /**
  27631. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  27632. *
  27633. * @tsl
  27634. * @function
  27635. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  27636. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  27637. * @param {?Node<int>} [levelNode=null] - The level node.
  27638. * @returns {TextureNode}
  27639. */
  27640. const texture3DLevel = ( value, uvNode, levelNode ) => texture3D( value, uvNode ).level( levelNode );
  27641. /**
  27642. * A special type of reference node that allows to link values in
  27643. * `userData` fields to node objects.
  27644. * ```js
  27645. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  27646. *
  27647. * const material = new THREE.SpriteNodeMaterial();
  27648. * material.rotationNode = userData( 'rotation', 'float' );
  27649. * ```
  27650. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  27651. * will automatically be updated when the `rotation` user data field changes.
  27652. *
  27653. * @augments ReferenceNode
  27654. */
  27655. class UserDataNode extends ReferenceNode {
  27656. static get type() {
  27657. return 'UserDataNode';
  27658. }
  27659. /**
  27660. * Constructs a new user data node.
  27661. *
  27662. * @param {string} property - The property name that should be referenced by the node.
  27663. * @param {string} inputType - The node data type of the reference.
  27664. * @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.
  27665. */
  27666. constructor( property, inputType, userData = null ) {
  27667. super( property, inputType, userData );
  27668. /**
  27669. * A reference to the `userData` object. If not provided, the `userData`
  27670. * property of the 3D object that uses the node material is evaluated.
  27671. *
  27672. * @type {?Object}
  27673. * @default null
  27674. */
  27675. this.userData = userData;
  27676. }
  27677. /**
  27678. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  27679. * `userData` field.
  27680. *
  27681. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  27682. * @return {Object} A reference to the `userData` field.
  27683. */
  27684. updateReference( state ) {
  27685. this.reference = this.userData !== null ? this.userData : state.object.userData;
  27686. return this.reference;
  27687. }
  27688. }
  27689. /**
  27690. * TSL function for creating a user data node.
  27691. *
  27692. * @tsl
  27693. * @function
  27694. * @param {string} name - The property name that should be referenced by the node.
  27695. * @param {string} inputType - The node data type of the reference.
  27696. * @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.
  27697. * @returns {UserDataNode}
  27698. */
  27699. const userData = ( name, inputType, userData ) => new UserDataNode( name, inputType, userData );
  27700. const _objectData = new WeakMap();
  27701. /**
  27702. * A node for representing motion or velocity vectors. Foundation
  27703. * for advanced post processing effects like motion blur or TRAA.
  27704. *
  27705. * The node keeps track of the model, view and projection matrices
  27706. * of the previous frame and uses them to compute offsets in NDC space.
  27707. * These offsets represent the final velocity.
  27708. *
  27709. * @augments TempNode
  27710. */
  27711. class VelocityNode extends TempNode {
  27712. static get type() {
  27713. return 'VelocityNode';
  27714. }
  27715. /**
  27716. * Constructs a new vertex color node.
  27717. */
  27718. constructor() {
  27719. super( 'vec2' );
  27720. /**
  27721. * The current projection matrix.
  27722. *
  27723. * @type {?Matrix4}
  27724. * @default null
  27725. */
  27726. this.projectionMatrix = null;
  27727. /**
  27728. * Overwritten since velocity nodes are updated per object.
  27729. *
  27730. * @type {string}
  27731. * @default 'object'
  27732. */
  27733. this.updateType = NodeUpdateType.OBJECT;
  27734. /**
  27735. * Overwritten since velocity nodes save data after the update.
  27736. *
  27737. * @type {string}
  27738. * @default 'object'
  27739. */
  27740. this.updateAfterType = NodeUpdateType.OBJECT;
  27741. /**
  27742. * Uniform node representing the previous model matrix in world space.
  27743. *
  27744. * @type {UniformNode<mat4>}
  27745. * @default null
  27746. */
  27747. this.previousModelWorldMatrix = uniform( new Matrix4() );
  27748. /**
  27749. * Uniform node representing the previous projection matrix.
  27750. *
  27751. * @type {UniformNode<mat4>}
  27752. * @default null
  27753. */
  27754. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  27755. /**
  27756. * Uniform node representing the previous view matrix.
  27757. *
  27758. * @type {UniformNode<mat4>}
  27759. * @default null
  27760. */
  27761. this.previousCameraViewMatrix = uniform( new Matrix4() );
  27762. }
  27763. /**
  27764. * Sets the given projection matrix.
  27765. *
  27766. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  27767. */
  27768. setProjectionMatrix( projectionMatrix ) {
  27769. this.projectionMatrix = projectionMatrix;
  27770. }
  27771. /**
  27772. * Updates velocity specific uniforms.
  27773. *
  27774. * @param {NodeFrame} frame - A reference to the current node frame.
  27775. */
  27776. update( { frameId, camera, object } ) {
  27777. const previousModelMatrix = getPreviousMatrix( object );
  27778. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  27779. //
  27780. const cameraData = getData( camera );
  27781. if ( cameraData.frameId !== frameId ) {
  27782. cameraData.frameId = frameId;
  27783. if ( cameraData.previousProjectionMatrix === undefined ) {
  27784. cameraData.previousProjectionMatrix = new Matrix4();
  27785. cameraData.previousCameraViewMatrix = new Matrix4();
  27786. cameraData.currentProjectionMatrix = new Matrix4();
  27787. cameraData.currentCameraViewMatrix = new Matrix4();
  27788. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  27789. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  27790. } else {
  27791. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  27792. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  27793. }
  27794. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  27795. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  27796. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  27797. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  27798. }
  27799. }
  27800. /**
  27801. * Overwritten to updated velocity specific uniforms.
  27802. *
  27803. * @param {NodeFrame} frame - A reference to the current node frame.
  27804. */
  27805. updateAfter( { object } ) {
  27806. getPreviousMatrix( object ).copy( object.matrixWorld );
  27807. }
  27808. /**
  27809. * Implements the velocity computation based on the previous and current vertex data.
  27810. *
  27811. * @param {NodeBuilder} builder - A reference to the current node builder.
  27812. * @return {Node<vec2>} The motion vector.
  27813. */
  27814. setup( /*builder*/ ) {
  27815. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  27816. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  27817. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  27818. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  27819. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  27820. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  27821. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  27822. return velocity;
  27823. }
  27824. }
  27825. function getData( object ) {
  27826. let objectData = _objectData.get( object );
  27827. if ( objectData === undefined ) {
  27828. objectData = {};
  27829. _objectData.set( object, objectData );
  27830. }
  27831. return objectData;
  27832. }
  27833. function getPreviousMatrix( object, index = 0 ) {
  27834. const objectData = getData( object );
  27835. let matrix = objectData[ index ];
  27836. if ( matrix === undefined ) {
  27837. objectData[ index ] = matrix = new Matrix4();
  27838. objectData[ index ].copy( object.matrixWorld );
  27839. }
  27840. return matrix;
  27841. }
  27842. /**
  27843. * TSL object that represents the velocity of a render pass.
  27844. *
  27845. * @tsl
  27846. * @type {VelocityNode}
  27847. */
  27848. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  27849. /**
  27850. * Represents a "Color Burn" blend mode.
  27851. *
  27852. * It's designed to darken the base layer's colors based on the color of the blend layer.
  27853. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  27854. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  27855. *
  27856. * @tsl
  27857. * @function
  27858. * @param {Node<vec3>} base - The base color.
  27859. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  27860. * @return {Node<vec3>} The result.
  27861. */
  27862. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  27863. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  27864. } ).setLayout( {
  27865. name: 'blendBurn',
  27866. type: 'vec3',
  27867. inputs: [
  27868. { name: 'base', type: 'vec3' },
  27869. { name: 'blend', type: 'vec3' }
  27870. ]
  27871. } );
  27872. /**
  27873. * Represents a "Color Dodge" blend mode.
  27874. *
  27875. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  27876. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  27877. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  27878. *
  27879. * @tsl
  27880. * @function
  27881. * @param {Node<vec3>} base - The base color.
  27882. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  27883. * @return {Node<vec3>} The result.
  27884. */
  27885. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  27886. return min$1( base.div( blend.oneMinus() ), 1.0 );
  27887. } ).setLayout( {
  27888. name: 'blendDodge',
  27889. type: 'vec3',
  27890. inputs: [
  27891. { name: 'base', type: 'vec3' },
  27892. { name: 'blend', type: 'vec3' }
  27893. ]
  27894. } );
  27895. /**
  27896. * Represents a "Screen" blend mode.
  27897. *
  27898. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  27899. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  27900. * effects.
  27901. *
  27902. * @tsl
  27903. * @function
  27904. * @param {Node<vec3>} base - The base color.
  27905. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  27906. * @return {Node<vec3>} The result.
  27907. */
  27908. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  27909. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  27910. } ).setLayout( {
  27911. name: 'blendScreen',
  27912. type: 'vec3',
  27913. inputs: [
  27914. { name: 'base', type: 'vec3' },
  27915. { name: 'blend', type: 'vec3' }
  27916. ]
  27917. } );
  27918. /**
  27919. * Represents a "Overlay" blend mode.
  27920. *
  27921. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  27922. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  27923. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  27924. *
  27925. * @tsl
  27926. * @function
  27927. * @param {Node<vec3>} base - The base color.
  27928. * @param {Node<vec3>} blend - The blend color
  27929. * @return {Node<vec3>} The result.
  27930. */
  27931. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  27932. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  27933. } ).setLayout( {
  27934. name: 'blendOverlay',
  27935. type: 'vec3',
  27936. inputs: [
  27937. { name: 'base', type: 'vec3' },
  27938. { name: 'blend', type: 'vec3' }
  27939. ]
  27940. } );
  27941. /**
  27942. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  27943. * It assumes both input colors have non-premultiplied alpha.
  27944. *
  27945. * @tsl
  27946. * @function
  27947. * @param {Node<vec4>} base - The base color.
  27948. * @param {Node<vec4>} blend - The blend color
  27949. * @return {Node<vec4>} The result.
  27950. */
  27951. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  27952. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  27953. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  27954. } ).setLayout( {
  27955. name: 'blendColor',
  27956. type: 'vec4',
  27957. inputs: [
  27958. { name: 'base', type: 'vec4' },
  27959. { name: 'blend', type: 'vec4' }
  27960. ]
  27961. } );
  27962. /**
  27963. * Computes a grayscale value for the given RGB color value.
  27964. *
  27965. * @tsl
  27966. * @function
  27967. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  27968. * @return {Node<vec3>} The grayscale color.
  27969. */
  27970. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  27971. return luminance( color.rgb );
  27972. } );
  27973. /**
  27974. * Super-saturates or desaturates the given RGB color.
  27975. *
  27976. * @tsl
  27977. * @function
  27978. * @param {Node<vec3>} color - The input color.
  27979. * @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.
  27980. * @return {Node<vec3>} The saturated color.
  27981. */
  27982. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  27983. return adjustment.mix( luminance( color.rgb ), color.rgb );
  27984. } );
  27985. /**
  27986. * Selectively enhance the intensity of less saturated RGB colors. Can result
  27987. * in a more natural and visually appealing image with enhanced color depth
  27988. * compared to {@link ColorAdjustment#saturation}.
  27989. *
  27990. * @tsl
  27991. * @function
  27992. * @param {Node<vec3>} color - The input color.
  27993. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  27994. * @return {Node<vec3>} The updated color.
  27995. */
  27996. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  27997. const average = add( color.r, color.g, color.b ).div( 3.0 );
  27998. const mx = color.r.max( color.g.max( color.b ) );
  27999. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  28000. return mix( color.rgb, mx, amt );
  28001. } );
  28002. /**
  28003. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  28004. *
  28005. * @tsl
  28006. * @function
  28007. * @param {Node<vec3>} color - The input color.
  28008. * @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.
  28009. * @return {Node<vec3>} The updated color.
  28010. */
  28011. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  28012. const k = vec3( 0.57735, 0.57735, 0.57735 );
  28013. const cosAngle = adjustment.cos();
  28014. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  28015. } );
  28016. /**
  28017. * Computes the luminance for the given RGB color value.
  28018. *
  28019. * @tsl
  28020. * @function
  28021. * @param {Node<vec3>} color - The color value to compute the luminance for.
  28022. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  28023. * @return {Node<float>} The luminance.
  28024. */
  28025. const luminance = (
  28026. color,
  28027. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  28028. ) => dot( color, luminanceCoefficients );
  28029. /**
  28030. * Color Decision List (CDL) v1.2
  28031. *
  28032. * Compact representation of color grading information, defined by slope, offset, power, and
  28033. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  28034. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  28035. *
  28036. * @tsl
  28037. * @function
  28038. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  28039. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  28040. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  28041. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  28042. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  28043. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  28044. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  28045. *
  28046. * References:
  28047. * - ASC CDL v1.2
  28048. * - {@link https://blender.stackexchange.com/a/55239/43930}
  28049. * - {@link https://docs.acescentral.com/specifications/acescc/}
  28050. */
  28051. const cdl = /*@__PURE__*/ Fn( ( [
  28052. color,
  28053. slope = vec3( 1 ),
  28054. offset = vec3( 0 ),
  28055. power = vec3( 1 ),
  28056. saturation = float( 1 ),
  28057. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  28058. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  28059. ] ) => {
  28060. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  28061. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  28062. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  28063. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  28064. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  28065. const pv = v.pow( power ).toVar();
  28066. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  28067. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  28068. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  28069. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  28070. return vec4( v.rgb, color.a );
  28071. } );
  28072. /**
  28073. * TSL function for creating a posterize effect which reduces the number of colors
  28074. * in an image, resulting in a more blocky and stylized appearance.
  28075. *
  28076. * @tsl
  28077. * @function
  28078. * @param {Node} sourceNode - The input color.
  28079. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  28080. * @returns {Node} The posterized color.
  28081. */
  28082. const posterize = Fn( ( [ source, steps ] ) => {
  28083. return source.mul( steps ).floor().div( steps );
  28084. } );
  28085. let _sharedFramebuffer = null;
  28086. /**
  28087. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  28088. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  28089. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  28090. *
  28091. * @augments ViewportTextureNode
  28092. */
  28093. class ViewportSharedTextureNode extends ViewportTextureNode {
  28094. static get type() {
  28095. return 'ViewportSharedTextureNode';
  28096. }
  28097. /**
  28098. * Constructs a new viewport shared texture node.
  28099. *
  28100. * @param {Node} [uvNode=screenUV] - The uv node.
  28101. * @param {?Node} [levelNode=null] - The level node.
  28102. */
  28103. constructor( uvNode = screenUV, levelNode = null ) {
  28104. if ( _sharedFramebuffer === null ) {
  28105. _sharedFramebuffer = new FramebufferTexture();
  28106. }
  28107. super( uvNode, levelNode, _sharedFramebuffer );
  28108. }
  28109. /**
  28110. * Overwritten so the method always returns the unique shared
  28111. * framebuffer texture.
  28112. *
  28113. * @return {FramebufferTexture} The shared framebuffer texture.
  28114. */
  28115. getTextureForReference() {
  28116. return _sharedFramebuffer;
  28117. }
  28118. updateReference() {
  28119. return this;
  28120. }
  28121. }
  28122. /**
  28123. * TSL function for creating a shared viewport texture node.
  28124. *
  28125. * @tsl
  28126. * @function
  28127. * @param {?Node} [uvNode=screenUV] - The uv node.
  28128. * @param {?Node} [levelNode=null] - The level node.
  28129. * @returns {ViewportSharedTextureNode}
  28130. */
  28131. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  28132. const _size = /*@__PURE__*/ new Vector2();
  28133. /**
  28134. * Represents the texture of a pass node.
  28135. *
  28136. * @augments TextureNode
  28137. */
  28138. class PassTextureNode extends TextureNode {
  28139. static get type() {
  28140. return 'PassTextureNode';
  28141. }
  28142. /**
  28143. * Constructs a new pass texture node.
  28144. *
  28145. * @param {PassNode} passNode - The pass node.
  28146. * @param {Texture} texture - The output texture.
  28147. */
  28148. constructor( passNode, texture ) {
  28149. super( texture );
  28150. /**
  28151. * A reference to the pass node.
  28152. *
  28153. * @type {PassNode}
  28154. */
  28155. this.passNode = passNode;
  28156. /**
  28157. * This flag can be used for type testing.
  28158. *
  28159. * @type {boolean}
  28160. * @default true
  28161. * @readonly
  28162. */
  28163. this.isPassTextureNode = true;
  28164. this.setUpdateMatrix( false );
  28165. }
  28166. setup( builder ) {
  28167. const properties = builder.getNodeProperties( this );
  28168. properties.passNode = this.passNode;
  28169. return super.setup( builder );
  28170. }
  28171. clone() {
  28172. return new this.constructor( this.passNode, this.value );
  28173. }
  28174. }
  28175. /**
  28176. * An extension of `PassTextureNode` which allows to manage more than one
  28177. * internal texture. Relevant for the `getPreviousTexture()` related API.
  28178. *
  28179. * @augments PassTextureNode
  28180. */
  28181. class PassMultipleTextureNode extends PassTextureNode {
  28182. static get type() {
  28183. return 'PassMultipleTextureNode';
  28184. }
  28185. /**
  28186. * Constructs a new pass texture node.
  28187. *
  28188. * @param {PassNode} passNode - The pass node.
  28189. * @param {string} textureName - The output texture name.
  28190. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  28191. */
  28192. constructor( passNode, textureName, previousTexture = false ) {
  28193. // null is passed to the super call since this class does not
  28194. // use an external texture for rendering pass data into. Instead
  28195. // the texture is managed by the pass node itself
  28196. super( passNode, null );
  28197. /**
  28198. * The output texture name.
  28199. *
  28200. * @type {string}
  28201. */
  28202. this.textureName = textureName;
  28203. /**
  28204. * Whether previous frame data should be used or not.
  28205. *
  28206. * @type {boolean}
  28207. */
  28208. this.previousTexture = previousTexture;
  28209. /**
  28210. * This flag can be used for type testing.
  28211. *
  28212. * @type {boolean}
  28213. * @default true
  28214. * @readonly
  28215. */
  28216. this.isPassMultipleTextureNode = true;
  28217. }
  28218. /**
  28219. * Updates the texture reference of this node.
  28220. */
  28221. updateTexture() {
  28222. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  28223. }
  28224. setup( builder ) {
  28225. this.updateTexture();
  28226. return super.setup( builder );
  28227. }
  28228. clone() {
  28229. const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture );
  28230. newNode.uvNode = this.uvNode;
  28231. newNode.levelNode = this.levelNode;
  28232. newNode.biasNode = this.biasNode;
  28233. newNode.sampler = this.sampler;
  28234. newNode.depthNode = this.depthNode;
  28235. newNode.compareNode = this.compareNode;
  28236. newNode.gradNode = this.gradNode;
  28237. newNode.gatherNode = this.gatherNode;
  28238. newNode.offsetNode = this.offsetNode;
  28239. return newNode;
  28240. }
  28241. }
  28242. /**
  28243. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  28244. * This pass produces a render for the given scene and camera and can provide multiple outputs
  28245. * via MRT for further processing.
  28246. *
  28247. * ```js
  28248. * const postProcessing = new RenderPipeline( renderer );
  28249. *
  28250. * const scenePass = pass( scene, camera );
  28251. *
  28252. * postProcessing.outputNode = scenePass;
  28253. * ```
  28254. *
  28255. * @augments TempNode
  28256. */
  28257. class PassNode extends TempNode {
  28258. static get type() {
  28259. return 'PassNode';
  28260. }
  28261. /**
  28262. * Constructs a new pass node.
  28263. *
  28264. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  28265. * @param {Scene} scene - A reference to the scene.
  28266. * @param {Camera} camera - A reference to the camera.
  28267. * @param {Object} options - Options for the internal render target.
  28268. */
  28269. constructor( scope, scene, camera, options = {} ) {
  28270. super( 'vec4' );
  28271. /**
  28272. * The scope of the pass. The scope determines whether the node outputs color or depth.
  28273. *
  28274. * @type {('color'|'depth')}
  28275. */
  28276. this.scope = scope;
  28277. /**
  28278. * A reference to the scene.
  28279. *
  28280. * @type {Scene}
  28281. */
  28282. this.scene = scene;
  28283. /**
  28284. * A reference to the camera.
  28285. *
  28286. * @type {Camera}
  28287. */
  28288. this.camera = camera;
  28289. /**
  28290. * Options for the internal render target.
  28291. *
  28292. * @type {Object}
  28293. */
  28294. this.options = options;
  28295. /**
  28296. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  28297. *
  28298. * @private
  28299. * @type {number}
  28300. * @default 1
  28301. */
  28302. this._pixelRatio = 1;
  28303. /**
  28304. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  28305. * @private
  28306. * @type {number}
  28307. * @default 1
  28308. */
  28309. this._width = 1;
  28310. /**
  28311. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  28312. * @private
  28313. * @type {number}
  28314. * @default 1
  28315. */
  28316. this._height = 1;
  28317. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  28318. renderTarget.texture.name = 'output';
  28319. let depthTexture = null;
  28320. if ( this.scope === PassNode.DEPTH || options.depthBuffer !== false ) {
  28321. depthTexture = new DepthTexture();
  28322. depthTexture.isRenderTargetTexture = true;
  28323. //depthTexture.type = FloatType;
  28324. depthTexture.name = 'depth';
  28325. renderTarget.depthTexture = depthTexture;
  28326. }
  28327. /**
  28328. * The pass's render target.
  28329. *
  28330. * @type {RenderTarget}
  28331. */
  28332. this.renderTarget = renderTarget;
  28333. /**
  28334. * An optional override material for the pass.
  28335. *
  28336. * @type {Material|null}
  28337. */
  28338. this.overrideMaterial = null;
  28339. /**
  28340. * Whether the pass is transparent.
  28341. *
  28342. * @type {boolean}
  28343. * @default false
  28344. */
  28345. this.transparent = true;
  28346. /**
  28347. * Whether the pass is opaque.
  28348. *
  28349. * @type {boolean}
  28350. * @default true
  28351. */
  28352. this.opaque = true;
  28353. /**
  28354. * An optional global context for the pass.
  28355. *
  28356. * @type {ContextNode|null}
  28357. */
  28358. this.contextNode = null;
  28359. /**
  28360. * A cache for the context node.
  28361. *
  28362. * @private
  28363. * @type {?Object}
  28364. * @default null
  28365. */
  28366. this._contextNodeCache = null;
  28367. /**
  28368. * A dictionary holding the internal result textures.
  28369. *
  28370. * @private
  28371. * @type {{ output: Texture, depth?: DepthTexture }}
  28372. */
  28373. this._textures = {
  28374. output: renderTarget.texture
  28375. };
  28376. if ( depthTexture !== null ) {
  28377. this._textures.depth = depthTexture;
  28378. }
  28379. /**
  28380. * A dictionary holding the internal texture nodes.
  28381. *
  28382. * @private
  28383. * @type {Object<string, TextureNode>}
  28384. */
  28385. this._textureNodes = {};
  28386. /**
  28387. * A dictionary holding the internal depth nodes.
  28388. *
  28389. * @private
  28390. * @type {Object}
  28391. */
  28392. this._linearDepthNodes = {};
  28393. /**
  28394. * A dictionary holding the internal viewZ nodes.
  28395. *
  28396. * @private
  28397. * @type {Object}
  28398. */
  28399. this._viewZNodes = {};
  28400. /**
  28401. * A dictionary holding the texture data of the previous frame.
  28402. * Used for computing velocity/motion vectors.
  28403. *
  28404. * @private
  28405. * @type {Object<string, Texture>}
  28406. */
  28407. this._previousTextures = {};
  28408. /**
  28409. * A dictionary holding the texture nodes of the previous frame.
  28410. * Used for computing velocity/motion vectors.
  28411. *
  28412. * @private
  28413. * @type {Object<string, TextureNode>}
  28414. */
  28415. this._previousTextureNodes = {};
  28416. /**
  28417. * The `near` property of the camera as a uniform.
  28418. *
  28419. * @private
  28420. * @type {UniformNode}
  28421. */
  28422. this._cameraNear = uniform( 0 );
  28423. /**
  28424. * The `far` property of the camera as a uniform.
  28425. *
  28426. * @private
  28427. * @type {UniformNode}
  28428. */
  28429. this._cameraFar = uniform( 0 );
  28430. /**
  28431. * A MRT node configuring the MRT settings.
  28432. *
  28433. * @private
  28434. * @type {?MRTNode}
  28435. * @default null
  28436. */
  28437. this._mrt = null;
  28438. /**
  28439. * Layer object for configuring the camera that is used
  28440. * to produce the pass.
  28441. *
  28442. * @private
  28443. * @type {?Layers}
  28444. * @default null
  28445. */
  28446. this._layers = null;
  28447. /**
  28448. * Scales the resolution of the internal render target.
  28449. *
  28450. * @private
  28451. * @type {number}
  28452. * @default 1
  28453. */
  28454. this._resolutionScale = 1;
  28455. /**
  28456. * Custom viewport definition.
  28457. *
  28458. * @private
  28459. * @type {?Vector4}
  28460. * @default null
  28461. */
  28462. this._viewport = null;
  28463. /**
  28464. * Custom scissor definition.
  28465. *
  28466. * @private
  28467. * @type {?Vector4}
  28468. * @default null
  28469. */
  28470. this._scissor = null;
  28471. /**
  28472. * This flag can be used for type testing.
  28473. *
  28474. * @type {boolean}
  28475. * @readonly
  28476. * @default true
  28477. */
  28478. this.isPassNode = true;
  28479. /**
  28480. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  28481. * scene once per frame in its {@link PassNode#updateBefore} method.
  28482. *
  28483. * @type {string}
  28484. * @default 'frame'
  28485. */
  28486. this.updateBeforeType = NodeUpdateType.FRAME;
  28487. /**
  28488. * This flag is used for global cache.
  28489. *
  28490. * @type {boolean}
  28491. * @default true
  28492. */
  28493. this.global = true;
  28494. }
  28495. /**
  28496. * Sets the resolution scale for the pass.
  28497. * The resolution scale is a factor that is multiplied with the renderer's width and height.
  28498. *
  28499. * @param {number} resolutionScale - The resolution scale to set. A value of `1` means full resolution.
  28500. * @return {PassNode} A reference to this pass.
  28501. */
  28502. setResolutionScale( resolutionScale ) {
  28503. this._resolutionScale = resolutionScale;
  28504. return this;
  28505. }
  28506. /**
  28507. * Gets the current resolution scale of the pass.
  28508. *
  28509. * @return {number} The current resolution scale. A value of `1` means full resolution.
  28510. */
  28511. getResolutionScale() {
  28512. return this._resolutionScale;
  28513. }
  28514. /**
  28515. * Sets the resolution for the pass.
  28516. * The resolution is a factor that is multiplied with the renderer's width and height.
  28517. *
  28518. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  28519. * @return {PassNode} A reference to this pass.
  28520. * @deprecated since r181. Use {@link PassNode#setResolutionScale `setResolutionScale()`} instead.
  28521. */
  28522. setResolution( resolution ) { // @deprecated, r181
  28523. warn( 'PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead.' );
  28524. return this.setResolutionScale( resolution );
  28525. }
  28526. /**
  28527. * Gets the current resolution of the pass.
  28528. *
  28529. * @return {number} The current resolution. A value of `1` means full resolution.
  28530. * @deprecated since r181. Use {@link PassNode#getResolutionScale `getResolutionScale()`} instead.
  28531. */
  28532. getResolution() { // @deprecated, r181
  28533. warn( 'PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead.' );
  28534. return this.getResolutionScale();
  28535. }
  28536. /**
  28537. * Sets the layer configuration that should be used when rendering the pass.
  28538. *
  28539. * @param {Layers} layers - The layers object to set.
  28540. * @return {PassNode} A reference to this pass.
  28541. */
  28542. setLayers( layers ) {
  28543. this._layers = layers;
  28544. return this;
  28545. }
  28546. /**
  28547. * Gets the current layer configuration of the pass.
  28548. *
  28549. * @return {?Layers} .
  28550. */
  28551. getLayers() {
  28552. return this._layers;
  28553. }
  28554. /**
  28555. * Sets the given MRT node to setup MRT for this pass.
  28556. *
  28557. * @param {MRTNode} mrt - The MRT object.
  28558. * @return {PassNode} A reference to this pass.
  28559. */
  28560. setMRT( mrt ) {
  28561. this._mrt = mrt;
  28562. return this;
  28563. }
  28564. /**
  28565. * Returns the current MRT node.
  28566. *
  28567. * @return {MRTNode} The current MRT node.
  28568. */
  28569. getMRT() {
  28570. return this._mrt;
  28571. }
  28572. /**
  28573. * Returns the texture for the given output name.
  28574. *
  28575. * @param {string} name - The output name to get the texture for.
  28576. * @return {Texture} The texture.
  28577. */
  28578. getTexture( name ) {
  28579. let texture = this._textures[ name ];
  28580. if ( texture === undefined ) {
  28581. if ( name === 'depth' ) {
  28582. throw new Error( 'THREE.PassNode: Depth texture is not available for this pass.' );
  28583. }
  28584. const refTexture = this.renderTarget.texture;
  28585. texture = refTexture.clone();
  28586. texture.name = name;
  28587. this._textures[ name ] = texture;
  28588. this.renderTarget.textures.push( texture );
  28589. }
  28590. return texture;
  28591. }
  28592. /**
  28593. * Returns the texture holding the data of the previous frame for the given output name.
  28594. *
  28595. * @param {string} name - The output name to get the texture for.
  28596. * @return {Texture} The texture holding the data of the previous frame.
  28597. */
  28598. getPreviousTexture( name ) {
  28599. let texture = this._previousTextures[ name ];
  28600. if ( texture === undefined ) {
  28601. texture = this.getTexture( name ).clone();
  28602. this._previousTextures[ name ] = texture;
  28603. }
  28604. return texture;
  28605. }
  28606. /**
  28607. * Switches current and previous textures for the given output name.
  28608. *
  28609. * @param {string} name - The output name.
  28610. */
  28611. toggleTexture( name ) {
  28612. const prevTexture = this._previousTextures[ name ];
  28613. if ( prevTexture !== undefined ) {
  28614. const texture = this._textures[ name ];
  28615. const index = this.renderTarget.textures.indexOf( texture );
  28616. this.renderTarget.textures[ index ] = prevTexture;
  28617. this._textures[ name ] = prevTexture;
  28618. this._previousTextures[ name ] = texture;
  28619. this._textureNodes[ name ].updateTexture();
  28620. this._previousTextureNodes[ name ].updateTexture();
  28621. }
  28622. }
  28623. /**
  28624. * Returns the texture node for the given output name.
  28625. *
  28626. * @param {string} [name='output'] - The output name to get the texture node for.
  28627. * @return {TextureNode} The texture node.
  28628. */
  28629. getTextureNode( name = 'output' ) {
  28630. let textureNode = this._textureNodes[ name ];
  28631. if ( textureNode === undefined ) {
  28632. textureNode = new PassMultipleTextureNode( this, name );
  28633. textureNode.updateTexture();
  28634. this._textureNodes[ name ] = textureNode;
  28635. }
  28636. return textureNode;
  28637. }
  28638. /**
  28639. * Returns the previous texture node for the given output name.
  28640. *
  28641. * @param {string} [name='output'] - The output name to get the previous texture node for.
  28642. * @return {TextureNode} The previous texture node.
  28643. */
  28644. getPreviousTextureNode( name = 'output' ) {
  28645. let textureNode = this._previousTextureNodes[ name ];
  28646. if ( textureNode === undefined ) {
  28647. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  28648. textureNode = new PassMultipleTextureNode( this, name, true );
  28649. textureNode.updateTexture();
  28650. this._previousTextureNodes[ name ] = textureNode;
  28651. }
  28652. return textureNode;
  28653. }
  28654. /**
  28655. * Returns a viewZ node of this pass.
  28656. *
  28657. * @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.
  28658. * @return {Node} The viewZ node.
  28659. */
  28660. getViewZNode( name = 'depth' ) {
  28661. let viewZNode = this._viewZNodes[ name ];
  28662. if ( viewZNode === undefined ) {
  28663. const cameraNear = this._cameraNear;
  28664. const cameraFar = this._cameraFar;
  28665. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  28666. }
  28667. return viewZNode;
  28668. }
  28669. /**
  28670. * Returns a linear depth node of this pass.
  28671. *
  28672. * @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.
  28673. * @return {Node} The linear depth node.
  28674. */
  28675. getLinearDepthNode( name = 'depth' ) {
  28676. let linearDepthNode = this._linearDepthNodes[ name ];
  28677. if ( linearDepthNode === undefined ) {
  28678. const cameraNear = this._cameraNear;
  28679. const cameraFar = this._cameraFar;
  28680. const viewZNode = this.getViewZNode( name );
  28681. // TODO: just if ( builder.camera.isPerspectiveCamera )
  28682. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  28683. }
  28684. return linearDepthNode;
  28685. }
  28686. /**
  28687. * Precompiles the pass.
  28688. *
  28689. * Note that this method must be called after the pass configuration is complete.
  28690. * So calls like `setMRT()` and `getTextureNode()` must proceed the precompilation.
  28691. *
  28692. * @async
  28693. * @param {Renderer} renderer - The renderer.
  28694. * @return {Promise} A Promise that resolves when the compile has been finished.
  28695. * @see {@link Renderer#compileAsync}
  28696. */
  28697. async compileAsync( renderer ) {
  28698. const currentRenderTarget = renderer.getRenderTarget();
  28699. const currentMRT = renderer.getMRT();
  28700. renderer.setRenderTarget( this.renderTarget );
  28701. renderer.setMRT( this._mrt );
  28702. await renderer.compileAsync( this.scene, this.camera );
  28703. renderer.setRenderTarget( currentRenderTarget );
  28704. renderer.setMRT( currentMRT );
  28705. }
  28706. setup( { renderer } ) {
  28707. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  28708. this.renderTarget.texture.type = renderer.getOutputBufferType();
  28709. if ( renderer.reversedDepthBuffer === true && this.renderTarget.depthTexture !== null ) {
  28710. this.renderTarget.depthTexture.type = FloatType;
  28711. }
  28712. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  28713. }
  28714. updateBefore( frame ) {
  28715. const { renderer } = frame;
  28716. const { scene } = this;
  28717. let camera;
  28718. let pixelRatio;
  28719. const outputRenderTarget = renderer.getOutputRenderTarget();
  28720. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  28721. pixelRatio = 1;
  28722. camera = renderer.xr.getCamera();
  28723. renderer.xr.updateCamera( camera );
  28724. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  28725. } else {
  28726. camera = this.camera;
  28727. pixelRatio = renderer.getPixelRatio();
  28728. renderer.getSize( _size );
  28729. }
  28730. this._pixelRatio = pixelRatio;
  28731. this.setSize( _size.width, _size.height );
  28732. const currentRenderTarget = renderer.getRenderTarget();
  28733. const currentMRT = renderer.getMRT();
  28734. const currentAutoClear = renderer.autoClear;
  28735. const currentTransparent = renderer.transparent;
  28736. const currentOpaque = renderer.opaque;
  28737. const currentMask = camera.layers.mask;
  28738. const currentContextNode = renderer.contextNode;
  28739. const currentOverrideMaterial = scene.overrideMaterial;
  28740. this._cameraNear.value = camera.near;
  28741. this._cameraFar.value = camera.far;
  28742. if ( this._layers !== null ) {
  28743. camera.layers.mask = this._layers.mask;
  28744. }
  28745. for ( const name in this._previousTextures ) {
  28746. this.toggleTexture( name );
  28747. }
  28748. if ( this.overrideMaterial !== null ) {
  28749. scene.overrideMaterial = this.overrideMaterial;
  28750. }
  28751. renderer.setRenderTarget( this.renderTarget );
  28752. renderer.setMRT( this._mrt );
  28753. renderer.autoClear = true;
  28754. renderer.transparent = this.transparent;
  28755. renderer.opaque = this.opaque;
  28756. if ( this.contextNode !== null ) {
  28757. if ( this._contextNodeCache === null || this._contextNodeCache.version !== this.version ) {
  28758. this._contextNodeCache = {
  28759. version: this.version,
  28760. context: context( { ...renderer.contextNode.getFlowContextData(), ...this.contextNode.getFlowContextData() } )
  28761. };
  28762. }
  28763. renderer.contextNode = this._contextNodeCache.context;
  28764. }
  28765. const currentSceneName = scene.name;
  28766. scene.name = this.name ? this.name : scene.name;
  28767. renderer.render( scene, camera );
  28768. scene.name = currentSceneName;
  28769. scene.overrideMaterial = currentOverrideMaterial;
  28770. renderer.setRenderTarget( currentRenderTarget );
  28771. renderer.setMRT( currentMRT );
  28772. renderer.autoClear = currentAutoClear;
  28773. renderer.transparent = currentTransparent;
  28774. renderer.opaque = currentOpaque;
  28775. renderer.contextNode = currentContextNode;
  28776. camera.layers.mask = currentMask;
  28777. }
  28778. /**
  28779. * Sets the size of the pass's render target. Honors the pixel ratio.
  28780. *
  28781. * @param {number} width - The width to set.
  28782. * @param {number} height - The height to set.
  28783. */
  28784. setSize( width, height ) {
  28785. this._width = width;
  28786. this._height = height;
  28787. const effectiveWidth = Math.floor( this._width * this._pixelRatio * this._resolutionScale );
  28788. const effectiveHeight = Math.floor( this._height * this._pixelRatio * this._resolutionScale );
  28789. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  28790. // scissor
  28791. if ( this._scissor !== null ) {
  28792. this.renderTarget.scissor.copy( this._scissor ).multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  28793. this.renderTarget.scissorTest = true;
  28794. } else {
  28795. this.renderTarget.scissorTest = false;
  28796. }
  28797. // viewport
  28798. if ( this._viewport !== null ) {
  28799. this.renderTarget.viewport.copy( this._viewport ).multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  28800. }
  28801. }
  28802. /**
  28803. * This method allows to define the pass's scissor rectangle. By default, the scissor rectangle is kept
  28804. * in sync with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  28805. * with `null` as the single argument.
  28806. *
  28807. * @param {?(number | Vector4)} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  28808. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  28809. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  28810. * @param {number} width - The width of the scissor box in logical pixel unit.
  28811. * @param {number} height - The height of the scissor box in logical pixel unit.
  28812. */
  28813. setScissor( x, y, width, height ) {
  28814. if ( x === null ) {
  28815. this._scissor = null;
  28816. } else {
  28817. if ( this._scissor === null ) this._scissor = new Vector4();
  28818. if ( x.isVector4 ) {
  28819. this._scissor.copy( x );
  28820. } else {
  28821. this._scissor.set( x, y, width, height );
  28822. }
  28823. }
  28824. }
  28825. /**
  28826. * This method allows to define the pass's viewport. By default, the viewport is kept in sync
  28827. * with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  28828. * with `null` as the single argument.
  28829. *
  28830. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  28831. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  28832. * @param {number} width - The width of the viewport in logical pixel unit.
  28833. * @param {number} height - The height of the viewport in logical pixel unit.
  28834. */
  28835. setViewport( x, y, width, height ) {
  28836. if ( x === null ) {
  28837. this._viewport = null;
  28838. } else {
  28839. if ( this._viewport === null ) this._viewport = new Vector4();
  28840. if ( x.isVector4 ) {
  28841. this._viewport.copy( x );
  28842. } else {
  28843. this._viewport.set( x, y, width, height );
  28844. }
  28845. }
  28846. }
  28847. /**
  28848. * Sets the pixel ratio the pass's render target and updates the size.
  28849. *
  28850. * @param {number} pixelRatio - The pixel ratio to set.
  28851. */
  28852. setPixelRatio( pixelRatio ) {
  28853. this._pixelRatio = pixelRatio;
  28854. this.setSize( this._width, this._height );
  28855. }
  28856. /**
  28857. * Frees internal resources. Should be called when the node is no longer in use.
  28858. */
  28859. dispose() {
  28860. this.renderTarget.dispose();
  28861. }
  28862. }
  28863. /**
  28864. * @static
  28865. * @type {'color'}
  28866. * @default 'color'
  28867. */
  28868. PassNode.COLOR = 'color';
  28869. /**
  28870. * @static
  28871. * @type {'depth'}
  28872. * @default 'depth'
  28873. */
  28874. PassNode.DEPTH = 'depth';
  28875. /**
  28876. * TSL function for creating a pass node.
  28877. *
  28878. * @tsl
  28879. * @function
  28880. * @param {Scene} scene - A reference to the scene.
  28881. * @param {Camera} camera - A reference to the camera.
  28882. * @param {Object} options - Options for the internal render target.
  28883. * @returns {PassNode}
  28884. */
  28885. const pass = ( scene, camera, options ) => new PassNode( PassNode.COLOR, scene, camera, options );
  28886. /**
  28887. * TSL function for creating a pass texture node.
  28888. *
  28889. * @tsl
  28890. * @function
  28891. * @param {PassNode} pass - The pass node.
  28892. * @param {Texture} texture - The output texture.
  28893. * @returns {PassTextureNode}
  28894. */
  28895. const passTexture = ( pass, texture ) => new PassTextureNode( pass, texture );
  28896. /**
  28897. * TSL function for creating a depth pass node.
  28898. *
  28899. * @tsl
  28900. * @function
  28901. * @param {Scene} scene - A reference to the scene.
  28902. * @param {Camera} camera - A reference to the camera.
  28903. * @param {Object} options - Options for the internal render target.
  28904. * @returns {PassNode}
  28905. */
  28906. const depthPass = ( scene, camera, options ) => new PassNode( PassNode.DEPTH, scene, camera, options );
  28907. /**
  28908. * Represents a render pass for producing a toon outline effect on compatible objects.
  28909. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  28910. * will receive the outline.
  28911. *
  28912. * ```js
  28913. * const postProcessing = new RenderPipeline( renderer );
  28914. *
  28915. * const scenePass = toonOutlinePass( scene, camera );
  28916. *
  28917. * postProcessing.outputNode = scenePass;
  28918. * ```
  28919. * @augments PassNode
  28920. */
  28921. class ToonOutlinePassNode extends PassNode {
  28922. static get type() {
  28923. return 'ToonOutlinePassNode';
  28924. }
  28925. /**
  28926. * Constructs a new outline pass node.
  28927. *
  28928. * @param {Scene} scene - A reference to the scene.
  28929. * @param {Camera} camera - A reference to the camera.
  28930. * @param {Node} colorNode - Defines the outline's color.
  28931. * @param {Node} thicknessNode - Defines the outline's thickness.
  28932. * @param {Node} alphaNode - Defines the outline's alpha.
  28933. */
  28934. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  28935. super( PassNode.COLOR, scene, camera );
  28936. /**
  28937. * Defines the outline's color.
  28938. *
  28939. * @type {Node}
  28940. */
  28941. this.colorNode = colorNode;
  28942. /**
  28943. * Defines the outline's thickness.
  28944. *
  28945. * @type {Node}
  28946. */
  28947. this.thicknessNode = thicknessNode;
  28948. /**
  28949. * Defines the outline's alpha.
  28950. *
  28951. * @type {Node}
  28952. */
  28953. this.alphaNode = alphaNode;
  28954. /**
  28955. * An internal material cache.
  28956. *
  28957. * @private
  28958. * @type {WeakMap<Material, NodeMaterial>}
  28959. */
  28960. this._materialCache = new WeakMap();
  28961. /**
  28962. * The name of this pass.
  28963. *
  28964. * @type {string}
  28965. * @default 'Outline Pass'
  28966. */
  28967. this.name = 'Outline Pass';
  28968. }
  28969. updateBefore( frame ) {
  28970. const { renderer } = frame;
  28971. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  28972. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  28973. // only render outline for supported materials
  28974. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  28975. if ( material.wireframe === false ) {
  28976. const outlineMaterial = this._getOutlineMaterial( material );
  28977. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  28978. }
  28979. }
  28980. // default
  28981. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  28982. } );
  28983. super.updateBefore( frame );
  28984. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  28985. }
  28986. /**
  28987. * Creates the material used for outline rendering.
  28988. *
  28989. * @private
  28990. * @return {NodeMaterial} The outline material.
  28991. */
  28992. _createMaterial() {
  28993. const material = new NodeMaterial();
  28994. material.isMeshToonOutlineMaterial = true;
  28995. material.name = 'Toon_Outline';
  28996. material.side = BackSide;
  28997. // vertex node
  28998. const outlineNormal = normalLocal.negate();
  28999. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  29000. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  29001. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  29002. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  29003. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  29004. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  29005. // color node
  29006. material.colorNode = vec4( this.colorNode, this.alphaNode );
  29007. return material;
  29008. }
  29009. /**
  29010. * For the given toon material, this method returns a corresponding
  29011. * outline material.
  29012. *
  29013. * @private
  29014. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  29015. * @return {NodeMaterial} The outline material.
  29016. */
  29017. _getOutlineMaterial( originalMaterial ) {
  29018. let outlineMaterial = this._materialCache.get( originalMaterial );
  29019. if ( outlineMaterial === undefined ) {
  29020. outlineMaterial = this._createMaterial();
  29021. this._materialCache.set( originalMaterial, outlineMaterial );
  29022. }
  29023. return outlineMaterial;
  29024. }
  29025. }
  29026. /**
  29027. * TSL function for creating a toon outline pass node.
  29028. *
  29029. * @tsl
  29030. * @function
  29031. * @param {Scene} scene - A reference to the scene.
  29032. * @param {Camera} camera - A reference to the camera.
  29033. * @param {Color} color - Defines the outline's color.
  29034. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  29035. * @param {number} [alpha=1] - Defines the outline's alpha.
  29036. * @returns {ToonOutlinePassNode}
  29037. */
  29038. 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 ) );
  29039. /**
  29040. * Linear tone mapping, exposure only.
  29041. *
  29042. * @tsl
  29043. * @function
  29044. * @param {Node<vec3>} color - The color that should be tone mapped.
  29045. * @param {Node<float>} exposure - The exposure.
  29046. * @return {Node<vec3>} The tone mapped color.
  29047. */
  29048. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  29049. return color.mul( exposure ).clamp();
  29050. } ).setLayout( {
  29051. name: 'linearToneMapping',
  29052. type: 'vec3',
  29053. inputs: [
  29054. { name: 'color', type: 'vec3' },
  29055. { name: 'exposure', type: 'float' }
  29056. ]
  29057. } );
  29058. /**
  29059. * Reinhard tone mapping.
  29060. *
  29061. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  29062. *
  29063. * @tsl
  29064. * @function
  29065. * @param {Node<vec3>} color - The color that should be tone mapped.
  29066. * @param {Node<float>} exposure - The exposure.
  29067. * @return {Node<vec3>} The tone mapped color.
  29068. */
  29069. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  29070. color = color.mul( exposure );
  29071. return color.div( color.add( 1.0 ) ).clamp();
  29072. } ).setLayout( {
  29073. name: 'reinhardToneMapping',
  29074. type: 'vec3',
  29075. inputs: [
  29076. { name: 'color', type: 'vec3' },
  29077. { name: 'exposure', type: 'float' }
  29078. ]
  29079. } );
  29080. /**
  29081. * Cineon tone mapping.
  29082. *
  29083. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  29084. *
  29085. * @tsl
  29086. * @function
  29087. * @param {Node<vec3>} color - The color that should be tone mapped.
  29088. * @param {Node<float>} exposure - The exposure.
  29089. * @return {Node<vec3>} The tone mapped color.
  29090. */
  29091. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  29092. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  29093. color = color.mul( exposure );
  29094. color = color.sub( 0.004 ).max( 0.0 );
  29095. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  29096. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  29097. return a.div( b ).pow( 2.2 );
  29098. } ).setLayout( {
  29099. name: 'cineonToneMapping',
  29100. type: 'vec3',
  29101. inputs: [
  29102. { name: 'color', type: 'vec3' },
  29103. { name: 'exposure', type: 'float' }
  29104. ]
  29105. } );
  29106. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  29107. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  29108. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  29109. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  29110. return a.div( b );
  29111. } );
  29112. /**
  29113. * ACESFilmic tone mapping.
  29114. *
  29115. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  29116. *
  29117. * @tsl
  29118. * @function
  29119. * @param {Node<vec3>} color - The color that should be tone mapped.
  29120. * @param {Node<float>} exposure - The exposure.
  29121. * @return {Node<vec3>} The tone mapped color.
  29122. */
  29123. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  29124. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  29125. const ACESInputMat = mat3(
  29126. 0.59719, 0.35458, 0.04823,
  29127. 0.07600, 0.90834, 0.01566,
  29128. 0.02840, 0.13383, 0.83777
  29129. );
  29130. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  29131. const ACESOutputMat = mat3(
  29132. 1.60475, -0.53108, -0.07367,
  29133. -0.10208, 1.10813, -605e-5,
  29134. -327e-5, -0.07276, 1.07602
  29135. );
  29136. color = color.mul( exposure ).div( 0.6 );
  29137. color = ACESInputMat.mul( color );
  29138. // Apply RRT and ODT
  29139. color = RRTAndODTFit( color );
  29140. color = ACESOutputMat.mul( color );
  29141. // Clamp to [0, 1]
  29142. return color.clamp();
  29143. } ).setLayout( {
  29144. name: 'acesFilmicToneMapping',
  29145. type: 'vec3',
  29146. inputs: [
  29147. { name: 'color', type: 'vec3' },
  29148. { name: 'exposure', type: 'float' }
  29149. ]
  29150. } );
  29151. 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 ) );
  29152. 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 ) );
  29153. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  29154. const x = vec3( x_immutable ).toVar();
  29155. const x2 = vec3( x.mul( x ) ).toVar();
  29156. const x4 = vec3( x2.mul( x2 ) ).toVar();
  29157. 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 ) ) ) );
  29158. } );
  29159. /**
  29160. * AgX tone mapping.
  29161. *
  29162. * @tsl
  29163. * @function
  29164. * @param {Node<vec3>} color - The color that should be tone mapped.
  29165. * @param {Node<float>} exposure - The exposure.
  29166. * @return {Node<vec3>} The tone mapped color.
  29167. */
  29168. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  29169. const colortone = vec3( color ).toVar();
  29170. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  29171. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  29172. const AgxMinEv = float( -12.47393 );
  29173. const AgxMaxEv = float( 4.026069 );
  29174. colortone.mulAssign( exposure );
  29175. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  29176. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  29177. colortone.assign( max$1( colortone, 1e-10 ) );
  29178. colortone.assign( log2( colortone ) );
  29179. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  29180. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  29181. colortone.assign( agxDefaultContrastApprox( colortone ) );
  29182. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  29183. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  29184. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  29185. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  29186. return colortone;
  29187. } ).setLayout( {
  29188. name: 'agxToneMapping',
  29189. type: 'vec3',
  29190. inputs: [
  29191. { name: 'color', type: 'vec3' },
  29192. { name: 'exposure', type: 'float' }
  29193. ]
  29194. } );
  29195. /**
  29196. * Neutral tone mapping.
  29197. *
  29198. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  29199. *
  29200. * @tsl
  29201. * @function
  29202. * @param {Node<vec3>} color - The color that should be tone mapped.
  29203. * @param {Node<float>} exposure - The exposure.
  29204. * @return {Node<vec3>} The tone mapped color.
  29205. */
  29206. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  29207. const StartCompression = float( 0.8 - 0.04 );
  29208. const Desaturation = float( 0.15 );
  29209. color = color.mul( exposure );
  29210. const x = min$1( color.r, min$1( color.g, color.b ) );
  29211. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  29212. color.subAssign( offset );
  29213. const peak = max$1( color.r, max$1( color.g, color.b ) );
  29214. If( peak.lessThan( StartCompression ), () => {
  29215. return color;
  29216. } );
  29217. const d = sub( 1, StartCompression );
  29218. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  29219. color.mulAssign( newPeak.div( peak ) );
  29220. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  29221. return mix( color, vec3( newPeak ), g );
  29222. } ).setLayout( {
  29223. name: 'neutralToneMapping',
  29224. type: 'vec3',
  29225. inputs: [
  29226. { name: 'color', type: 'vec3' },
  29227. { name: 'exposure', type: 'float' }
  29228. ]
  29229. } );
  29230. /**
  29231. * This class represents native code sections. It is the base
  29232. * class for modules like {@link FunctionNode} which allows to implement
  29233. * functions with native shader languages.
  29234. *
  29235. * @augments Node
  29236. */
  29237. class CodeNode extends Node {
  29238. static get type() {
  29239. return 'CodeNode';
  29240. }
  29241. /**
  29242. * Constructs a new code node.
  29243. *
  29244. * @param {string} [code=''] - The native code.
  29245. * @param {Array<Node>} [includes=[]] - An array of includes.
  29246. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  29247. */
  29248. constructor( code = '', includes = [], language = '' ) {
  29249. super( 'code' );
  29250. /**
  29251. * This flag can be used for type testing.
  29252. *
  29253. * @type {boolean}
  29254. * @readonly
  29255. * @default true
  29256. */
  29257. this.isCodeNode = true;
  29258. /**
  29259. * This flag is used for global cache.
  29260. *
  29261. * @type {boolean}
  29262. * @default true
  29263. */
  29264. this.global = true;
  29265. /**
  29266. * The native code.
  29267. *
  29268. * @type {string}
  29269. * @default ''
  29270. */
  29271. this.code = code;
  29272. /**
  29273. * An array of includes
  29274. *
  29275. * @type {Array<Node>}
  29276. * @default []
  29277. */
  29278. this.includes = includes;
  29279. /**
  29280. * The used language.
  29281. *
  29282. * @type {('js'|'wgsl'|'glsl')}
  29283. * @default ''
  29284. */
  29285. this.language = language;
  29286. }
  29287. /**
  29288. * Sets the includes of this code node.
  29289. *
  29290. * @param {Array<Node>} includes - The includes to set.
  29291. * @return {CodeNode} A reference to this node.
  29292. */
  29293. setIncludes( includes ) {
  29294. this.includes = includes;
  29295. return this;
  29296. }
  29297. /**
  29298. * Returns the includes of this code node.
  29299. *
  29300. * @param {NodeBuilder} builder - The current node builder.
  29301. * @return {Array<Node>} The includes.
  29302. */
  29303. getIncludes( /*builder*/ ) {
  29304. return this.includes;
  29305. }
  29306. generate( builder ) {
  29307. const includes = this.getIncludes( builder );
  29308. for ( const include of includes ) {
  29309. include.build( builder );
  29310. }
  29311. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  29312. nodeCode.code = this.code;
  29313. return nodeCode.code;
  29314. }
  29315. serialize( data ) {
  29316. super.serialize( data );
  29317. data.code = this.code;
  29318. data.language = this.language;
  29319. }
  29320. deserialize( data ) {
  29321. super.deserialize( data );
  29322. this.code = data.code;
  29323. this.language = data.language;
  29324. }
  29325. }
  29326. /**
  29327. * TSL function for creating a code node.
  29328. *
  29329. * @tsl
  29330. * @function
  29331. * @param {string} [code] - The native code.
  29332. * @param {?Array<Node>} [includes=[]] - An array of includes.
  29333. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  29334. * @returns {CodeNode}
  29335. */
  29336. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  29337. /**
  29338. * TSL function for creating a JS code node.
  29339. *
  29340. * @tsl
  29341. * @function
  29342. * @param {string} src - The native code.
  29343. * @param {Array<Node>} includes - An array of includes.
  29344. * @returns {CodeNode}
  29345. */
  29346. const js = ( src, includes ) => code( src, includes, 'js' );
  29347. /**
  29348. * TSL function for creating a WGSL code node.
  29349. *
  29350. * @tsl
  29351. * @function
  29352. * @param {string} src - The native code.
  29353. * @param {Array<Node>} includes - An array of includes.
  29354. * @returns {CodeNode}
  29355. */
  29356. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  29357. /**
  29358. * TSL function for creating a GLSL code node.
  29359. *
  29360. * @tsl
  29361. * @function
  29362. * @param {string} src - The native code.
  29363. * @param {Array<Node>} includes - An array of includes.
  29364. * @returns {CodeNode}
  29365. */
  29366. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  29367. /**
  29368. * This class represents a native shader function. It can be used to implement
  29369. * certain aspects of a node material with native shader code. There are two predefined
  29370. * TSL functions for easier usage.
  29371. *
  29372. * - `wgslFn`: Creates a WGSL function node.
  29373. * - `glslFn`: Creates a GLSL function node.
  29374. *
  29375. * A basic example with one include looks like so:
  29376. *
  29377. * ```js
  29378. * const desaturateWGSLFn = wgslFn( `
  29379. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  29380. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  29381. * return vec3<f32>( dot( lum, color ) );
  29382. * }`
  29383. *);
  29384. * const someWGSLFn = wgslFn( `
  29385. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  29386. * return desaturate( color );
  29387. * }
  29388. * `, [ desaturateWGSLFn ] );
  29389. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  29390. *```
  29391. * @augments CodeNode
  29392. */
  29393. class FunctionNode extends CodeNode {
  29394. static get type() {
  29395. return 'FunctionNode';
  29396. }
  29397. /**
  29398. * Constructs a new function node.
  29399. *
  29400. * @param {string} [code=''] - The native code.
  29401. * @param {Array<Node>} [includes=[]] - An array of includes.
  29402. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  29403. */
  29404. constructor( code = '', includes = [], language = '' ) {
  29405. super( code, includes, language );
  29406. }
  29407. /**
  29408. * Returns the type of this function node.
  29409. *
  29410. * @param {NodeBuilder} builder - The current node builder.
  29411. * @return {string} The type.
  29412. */
  29413. generateNodeType( builder ) {
  29414. return this.getNodeFunction( builder ).type;
  29415. }
  29416. /**
  29417. * Returns the type of a member of this function node.
  29418. *
  29419. * @param {NodeBuilder} builder - The current node builder.
  29420. * @param {string} name - The name of the member.
  29421. * @return {string} The type of the member.
  29422. */
  29423. getMemberType( builder, name ) {
  29424. const type = this.getNodeType( builder );
  29425. const structType = builder.getStructTypeNode( type );
  29426. return structType.getMemberType( builder, name );
  29427. }
  29428. /**
  29429. * Returns the inputs of this function node.
  29430. *
  29431. * @param {NodeBuilder} builder - The current node builder.
  29432. * @return {Array<NodeFunctionInput>} The inputs.
  29433. */
  29434. getInputs( builder ) {
  29435. return this.getNodeFunction( builder ).inputs;
  29436. }
  29437. /**
  29438. * Returns the node function for this function node.
  29439. *
  29440. * @param {NodeBuilder} builder - The current node builder.
  29441. * @return {NodeFunction} The node function.
  29442. */
  29443. getNodeFunction( builder ) {
  29444. const nodeData = builder.getDataFromNode( this );
  29445. let nodeFunction = nodeData.nodeFunction;
  29446. if ( nodeFunction === undefined ) {
  29447. nodeFunction = builder.parser.parseFunction( this.code );
  29448. nodeData.nodeFunction = nodeFunction;
  29449. }
  29450. return nodeFunction;
  29451. }
  29452. generate( builder, output ) {
  29453. super.generate( builder );
  29454. const nodeFunction = this.getNodeFunction( builder );
  29455. const name = nodeFunction.name;
  29456. const type = nodeFunction.type;
  29457. const nodeCode = builder.getCodeFromNode( this, type );
  29458. if ( name !== '' ) {
  29459. // use a custom property name
  29460. nodeCode.name = name;
  29461. }
  29462. const propertyName = builder.getPropertyName( nodeCode );
  29463. const code = this.getNodeFunction( builder ).getCode( propertyName );
  29464. nodeCode.code = code + '\n';
  29465. if ( output === 'property' ) {
  29466. return propertyName;
  29467. } else {
  29468. return builder.format( `${ propertyName }()`, type, output );
  29469. }
  29470. }
  29471. }
  29472. const nativeFn = ( code, includes = [], language = '' ) => {
  29473. for ( let i = 0; i < includes.length; i ++ ) {
  29474. const include = includes[ i ];
  29475. // TSL Function: glslFn, wgslFn
  29476. if ( typeof include === 'function' ) {
  29477. includes[ i ] = include.functionNode;
  29478. }
  29479. }
  29480. const functionNode = new FunctionNode( code, includes, language );
  29481. const fn = ( ...params ) => functionNode.call( ...params );
  29482. fn.functionNode = functionNode;
  29483. return fn;
  29484. };
  29485. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  29486. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  29487. /**
  29488. * Returns a node that represents the `z` coordinate in view space
  29489. * for the current fragment. It's a different representation of the
  29490. * default depth value.
  29491. *
  29492. * This value can be part of a computation that defines how the fog
  29493. * density increases when moving away from the camera.
  29494. *
  29495. * @param {NodeBuilder} builder - The current node builder.
  29496. * @return {Node} The viewZ node.
  29497. */
  29498. function getViewZNode( builder ) {
  29499. let viewZ;
  29500. const getViewZ = builder.context.getViewZ;
  29501. if ( getViewZ !== undefined ) {
  29502. viewZ = getViewZ( this );
  29503. }
  29504. return ( viewZ || positionView.z ).negate();
  29505. }
  29506. /**
  29507. * Constructs a new range factor node.
  29508. *
  29509. * @tsl
  29510. * @function
  29511. * @param {Node} near - Defines the near value.
  29512. * @param {Node} far - Defines the far value.
  29513. */
  29514. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  29515. const viewZ = getViewZNode( builder );
  29516. return smoothstep( near, far, viewZ );
  29517. } );
  29518. /**
  29519. * Represents an exponential squared fog. This type of fog gives
  29520. * a clear view near the camera and a faster than exponentially
  29521. * densening fog farther from the camera.
  29522. *
  29523. * @tsl
  29524. * @function
  29525. * @param {Node} density - Defines the fog density.
  29526. */
  29527. const densityFogFactor = Fn( ( [ density ], builder ) => {
  29528. const viewZ = getViewZNode( builder );
  29529. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  29530. } );
  29531. /**
  29532. * Constructs a new height fog factor node. This fog factor requires a Y-up coordinate system.
  29533. *
  29534. * @tsl
  29535. * @function
  29536. * @param {Node} density - Defines the fog density.
  29537. * @param {Node} height - The height threshold in world space. Everything below this y-coordinate is affected by fog.
  29538. */
  29539. const exponentialHeightFogFactor = Fn( ( [ density, height ], builder ) => {
  29540. const viewZ = getViewZNode( builder );
  29541. const distance = height.sub( positionWorld.y ).max( 0 ).toConst();
  29542. const m = distance.mul( viewZ ).toConst();
  29543. return density.mul( density, m, m ).negate().exp().oneMinus();
  29544. } );
  29545. /**
  29546. * This class can be used to configure a fog for the scene.
  29547. * Nodes of this type are assigned to `Scene.fogNode`.
  29548. *
  29549. * @tsl
  29550. * @function
  29551. * @param {Node} color - Defines the color of the fog.
  29552. * @param {Node} factor - Defines how the fog is factored in the scene.
  29553. */
  29554. const fog = Fn( ( [ color, factor ] ) => {
  29555. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  29556. } );
  29557. let min = null;
  29558. let max = null;
  29559. /**
  29560. * `RangeNode` generates random instanced attribute data in a defined range.
  29561. * An exemplary use case for this utility node is to generate random per-instance
  29562. * colors:
  29563. * ```js
  29564. * const material = new MeshBasicNodeMaterial();
  29565. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  29566. * const mesh = new InstancedMesh( geometry, material, count );
  29567. * ```
  29568. * @augments Node
  29569. */
  29570. class RangeNode extends Node {
  29571. static get type() {
  29572. return 'RangeNode';
  29573. }
  29574. /**
  29575. * Constructs a new range node.
  29576. *
  29577. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  29578. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  29579. */
  29580. constructor( minNode = float(), maxNode = float() ) {
  29581. super();
  29582. /**
  29583. * A node defining the lower bound of the range.
  29584. *
  29585. * @type {Node<any>}
  29586. * @default float()
  29587. */
  29588. this.minNode = minNode;
  29589. /**
  29590. * A node defining the upper bound of the range.
  29591. *
  29592. * @type {Node<any>}
  29593. * @default float()
  29594. */
  29595. this.maxNode = maxNode;
  29596. }
  29597. /**
  29598. * Returns the vector length which is computed based on the range definition.
  29599. *
  29600. * @param {NodeBuilder} builder - The current node builder.
  29601. * @return {number} The vector length.
  29602. */
  29603. getVectorLength( builder ) {
  29604. const minNode = this.getConstNode( this.minNode );
  29605. const maxNode = this.getConstNode( this.maxNode );
  29606. const minLength = builder.getTypeLength( getValueType( minNode.value ) );
  29607. const maxLength = builder.getTypeLength( getValueType( maxNode.value ) );
  29608. return minLength > maxLength ? minLength : maxLength;
  29609. }
  29610. /**
  29611. * This method is overwritten since the node type is inferred from range definition.
  29612. *
  29613. * @param {NodeBuilder} builder - The current node builder.
  29614. * @return {string} The node type.
  29615. */
  29616. generateNodeType( builder ) {
  29617. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  29618. }
  29619. /**
  29620. * Returns a constant node from the given node by traversing it.
  29621. *
  29622. * @param {Node} node - The node to traverse.
  29623. * @returns {Node} The constant node, if found.
  29624. */
  29625. getConstNode( node ) {
  29626. let output = null;
  29627. node.traverse( n => {
  29628. if ( n.isConstNode === true ) {
  29629. output = n;
  29630. }
  29631. } );
  29632. if ( output === null ) {
  29633. throw new NodeError( 'THREE.TSL: No "ConstNode" found in node graph.', this.stackTrace );
  29634. }
  29635. return output;
  29636. }
  29637. setup( builder ) {
  29638. const object = builder.object;
  29639. let output = null;
  29640. if ( object.count > 1 ) {
  29641. const minNode = this.getConstNode( this.minNode );
  29642. const maxNode = this.getConstNode( this.maxNode );
  29643. const minValue = minNode.value;
  29644. const maxValue = maxNode.value;
  29645. const minLength = builder.getTypeLength( getValueType( minValue ) );
  29646. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  29647. min = min || new Vector4();
  29648. max = max || new Vector4();
  29649. min.setScalar( 0 );
  29650. max.setScalar( 0 );
  29651. if ( minLength === 1 ) min.setScalar( minValue );
  29652. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  29653. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  29654. if ( maxLength === 1 ) max.setScalar( maxValue );
  29655. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  29656. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  29657. const stride = 4;
  29658. const length = stride * object.count;
  29659. const array = new Float32Array( length );
  29660. for ( let i = 0; i < length; i ++ ) {
  29661. const index = i % stride;
  29662. const minElementValue = min.getComponent( index );
  29663. const maxElementValue = max.getComponent( index );
  29664. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  29665. }
  29666. const nodeType = this.getNodeType( builder );
  29667. const uniformBufferSize = object.count * 4 * 4; // count * 4 components * 4 bytes (float)
  29668. if ( uniformBufferSize <= builder.getUniformBufferLimit() ) {
  29669. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  29670. } else {
  29671. // TODO: Improve anonymous buffer attribute creation removing this part
  29672. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  29673. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  29674. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  29675. }
  29676. } else {
  29677. output = float( 0 );
  29678. }
  29679. return output;
  29680. }
  29681. }
  29682. /**
  29683. * TSL function for creating a range node.
  29684. *
  29685. * @tsl
  29686. * @function
  29687. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  29688. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  29689. * @returns {RangeNode}
  29690. */
  29691. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  29692. /**
  29693. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  29694. * about the currently running dispatch and/or the device it is running on.
  29695. *
  29696. * This node can only be used with a WebGPU backend.
  29697. *
  29698. * @augments Node
  29699. */
  29700. class ComputeBuiltinNode extends Node {
  29701. static get type() {
  29702. return 'ComputeBuiltinNode';
  29703. }
  29704. /**
  29705. * Constructs a new compute builtin node.
  29706. *
  29707. * @param {string} builtinName - The built-in name.
  29708. * @param {string} nodeType - The node type.
  29709. */
  29710. constructor( builtinName, nodeType ) {
  29711. super( nodeType );
  29712. /**
  29713. * The built-in name.
  29714. *
  29715. * @private
  29716. * @type {string}
  29717. */
  29718. this._builtinName = builtinName;
  29719. }
  29720. /**
  29721. * This method is overwritten since hash is derived from the built-in name.
  29722. *
  29723. * @param {NodeBuilder} builder - The current node builder.
  29724. * @return {string} The hash.
  29725. */
  29726. getHash( builder ) {
  29727. return this.getBuiltinName( builder );
  29728. }
  29729. /**
  29730. * This method is overwritten since the node type is simply derived from `nodeType`..
  29731. *
  29732. * @param {NodeBuilder} builder - The current node builder.
  29733. * @return {string} The node type.
  29734. */
  29735. generateNodeType( /*builder*/ ) {
  29736. return this.nodeType;
  29737. }
  29738. /**
  29739. * Sets the builtin name.
  29740. *
  29741. * @param {string} builtinName - The built-in name.
  29742. * @return {ComputeBuiltinNode} A reference to this node.
  29743. */
  29744. setBuiltinName( builtinName ) {
  29745. this._builtinName = builtinName;
  29746. return this;
  29747. }
  29748. /**
  29749. * Returns the builtin name.
  29750. *
  29751. * @param {NodeBuilder} builder - The current node builder.
  29752. * @return {string} The builtin name.
  29753. */
  29754. getBuiltinName( /*builder*/ ) {
  29755. return this._builtinName;
  29756. }
  29757. /**
  29758. * Whether the current node builder has the builtin or not.
  29759. *
  29760. * @param {NodeBuilder} builder - The current node builder.
  29761. * @return {boolean} Whether the builder has the builtin or not.
  29762. */
  29763. hasBuiltin( builder ) {
  29764. return builder.hasBuiltin( this._builtinName );
  29765. }
  29766. generate( builder, output ) {
  29767. const builtinName = this.getBuiltinName( builder );
  29768. const nodeType = this.getNodeType( builder );
  29769. if ( builder.shaderStage === 'compute' ) {
  29770. return builder.format( builtinName, nodeType, output );
  29771. } else {
  29772. warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  29773. return builder.generateConst( nodeType );
  29774. }
  29775. }
  29776. serialize( data ) {
  29777. super.serialize( data );
  29778. data.global = this.global;
  29779. data._builtinName = this._builtinName;
  29780. }
  29781. deserialize( data ) {
  29782. super.deserialize( data );
  29783. this.global = data.global;
  29784. this._builtinName = data._builtinName;
  29785. }
  29786. }
  29787. /**
  29788. * TSL function for creating a compute builtin node.
  29789. *
  29790. * @tsl
  29791. * @function
  29792. * @param {string} name - The built-in name.
  29793. * @param {string} nodeType - The node type.
  29794. * @returns {ComputeBuiltinNode}
  29795. */
  29796. const computeBuiltin = ( name, nodeType ) => new ComputeBuiltinNode( name, nodeType );
  29797. /**
  29798. * Represents the number of workgroups dispatched by the compute shader.
  29799. * ```js
  29800. * // Run 512 invocations/threads with a workgroup size of 128.
  29801. * const computeFn = Fn(() => {
  29802. *
  29803. * // numWorkgroups.x = 4
  29804. * storageBuffer.element(0).assign(numWorkgroups.x)
  29805. *
  29806. * })().compute(512, [128]);
  29807. *
  29808. * // Run 512 invocations/threads with the default workgroup size of 64.
  29809. * const computeFn = Fn(() => {
  29810. *
  29811. * // numWorkgroups.x = 8
  29812. * storageBuffer.element(0).assign(numWorkgroups.x)
  29813. *
  29814. * })().compute(512);
  29815. * ```
  29816. *
  29817. * @tsl
  29818. * @type {ComputeBuiltinNode<uvec3>}
  29819. */
  29820. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  29821. /**
  29822. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  29823. * ```js
  29824. * // Execute 12 compute threads with a workgroup size of 3.
  29825. * const computeFn = Fn( () => {
  29826. *
  29827. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  29828. *
  29829. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  29830. *
  29831. * } ).Else( () => {
  29832. *
  29833. * storageBuffer.element( instanceIndex ).assign( 0 );
  29834. *
  29835. * } );
  29836. *
  29837. * } )().compute( 12, [ 3 ] );
  29838. *
  29839. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  29840. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  29841. * ```
  29842. *
  29843. * @tsl
  29844. * @type {ComputeBuiltinNode<uvec3>}
  29845. */
  29846. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  29847. /**
  29848. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  29849. *
  29850. * @tsl
  29851. * @type {ComputeBuiltinNode<uvec3>}
  29852. */
  29853. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  29854. /**
  29855. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  29856. *
  29857. * @tsl
  29858. * @type {ComputeBuiltinNode<uvec3>}
  29859. */
  29860. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  29861. /**
  29862. * A device dependent variable that exposes the size of the current invocation's subgroup.
  29863. *
  29864. * @tsl
  29865. * @type {ComputeBuiltinNode<uint>}
  29866. */
  29867. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  29868. /**
  29869. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  29870. *
  29871. * This node can only be used with a WebGPU backend.
  29872. *
  29873. * @augments Node
  29874. */
  29875. class BarrierNode extends Node {
  29876. /**
  29877. * Constructs a new barrier node.
  29878. *
  29879. * @param {string} scope - The scope defines the behavior of the node.
  29880. */
  29881. constructor( scope ) {
  29882. super();
  29883. this.scope = scope;
  29884. this.isBarrierNode = true;
  29885. }
  29886. setup( builder ) {
  29887. builder.allowEarlyReturns = false;
  29888. builder.allowGlobalVariables = false;
  29889. }
  29890. generate( builder ) {
  29891. const { scope } = this;
  29892. const { renderer } = builder;
  29893. if ( renderer.backend.isWebGLBackend === true ) {
  29894. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  29895. } else {
  29896. builder.addLineFlowCode( `${scope}Barrier()`, this );
  29897. }
  29898. }
  29899. }
  29900. /**
  29901. * TSL function for creating a barrier node.
  29902. *
  29903. * @tsl
  29904. * @function
  29905. * @param {string} scope - The scope defines the behavior of the node..
  29906. * @returns {BarrierNode}
  29907. */
  29908. const barrier = nodeProxy( BarrierNode );
  29909. /**
  29910. * TSL function for creating a workgroup barrier. All compute shader
  29911. * invocations must wait for each invocation within a workgroup to
  29912. * complete before the barrier can be surpassed.
  29913. *
  29914. * @tsl
  29915. * @function
  29916. * @returns {BarrierNode}
  29917. */
  29918. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  29919. /**
  29920. * TSL function for creating a storage barrier. All invocations must
  29921. * wait for each access to variables within the 'storage' address space
  29922. * to complete before the barrier can be passed.
  29923. *
  29924. * @tsl
  29925. * @function
  29926. * @returns {BarrierNode}
  29927. */
  29928. const storageBarrier = () => barrier( 'storage' ).toStack();
  29929. /**
  29930. * TSL function for creating a texture barrier. All invocations must
  29931. * wait for each access to variables within the 'texture' address space
  29932. * to complete before the barrier can be passed.
  29933. *
  29934. * @tsl
  29935. * @function
  29936. * @returns {BarrierNode}
  29937. */
  29938. const textureBarrier = () => barrier( 'texture' ).toStack();
  29939. /**
  29940. * Represents an element of a 'workgroup' scoped buffer.
  29941. *
  29942. * @augments ArrayElementNode
  29943. */
  29944. class WorkgroupInfoElementNode extends ArrayElementNode {
  29945. /**
  29946. * Constructs a new workgroup info element node.
  29947. *
  29948. * @param {Node} workgroupInfoNode - The workgroup info node.
  29949. * @param {Node} indexNode - The index node that defines the element access.
  29950. */
  29951. constructor( workgroupInfoNode, indexNode ) {
  29952. super( workgroupInfoNode, indexNode );
  29953. /**
  29954. * This flag can be used for type testing.
  29955. *
  29956. * @type {boolean}
  29957. * @readonly
  29958. * @default true
  29959. */
  29960. this.isWorkgroupInfoElementNode = true;
  29961. }
  29962. generate( builder, output ) {
  29963. let snippet;
  29964. const isAssignContext = builder.context.assign;
  29965. snippet = super.generate( builder );
  29966. if ( isAssignContext !== true ) {
  29967. const type = this.getNodeType( builder );
  29968. snippet = builder.format( snippet, type, output );
  29969. }
  29970. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  29971. return snippet;
  29972. }
  29973. }
  29974. /**
  29975. * A node allowing the user to create a 'workgroup' scoped buffer within the
  29976. * context of a compute shader. Typically, workgroup scoped buffers are
  29977. * created to hold data that is transferred from a global storage scope into
  29978. * a local workgroup scope. For invocations within a workgroup, data
  29979. * access speeds on 'workgroup' scoped buffers can be significantly faster
  29980. * than similar access operations on globally accessible storage buffers.
  29981. *
  29982. * This node can only be used with a WebGPU backend.
  29983. *
  29984. * @augments Node
  29985. */
  29986. class WorkgroupInfoNode extends Node {
  29987. /**
  29988. * Constructs a new buffer scoped to type scope.
  29989. *
  29990. * @param {string} scope - TODO.
  29991. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  29992. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  29993. */
  29994. constructor( scope, bufferType, bufferCount = 0 ) {
  29995. super( bufferType );
  29996. /**
  29997. * The buffer type.
  29998. *
  29999. * @type {string}
  30000. */
  30001. this.bufferType = bufferType;
  30002. /**
  30003. * The buffer count.
  30004. *
  30005. * @type {number}
  30006. * @default 0
  30007. */
  30008. this.bufferCount = bufferCount;
  30009. /**
  30010. * This flag can be used for type testing.
  30011. *
  30012. * @type {boolean}
  30013. * @readonly
  30014. * @default true
  30015. */
  30016. this.isWorkgroupInfoNode = true;
  30017. /**
  30018. * The data type of the array buffer.
  30019. *
  30020. * @type {string}
  30021. */
  30022. this.elementType = bufferType;
  30023. /**
  30024. * TODO.
  30025. *
  30026. * @type {string}
  30027. */
  30028. this.scope = scope;
  30029. /**
  30030. * The name of the workgroup scoped buffer.
  30031. *
  30032. * @type {string}
  30033. * @default ''
  30034. */
  30035. this.name = '';
  30036. }
  30037. /**
  30038. * Sets the name of this node.
  30039. *
  30040. * @param {string} name - The name to set.
  30041. * @return {WorkgroupInfoNode} A reference to this node.
  30042. */
  30043. setName( name ) {
  30044. this.name = name;
  30045. return this;
  30046. }
  30047. /**
  30048. * Sets the name/label of this node.
  30049. *
  30050. * @deprecated
  30051. * @param {string} name - The name to set.
  30052. * @return {WorkgroupInfoNode} A reference to this node.
  30053. */
  30054. label( name ) {
  30055. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.', new StackTrace() ); // @deprecated r179
  30056. return this.setName( name );
  30057. }
  30058. /**
  30059. * Sets the scope of this node.
  30060. *
  30061. * @param {string} scope - The scope to set.
  30062. * @return {WorkgroupInfoNode} A reference to this node.
  30063. */
  30064. setScope( scope ) {
  30065. this.scope = scope;
  30066. return this;
  30067. }
  30068. /**
  30069. * The data type of the array buffer.
  30070. *
  30071. * @return {string} The element type.
  30072. */
  30073. getElementType() {
  30074. return this.elementType;
  30075. }
  30076. /**
  30077. * Overwrites the default implementation since the input type
  30078. * is inferred from the scope.
  30079. *
  30080. * @param {NodeBuilder} builder - The current node builder.
  30081. * @return {string} The input type.
  30082. */
  30083. getInputType( /*builder*/ ) {
  30084. return `${this.scope}Array`;
  30085. }
  30086. /**
  30087. * This method can be used to access elements via an index node.
  30088. *
  30089. * @param {IndexNode} indexNode - indexNode.
  30090. * @return {WorkgroupInfoElementNode} A reference to an element.
  30091. */
  30092. element( indexNode ) {
  30093. return new WorkgroupInfoElementNode( this, indexNode );
  30094. }
  30095. generate( builder ) {
  30096. const name = ( this.name !== '' ) ? this.name : `${this.scope}Array_${this.id}`;
  30097. return builder.getScopedArray( name, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  30098. }
  30099. }
  30100. /**
  30101. * TSL function for creating a workgroup info node.
  30102. * Creates a new 'workgroup' scoped array buffer.
  30103. *
  30104. * @tsl
  30105. * @function
  30106. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  30107. * @param {number} [count=0] - The number of elements in the buffer.
  30108. * @returns {WorkgroupInfoNode}
  30109. */
  30110. const workgroupArray = ( type, count ) => new WorkgroupInfoNode( 'Workgroup', type, count );
  30111. /**
  30112. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  30113. * within a shader. In an atomic function, any modification to an atomic variable will
  30114. * occur as an indivisible step with a defined order relative to other modifications.
  30115. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  30116. * atomic operations will not interfere with each other.
  30117. *
  30118. * This node can only be used with a WebGPU backend.
  30119. *
  30120. * @augments Node
  30121. */
  30122. class AtomicFunctionNode extends Node {
  30123. static get type() {
  30124. return 'AtomicFunctionNode';
  30125. }
  30126. /**
  30127. * Constructs a new atomic function node.
  30128. *
  30129. * @param {string} method - The signature of the atomic function to construct.
  30130. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30131. * @param {Node} valueNode - The value that mutates the atomic variable.
  30132. */
  30133. constructor( method, pointerNode, valueNode ) {
  30134. super( 'uint' );
  30135. /**
  30136. * The signature of the atomic function to construct.
  30137. *
  30138. * @type {string}
  30139. */
  30140. this.method = method;
  30141. /**
  30142. * An atomic variable or element of an atomic buffer.
  30143. *
  30144. * @type {Node}
  30145. */
  30146. this.pointerNode = pointerNode;
  30147. /**
  30148. * A value that modifies the atomic variable.
  30149. *
  30150. * @type {Node}
  30151. */
  30152. this.valueNode = valueNode;
  30153. /**
  30154. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  30155. *
  30156. * @type {boolean}
  30157. * @default true
  30158. */
  30159. this.parents = true;
  30160. }
  30161. /**
  30162. * Overwrites the default implementation to return the type of
  30163. * the pointer node.
  30164. *
  30165. * @param {NodeBuilder} builder - The current node builder.
  30166. * @return {string} The input type.
  30167. */
  30168. getInputType( builder ) {
  30169. return this.pointerNode.getNodeType( builder );
  30170. }
  30171. /**
  30172. * Overwritten since the node type is inferred from the input type.
  30173. *
  30174. * @param {NodeBuilder} builder - The current node builder.
  30175. * @return {string} The node type.
  30176. */
  30177. generateNodeType( builder ) {
  30178. return this.getInputType( builder );
  30179. }
  30180. generate( builder ) {
  30181. const properties = builder.getNodeProperties( this );
  30182. const parents = properties.parents;
  30183. const method = this.method;
  30184. const type = this.getNodeType( builder );
  30185. const inputType = this.getInputType( builder );
  30186. const a = this.pointerNode;
  30187. const b = this.valueNode;
  30188. const params = [];
  30189. params.push( `&${ a.build( builder, inputType ) }` );
  30190. if ( b !== null ) {
  30191. params.push( b.build( builder, inputType ) );
  30192. }
  30193. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  30194. const isVoid = parents ? ( parents.length === 1 && parents[ 0 ].isStackNode === true ) : false;
  30195. if ( isVoid ) {
  30196. builder.addLineFlowCode( methodSnippet, this );
  30197. } else {
  30198. if ( properties.constNode === undefined ) {
  30199. properties.constNode = expression( methodSnippet, type ).toConst();
  30200. }
  30201. return properties.constNode.build( builder );
  30202. }
  30203. }
  30204. }
  30205. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  30206. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  30207. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  30208. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  30209. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  30210. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  30211. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  30212. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  30213. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  30214. /**
  30215. * TSL function for creating an atomic function node.
  30216. *
  30217. * @tsl
  30218. * @function
  30219. * @param {string} method - The signature of the atomic function to construct.
  30220. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30221. * @param {Node} valueNode - The value that mutates the atomic variable.
  30222. * @returns {AtomicFunctionNode}
  30223. */
  30224. const atomicNode = nodeProxy( AtomicFunctionNode );
  30225. /**
  30226. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  30227. *
  30228. * @tsl
  30229. * @function
  30230. * @param {string} method - The signature of the atomic function to construct.
  30231. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30232. * @param {Node} valueNode - The value that mutates the atomic variable.
  30233. * @returns {AtomicFunctionNode}
  30234. */
  30235. const atomicFunc = ( method, pointerNode, valueNode ) => {
  30236. return atomicNode( method, pointerNode, valueNode ).toStack();
  30237. };
  30238. /**
  30239. * Loads the value stored in the atomic variable.
  30240. *
  30241. * @tsl
  30242. * @function
  30243. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30244. * @returns {AtomicFunctionNode}
  30245. */
  30246. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  30247. /**
  30248. * Stores a value in the atomic variable.
  30249. *
  30250. * @tsl
  30251. * @function
  30252. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30253. * @param {Node} valueNode - The value that mutates the atomic variable.
  30254. * @returns {AtomicFunctionNode}
  30255. */
  30256. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  30257. /**
  30258. * Increments the value stored in the atomic variable.
  30259. *
  30260. * @tsl
  30261. * @function
  30262. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30263. * @param {Node} valueNode - The value that mutates the atomic variable.
  30264. * @returns {AtomicFunctionNode}
  30265. */
  30266. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  30267. /**
  30268. * Decrements the value stored in the atomic variable.
  30269. *
  30270. * @tsl
  30271. * @function
  30272. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30273. * @param {Node} valueNode - The value that mutates the atomic variable.
  30274. * @returns {AtomicFunctionNode}
  30275. */
  30276. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  30277. /**
  30278. * Stores in an atomic variable the maximum between its current value and a parameter.
  30279. *
  30280. * @tsl
  30281. * @function
  30282. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30283. * @param {Node} valueNode - The value that mutates the atomic variable.
  30284. * @returns {AtomicFunctionNode}
  30285. */
  30286. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  30287. /**
  30288. * Stores in an atomic variable the minimum between its current value and a parameter.
  30289. *
  30290. * @tsl
  30291. * @function
  30292. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30293. * @param {Node} valueNode - The value that mutates the atomic variable.
  30294. * @returns {AtomicFunctionNode}
  30295. */
  30296. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  30297. /**
  30298. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  30299. *
  30300. * @tsl
  30301. * @function
  30302. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30303. * @param {Node} valueNode - The value that mutates the atomic variable.
  30304. * @returns {AtomicFunctionNode}
  30305. */
  30306. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  30307. /**
  30308. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  30309. *
  30310. * @tsl
  30311. * @function
  30312. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30313. * @param {Node} valueNode - The value that mutates the atomic variable.
  30314. * @returns {AtomicFunctionNode}
  30315. */
  30316. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  30317. /**
  30318. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  30319. *
  30320. * @tsl
  30321. * @function
  30322. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30323. * @param {Node} valueNode - The value that mutates the atomic variable.
  30324. * @returns {AtomicFunctionNode}
  30325. */
  30326. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  30327. /**
  30328. * This class represents a set of built in WGSL shader functions that sync
  30329. * synchronously execute an operation across a subgroup, or 'warp', of compute
  30330. * or fragment shader invocations within a workgroup. Typically, these functions
  30331. * will synchronously execute an operation using data from all active invocations
  30332. * within the subgroup, then broadcast that result to all active invocations. In
  30333. * other graphics APIs, subgroup functions are also referred to as wave intrinsics
  30334. * (DirectX/HLSL) or warp intrinsics (CUDA).
  30335. *
  30336. * @augments TempNode
  30337. */
  30338. class SubgroupFunctionNode extends TempNode {
  30339. static get type() {
  30340. return 'SubgroupFunctionNode';
  30341. }
  30342. /**
  30343. * Constructs a new function node.
  30344. *
  30345. * @param {string} method - The subgroup/wave intrinsic method to construct.
  30346. * @param {Node} [aNode=null] - The method's first argument.
  30347. * @param {Node} [bNode=null] - The method's second argument.
  30348. */
  30349. constructor( method, aNode = null, bNode = null ) {
  30350. super();
  30351. /**
  30352. * The subgroup/wave intrinsic method to construct.
  30353. *
  30354. * @type {string}
  30355. */
  30356. this.method = method;
  30357. /**
  30358. * The method's first argument.
  30359. *
  30360. * @type {Node}
  30361. */
  30362. this.aNode = aNode;
  30363. /**
  30364. * The method's second argument.
  30365. *
  30366. * @type {Node}
  30367. */
  30368. this.bNode = bNode;
  30369. }
  30370. getInputType( builder ) {
  30371. const aType = this.aNode ? this.aNode.getNodeType( builder ) : null;
  30372. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  30373. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  30374. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  30375. if ( aLen > bLen ) {
  30376. return aType;
  30377. } else {
  30378. return bType;
  30379. }
  30380. }
  30381. generateNodeType( builder ) {
  30382. const method = this.method;
  30383. if ( method === SubgroupFunctionNode.SUBGROUP_ELECT ) {
  30384. return 'bool';
  30385. } else if ( method === SubgroupFunctionNode.SUBGROUP_BALLOT ) {
  30386. return 'uvec4';
  30387. } else {
  30388. return this.getInputType( builder );
  30389. }
  30390. }
  30391. generate( builder, output ) {
  30392. const method = this.method;
  30393. const type = this.getNodeType( builder );
  30394. const inputType = this.getInputType( builder );
  30395. const a = this.aNode;
  30396. const b = this.bNode;
  30397. const params = [];
  30398. if (
  30399. method === SubgroupFunctionNode.SUBGROUP_BROADCAST ||
  30400. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE ||
  30401. method === SubgroupFunctionNode.QUAD_BROADCAST
  30402. ) {
  30403. const bType = b.getNodeType( builder );
  30404. params.push(
  30405. a.build( builder, type ),
  30406. b.build( builder, bType === 'float' ? 'int' : type )
  30407. );
  30408. } else if (
  30409. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ||
  30410. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ||
  30411. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP
  30412. ) {
  30413. params.push(
  30414. a.build( builder, type ),
  30415. b.build( builder, 'uint' )
  30416. );
  30417. } else {
  30418. if ( a !== null ) params.push( a.build( builder, inputType ) );
  30419. if ( b !== null ) params.push( b.build( builder, inputType ) );
  30420. }
  30421. const paramsString = params.length === 0 ? '()' : `( ${params.join( ', ' )} )`;
  30422. return builder.format( `${ builder.getMethod( method, type ) }${paramsString}`, type, output );
  30423. }
  30424. serialize( data ) {
  30425. super.serialize( data );
  30426. data.method = this.method;
  30427. }
  30428. deserialize( data ) {
  30429. super.deserialize( data );
  30430. this.method = data.method;
  30431. }
  30432. }
  30433. // 0 inputs
  30434. SubgroupFunctionNode.SUBGROUP_ELECT = 'subgroupElect';
  30435. // 1 input
  30436. SubgroupFunctionNode.SUBGROUP_BALLOT = 'subgroupBallot';
  30437. SubgroupFunctionNode.SUBGROUP_ADD = 'subgroupAdd';
  30438. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD = 'subgroupInclusiveAdd';
  30439. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND = 'subgroupExclusiveAdd';
  30440. SubgroupFunctionNode.SUBGROUP_MUL = 'subgroupMul';
  30441. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL = 'subgroupInclusiveMul';
  30442. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL = 'subgroupExclusiveMul';
  30443. SubgroupFunctionNode.SUBGROUP_AND = 'subgroupAnd';
  30444. SubgroupFunctionNode.SUBGROUP_OR = 'subgroupOr';
  30445. SubgroupFunctionNode.SUBGROUP_XOR = 'subgroupXor';
  30446. SubgroupFunctionNode.SUBGROUP_MIN = 'subgroupMin';
  30447. SubgroupFunctionNode.SUBGROUP_MAX = 'subgroupMax';
  30448. SubgroupFunctionNode.SUBGROUP_ALL = 'subgroupAll';
  30449. SubgroupFunctionNode.SUBGROUP_ANY = 'subgroupAny';
  30450. SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST = 'subgroupBroadcastFirst';
  30451. SubgroupFunctionNode.QUAD_SWAP_X = 'quadSwapX';
  30452. SubgroupFunctionNode.QUAD_SWAP_Y = 'quadSwapY';
  30453. SubgroupFunctionNode.QUAD_SWAP_DIAGONAL = 'quadSwapDiagonal';
  30454. // 2 inputs
  30455. SubgroupFunctionNode.SUBGROUP_BROADCAST = 'subgroupBroadcast';
  30456. SubgroupFunctionNode.SUBGROUP_SHUFFLE = 'subgroupShuffle';
  30457. SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR = 'subgroupShuffleXor';
  30458. SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP = 'subgroupShuffleUp';
  30459. SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN = 'subgroupShuffleDown';
  30460. SubgroupFunctionNode.QUAD_BROADCAST = 'quadBroadcast';
  30461. /**
  30462. * Returns true if this invocation has the lowest subgroup_invocation_id
  30463. * among active invocations in the subgroup.
  30464. *
  30465. * @tsl
  30466. * @method
  30467. * @return {bool} The result of the computation.
  30468. */
  30469. const subgroupElect = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ELECT ).setParameterLength( 0 );
  30470. /**
  30471. * Returns a set of bitfields where the bit corresponding to subgroup_invocation_id
  30472. * is 1 if pred is true for that active invocation and 0 otherwise.
  30473. *
  30474. * @tsl
  30475. * @method
  30476. * @param {bool} pred - A boolean that sets the bit corresponding to the invocations subgroup invocation id.
  30477. * @return {vec4<u32>}- A bitfield corresponding to the pred value of each subgroup invocation.
  30478. */
  30479. const subgroupBallot = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BALLOT ).setParameterLength( 1 );
  30480. /**
  30481. * A reduction that adds e among all active invocations and returns that result.
  30482. *
  30483. * @tsl
  30484. * @method
  30485. * @param {number} e - The value provided to the reduction by the current invocation.
  30486. * @return {number} The accumulated result of the reduction operation.
  30487. */
  30488. const subgroupAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ADD ).setParameterLength( 1 );
  30489. /**
  30490. * An inclusive scan returning the sum of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  30491. *
  30492. * @tsl
  30493. * @method
  30494. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  30495. * @return {number} The accumulated result of the inclusive scan operation.
  30496. */
  30497. const subgroupInclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD ).setParameterLength( 1 );
  30498. /**
  30499. * An exclusive scan that returns the sum of e for all active invocations with subgroup_invocation_id less than this invocation.
  30500. *
  30501. * @tsl
  30502. * @method
  30503. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  30504. * @return {number} The accumulated result of the exclusive scan operation.
  30505. */
  30506. const subgroupExclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND ).setParameterLength( 1 );
  30507. /**
  30508. * A reduction that multiplies e among all active invocations and returns that result.
  30509. *
  30510. * @tsl
  30511. * @method
  30512. * @param {number} e - The value provided to the reduction by the current invocation.
  30513. * @return {number} The accumulated result of the reduction operation.
  30514. */
  30515. const subgroupMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MUL ).setParameterLength( 1 );
  30516. /**
  30517. * An inclusive scan returning the product of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  30518. *
  30519. * @tsl
  30520. * @method
  30521. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  30522. * @return {number} The accumulated result of the inclusive scan operation.
  30523. */
  30524. const subgroupInclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL ).setParameterLength( 1 );
  30525. /**
  30526. * An exclusive scan that returns the product of e for all active invocations with subgroup_invocation_id less than this invocation.
  30527. *
  30528. * @tsl
  30529. * @method
  30530. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  30531. * @return {number} The accumulated result of the exclusive scan operation.
  30532. */
  30533. const subgroupExclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL ).setParameterLength( 1 );
  30534. /**
  30535. * A reduction that performs a bitwise and of e among all active invocations and returns that result.
  30536. *
  30537. * @tsl
  30538. * @method
  30539. * @param {number} e - The value provided to the reduction by the current invocation.
  30540. * @return {number} The result of the reduction operation.
  30541. */
  30542. const subgroupAnd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_AND ).setParameterLength( 1 );
  30543. /**
  30544. * A reduction that performs a bitwise or of e among all active invocations and returns that result.
  30545. *
  30546. * @tsl
  30547. * @method
  30548. * @param {number} e - The value provided to the reduction by the current invocation.
  30549. * @return {number} The result of the reduction operation.
  30550. */
  30551. const subgroupOr = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_OR ).setParameterLength( 1 );
  30552. /**
  30553. * A reduction that performs a bitwise xor of e among all active invocations and returns that result.
  30554. *
  30555. * @tsl
  30556. * @method
  30557. * @param {number} e - The value provided to the reduction by the current invocation.
  30558. * @return {number} The result of the reduction operation.
  30559. */
  30560. const subgroupXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_XOR ).setParameterLength( 1 );
  30561. /**
  30562. * A reduction that performs a min of e among all active invocations and returns that result.
  30563. *
  30564. * @tsl
  30565. * @method
  30566. * @param {number} e - The value provided to the reduction by the current invocation.
  30567. * @return {number} The result of the reduction operation.
  30568. */
  30569. const subgroupMin = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MIN ).setParameterLength( 1 );
  30570. /**
  30571. * A reduction that performs a max of e among all active invocations and returns that result.
  30572. *
  30573. * @tsl
  30574. * @method
  30575. * @param {number} e - The value provided to the reduction by the current invocation.
  30576. * @return {number} The result of the reduction operation.
  30577. */
  30578. const subgroupMax = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MAX ).setParameterLength( 1 );
  30579. /**
  30580. * Returns true if e is true for all active invocations in the subgroup.
  30581. *
  30582. * @tsl
  30583. * @method
  30584. * @return {bool} The result of the computation.
  30585. */
  30586. const subgroupAll = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ALL ).setParameterLength( 0 );
  30587. /**
  30588. * Returns true if e is true for any active invocation in the subgroup
  30589. *
  30590. * @tsl
  30591. * @method
  30592. * @return {bool} The result of the computation.
  30593. */
  30594. const subgroupAny = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ANY ).setParameterLength( 0 );
  30595. /**
  30596. * Broadcasts e from the active invocation with the lowest subgroup_invocation_id in the subgroup to all other active invocations.
  30597. *
  30598. * @tsl
  30599. * @method
  30600. * @param {number} e - The value to broadcast from the lowest subgroup invocation.
  30601. * @param {number} id - The subgroup invocation to broadcast from.
  30602. * @return {number} The broadcast value.
  30603. */
  30604. const subgroupBroadcastFirst = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST ).setParameterLength( 2 );
  30605. /**
  30606. * Swaps e between invocations in the quad in the X direction.
  30607. *
  30608. * @tsl
  30609. * @method
  30610. * @param {number} e - The value to swap from the current invocation.
  30611. * @return {number} The value received from the swap operation.
  30612. */
  30613. const quadSwapX = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_X ).setParameterLength( 1 );
  30614. /**
  30615. * Swaps e between invocations in the quad in the Y direction.
  30616. *
  30617. * @tsl
  30618. * @method
  30619. * @param {number} e - The value to swap from the current invocation.
  30620. * @return {number} The value received from the swap operation.
  30621. */
  30622. const quadSwapY = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_Y ).setParameterLength( 1 );
  30623. /**
  30624. * Swaps e between invocations in the quad diagonally.
  30625. *
  30626. * @tsl
  30627. * @method
  30628. * @param {number} e - The value to swap from the current invocation.
  30629. * @return {number} The value received from the swap operation.
  30630. */
  30631. const quadSwapDiagonal = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_DIAGONAL ).setParameterLength( 1 );
  30632. /**
  30633. * Broadcasts e from the invocation whose subgroup_invocation_id matches id, to all active invocations.
  30634. *
  30635. * @tsl
  30636. * @method
  30637. * @param {number} e - The value to broadcast from subgroup invocation 'id'.
  30638. * @param {number} id - The subgroup invocation to broadcast from.
  30639. * @return {number} The broadcast value.
  30640. */
  30641. const subgroupBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST ).setParameterLength( 2 );
  30642. /**
  30643. * Returns v from the active invocation whose subgroup_invocation_id matches id
  30644. *
  30645. * @tsl
  30646. * @method
  30647. * @param {number} v - The value to return from subgroup invocation id^mask.
  30648. * @param {number} id - The subgroup invocation which returns the value v.
  30649. * @return {number} The broadcast value.
  30650. */
  30651. const subgroupShuffle = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE ).setParameterLength( 2 );
  30652. /**
  30653. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id ^ mask.
  30654. *
  30655. * @tsl
  30656. * @method
  30657. * @param {number} v - The value to return from subgroup invocation id^mask.
  30658. * @param {number} mask - A bitmask that determines the target invocation via a XOR operation.
  30659. * @return {number} The broadcast value.
  30660. */
  30661. const subgroupShuffleXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ).setParameterLength( 2 );
  30662. /**
  30663. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id - delta
  30664. *
  30665. * @tsl
  30666. * @method
  30667. * @param {number} v - The value to return from subgroup invocation id^mask.
  30668. * @param {number} delta - A value that offsets the current in.
  30669. * @return {number} The broadcast value.
  30670. */
  30671. const subgroupShuffleUp = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP ).setParameterLength( 2 );
  30672. /**
  30673. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id + delta
  30674. *
  30675. * @tsl
  30676. * @method
  30677. * @param {number} v - The value to return from subgroup invocation id^mask.
  30678. * @param {number} delta - A value that offsets the current subgroup invocation.
  30679. * @return {number} The broadcast value.
  30680. */
  30681. const subgroupShuffleDown = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ).setParameterLength( 2 );
  30682. /**
  30683. * Broadcasts e from the quad invocation with id equal to id.
  30684. *
  30685. * @tsl
  30686. * @method
  30687. * @param {number} e - The value to broadcast.
  30688. * @return {number} The broadcast value.
  30689. */
  30690. const quadBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_BROADCAST ).setParameterLength( 1 );
  30691. let uniformsLib;
  30692. function getLightData( light ) {
  30693. uniformsLib = uniformsLib || new WeakMap();
  30694. let uniforms = uniformsLib.get( light );
  30695. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  30696. return uniforms;
  30697. }
  30698. /**
  30699. * TSL function for getting a shadow matrix uniform node for the given light.
  30700. *
  30701. * @tsl
  30702. * @function
  30703. * @param {Light} light -The light source.
  30704. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  30705. */
  30706. function lightShadowMatrix( light ) {
  30707. const data = getLightData( light );
  30708. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  30709. // normally, shadow matrices are updated in ShadowNode. However, if the shadow matrix is used outside
  30710. // of shadow rendering (like in ProjectorLightNode), the shadow matrix still requires an update
  30711. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  30712. if ( light.shadow.camera.coordinateSystem !== frame.camera.coordinateSystem ) {
  30713. light.shadow.camera.coordinateSystem = frame.camera.coordinateSystem;
  30714. light.shadow.camera.updateProjectionMatrix();
  30715. }
  30716. light.shadow.updateMatrices( light );
  30717. }
  30718. return light.shadow.matrix;
  30719. } ) );
  30720. }
  30721. /**
  30722. * TSL function for getting projected uv coordinates for the given light.
  30723. * Relevant when using maps with spot lights.
  30724. *
  30725. * @tsl
  30726. * @function
  30727. * @param {Light} light -The light source.
  30728. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  30729. * @returns {Node<vec3>} The projected uvs.
  30730. */
  30731. function lightProjectionUV( light, position = positionWorld ) {
  30732. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  30733. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  30734. return projectionUV;
  30735. }
  30736. /**
  30737. * TSL function for getting the position in world space for the given light.
  30738. *
  30739. * @tsl
  30740. * @function
  30741. * @param {Light} light -The light source.
  30742. * @returns {UniformNode<vec3>} The light's position in world space.
  30743. */
  30744. function lightPosition( light ) {
  30745. const data = getLightData( light );
  30746. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  30747. }
  30748. /**
  30749. * TSL function for getting the light target position in world space for the given light.
  30750. *
  30751. * @tsl
  30752. * @function
  30753. * @param {Light} light -The light source.
  30754. * @returns {UniformNode<vec3>} The light target position in world space.
  30755. */
  30756. function lightTargetPosition( light ) {
  30757. const data = getLightData( light );
  30758. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  30759. }
  30760. /**
  30761. * TSL function for getting the position in view space for the given light.
  30762. *
  30763. * @tsl
  30764. * @function
  30765. * @param {Light} light - The light source.
  30766. * @returns {UniformNode<vec3>} The light's position in view space.
  30767. */
  30768. function lightViewPosition( light ) {
  30769. const data = getLightData( light );
  30770. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  30771. self.value = self.value || new Vector3();
  30772. self.value.setFromMatrixPosition( light.matrixWorld );
  30773. self.value.applyMatrix4( camera.matrixWorldInverse );
  30774. } ) );
  30775. }
  30776. /**
  30777. * TSL function for getting the light target direction for the given light.
  30778. *
  30779. * @tsl
  30780. * @function
  30781. * @param {Light} light -The light source.
  30782. * @returns {Node<vec3>} The light's target direction.
  30783. */
  30784. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  30785. const sortLights = ( lights ) => {
  30786. return lights.sort( ( a, b ) => a.id - b.id );
  30787. };
  30788. const getLightNodeById = ( id, lightNodes ) => {
  30789. for ( const lightNode of lightNodes ) {
  30790. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  30791. return lightNode;
  30792. }
  30793. }
  30794. return null;
  30795. };
  30796. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  30797. const _hashData = [];
  30798. /**
  30799. * This node represents the scene's lighting and manages the lighting model's life cycle
  30800. * for the current build 3D object. It is responsible for computing the total outgoing
  30801. * light in a given lighting context.
  30802. *
  30803. * @augments Node
  30804. */
  30805. class LightsNode extends Node {
  30806. static get type() {
  30807. return 'LightsNode';
  30808. }
  30809. /**
  30810. * Constructs a new lights node.
  30811. */
  30812. constructor() {
  30813. super( 'vec3' );
  30814. /**
  30815. * A node representing the total diffuse light.
  30816. *
  30817. * @type {Node<vec3>}
  30818. */
  30819. this.totalDiffuseNode = property( 'vec3', 'totalDiffuse' );
  30820. /**
  30821. * A node representing the total specular light.
  30822. *
  30823. * @type {Node<vec3>}
  30824. */
  30825. this.totalSpecularNode = property( 'vec3', 'totalSpecular' );
  30826. /**
  30827. * A node representing the outgoing light.
  30828. *
  30829. * @type {Node<vec3>}
  30830. */
  30831. this.outgoingLightNode = property( 'vec3', 'outgoingLight' );
  30832. /**
  30833. * An array representing the lights in the scene.
  30834. *
  30835. * @private
  30836. * @type {Array<Light>}
  30837. */
  30838. this._lights = [];
  30839. /**
  30840. * For each light in the scene, this node will create a
  30841. * corresponding light node.
  30842. *
  30843. * @private
  30844. * @type {?Array<LightingNode>}
  30845. * @default null
  30846. */
  30847. this._lightNodes = null;
  30848. /**
  30849. * A hash for identifying the current light nodes setup.
  30850. *
  30851. * @private
  30852. * @type {?string}
  30853. * @default null
  30854. */
  30855. this._lightNodesHash = null;
  30856. /**
  30857. * `LightsNode` sets this property to `true` by default.
  30858. *
  30859. * @type {boolean}
  30860. * @default true
  30861. */
  30862. this.global = true;
  30863. }
  30864. /**
  30865. * Overwrites the default {@link Node#customCacheKey} implementation by including
  30866. * light data into the cache key.
  30867. *
  30868. * @return {number} The custom cache key.
  30869. */
  30870. customCacheKey() {
  30871. const lights = this._lights;
  30872. for ( let i = 0; i < lights.length; i ++ ) {
  30873. const light = lights[ i ];
  30874. _hashData.push( light.id );
  30875. _hashData.push( light.castShadow ? 1 : 0 );
  30876. if ( light.isSpotLight === true ) {
  30877. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  30878. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  30879. _hashData.push( hashMap, hashColorNode );
  30880. }
  30881. }
  30882. const cacheKey = hashArray( _hashData );
  30883. _hashData.length = 0;
  30884. return cacheKey;
  30885. }
  30886. /**
  30887. * Computes a hash value for identifying the current light nodes setup.
  30888. *
  30889. * @param {NodeBuilder} builder - A reference to the current node builder.
  30890. * @return {string} The computed hash.
  30891. */
  30892. getHash( builder ) {
  30893. if ( this._lightNodesHash === null ) {
  30894. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  30895. const hash = [];
  30896. for ( const lightNode of this._lightNodes ) {
  30897. hash.push( lightNode.getHash() );
  30898. }
  30899. this._lightNodesHash = 'lights-' + hash.join( ',' );
  30900. }
  30901. return this._lightNodesHash;
  30902. }
  30903. analyze( builder ) {
  30904. const properties = builder.getNodeProperties( this );
  30905. for ( const node of properties.nodes ) {
  30906. node.build( builder );
  30907. }
  30908. properties.outputNode.build( builder );
  30909. }
  30910. /**
  30911. * Creates lighting nodes for each scene light. This makes it possible to further
  30912. * process lights in the node system.
  30913. *
  30914. * @param {NodeBuilder} builder - A reference to the current node builder.
  30915. */
  30916. setupLightsNode( builder ) {
  30917. const lightNodes = [];
  30918. const previousLightNodes = this._lightNodes;
  30919. const lights = sortLights( this._lights );
  30920. const nodeLibrary = builder.renderer.library;
  30921. for ( const light of lights ) {
  30922. if ( light.isNode ) {
  30923. lightNodes.push( nodeObject( light ) );
  30924. } else {
  30925. let lightNode = null;
  30926. if ( previousLightNodes !== null ) {
  30927. lightNode = getLightNodeById( light.id, previousLightNodes );
  30928. }
  30929. if ( lightNode === null ) {
  30930. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  30931. if ( lightNodeClass === null ) {
  30932. warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  30933. continue;
  30934. }
  30935. if ( _lightsNodeRef.has( light ) === false ) {
  30936. _lightsNodeRef.set( light, new lightNodeClass( light ) );
  30937. }
  30938. lightNode = _lightsNodeRef.get( light );
  30939. }
  30940. lightNodes.push( lightNode );
  30941. }
  30942. }
  30943. this._lightNodes = lightNodes;
  30944. }
  30945. /**
  30946. * Sets up a direct light in the lighting model.
  30947. *
  30948. * @param {Object} builder - The builder object containing the context and stack.
  30949. * @param {Object} lightNode - The light node.
  30950. * @param {Object} lightData - The light object containing color and direction properties.
  30951. */
  30952. setupDirectLight( builder, lightNode, lightData ) {
  30953. const { lightingModel, reflectedLight } = builder.context;
  30954. lightingModel.direct( {
  30955. ...lightData,
  30956. lightNode,
  30957. reflectedLight
  30958. }, builder );
  30959. }
  30960. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  30961. const { lightingModel, reflectedLight } = builder.context;
  30962. lightingModel.directRectArea( {
  30963. ...lightData,
  30964. lightNode,
  30965. reflectedLight
  30966. }, builder );
  30967. }
  30968. /**
  30969. * Setups the internal lights by building all respective
  30970. * light nodes.
  30971. *
  30972. * @param {NodeBuilder} builder - A reference to the current node builder.
  30973. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  30974. */
  30975. setupLights( builder, lightNodes ) {
  30976. for ( const lightNode of lightNodes ) {
  30977. lightNode.build( builder );
  30978. }
  30979. }
  30980. getLightNodes( builder ) {
  30981. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  30982. return this._lightNodes;
  30983. }
  30984. /**
  30985. * The implementation makes sure that for each light in the scene
  30986. * there is a corresponding light node. By building the light nodes
  30987. * and evaluating the lighting model the outgoing light is computed.
  30988. *
  30989. * @param {NodeBuilder} builder - A reference to the current node builder.
  30990. * @return {Node<vec3>} A node representing the outgoing light.
  30991. */
  30992. setup( builder ) {
  30993. const currentLightsNode = builder.lightsNode;
  30994. builder.lightsNode = this;
  30995. let outgoingLightNode = this.outgoingLightNode;
  30996. const context = builder.context;
  30997. const lightingModel = context.lightingModel;
  30998. const properties = builder.getNodeProperties( this );
  30999. if ( lightingModel ) {
  31000. const { totalDiffuseNode, totalSpecularNode } = this;
  31001. context.outgoingLight = outgoingLightNode;
  31002. const stack = builder.addStack();
  31003. properties.nodes = stack.nodes;
  31004. lightingModel.start( builder );
  31005. const { backdrop, backdropAlpha } = context;
  31006. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  31007. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  31008. if ( backdrop !== null ) {
  31009. if ( backdropAlpha !== null ) {
  31010. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  31011. } else {
  31012. totalDiffuse = vec3( backdrop );
  31013. }
  31014. }
  31015. totalDiffuseNode.assign( totalDiffuse );
  31016. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  31017. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  31018. lightingModel.finish( builder );
  31019. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  31020. } else {
  31021. properties.nodes = [];
  31022. }
  31023. builder.lightsNode = currentLightsNode;
  31024. return outgoingLightNode;
  31025. }
  31026. /**
  31027. * Configures this node with an array of lights.
  31028. *
  31029. * @param {Array<Light>} lights - An array of lights.
  31030. * @return {LightsNode} A reference to this node.
  31031. */
  31032. setLights( lights ) {
  31033. this._lights = lights;
  31034. this._lightNodes = null;
  31035. this._lightNodesHash = null;
  31036. return this;
  31037. }
  31038. /**
  31039. * Returns an array of the scene's lights.
  31040. *
  31041. * @return {Array<Light>} The scene's lights.
  31042. */
  31043. getLights() {
  31044. return this._lights;
  31045. }
  31046. /**
  31047. * Whether the scene has lights or not.
  31048. *
  31049. * @type {boolean}
  31050. */
  31051. get hasLights() {
  31052. return this._lights.length > 0;
  31053. }
  31054. }
  31055. /**
  31056. * TSL function for creating an instance of `LightsNode` and configuring
  31057. * it with the given array of lights.
  31058. *
  31059. * @tsl
  31060. * @function
  31061. * @param {Array<Light>} lights - An array of lights.
  31062. * @return {LightsNode} The created lights node.
  31063. */
  31064. const lights = ( lights = [] ) => new LightsNode().setLights( lights );
  31065. /**
  31066. * Base class for all shadow nodes.
  31067. *
  31068. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  31069. * Lighting nodes might share the same shadow node type or use specific ones depending on
  31070. * their requirements.
  31071. *
  31072. * @augments Node
  31073. */
  31074. class ShadowBaseNode extends Node {
  31075. static get type() {
  31076. return 'ShadowBaseNode';
  31077. }
  31078. /**
  31079. * Constructs a new shadow base node.
  31080. *
  31081. * @param {Light} light - The shadow casting light.
  31082. */
  31083. constructor( light ) {
  31084. super();
  31085. /**
  31086. * The shadow casting light.
  31087. *
  31088. * @type {Light}
  31089. */
  31090. this.light = light;
  31091. /**
  31092. * Overwritten since shadows are updated by default per render.
  31093. *
  31094. * @type {string}
  31095. * @default 'render'
  31096. */
  31097. this.updateBeforeType = NodeUpdateType.RENDER;
  31098. /**
  31099. * This flag can be used for type testing.
  31100. *
  31101. * @type {boolean}
  31102. * @readonly
  31103. * @default true
  31104. */
  31105. this.isShadowBaseNode = true;
  31106. }
  31107. /**
  31108. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  31109. *
  31110. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  31111. */
  31112. setupShadowPosition( { context, material } ) {
  31113. // Use assign inside an Fn()
  31114. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  31115. }
  31116. }
  31117. /**
  31118. * TSL object that represents the vertex position in world space during the shadow pass.
  31119. *
  31120. * @tsl
  31121. * @type {Node<vec3>}
  31122. */
  31123. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  31124. /**
  31125. * Saves the state of the given renderer and stores it into the given state object.
  31126. *
  31127. * If not state object is provided, the function creates one.
  31128. *
  31129. * @private
  31130. * @function
  31131. * @param {Renderer} renderer - The renderer.
  31132. * @param {Object} [state={}] - The state.
  31133. * @return {Object} The state.
  31134. */
  31135. function saveRendererState( renderer, state = {} ) {
  31136. state.toneMapping = renderer.toneMapping;
  31137. state.toneMappingExposure = renderer.toneMappingExposure;
  31138. state.outputColorSpace = renderer.outputColorSpace;
  31139. state.renderTarget = renderer.getRenderTarget();
  31140. state.activeCubeFace = renderer.getActiveCubeFace();
  31141. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  31142. state.renderObjectFunction = renderer.getRenderObjectFunction();
  31143. state.pixelRatio = renderer.getPixelRatio();
  31144. state.mrt = renderer.getMRT();
  31145. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  31146. state.clearAlpha = renderer.getClearAlpha();
  31147. state.autoClear = renderer.autoClear;
  31148. state.scissorTest = renderer.getScissorTest();
  31149. return state;
  31150. }
  31151. /**
  31152. * Saves the state of the given renderer and stores it into the given state object.
  31153. * Besides, the function also resets the state of the renderer to its default values.
  31154. *
  31155. * If not state object is provided, the function creates one.
  31156. *
  31157. * @private
  31158. * @function
  31159. * @param {Renderer} renderer - The renderer.
  31160. * @param {Object} [state={}] - The state.
  31161. * @return {Object} The state.
  31162. */
  31163. function resetRendererState( renderer, state ) {
  31164. state = saveRendererState( renderer, state );
  31165. renderer.setMRT( null );
  31166. renderer.setRenderObjectFunction( null );
  31167. renderer.setClearColor( 0x000000, 1 );
  31168. renderer.autoClear = true;
  31169. return state;
  31170. }
  31171. /**
  31172. * Restores the state of the given renderer from the given state object.
  31173. *
  31174. * @private
  31175. * @function
  31176. * @param {Renderer} renderer - The renderer.
  31177. * @param {Object} state - The state to restore.
  31178. */
  31179. function restoreRendererState( renderer, state ) {
  31180. renderer.toneMapping = state.toneMapping;
  31181. renderer.toneMappingExposure = state.toneMappingExposure;
  31182. renderer.outputColorSpace = state.outputColorSpace;
  31183. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  31184. renderer.setRenderObjectFunction( state.renderObjectFunction );
  31185. renderer.setPixelRatio( state.pixelRatio );
  31186. renderer.setMRT( state.mrt );
  31187. renderer.setClearColor( state.clearColor, state.clearAlpha );
  31188. renderer.autoClear = state.autoClear;
  31189. renderer.setScissorTest( state.scissorTest );
  31190. }
  31191. /**
  31192. * Saves the state of the given scene and stores it into the given state object.
  31193. *
  31194. * If not state object is provided, the function creates one.
  31195. *
  31196. * @private
  31197. * @function
  31198. * @param {Scene} scene - The scene.
  31199. * @param {Object} [state={}] - The state.
  31200. * @return {Object} The state.
  31201. */
  31202. function saveSceneState( scene, state = {} ) {
  31203. state.background = scene.background;
  31204. state.backgroundNode = scene.backgroundNode;
  31205. state.overrideMaterial = scene.overrideMaterial;
  31206. return state;
  31207. }
  31208. /**
  31209. * Saves the state of the given scene and stores it into the given state object.
  31210. * Besides, the function also resets the state of the scene to its default values.
  31211. *
  31212. * If not state object is provided, the function creates one.
  31213. *
  31214. * @private
  31215. * @function
  31216. * @param {Scene} scene - The scene.
  31217. * @param {Object} [state={}] - The state.
  31218. * @return {Object} The state.
  31219. */
  31220. function resetSceneState( scene, state ) {
  31221. state = saveSceneState( scene, state );
  31222. scene.background = null;
  31223. scene.backgroundNode = null;
  31224. scene.overrideMaterial = null;
  31225. return state;
  31226. }
  31227. /**
  31228. * Restores the state of the given scene from the given state object.
  31229. *
  31230. * @private
  31231. * @function
  31232. * @param {Scene} scene - The scene.
  31233. * @param {Object} state - The state to restore.
  31234. */
  31235. function restoreSceneState( scene, state ) {
  31236. scene.background = state.background;
  31237. scene.backgroundNode = state.backgroundNode;
  31238. scene.overrideMaterial = state.overrideMaterial;
  31239. }
  31240. /**
  31241. * Saves the state of the given renderer and scene and stores it into the given state object.
  31242. *
  31243. * If not state object is provided, the function creates one.
  31244. *
  31245. * @private
  31246. * @function
  31247. * @param {Renderer} renderer - The renderer.
  31248. * @param {Scene} scene - The scene.
  31249. * @param {Object} [state={}] - The state.
  31250. * @return {Object} The state.
  31251. */
  31252. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  31253. state = saveRendererState( renderer, state );
  31254. state = saveSceneState( scene, state );
  31255. return state;
  31256. }
  31257. /**
  31258. * Saves the state of the given renderer and scene and stores it into the given state object.
  31259. * Besides, the function also resets the state of the renderer and scene to its default values.
  31260. *
  31261. * If not state object is provided, the function creates one.
  31262. *
  31263. * @private
  31264. * @function
  31265. * @param {Renderer} renderer - The renderer.
  31266. * @param {Scene} scene - The scene.
  31267. * @param {Object} [state={}] - The state.
  31268. * @return {Object} The state.
  31269. */
  31270. function resetRendererAndSceneState( renderer, scene, state ) {
  31271. state = resetRendererState( renderer, state );
  31272. state = resetSceneState( scene, state );
  31273. return state;
  31274. }
  31275. /**
  31276. * Restores the state of the given renderer and scene from the given state object.
  31277. *
  31278. * @private
  31279. * @function
  31280. * @param {Renderer} renderer - The renderer.
  31281. * @param {Scene} scene - The scene.
  31282. * @param {Object} state - The state to restore.
  31283. */
  31284. function restoreRendererAndSceneState( renderer, scene, state ) {
  31285. restoreRendererState( renderer, state );
  31286. restoreSceneState( scene, state );
  31287. }
  31288. var RendererUtils = /*#__PURE__*/Object.freeze({
  31289. __proto__: null,
  31290. resetRendererAndSceneState: resetRendererAndSceneState,
  31291. resetRendererState: resetRendererState,
  31292. resetSceneState: resetSceneState,
  31293. restoreRendererAndSceneState: restoreRendererAndSceneState,
  31294. restoreRendererState: restoreRendererState,
  31295. restoreSceneState: restoreSceneState,
  31296. saveRendererAndSceneState: saveRendererAndSceneState,
  31297. saveRendererState: saveRendererState,
  31298. saveSceneState: saveSceneState
  31299. });
  31300. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  31301. /**
  31302. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  31303. * with a binary `[0,1]` result.
  31304. *
  31305. * @method
  31306. * @param {Object} inputs - The input parameter object.
  31307. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31308. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  31309. * @return {Node<float>} The filtering result.
  31310. */
  31311. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  31312. let basic = texture( depthTexture, shadowCoord.xy ).setName( 't_basic' );
  31313. if ( depthTexture.isArrayTexture ) {
  31314. basic = basic.depth( depthLayer );
  31315. }
  31316. return basic.compare( shadowCoord.z );
  31317. } );
  31318. /**
  31319. * A shadow filtering function performing PCF filtering with Vogel disk sampling and IGN.
  31320. *
  31321. * Uses 5 samples distributed via Vogel disk pattern, rotated per-pixel using Interleaved
  31322. * Gradient Noise (IGN) to break up banding artifacts. Combined with hardware PCF (4-tap
  31323. * filtering per sample), this effectively provides 20 filtered taps with better distribution.
  31324. *
  31325. * @method
  31326. * @param {Object} inputs - The input parameter object.
  31327. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31328. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  31329. * @param {LightShadow} inputs.shadow - The light shadow.
  31330. * @return {Node<float>} The filtering result.
  31331. */
  31332. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  31333. const depthCompare = ( uv, compare ) => {
  31334. let depth = texture( depthTexture, uv );
  31335. if ( depthTexture.isArrayTexture ) {
  31336. depth = depth.depth( depthLayer );
  31337. }
  31338. return depth.compare( compare );
  31339. };
  31340. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  31341. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  31342. const texelSize = vec2( 1 ).div( mapSize );
  31343. const radiusScaled = radius.mul( texelSize.x );
  31344. // Use IGN to rotate sampling pattern per pixel (phi = IGN * 2π)
  31345. const phi = interleavedGradientNoise( screenCoordinate.xy ).mul( 6.28318530718 );
  31346. // 5 samples using Vogel disk distribution
  31347. return add(
  31348. depthCompare( shadowCoord.xy.add( vogelDiskSample( 0, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  31349. depthCompare( shadowCoord.xy.add( vogelDiskSample( 1, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  31350. depthCompare( shadowCoord.xy.add( vogelDiskSample( 2, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  31351. depthCompare( shadowCoord.xy.add( vogelDiskSample( 3, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  31352. depthCompare( shadowCoord.xy.add( vogelDiskSample( 4, 5, phi ).mul( radiusScaled ) ), shadowCoord.z )
  31353. ).mul( 1 / 5 );
  31354. } );
  31355. /**
  31356. * A shadow filtering function performing PCF soft filtering.
  31357. *
  31358. * @method
  31359. * @param {Object} inputs - The input parameter object.
  31360. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31361. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  31362. * @param {LightShadow} inputs.shadow - The light shadow.
  31363. * @return {Node<float>} The filtering result.
  31364. */
  31365. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  31366. const depthCompare = ( uv, compare ) => {
  31367. let depth = texture( depthTexture, uv );
  31368. if ( depthTexture.isArrayTexture ) {
  31369. depth = depth.depth( depthLayer );
  31370. }
  31371. return depth.compare( compare );
  31372. };
  31373. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  31374. const texelSize = vec2( 1 ).div( mapSize );
  31375. const dx = texelSize.x;
  31376. const dy = texelSize.y;
  31377. const uv = shadowCoord.xy;
  31378. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  31379. uv.subAssign( f.mul( texelSize ) );
  31380. return add(
  31381. depthCompare( uv, shadowCoord.z ),
  31382. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  31383. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  31384. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  31385. mix(
  31386. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  31387. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  31388. f.x
  31389. ),
  31390. mix(
  31391. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  31392. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  31393. f.x
  31394. ),
  31395. mix(
  31396. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  31397. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  31398. f.y
  31399. ),
  31400. mix(
  31401. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  31402. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  31403. f.y
  31404. ),
  31405. mix(
  31406. mix(
  31407. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  31408. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  31409. f.x
  31410. ),
  31411. mix(
  31412. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  31413. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  31414. f.x
  31415. ),
  31416. f.y
  31417. )
  31418. ).mul( 1 / 9 );
  31419. } );
  31420. /**
  31421. * A shadow filtering function performing VSM filtering.
  31422. *
  31423. * @method
  31424. * @param {Object} inputs - The input parameter object.
  31425. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31426. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  31427. * @return {Node<float>} The filtering result.
  31428. */
  31429. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer }, builder ) => {
  31430. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  31431. if ( depthTexture.isArrayTexture ) {
  31432. distribution = distribution.depth( depthLayer );
  31433. }
  31434. distribution = distribution.rg;
  31435. const mean = distribution.x;
  31436. const variance = max$1( 0.0000001, distribution.y.mul( distribution.y ) );
  31437. const hardShadow = ( builder.renderer.reversedDepthBuffer ) ? step( mean, shadowCoord.z ) : step( shadowCoord.z, mean );
  31438. const output = float( 1 ).toVar(); // default, fully lit
  31439. If( hardShadow.notEqual( 1.0 ), () => {
  31440. // Distance from mean
  31441. const d = shadowCoord.z.sub( mean );
  31442. // Chebyshev's inequality for upper bound on probability
  31443. let p_max = variance.div( variance.add( d.mul( d ) ) );
  31444. // Reduce light bleeding by remapping [amount, 1] to [0, 1]
  31445. p_max = clamp( sub( p_max, 0.3 ).div( 0.65 ) );
  31446. output.assign( max$1( hardShadow, p_max ) );
  31447. } );
  31448. return output;
  31449. } );
  31450. /**
  31451. * Retrieves or creates a shadow material for the given light source.
  31452. *
  31453. * This function checks if a shadow material already exists for the provided light.
  31454. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  31455. * in the `shadowMaterialLib` for future use.
  31456. *
  31457. * @tsl
  31458. * @function
  31459. * @param {Light} light - The light source for which the shadow material is needed.
  31460. * If the light is a point light, a depth node is calculated
  31461. * using the linear shadow distance.
  31462. * @returns {NodeMaterial} The shadow material associated with the given light.
  31463. */
  31464. const getShadowMaterial = ( light ) => {
  31465. let material = shadowMaterialLib.get( light );
  31466. if ( material === undefined ) {
  31467. material = new NodeMaterial();
  31468. material.colorNode = vec4( 0, 0, 0, 1 );
  31469. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  31470. material.name = 'ShadowMaterial';
  31471. material.blending = NoBlending;
  31472. material.fog = false;
  31473. shadowMaterialLib.set( light, material );
  31474. }
  31475. return material;
  31476. };
  31477. /**
  31478. * Disposes the shadow material for the given light source.
  31479. *
  31480. * @param {Light} light - The light source.
  31481. */
  31482. const disposeShadowMaterial = ( light ) => {
  31483. const material = shadowMaterialLib.get( light );
  31484. if ( material !== undefined ) {
  31485. material.dispose();
  31486. shadowMaterialLib.delete( light );
  31487. }
  31488. };
  31489. //
  31490. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  31491. const _shadowRenderObjectKeys = [];
  31492. /**
  31493. * Creates a function to render shadow objects in a scene.
  31494. *
  31495. * @tsl
  31496. * @function
  31497. * @param {Renderer} renderer - The renderer.
  31498. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  31499. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  31500. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  31501. * @return {shadowRenderObjectFunction} A function that renders shadow objects.
  31502. */
  31503. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  31504. _shadowRenderObjectKeys[ 0 ] = renderer;
  31505. _shadowRenderObjectKeys[ 1 ] = shadow;
  31506. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  31507. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  31508. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  31509. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  31510. if ( useVelocity ) {
  31511. getDataFromObject( object ).useVelocity = true;
  31512. }
  31513. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  31514. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  31515. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  31516. }
  31517. };
  31518. renderObjectFunction.shadowType = shadowType;
  31519. renderObjectFunction.useVelocity = useVelocity;
  31520. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  31521. }
  31522. _shadowRenderObjectKeys[ 0 ] = null;
  31523. _shadowRenderObjectKeys[ 1 ] = null;
  31524. return renderObjectFunction;
  31525. };
  31526. /**
  31527. * Represents the shader code for the first VSM render pass.
  31528. *
  31529. * @private
  31530. * @method
  31531. * @param {Object} inputs - The input parameter object.
  31532. * @param {Node<float>} inputs.samples - The number of samples
  31533. * @param {Node<float>} inputs.radius - The radius.
  31534. * @param {Node<float>} inputs.size - The size.
  31535. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  31536. * @return {Node<vec2>} The VSM output.
  31537. */
  31538. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  31539. const mean = float( 0 ).toVar( 'meanVertical' );
  31540. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  31541. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  31542. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  31543. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  31544. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  31545. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  31546. if ( shadowPass.value.isArrayTexture ) {
  31547. depth = depth.depth( depthLayer );
  31548. }
  31549. depth = depth.x;
  31550. mean.addAssign( depth );
  31551. squaredMean.addAssign( depth.mul( depth ) );
  31552. } );
  31553. mean.divAssign( samples );
  31554. squaredMean.divAssign( samples );
  31555. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ).max( 0 ) );
  31556. return vec2( mean, std_dev );
  31557. } );
  31558. /**
  31559. * Represents the shader code for the second VSM render pass.
  31560. *
  31561. * @private
  31562. * @method
  31563. * @param {Object} inputs - The input parameter object.
  31564. * @param {Node<float>} inputs.samples - The number of samples
  31565. * @param {Node<float>} inputs.radius - The radius.
  31566. * @param {Node<float>} inputs.size - The size.
  31567. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  31568. * @return {Node<vec2>} The VSM output.
  31569. */
  31570. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  31571. const mean = float( 0 ).toVar( 'meanHorizontal' );
  31572. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  31573. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  31574. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  31575. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  31576. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  31577. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  31578. if ( shadowPass.value.isArrayTexture ) {
  31579. distribution = distribution.depth( depthLayer );
  31580. }
  31581. mean.addAssign( distribution.x );
  31582. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  31583. } );
  31584. mean.divAssign( samples );
  31585. squaredMean.divAssign( samples );
  31586. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ).max( 0 ) );
  31587. return vec2( mean, std_dev );
  31588. } );
  31589. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  31590. //
  31591. let _rendererState;
  31592. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  31593. /**
  31594. * Represents the default shadow implementation for lighting nodes.
  31595. *
  31596. * @augments ShadowBaseNode
  31597. */
  31598. class ShadowNode extends ShadowBaseNode {
  31599. static get type() {
  31600. return 'ShadowNode';
  31601. }
  31602. /**
  31603. * Constructs a new shadow node.
  31604. *
  31605. * @param {Light} light - The shadow casting light.
  31606. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  31607. */
  31608. constructor( light, shadow = null ) {
  31609. super( light );
  31610. /**
  31611. * The light shadow which defines the properties light's
  31612. * shadow.
  31613. *
  31614. * @type {?LightShadow}
  31615. * @default null
  31616. */
  31617. this.shadow = shadow || light.shadow;
  31618. /**
  31619. * A reference to the shadow map which is a render target.
  31620. *
  31621. * @type {?RenderTarget}
  31622. * @default null
  31623. */
  31624. this.shadowMap = null;
  31625. /**
  31626. * Only relevant for VSM shadows. Render target for the
  31627. * first VSM render pass.
  31628. *
  31629. * @type {?RenderTarget}
  31630. * @default null
  31631. */
  31632. this.vsmShadowMapVertical = null;
  31633. /**
  31634. * Only relevant for VSM shadows. Render target for the
  31635. * second VSM render pass.
  31636. *
  31637. * @type {?RenderTarget}
  31638. * @default null
  31639. */
  31640. this.vsmShadowMapHorizontal = null;
  31641. /**
  31642. * Only relevant for VSM shadows. Node material which
  31643. * is used to render the first VSM pass.
  31644. *
  31645. * @type {?NodeMaterial}
  31646. * @default null
  31647. */
  31648. this.vsmMaterialVertical = null;
  31649. /**
  31650. * Only relevant for VSM shadows. Node material which
  31651. * is used to render the second VSM pass.
  31652. *
  31653. * @type {?NodeMaterial}
  31654. * @default null
  31655. */
  31656. this.vsmMaterialHorizontal = null;
  31657. /**
  31658. * A reference to the output node which defines the
  31659. * final result of this shadow node.
  31660. *
  31661. * @type {?Node}
  31662. * @private
  31663. * @default null
  31664. */
  31665. this._node = null;
  31666. /**
  31667. * The current shadow map type of this shadow node.
  31668. *
  31669. * @type {?number}
  31670. * @private
  31671. * @default null
  31672. */
  31673. this._currentShadowType = null;
  31674. /**
  31675. * A Weak Map holding the current frame ID per camera. Used
  31676. * to control the update of shadow maps.
  31677. *
  31678. * @type {WeakMap<Camera,number>}
  31679. * @private
  31680. */
  31681. this._cameraFrameId = new WeakMap();
  31682. /**
  31683. * This flag can be used for type testing.
  31684. *
  31685. * @type {boolean}
  31686. * @readonly
  31687. * @default true
  31688. */
  31689. this.isShadowNode = true;
  31690. /**
  31691. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  31692. *
  31693. * @type {number}
  31694. * @readonly
  31695. * @default true
  31696. */
  31697. this.depthLayer = 0;
  31698. }
  31699. /**
  31700. * Setups the shadow filtering.
  31701. *
  31702. * @param {NodeBuilder} builder - A reference to the current node builder.
  31703. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  31704. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  31705. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31706. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  31707. * @param {LightShadow} inputs.shadow - The light shadow.
  31708. * @return {Node<float>} The result node of the shadow filtering.
  31709. */
  31710. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  31711. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  31712. .and( shadowCoord.x.lessThanEqual( 1 ) )
  31713. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  31714. .and( shadowCoord.y.lessThanEqual( 1 ) )
  31715. .and( shadowCoord.z.lessThanEqual( 1 ) );
  31716. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  31717. return frustumTest.select( shadowNode, float( 1 ) );
  31718. }
  31719. /**
  31720. * Setups the shadow coordinates.
  31721. *
  31722. * @param {NodeBuilder} builder - A reference to the current node builder.
  31723. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  31724. * @return {Node<vec3>} The shadow coordinates.
  31725. */
  31726. setupShadowCoord( builder, shadowPosition ) {
  31727. const { shadow } = this;
  31728. const { renderer } = builder;
  31729. const bias = shadow.biasNode || reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  31730. let shadowCoord = shadowPosition;
  31731. let coordZ;
  31732. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  31733. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  31734. coordZ = shadowCoord.z;
  31735. } else {
  31736. const w = shadowCoord.w;
  31737. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  31738. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  31739. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  31740. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  31741. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  31742. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  31743. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  31744. }
  31745. shadowCoord = vec3(
  31746. shadowCoord.x,
  31747. shadowCoord.y.oneMinus(), // follow webgpu standards
  31748. renderer.reversedDepthBuffer ? coordZ.sub( bias ) : coordZ.add( bias )
  31749. );
  31750. return shadowCoord;
  31751. }
  31752. /**
  31753. * Returns the shadow filtering function for the given shadow type.
  31754. *
  31755. * @param {number} type - The shadow type.
  31756. * @return {Function} The filtering function.
  31757. */
  31758. getShadowFilterFn( type ) {
  31759. return _shadowFilterLib[ type ];
  31760. }
  31761. setupRenderTarget( shadow, builder ) {
  31762. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  31763. depthTexture.name = 'ShadowDepthTexture';
  31764. depthTexture.compareFunction = builder.renderer.reversedDepthBuffer ? GreaterEqualCompare : LessEqualCompare;
  31765. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  31766. shadowMap.texture.name = 'ShadowMap';
  31767. shadowMap.texture.type = shadow.mapType;
  31768. shadowMap.depthTexture = depthTexture;
  31769. return { shadowMap, depthTexture };
  31770. }
  31771. /**
  31772. * Setups the shadow output node.
  31773. *
  31774. * @param {NodeBuilder} builder - A reference to the current node builder.
  31775. * @return {Node<vec3>} The shadow output node.
  31776. */
  31777. setupShadow( builder ) {
  31778. const { renderer, camera } = builder;
  31779. const { light, shadow } = this;
  31780. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  31781. const shadowMapType = renderer.shadowMap.type;
  31782. const hasTextureCompare = renderer.hasCompatibility( Compatibility.TEXTURE_COMPARE );
  31783. if ( ( shadowMapType === PCFShadowMap || shadowMapType === PCFSoftShadowMap ) && hasTextureCompare ) {
  31784. depthTexture.minFilter = LinearFilter;
  31785. depthTexture.magFilter = LinearFilter;
  31786. } else {
  31787. depthTexture.minFilter = NearestFilter;
  31788. depthTexture.magFilter = NearestFilter;
  31789. }
  31790. shadow.camera.coordinateSystem = camera.coordinateSystem;
  31791. shadow.camera.updateProjectionMatrix();
  31792. // VSM
  31793. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  31794. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  31795. if ( shadowMap.depth > 1 ) {
  31796. if ( ! shadowMap._vsmShadowMapVertical ) {
  31797. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  31798. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  31799. }
  31800. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  31801. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  31802. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  31803. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  31804. }
  31805. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  31806. } else {
  31807. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  31808. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  31809. }
  31810. let shadowPassVertical = texture( depthTexture );
  31811. if ( depthTexture.isArrayTexture ) {
  31812. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  31813. }
  31814. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  31815. if ( depthTexture.isArrayTexture ) {
  31816. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  31817. }
  31818. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  31819. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  31820. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  31821. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  31822. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  31823. material.name = 'VSMVertical';
  31824. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  31825. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  31826. material.name = 'VSMHorizontal';
  31827. }
  31828. //
  31829. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  31830. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  31831. const shadowMatrix = lightShadowMatrix( light );
  31832. const shadowNormalBias = normalWorld.mul( normalBias );
  31833. let shadowPosition;
  31834. if ( ! renderer.highPrecision || builder.material.receivedShadowPositionNode || builder.context.shadowPositionWorld ) {
  31835. shadowPosition = shadowMatrix.mul( shadowPositionWorld.add( shadowNormalBias ) );
  31836. } else {
  31837. const highpShadowModelMatrix = uniform( 'mat4' ).onObjectUpdate( ( { object }, self ) => {
  31838. return self.value.multiplyMatrices( shadowMatrix.value, object.matrixWorld );
  31839. } );
  31840. shadowPosition = highpShadowModelMatrix.mul( positionLocal ).add( shadowMatrix.mul( vec4( shadowNormalBias, 0 ) ) );
  31841. }
  31842. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  31843. //
  31844. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  31845. if ( filterFn === null ) {
  31846. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  31847. }
  31848. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  31849. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  31850. let shadowColor;
  31851. if ( renderer.shadowMap.transmitted === true ) {
  31852. if ( shadowMap.texture.isCubeTexture ) {
  31853. // For cube shadow maps (point lights), use cubeTexture with vec3 coordinates
  31854. shadowColor = cubeTexture( shadowMap.texture, shadowCoord.xyz );
  31855. } else {
  31856. shadowColor = texture( shadowMap.texture, shadowCoord );
  31857. if ( depthTexture.isArrayTexture ) {
  31858. shadowColor = shadowColor.depth( this.depthLayer );
  31859. }
  31860. }
  31861. }
  31862. //
  31863. let shadowOutput;
  31864. if ( shadowColor ) {
  31865. shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  31866. } else {
  31867. shadowOutput = mix( 1, shadowNode, shadowIntensity ).toVar();
  31868. }
  31869. this.shadowMap = shadowMap;
  31870. this.shadow.map = shadowMap;
  31871. // Shadow Output + Inspector
  31872. const inspectName = `${ this.light.type } Shadow [ ${ this.light.name || 'ID: ' + this.light.id } ]`;
  31873. if ( shadowColor ) {
  31874. shadowOutput.toInspector( `${ inspectName } / Color`, () => {
  31875. if ( this.shadowMap.texture.isCubeTexture ) {
  31876. return cubeTexture( this.shadowMap.texture );
  31877. }
  31878. return texture( this.shadowMap.texture );
  31879. } );
  31880. }
  31881. return shadowOutput.toInspector( `${ inspectName } / Depth`, () => {
  31882. // TODO: Use linear depth
  31883. if ( this.shadowMap.texture.isCubeTexture ) {
  31884. return cubeTexture( this.shadowMap.texture ).r.oneMinus();
  31885. }
  31886. return textureLoad( this.shadowMap.depthTexture, uv$1().mul( textureSize( texture( this.shadowMap.depthTexture ) ) ) ).r.oneMinus();
  31887. } );
  31888. }
  31889. /**
  31890. * The implementation performs the setup of the output node. An output is only
  31891. * produces if shadow mapping is globally enabled in the renderer.
  31892. *
  31893. * @param {NodeBuilder} builder - A reference to the current node builder.
  31894. * @return {ShaderCallNodeInternal} The output node.
  31895. */
  31896. setup( builder ) {
  31897. if ( builder.renderer.shadowMap.enabled === false ) return;
  31898. return Fn( () => {
  31899. const currentShadowType = builder.renderer.shadowMap.type;
  31900. if ( this._currentShadowType !== currentShadowType ) {
  31901. this._reset();
  31902. this._node = null;
  31903. }
  31904. let node = this._node;
  31905. this.setupShadowPosition( builder );
  31906. if ( node === null ) {
  31907. this._node = node = this.setupShadow( builder );
  31908. this._currentShadowType = currentShadowType;
  31909. }
  31910. if ( builder.material.receivedShadowNode ) {
  31911. node = builder.material.receivedShadowNode( node );
  31912. }
  31913. return node;
  31914. } )();
  31915. }
  31916. /**
  31917. * Renders the shadow. The logic of this function could be included
  31918. * into {@link ShadowNode#updateShadow} however more specialized shadow
  31919. * nodes might require a custom shadow map rendering. By having a
  31920. * dedicated method, it's easier to overwrite the default behavior.
  31921. *
  31922. * @param {NodeFrame} frame - A reference to the current node frame.
  31923. */
  31924. renderShadow( frame ) {
  31925. const { shadow, shadowMap, light } = this;
  31926. const { renderer, scene } = frame;
  31927. shadow.updateMatrices( light );
  31928. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  31929. const currentSceneName = scene.name;
  31930. scene.name = `Shadow Map [ ${ light.name || 'ID: ' + light.id } ]`;
  31931. renderer.render( scene, shadow.camera );
  31932. scene.name = currentSceneName;
  31933. }
  31934. /**
  31935. * Updates the shadow.
  31936. *
  31937. * @param {NodeFrame} frame - A reference to the current node frame.
  31938. */
  31939. updateShadow( frame ) {
  31940. const { shadowMap, light, shadow } = this;
  31941. const { renderer, scene, camera } = frame;
  31942. const shadowType = renderer.shadowMap.type;
  31943. const depthVersion = shadowMap.depthTexture.version;
  31944. this._depthVersionCached = depthVersion;
  31945. const _shadowCameraLayer = shadow.camera.layers.mask;
  31946. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  31947. shadow.camera.layers.mask = camera.layers.mask;
  31948. }
  31949. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  31950. const currentMRT = renderer.getMRT();
  31951. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  31952. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  31953. scene.overrideMaterial = getShadowMaterial( light );
  31954. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  31955. renderer.setClearColor( 0x000000, 0 );
  31956. renderer.setRenderTarget( shadowMap );
  31957. this.renderShadow( frame );
  31958. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  31959. // vsm blur pass
  31960. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  31961. this.vsmPass( renderer );
  31962. }
  31963. shadow.camera.layers.mask = _shadowCameraLayer;
  31964. restoreRendererAndSceneState( renderer, scene, _rendererState );
  31965. }
  31966. /**
  31967. * For VSM additional render passes are required.
  31968. *
  31969. * @param {Renderer} renderer - A reference to the current renderer.
  31970. */
  31971. vsmPass( renderer ) {
  31972. const { shadow } = this;
  31973. const depth = this.shadowMap.depth;
  31974. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  31975. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  31976. renderer.setRenderTarget( this.vsmShadowMapVertical );
  31977. _quadMesh.material = this.vsmMaterialVertical;
  31978. _quadMesh.render( renderer );
  31979. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  31980. _quadMesh.material = this.vsmMaterialHorizontal;
  31981. _quadMesh.render( renderer );
  31982. }
  31983. /**
  31984. * Frees the internal resources of this shadow node.
  31985. */
  31986. dispose() {
  31987. this._reset();
  31988. super.dispose();
  31989. }
  31990. /**
  31991. * Resets the resouce state of this shadow node.
  31992. *
  31993. * @private
  31994. */
  31995. _reset() {
  31996. this._currentShadowType = null;
  31997. disposeShadowMaterial( this.light );
  31998. if ( this.shadowMap ) {
  31999. this.shadowMap.dispose();
  32000. this.shadowMap = null;
  32001. }
  32002. if ( this.vsmShadowMapVertical !== null ) {
  32003. this.vsmShadowMapVertical.dispose();
  32004. this.vsmShadowMapVertical = null;
  32005. this.vsmMaterialVertical.dispose();
  32006. this.vsmMaterialVertical = null;
  32007. }
  32008. if ( this.vsmShadowMapHorizontal !== null ) {
  32009. this.vsmShadowMapHorizontal.dispose();
  32010. this.vsmShadowMapHorizontal = null;
  32011. this.vsmMaterialHorizontal.dispose();
  32012. this.vsmMaterialHorizontal = null;
  32013. }
  32014. }
  32015. /**
  32016. * The implementation performs the update of the shadow map if necessary.
  32017. *
  32018. * @param {NodeFrame} frame - A reference to the current node frame.
  32019. */
  32020. updateBefore( frame ) {
  32021. const { shadow } = this;
  32022. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  32023. if ( needsUpdate ) {
  32024. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  32025. needsUpdate = false;
  32026. }
  32027. this._cameraFrameId[ frame.camera ] = frame.frameId;
  32028. }
  32029. if ( needsUpdate ) {
  32030. this.updateShadow( frame );
  32031. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  32032. shadow.needsUpdate = false;
  32033. }
  32034. }
  32035. }
  32036. }
  32037. /**
  32038. * Shadow Render Object Function.
  32039. *
  32040. * @function shadowRenderObjectFunction
  32041. * @param {Object3D} object - The 3D object to render.
  32042. * @param {Scene} scene - The scene containing the object.
  32043. * @param {Camera} _camera - The camera used for rendering.
  32044. * @param {BufferGeometry} geometry - The geometry of the object.
  32045. * @param {Material} material - The material of the object.
  32046. * @param {Group} group - The group the object belongs to.
  32047. * @param {...any} params - Additional parameters for rendering.
  32048. */
  32049. /**
  32050. * TSL function for creating an instance of `ShadowNode`.
  32051. *
  32052. * @tsl
  32053. * @function
  32054. * @param {Light} light - The shadow casting light.
  32055. * @param {?LightShadow} [shadow] - The light shadow.
  32056. * @return {ShadowNode} The created shadow node.
  32057. */
  32058. const shadow = ( light, shadow ) => new ShadowNode( light, shadow );
  32059. const _clearColor$1 = /*@__PURE__*/ new Color();
  32060. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  32061. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  32062. const _lookTarget = /*@__PURE__*/ new Vector3();
  32063. // Cube map face directions and up vectors for point light shadows
  32064. // Face order: +X, -X, +Y, -Y, +Z, -Z
  32065. // WebGPU coordinate system - Y faces swapped to match texture sampling convention
  32066. const _cubeDirectionsWebGPU = [
  32067. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ),
  32068. /*@__PURE__*/ new Vector3( 0, 1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  32069. ];
  32070. const _cubeUpsWebGPU = [
  32071. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, -1 ),
  32072. /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  32073. ];
  32074. // WebGL coordinate system - standard OpenGL convention
  32075. const _cubeDirectionsWebGL = [
  32076. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, 1, 0 ),
  32077. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  32078. ];
  32079. const _cubeUpsWebGL = [
  32080. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ),
  32081. /*@__PURE__*/ new Vector3( 0, 0, -1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  32082. ];
  32083. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp } ) => {
  32084. return cubeTexture( depthTexture, bd3D ).compare( dp );
  32085. } );
  32086. /**
  32087. * A shadow filtering function for point lights using Vogel disk sampling and IGN.
  32088. *
  32089. * Uses 5 samples distributed via Vogel disk pattern in tangent space around the
  32090. * sample direction, rotated per-pixel using Interleaved Gradient Noise (IGN).
  32091. *
  32092. * @method
  32093. * @param {Object} inputs - The input parameter object.
  32094. * @param {CubeDepthTexture} inputs.depthTexture - A reference to the shadow cube map.
  32095. * @param {Node<vec3>} inputs.bd3D - The normalized direction from light to fragment.
  32096. * @param {Node<float>} inputs.dp - The depth value to compare against.
  32097. * @param {LightShadow} inputs.shadow - The light shadow.
  32098. * @return {Node<float>} The filtering result.
  32099. */
  32100. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, shadow } ) => {
  32101. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  32102. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  32103. const texelSize = radius.div( mapSize.x );
  32104. // Build a tangent-space coordinate system for applying offsets
  32105. const absDir = abs( bd3D );
  32106. const tangent = normalize( cross( bd3D, absDir.x.greaterThan( absDir.z ).select( vec3( 0, 1, 0 ), vec3( 1, 0, 0 ) ) ) );
  32107. const bitangent = cross( bd3D, tangent );
  32108. // Use IGN to rotate sampling pattern per pixel (phi = IGN * 2π)
  32109. const phi = interleavedGradientNoise( screenCoordinate.xy ).mul( 6.28318530718 );
  32110. // 5 samples using Vogel disk distribution in tangent space
  32111. const sample0 = vogelDiskSample( 0, 5, phi );
  32112. const sample1 = vogelDiskSample( 1, 5, phi );
  32113. const sample2 = vogelDiskSample( 2, 5, phi );
  32114. const sample3 = vogelDiskSample( 3, 5, phi );
  32115. const sample4 = vogelDiskSample( 4, 5, phi );
  32116. return cubeTexture( depthTexture, bd3D.add( tangent.mul( sample0.x ).add( bitangent.mul( sample0.y ) ).mul( texelSize ) ) ).compare( dp )
  32117. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample1.x ).add( bitangent.mul( sample1.y ) ).mul( texelSize ) ) ).compare( dp ) )
  32118. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample2.x ).add( bitangent.mul( sample2.y ) ).mul( texelSize ) ) ).compare( dp ) )
  32119. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample3.x ).add( bitangent.mul( sample3.y ) ).mul( texelSize ) ) ).compare( dp ) )
  32120. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample4.x ).add( bitangent.mul( sample4.y ) ).mul( texelSize ) ) ).compare( dp ) )
  32121. .mul( 1.0 / 5.0 );
  32122. } );
  32123. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow }, builder ) => {
  32124. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  32125. // the vector from the light to the world-space position of the fragment.
  32126. const shadowPosition = shadowCoord.xyz.toConst();
  32127. const shadowPositionAbs = shadowPosition.abs().toConst();
  32128. const viewZ = shadowPositionAbs.x.max( shadowPositionAbs.y ).max( shadowPositionAbs.z );
  32129. const shadowCameraNear = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  32130. const shadowCameraFar = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  32131. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  32132. const result = float( 1.0 ).toVar();
  32133. If( viewZ.sub( shadowCameraFar ).lessThanEqual( 0.0 ).and( viewZ.sub( shadowCameraNear ).greaterThanEqual( 0.0 ) ), () => {
  32134. let dp;
  32135. if ( builder.renderer.reversedDepthBuffer ) {
  32136. dp = viewZToReversedPerspectiveDepth( viewZ.negate(), shadowCameraNear, shadowCameraFar );
  32137. dp.subAssign( bias );
  32138. } else {
  32139. dp = viewZToPerspectiveDepth( viewZ.negate(), shadowCameraNear, shadowCameraFar );
  32140. dp.addAssign( bias );
  32141. }
  32142. // bd3D = base direction 3D (direction from light to fragment)
  32143. const bd3D = shadowPosition.normalize();
  32144. // percentage-closer filtering using cube texture sampling
  32145. result.assign( filterFn( { depthTexture, bd3D, dp, shadow } ) );
  32146. } );
  32147. return result;
  32148. } );
  32149. /**
  32150. * Represents the shadow implementation for point light nodes.
  32151. *
  32152. * @augments ShadowNode
  32153. */
  32154. class PointShadowNode extends ShadowNode {
  32155. static get type() {
  32156. return 'PointShadowNode';
  32157. }
  32158. /**
  32159. * Constructs a new point shadow node.
  32160. *
  32161. * @param {PointLight} light - The shadow casting point light.
  32162. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  32163. */
  32164. constructor( light, shadow = null ) {
  32165. super( light, shadow );
  32166. }
  32167. /**
  32168. * Overwrites the default implementation to return point light shadow specific
  32169. * filtering functions.
  32170. *
  32171. * @param {number} type - The shadow type.
  32172. * @return {Function} The filtering function.
  32173. */
  32174. getShadowFilterFn( type ) {
  32175. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  32176. }
  32177. /**
  32178. * Overwrites the default implementation so the unaltered shadow position is used.
  32179. *
  32180. * @param {NodeBuilder} builder - A reference to the current node builder.
  32181. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  32182. * @return {Node<vec3>} The shadow coordinates.
  32183. */
  32184. setupShadowCoord( builder, shadowPosition ) {
  32185. return shadowPosition;
  32186. }
  32187. /**
  32188. * Overwrites the default implementation to only use point light specific
  32189. * shadow filter functions.
  32190. *
  32191. * @param {NodeBuilder} builder - A reference to the current node builder.
  32192. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  32193. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  32194. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's depth texture.
  32195. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  32196. * @param {LightShadow} inputs.shadow - The light shadow.
  32197. * @return {Node<float>} The result node of the shadow filtering.
  32198. */
  32199. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  32200. return pointShadowFilter( { filterFn, depthTexture, shadowCoord, shadow } );
  32201. }
  32202. /**
  32203. * Overwrites the default implementation to create a CubeRenderTarget with CubeDepthTexture.
  32204. *
  32205. * @param {LightShadow} shadow - The light shadow object.
  32206. * @param {NodeBuilder} builder - A reference to the current node builder.
  32207. * @return {Object} An object containing the shadow map and depth texture.
  32208. */
  32209. setupRenderTarget( shadow, builder ) {
  32210. const depthTexture = new CubeDepthTexture( shadow.mapSize.width );
  32211. depthTexture.name = 'PointShadowDepthTexture';
  32212. depthTexture.compareFunction = builder.renderer.reversedDepthBuffer ? GreaterEqualCompare : LessEqualCompare;
  32213. const shadowMap = builder.createCubeRenderTarget( shadow.mapSize.width );
  32214. shadowMap.texture.name = 'PointShadowMap';
  32215. shadowMap.depthTexture = depthTexture;
  32216. return { shadowMap, depthTexture };
  32217. }
  32218. /**
  32219. * Overwrites the default implementation with point light specific
  32220. * rendering code.
  32221. *
  32222. * @param {NodeFrame} frame - A reference to the current node frame.
  32223. */
  32224. renderShadow( frame ) {
  32225. const { shadow, shadowMap, light } = this;
  32226. const { renderer, scene } = frame;
  32227. const camera = shadow.camera;
  32228. const shadowMatrix = shadow.matrix;
  32229. // Select cube directions/ups based on coordinate system
  32230. const isWebGPU = renderer.coordinateSystem === WebGPUCoordinateSystem;
  32231. const cubeDirections = isWebGPU ? _cubeDirectionsWebGPU : _cubeDirectionsWebGL;
  32232. const cubeUps = isWebGPU ? _cubeUpsWebGPU : _cubeUpsWebGL;
  32233. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.width );
  32234. //
  32235. const previousAutoClear = renderer.autoClear;
  32236. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  32237. const previousClearAlpha = renderer.getClearAlpha();
  32238. renderer.autoClear = false;
  32239. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  32240. // Render each cube face
  32241. for ( let face = 0; face < 6; face ++ ) {
  32242. // Set render target to the specific cube face
  32243. renderer.setRenderTarget( shadowMap, face );
  32244. renderer.clear();
  32245. // Update shadow camera matrices for this face
  32246. const far = light.distance || camera.far;
  32247. if ( far !== camera.far ) {
  32248. camera.far = far;
  32249. camera.updateProjectionMatrix();
  32250. }
  32251. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  32252. camera.position.copy( _lightPositionWorld );
  32253. _lookTarget.copy( camera.position );
  32254. _lookTarget.add( cubeDirections[ face ] );
  32255. camera.up.copy( cubeUps[ face ] );
  32256. camera.lookAt( _lookTarget );
  32257. camera.updateMatrixWorld();
  32258. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  32259. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  32260. shadow._frustum.setFromProjectionMatrix( _projScreenMatrix$1, camera.coordinateSystem, camera.reversedDepth );
  32261. //
  32262. const currentSceneName = scene.name;
  32263. scene.name = `Point Light Shadow [ ${ light.name || 'ID: ' + light.id } ] - Face ${ face + 1 }`;
  32264. renderer.render( scene, camera );
  32265. scene.name = currentSceneName;
  32266. }
  32267. //
  32268. renderer.autoClear = previousAutoClear;
  32269. renderer.setClearColor( previousClearColor, previousClearAlpha );
  32270. }
  32271. }
  32272. /**
  32273. * TSL function for creating an instance of `PointShadowNode`.
  32274. *
  32275. * @tsl
  32276. * @function
  32277. * @param {PointLight} light - The shadow casting point light.
  32278. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  32279. * @return {PointShadowNode} The created point shadow node.
  32280. */
  32281. const pointShadow = ( light, shadow ) => new PointShadowNode( light, shadow );
  32282. /**
  32283. * Base class for analytic light nodes.
  32284. *
  32285. * @augments LightingNode
  32286. */
  32287. class AnalyticLightNode extends LightingNode {
  32288. static get type() {
  32289. return 'AnalyticLightNode';
  32290. }
  32291. /**
  32292. * Constructs a new analytic light node.
  32293. *
  32294. * @param {?Light} [light=null] - The light source.
  32295. */
  32296. constructor( light = null ) {
  32297. super();
  32298. /**
  32299. * The light source.
  32300. *
  32301. * @type {?Light}
  32302. * @default null
  32303. */
  32304. this.light = light;
  32305. /**
  32306. * The light's color value.
  32307. *
  32308. * @type {Color}
  32309. */
  32310. this.color = new Color();
  32311. /**
  32312. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  32313. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  32314. *
  32315. * @type {Node}
  32316. */
  32317. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  32318. /**
  32319. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  32320. * The final color node is represented by a different node when using shadows.
  32321. *
  32322. * @type {?Node}
  32323. * @default null
  32324. */
  32325. this.baseColorNode = null;
  32326. /**
  32327. * Represents the light's shadow.
  32328. *
  32329. * @type {?ShadowNode}
  32330. * @default null
  32331. */
  32332. this.shadowNode = null;
  32333. /**
  32334. * Represents the light's shadow color.
  32335. *
  32336. * @type {?Node}
  32337. * @default null
  32338. */
  32339. this.shadowColorNode = null;
  32340. /**
  32341. * This flag can be used for type testing.
  32342. *
  32343. * @type {boolean}
  32344. * @readonly
  32345. * @default true
  32346. */
  32347. this.isAnalyticLightNode = true;
  32348. /**
  32349. * Overwritten since analytic light nodes are updated
  32350. * once per frame.
  32351. *
  32352. * @type {string}
  32353. * @default 'frame'
  32354. */
  32355. this.updateType = NodeUpdateType.FRAME;
  32356. if ( light && light.shadow ) {
  32357. this._shadowDisposeListener = () => {
  32358. this.disposeShadow();
  32359. };
  32360. light.addEventListener( 'dispose', this._shadowDisposeListener );
  32361. }
  32362. }
  32363. dispose() {
  32364. if ( this._shadowDisposeListener ) {
  32365. this.light.removeEventListener( 'dispose', this._shadowDisposeListener );
  32366. }
  32367. super.dispose();
  32368. }
  32369. /**
  32370. * Frees internal resources related to shadows.
  32371. */
  32372. disposeShadow() {
  32373. if ( this.shadowNode !== null ) {
  32374. this.shadowNode.dispose();
  32375. this.shadowNode = null;
  32376. }
  32377. this.shadowColorNode = null;
  32378. if ( this.baseColorNode !== null ) {
  32379. this.colorNode = this.baseColorNode;
  32380. this.baseColorNode = null;
  32381. }
  32382. }
  32383. getHash() {
  32384. return this.light.uuid;
  32385. }
  32386. /**
  32387. * Returns a node representing a direction vector which points from the current
  32388. * position in view space to the light's position in view space.
  32389. *
  32390. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  32391. * @return {Node<vec3>} The light vector node.
  32392. */
  32393. getLightVector( builder ) {
  32394. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  32395. }
  32396. /**
  32397. * Sets up the direct lighting for the analytic light node.
  32398. *
  32399. * @abstract
  32400. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  32401. * @return {Object|undefined} The direct light data (color and direction).
  32402. */
  32403. setupDirect( /*builder*/ ) { }
  32404. /**
  32405. * Sets up the direct rect area lighting for the analytic light node.
  32406. *
  32407. * @abstract
  32408. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  32409. * @return {Object|undefined} The direct rect area light data.
  32410. */
  32411. setupDirectRectArea( /*builder*/ ) { }
  32412. /**
  32413. * Setups the shadow node for this light. The method exists so concrete light classes
  32414. * can setup different types of shadow nodes.
  32415. *
  32416. * @return {ShadowNode} The created shadow node.
  32417. */
  32418. setupShadowNode() {
  32419. return shadow( this.light );
  32420. }
  32421. /**
  32422. * Setups the shadow for this light. This method is only executed if the light
  32423. * cast shadows and the current build object receives shadows. It incorporates
  32424. * shadows into the lighting computation.
  32425. *
  32426. * @param {NodeBuilder} builder - The current node builder.
  32427. */
  32428. setupShadow( builder ) {
  32429. const { renderer } = builder;
  32430. if ( renderer.shadowMap.enabled === false ) return;
  32431. let shadowColorNode = this.shadowColorNode;
  32432. if ( shadowColorNode === null ) {
  32433. const customShadowNode = this.light.shadow.shadowNode;
  32434. let shadowNode;
  32435. if ( customShadowNode !== undefined ) {
  32436. shadowNode = nodeObject( customShadowNode );
  32437. } else {
  32438. shadowNode = this.setupShadowNode();
  32439. }
  32440. this.shadowNode = shadowNode;
  32441. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  32442. this.baseColorNode = this.colorNode;
  32443. }
  32444. //
  32445. if ( builder.context.getShadow ) {
  32446. shadowColorNode = builder.context.getShadow( this, builder );
  32447. }
  32448. this.colorNode = shadowColorNode;
  32449. }
  32450. /**
  32451. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  32452. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  32453. * invocate the respective interface methods.
  32454. *
  32455. * @param {NodeBuilder} builder - The current node builder.
  32456. */
  32457. setup( builder ) {
  32458. this.colorNode = this.baseColorNode || this.colorNode;
  32459. if ( this.light.castShadow ) {
  32460. if ( builder.object.receiveShadow ) {
  32461. this.setupShadow( builder );
  32462. }
  32463. } else if ( this.shadowNode !== null ) {
  32464. this.shadowNode.dispose();
  32465. this.shadowNode = null;
  32466. this.shadowColorNode = null;
  32467. }
  32468. const directLightData = this.setupDirect( builder );
  32469. const directRectAreaLightData = this.setupDirectRectArea( builder );
  32470. if ( directLightData ) {
  32471. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  32472. }
  32473. if ( directRectAreaLightData ) {
  32474. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  32475. }
  32476. }
  32477. /**
  32478. * The update method is used to update light uniforms per frame.
  32479. * Potentially overwritten in concrete light nodes to update light
  32480. * specific uniforms.
  32481. *
  32482. * @param {NodeFrame} frame - A reference to the current node frame.
  32483. */
  32484. update( /*frame*/ ) {
  32485. const { light } = this;
  32486. this.color.copy( light.color ).multiplyScalar( light.intensity );
  32487. }
  32488. }
  32489. /**
  32490. * Represents a `discard` shader operation in TSL.
  32491. *
  32492. * @method
  32493. * @param {Object} inputs - The input parameter object.
  32494. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  32495. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  32496. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  32497. * @return {Node<float>} The distance falloff.
  32498. */
  32499. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  32500. // based upon Frostbite 3 Moving to Physically-based Rendering
  32501. // page 32, equation 26: E[window1]
  32502. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  32503. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  32504. return cutoffDistance.greaterThan( 0 ).select(
  32505. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  32506. distanceFalloff
  32507. );
  32508. } ); // validated
  32509. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  32510. const lightDirection = lightVector.normalize();
  32511. const lightDistance = lightVector.length();
  32512. const attenuation = getDistanceAttenuation( {
  32513. lightDistance,
  32514. cutoffDistance,
  32515. decayExponent
  32516. } );
  32517. const lightColor = color.mul( attenuation );
  32518. return { lightDirection, lightColor };
  32519. };
  32520. /**
  32521. * Module for representing point lights as nodes.
  32522. *
  32523. * @augments AnalyticLightNode
  32524. */
  32525. class PointLightNode extends AnalyticLightNode {
  32526. static get type() {
  32527. return 'PointLightNode';
  32528. }
  32529. /**
  32530. * Constructs a new point light node.
  32531. *
  32532. * @param {?PointLight} [light=null] - The point light source.
  32533. */
  32534. constructor( light = null ) {
  32535. super( light );
  32536. /**
  32537. * Uniform node representing the cutoff distance.
  32538. *
  32539. * @type {UniformNode<float>}
  32540. */
  32541. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  32542. /**
  32543. * Uniform node representing the decay exponent.
  32544. *
  32545. * @type {UniformNode<float>}
  32546. */
  32547. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  32548. }
  32549. /**
  32550. * Overwritten to updated point light specific uniforms.
  32551. *
  32552. * @param {NodeFrame} frame - A reference to the current node frame.
  32553. */
  32554. update( frame ) {
  32555. const { light } = this;
  32556. super.update( frame );
  32557. this.cutoffDistanceNode.value = light.distance;
  32558. this.decayExponentNode.value = light.decay;
  32559. }
  32560. /**
  32561. * Overwritten to setup point light specific shadow.
  32562. *
  32563. * @return {PointShadowNode}
  32564. */
  32565. setupShadowNode() {
  32566. return pointShadow( this.light );
  32567. }
  32568. setupDirect( builder ) {
  32569. return directPointLight( {
  32570. color: this.colorNode,
  32571. lightVector: this.getLightVector( builder ),
  32572. cutoffDistance: this.cutoffDistanceNode,
  32573. decayExponent: this.decayExponentNode
  32574. } );
  32575. }
  32576. }
  32577. /**
  32578. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  32579. *
  32580. * @tsl
  32581. * @function
  32582. * @param {Node<vec2>} coord - The uv coordinates.
  32583. * @return {Node<float>} The result data.
  32584. */
  32585. const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => {
  32586. const uv = coord.mul( 2.0 );
  32587. const cx = uv.x.floor();
  32588. const cy = uv.y.floor();
  32589. const result = cx.add( cy ).mod( 2.0 );
  32590. return result.sign();
  32591. } );
  32592. /**
  32593. * Generates a circle based on the uv coordinates.
  32594. *
  32595. * @tsl
  32596. * @function
  32597. * @param {Node<vec2>} coord - The uv to generate the circle.
  32598. * @return {Node<float>} The circle shape.
  32599. */
  32600. const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => {
  32601. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  32602. let alpha;
  32603. if ( material.alphaToCoverage && renderer.currentSamples > 0 ) {
  32604. const dlen = float( len2.fwidth() ).toVar();
  32605. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  32606. } else {
  32607. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  32608. }
  32609. return alpha;
  32610. } );
  32611. // Three.js Transpiler
  32612. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  32613. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  32614. const f = float( f_immutable ).toVar();
  32615. const t = float( t_immutable ).toVar();
  32616. const b = bool( b_immutable ).toVar();
  32617. return select( b, t, f );
  32618. } ).setLayout( {
  32619. name: 'mx_select',
  32620. type: 'float',
  32621. inputs: [
  32622. { name: 'b', type: 'bool' },
  32623. { name: 't', type: 'float' },
  32624. { name: 'f', type: 'float' }
  32625. ]
  32626. } );
  32627. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  32628. const b = bool( b_immutable ).toVar();
  32629. const val = float( val_immutable ).toVar();
  32630. return select( b, val.negate(), val );
  32631. } ).setLayout( {
  32632. name: 'mx_negate_if',
  32633. type: 'float',
  32634. inputs: [
  32635. { name: 'val', type: 'float' },
  32636. { name: 'b', type: 'bool' }
  32637. ]
  32638. } );
  32639. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  32640. const x = float( x_immutable ).toVar();
  32641. return int( floor( x ) );
  32642. } ).setLayout( {
  32643. name: 'mx_floor',
  32644. type: 'int',
  32645. inputs: [
  32646. { name: 'x', type: 'float' }
  32647. ]
  32648. } );
  32649. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  32650. const x = float( x_immutable ).toVar();
  32651. i.assign( mx_floor( x ) );
  32652. return x.sub( float( i ) );
  32653. } );
  32654. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  32655. const t = float( t_immutable ).toVar();
  32656. const s = float( s_immutable ).toVar();
  32657. const v3 = float( v3_immutable ).toVar();
  32658. const v2 = float( v2_immutable ).toVar();
  32659. const v1 = float( v1_immutable ).toVar();
  32660. const v0 = float( v0_immutable ).toVar();
  32661. const s1 = float( sub( 1.0, s ) ).toVar();
  32662. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  32663. } ).setLayout( {
  32664. name: 'mx_bilerp_0',
  32665. type: 'float',
  32666. inputs: [
  32667. { name: 'v0', type: 'float' },
  32668. { name: 'v1', type: 'float' },
  32669. { name: 'v2', type: 'float' },
  32670. { name: 'v3', type: 'float' },
  32671. { name: 's', type: 'float' },
  32672. { name: 't', type: 'float' }
  32673. ]
  32674. } );
  32675. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  32676. const t = float( t_immutable ).toVar();
  32677. const s = float( s_immutable ).toVar();
  32678. const v3 = vec3( v3_immutable ).toVar();
  32679. const v2 = vec3( v2_immutable ).toVar();
  32680. const v1 = vec3( v1_immutable ).toVar();
  32681. const v0 = vec3( v0_immutable ).toVar();
  32682. const s1 = float( sub( 1.0, s ) ).toVar();
  32683. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  32684. } ).setLayout( {
  32685. name: 'mx_bilerp_1',
  32686. type: 'vec3',
  32687. inputs: [
  32688. { name: 'v0', type: 'vec3' },
  32689. { name: 'v1', type: 'vec3' },
  32690. { name: 'v2', type: 'vec3' },
  32691. { name: 'v3', type: 'vec3' },
  32692. { name: 's', type: 'float' },
  32693. { name: 't', type: 'float' }
  32694. ]
  32695. } );
  32696. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  32697. 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 ] ) => {
  32698. const r = float( r_immutable ).toVar();
  32699. const t = float( t_immutable ).toVar();
  32700. const s = float( s_immutable ).toVar();
  32701. const v7 = float( v7_immutable ).toVar();
  32702. const v6 = float( v6_immutable ).toVar();
  32703. const v5 = float( v5_immutable ).toVar();
  32704. const v4 = float( v4_immutable ).toVar();
  32705. const v3 = float( v3_immutable ).toVar();
  32706. const v2 = float( v2_immutable ).toVar();
  32707. const v1 = float( v1_immutable ).toVar();
  32708. const v0 = float( v0_immutable ).toVar();
  32709. const s1 = float( sub( 1.0, s ) ).toVar();
  32710. const t1 = float( sub( 1.0, t ) ).toVar();
  32711. const r1 = float( sub( 1.0, r ) ).toVar();
  32712. 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 ) ) ) ) ) );
  32713. } ).setLayout( {
  32714. name: 'mx_trilerp_0',
  32715. type: 'float',
  32716. inputs: [
  32717. { name: 'v0', type: 'float' },
  32718. { name: 'v1', type: 'float' },
  32719. { name: 'v2', type: 'float' },
  32720. { name: 'v3', type: 'float' },
  32721. { name: 'v4', type: 'float' },
  32722. { name: 'v5', type: 'float' },
  32723. { name: 'v6', type: 'float' },
  32724. { name: 'v7', type: 'float' },
  32725. { name: 's', type: 'float' },
  32726. { name: 't', type: 'float' },
  32727. { name: 'r', type: 'float' }
  32728. ]
  32729. } );
  32730. 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 ] ) => {
  32731. const r = float( r_immutable ).toVar();
  32732. const t = float( t_immutable ).toVar();
  32733. const s = float( s_immutable ).toVar();
  32734. const v7 = vec3( v7_immutable ).toVar();
  32735. const v6 = vec3( v6_immutable ).toVar();
  32736. const v5 = vec3( v5_immutable ).toVar();
  32737. const v4 = vec3( v4_immutable ).toVar();
  32738. const v3 = vec3( v3_immutable ).toVar();
  32739. const v2 = vec3( v2_immutable ).toVar();
  32740. const v1 = vec3( v1_immutable ).toVar();
  32741. const v0 = vec3( v0_immutable ).toVar();
  32742. const s1 = float( sub( 1.0, s ) ).toVar();
  32743. const t1 = float( sub( 1.0, t ) ).toVar();
  32744. const r1 = float( sub( 1.0, r ) ).toVar();
  32745. 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 ) ) ) ) ) );
  32746. } ).setLayout( {
  32747. name: 'mx_trilerp_1',
  32748. type: 'vec3',
  32749. inputs: [
  32750. { name: 'v0', type: 'vec3' },
  32751. { name: 'v1', type: 'vec3' },
  32752. { name: 'v2', type: 'vec3' },
  32753. { name: 'v3', type: 'vec3' },
  32754. { name: 'v4', type: 'vec3' },
  32755. { name: 'v5', type: 'vec3' },
  32756. { name: 'v6', type: 'vec3' },
  32757. { name: 'v7', type: 'vec3' },
  32758. { name: 's', type: 'float' },
  32759. { name: 't', type: 'float' },
  32760. { name: 'r', type: 'float' }
  32761. ]
  32762. } );
  32763. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  32764. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  32765. const y = float( y_immutable ).toVar();
  32766. const x = float( x_immutable ).toVar();
  32767. const hash = uint( hash_immutable ).toVar();
  32768. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  32769. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  32770. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  32771. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  32772. } ).setLayout( {
  32773. name: 'mx_gradient_float_0',
  32774. type: 'float',
  32775. inputs: [
  32776. { name: 'hash', type: 'uint' },
  32777. { name: 'x', type: 'float' },
  32778. { name: 'y', type: 'float' }
  32779. ]
  32780. } );
  32781. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  32782. const z = float( z_immutable ).toVar();
  32783. const y = float( y_immutable ).toVar();
  32784. const x = float( x_immutable ).toVar();
  32785. const hash = uint( hash_immutable ).toVar();
  32786. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  32787. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  32788. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  32789. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  32790. } ).setLayout( {
  32791. name: 'mx_gradient_float_1',
  32792. type: 'float',
  32793. inputs: [
  32794. { name: 'hash', type: 'uint' },
  32795. { name: 'x', type: 'float' },
  32796. { name: 'y', type: 'float' },
  32797. { name: 'z', type: 'float' }
  32798. ]
  32799. } );
  32800. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  32801. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  32802. const y = float( y_immutable ).toVar();
  32803. const x = float( x_immutable ).toVar();
  32804. const hash = uvec3( hash_immutable ).toVar();
  32805. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  32806. } ).setLayout( {
  32807. name: 'mx_gradient_vec3_0',
  32808. type: 'vec3',
  32809. inputs: [
  32810. { name: 'hash', type: 'uvec3' },
  32811. { name: 'x', type: 'float' },
  32812. { name: 'y', type: 'float' }
  32813. ]
  32814. } );
  32815. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  32816. const z = float( z_immutable ).toVar();
  32817. const y = float( y_immutable ).toVar();
  32818. const x = float( x_immutable ).toVar();
  32819. const hash = uvec3( hash_immutable ).toVar();
  32820. 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 ) );
  32821. } ).setLayout( {
  32822. name: 'mx_gradient_vec3_1',
  32823. type: 'vec3',
  32824. inputs: [
  32825. { name: 'hash', type: 'uvec3' },
  32826. { name: 'x', type: 'float' },
  32827. { name: 'y', type: 'float' },
  32828. { name: 'z', type: 'float' }
  32829. ]
  32830. } );
  32831. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  32832. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32833. const v = float( v_immutable ).toVar();
  32834. return mul( 0.6616, v );
  32835. } ).setLayout( {
  32836. name: 'mx_gradient_scale2d_0',
  32837. type: 'float',
  32838. inputs: [
  32839. { name: 'v', type: 'float' }
  32840. ]
  32841. } );
  32842. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32843. const v = float( v_immutable ).toVar();
  32844. return mul( 0.9820, v );
  32845. } ).setLayout( {
  32846. name: 'mx_gradient_scale3d_0',
  32847. type: 'float',
  32848. inputs: [
  32849. { name: 'v', type: 'float' }
  32850. ]
  32851. } );
  32852. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32853. const v = vec3( v_immutable ).toVar();
  32854. return mul( 0.6616, v );
  32855. } ).setLayout( {
  32856. name: 'mx_gradient_scale2d_1',
  32857. type: 'vec3',
  32858. inputs: [
  32859. { name: 'v', type: 'vec3' }
  32860. ]
  32861. } );
  32862. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  32863. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32864. const v = vec3( v_immutable ).toVar();
  32865. return mul( 0.9820, v );
  32866. } ).setLayout( {
  32867. name: 'mx_gradient_scale3d_1',
  32868. type: 'vec3',
  32869. inputs: [
  32870. { name: 'v', type: 'vec3' }
  32871. ]
  32872. } );
  32873. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  32874. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  32875. const k = int( k_immutable ).toVar();
  32876. const x = uint( x_immutable ).toVar();
  32877. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  32878. } ).setLayout( {
  32879. name: 'mx_rotl32',
  32880. type: 'uint',
  32881. inputs: [
  32882. { name: 'x', type: 'uint' },
  32883. { name: 'k', type: 'int' }
  32884. ]
  32885. } );
  32886. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  32887. a.subAssign( c );
  32888. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  32889. c.addAssign( b );
  32890. b.subAssign( a );
  32891. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  32892. a.addAssign( c );
  32893. c.subAssign( b );
  32894. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  32895. b.addAssign( a );
  32896. a.subAssign( c );
  32897. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  32898. c.addAssign( b );
  32899. b.subAssign( a );
  32900. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  32901. a.addAssign( c );
  32902. c.subAssign( b );
  32903. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  32904. b.addAssign( a );
  32905. } );
  32906. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  32907. const c = uint( c_immutable ).toVar();
  32908. const b = uint( b_immutable ).toVar();
  32909. const a = uint( a_immutable ).toVar();
  32910. c.bitXorAssign( b );
  32911. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  32912. a.bitXorAssign( c );
  32913. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  32914. b.bitXorAssign( a );
  32915. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  32916. c.bitXorAssign( b );
  32917. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  32918. a.bitXorAssign( c );
  32919. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  32920. b.bitXorAssign( a );
  32921. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  32922. c.bitXorAssign( b );
  32923. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  32924. return c;
  32925. } ).setLayout( {
  32926. name: 'mx_bjfinal',
  32927. type: 'uint',
  32928. inputs: [
  32929. { name: 'a', type: 'uint' },
  32930. { name: 'b', type: 'uint' },
  32931. { name: 'c', type: 'uint' }
  32932. ]
  32933. } );
  32934. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  32935. const bits = uint( bits_immutable ).toVar();
  32936. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  32937. } ).setLayout( {
  32938. name: 'mx_bits_to_01',
  32939. type: 'float',
  32940. inputs: [
  32941. { name: 'bits', type: 'uint' }
  32942. ]
  32943. } );
  32944. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  32945. const t = float( t_immutable ).toVar();
  32946. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  32947. } ).setLayout( {
  32948. name: 'mx_fade',
  32949. type: 'float',
  32950. inputs: [
  32951. { name: 't', type: 'float' }
  32952. ]
  32953. } );
  32954. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  32955. const x = int( x_immutable ).toVar();
  32956. const len = uint( uint( 1 ) ).toVar();
  32957. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  32958. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  32959. } ).setLayout( {
  32960. name: 'mx_hash_int_0',
  32961. type: 'uint',
  32962. inputs: [
  32963. { name: 'x', type: 'int' }
  32964. ]
  32965. } );
  32966. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  32967. const y = int( y_immutable ).toVar();
  32968. const x = int( x_immutable ).toVar();
  32969. const len = uint( uint( 2 ) ).toVar();
  32970. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32971. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32972. a.addAssign( uint( x ) );
  32973. b.addAssign( uint( y ) );
  32974. return mx_bjfinal( a, b, c );
  32975. } ).setLayout( {
  32976. name: 'mx_hash_int_1',
  32977. type: 'uint',
  32978. inputs: [
  32979. { name: 'x', type: 'int' },
  32980. { name: 'y', type: 'int' }
  32981. ]
  32982. } );
  32983. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  32984. const z = int( z_immutable ).toVar();
  32985. const y = int( y_immutable ).toVar();
  32986. const x = int( x_immutable ).toVar();
  32987. const len = uint( uint( 3 ) ).toVar();
  32988. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32989. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32990. a.addAssign( uint( x ) );
  32991. b.addAssign( uint( y ) );
  32992. c.addAssign( uint( z ) );
  32993. return mx_bjfinal( a, b, c );
  32994. } ).setLayout( {
  32995. name: 'mx_hash_int_2',
  32996. type: 'uint',
  32997. inputs: [
  32998. { name: 'x', type: 'int' },
  32999. { name: 'y', type: 'int' },
  33000. { name: 'z', type: 'int' }
  33001. ]
  33002. } );
  33003. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  33004. const xx = int( xx_immutable ).toVar();
  33005. const z = int( z_immutable ).toVar();
  33006. const y = int( y_immutable ).toVar();
  33007. const x = int( x_immutable ).toVar();
  33008. const len = uint( uint( 4 ) ).toVar();
  33009. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  33010. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  33011. a.addAssign( uint( x ) );
  33012. b.addAssign( uint( y ) );
  33013. c.addAssign( uint( z ) );
  33014. mx_bjmix( a, b, c );
  33015. a.addAssign( uint( xx ) );
  33016. return mx_bjfinal( a, b, c );
  33017. } ).setLayout( {
  33018. name: 'mx_hash_int_3',
  33019. type: 'uint',
  33020. inputs: [
  33021. { name: 'x', type: 'int' },
  33022. { name: 'y', type: 'int' },
  33023. { name: 'z', type: 'int' },
  33024. { name: 'xx', type: 'int' }
  33025. ]
  33026. } );
  33027. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  33028. const yy = int( yy_immutable ).toVar();
  33029. const xx = int( xx_immutable ).toVar();
  33030. const z = int( z_immutable ).toVar();
  33031. const y = int( y_immutable ).toVar();
  33032. const x = int( x_immutable ).toVar();
  33033. const len = uint( uint( 5 ) ).toVar();
  33034. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  33035. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  33036. a.addAssign( uint( x ) );
  33037. b.addAssign( uint( y ) );
  33038. c.addAssign( uint( z ) );
  33039. mx_bjmix( a, b, c );
  33040. a.addAssign( uint( xx ) );
  33041. b.addAssign( uint( yy ) );
  33042. return mx_bjfinal( a, b, c );
  33043. } ).setLayout( {
  33044. name: 'mx_hash_int_4',
  33045. type: 'uint',
  33046. inputs: [
  33047. { name: 'x', type: 'int' },
  33048. { name: 'y', type: 'int' },
  33049. { name: 'z', type: 'int' },
  33050. { name: 'xx', type: 'int' },
  33051. { name: 'yy', type: 'int' }
  33052. ]
  33053. } );
  33054. 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 ] );
  33055. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  33056. const y = int( y_immutable ).toVar();
  33057. const x = int( x_immutable ).toVar();
  33058. const h = uint( mx_hash_int( x, y ) ).toVar();
  33059. const result = uvec3().toVar();
  33060. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  33061. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  33062. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  33063. return result;
  33064. } ).setLayout( {
  33065. name: 'mx_hash_vec3_0',
  33066. type: 'uvec3',
  33067. inputs: [
  33068. { name: 'x', type: 'int' },
  33069. { name: 'y', type: 'int' }
  33070. ]
  33071. } );
  33072. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  33073. const z = int( z_immutable ).toVar();
  33074. const y = int( y_immutable ).toVar();
  33075. const x = int( x_immutable ).toVar();
  33076. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  33077. const result = uvec3().toVar();
  33078. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  33079. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  33080. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  33081. return result;
  33082. } ).setLayout( {
  33083. name: 'mx_hash_vec3_1',
  33084. type: 'uvec3',
  33085. inputs: [
  33086. { name: 'x', type: 'int' },
  33087. { name: 'y', type: 'int' },
  33088. { name: 'z', type: 'int' }
  33089. ]
  33090. } );
  33091. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  33092. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33093. const p = vec2( p_immutable ).toVar();
  33094. const X = int().toVar(), Y = int().toVar();
  33095. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  33096. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  33097. const u = float( mx_fade( fx ) ).toVar();
  33098. const v = float( mx_fade( fy ) ).toVar();
  33099. 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();
  33100. return mx_gradient_scale2d( result );
  33101. } ).setLayout( {
  33102. name: 'mx_perlin_noise_float_0',
  33103. type: 'float',
  33104. inputs: [
  33105. { name: 'p', type: 'vec2' }
  33106. ]
  33107. } );
  33108. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33109. const p = vec3( p_immutable ).toVar();
  33110. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33111. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  33112. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  33113. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  33114. const u = float( mx_fade( fx ) ).toVar();
  33115. const v = float( mx_fade( fy ) ).toVar();
  33116. const w = float( mx_fade( fz ) ).toVar();
  33117. 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();
  33118. return mx_gradient_scale3d( result );
  33119. } ).setLayout( {
  33120. name: 'mx_perlin_noise_float_1',
  33121. type: 'float',
  33122. inputs: [
  33123. { name: 'p', type: 'vec3' }
  33124. ]
  33125. } );
  33126. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  33127. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33128. const p = vec2( p_immutable ).toVar();
  33129. const X = int().toVar(), Y = int().toVar();
  33130. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  33131. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  33132. const u = float( mx_fade( fx ) ).toVar();
  33133. const v = float( mx_fade( fy ) ).toVar();
  33134. 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();
  33135. return mx_gradient_scale2d( result );
  33136. } ).setLayout( {
  33137. name: 'mx_perlin_noise_vec3_0',
  33138. type: 'vec3',
  33139. inputs: [
  33140. { name: 'p', type: 'vec2' }
  33141. ]
  33142. } );
  33143. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33144. const p = vec3( p_immutable ).toVar();
  33145. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33146. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  33147. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  33148. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  33149. const u = float( mx_fade( fx ) ).toVar();
  33150. const v = float( mx_fade( fy ) ).toVar();
  33151. const w = float( mx_fade( fz ) ).toVar();
  33152. 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();
  33153. return mx_gradient_scale3d( result );
  33154. } ).setLayout( {
  33155. name: 'mx_perlin_noise_vec3_1',
  33156. type: 'vec3',
  33157. inputs: [
  33158. { name: 'p', type: 'vec3' }
  33159. ]
  33160. } );
  33161. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  33162. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33163. const p = float( p_immutable ).toVar();
  33164. const ix = int( mx_floor( p ) ).toVar();
  33165. return mx_bits_to_01( mx_hash_int( ix ) );
  33166. } ).setLayout( {
  33167. name: 'mx_cell_noise_float_0',
  33168. type: 'float',
  33169. inputs: [
  33170. { name: 'p', type: 'float' }
  33171. ]
  33172. } );
  33173. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33174. const p = vec2( p_immutable ).toVar();
  33175. const ix = int( mx_floor( p.x ) ).toVar();
  33176. const iy = int( mx_floor( p.y ) ).toVar();
  33177. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  33178. } ).setLayout( {
  33179. name: 'mx_cell_noise_float_1',
  33180. type: 'float',
  33181. inputs: [
  33182. { name: 'p', type: 'vec2' }
  33183. ]
  33184. } );
  33185. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33186. const p = vec3( p_immutable ).toVar();
  33187. const ix = int( mx_floor( p.x ) ).toVar();
  33188. const iy = int( mx_floor( p.y ) ).toVar();
  33189. const iz = int( mx_floor( p.z ) ).toVar();
  33190. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  33191. } ).setLayout( {
  33192. name: 'mx_cell_noise_float_2',
  33193. type: 'float',
  33194. inputs: [
  33195. { name: 'p', type: 'vec3' }
  33196. ]
  33197. } );
  33198. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33199. const p = vec4( p_immutable ).toVar();
  33200. const ix = int( mx_floor( p.x ) ).toVar();
  33201. const iy = int( mx_floor( p.y ) ).toVar();
  33202. const iz = int( mx_floor( p.z ) ).toVar();
  33203. const iw = int( mx_floor( p.w ) ).toVar();
  33204. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  33205. } ).setLayout( {
  33206. name: 'mx_cell_noise_float_3',
  33207. type: 'float',
  33208. inputs: [
  33209. { name: 'p', type: 'vec4' }
  33210. ]
  33211. } );
  33212. 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 ] );
  33213. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33214. const p = float( p_immutable ).toVar();
  33215. const ix = int( mx_floor( p ) ).toVar();
  33216. 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 ) ) ) );
  33217. } ).setLayout( {
  33218. name: 'mx_cell_noise_vec3_0',
  33219. type: 'vec3',
  33220. inputs: [
  33221. { name: 'p', type: 'float' }
  33222. ]
  33223. } );
  33224. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33225. const p = vec2( p_immutable ).toVar();
  33226. const ix = int( mx_floor( p.x ) ).toVar();
  33227. const iy = int( mx_floor( p.y ) ).toVar();
  33228. 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 ) ) ) );
  33229. } ).setLayout( {
  33230. name: 'mx_cell_noise_vec3_1',
  33231. type: 'vec3',
  33232. inputs: [
  33233. { name: 'p', type: 'vec2' }
  33234. ]
  33235. } );
  33236. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33237. const p = vec3( p_immutable ).toVar();
  33238. const ix = int( mx_floor( p.x ) ).toVar();
  33239. const iy = int( mx_floor( p.y ) ).toVar();
  33240. const iz = int( mx_floor( p.z ) ).toVar();
  33241. 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 ) ) ) );
  33242. } ).setLayout( {
  33243. name: 'mx_cell_noise_vec3_2',
  33244. type: 'vec3',
  33245. inputs: [
  33246. { name: 'p', type: 'vec3' }
  33247. ]
  33248. } );
  33249. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33250. const p = vec4( p_immutable ).toVar();
  33251. const ix = int( mx_floor( p.x ) ).toVar();
  33252. const iy = int( mx_floor( p.y ) ).toVar();
  33253. const iz = int( mx_floor( p.z ) ).toVar();
  33254. const iw = int( mx_floor( p.w ) ).toVar();
  33255. 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 ) ) ) );
  33256. } ).setLayout( {
  33257. name: 'mx_cell_noise_vec3_3',
  33258. type: 'vec3',
  33259. inputs: [
  33260. { name: 'p', type: 'vec4' }
  33261. ]
  33262. } );
  33263. 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 ] );
  33264. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  33265. const diminish = float( diminish_immutable ).toVar();
  33266. const lacunarity = float( lacunarity_immutable ).toVar();
  33267. const octaves = int( octaves_immutable ).toVar();
  33268. const p = vec3( p_immutable ).toVar();
  33269. const result = float( 0.0 ).toVar();
  33270. const amplitude = float( 1.0 ).toVar();
  33271. Loop( octaves, () => {
  33272. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  33273. amplitude.mulAssign( diminish );
  33274. p.mulAssign( lacunarity );
  33275. } );
  33276. return result;
  33277. } ).setLayout( {
  33278. name: 'mx_fractal_noise_float',
  33279. type: 'float',
  33280. inputs: [
  33281. { name: 'p', type: 'vec3' },
  33282. { name: 'octaves', type: 'int' },
  33283. { name: 'lacunarity', type: 'float' },
  33284. { name: 'diminish', type: 'float' }
  33285. ]
  33286. } );
  33287. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  33288. const diminish = float( diminish_immutable ).toVar();
  33289. const lacunarity = float( lacunarity_immutable ).toVar();
  33290. const octaves = int( octaves_immutable ).toVar();
  33291. const p = vec3( p_immutable ).toVar();
  33292. const result = vec3( 0.0 ).toVar();
  33293. const amplitude = float( 1.0 ).toVar();
  33294. Loop( octaves, () => {
  33295. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  33296. amplitude.mulAssign( diminish );
  33297. p.mulAssign( lacunarity );
  33298. } );
  33299. return result;
  33300. } ).setLayout( {
  33301. name: 'mx_fractal_noise_vec3',
  33302. type: 'vec3',
  33303. inputs: [
  33304. { name: 'p', type: 'vec3' },
  33305. { name: 'octaves', type: 'int' },
  33306. { name: 'lacunarity', type: 'float' },
  33307. { name: 'diminish', type: 'float' }
  33308. ]
  33309. } );
  33310. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  33311. const diminish = float( diminish_immutable ).toVar();
  33312. const lacunarity = float( lacunarity_immutable ).toVar();
  33313. const octaves = int( octaves_immutable ).toVar();
  33314. const p = vec3( p_immutable ).toVar();
  33315. 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 ) );
  33316. } ).setLayout( {
  33317. name: 'mx_fractal_noise_vec2',
  33318. type: 'vec2',
  33319. inputs: [
  33320. { name: 'p', type: 'vec3' },
  33321. { name: 'octaves', type: 'int' },
  33322. { name: 'lacunarity', type: 'float' },
  33323. { name: 'diminish', type: 'float' }
  33324. ]
  33325. } );
  33326. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  33327. const diminish = float( diminish_immutable ).toVar();
  33328. const lacunarity = float( lacunarity_immutable ).toVar();
  33329. const octaves = int( octaves_immutable ).toVar();
  33330. const p = vec3( p_immutable ).toVar();
  33331. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  33332. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  33333. return vec4( c, f );
  33334. } ).setLayout( {
  33335. name: 'mx_fractal_noise_vec4',
  33336. type: 'vec4',
  33337. inputs: [
  33338. { name: 'p', type: 'vec3' },
  33339. { name: 'octaves', type: 'int' },
  33340. { name: 'lacunarity', type: 'float' },
  33341. { name: 'diminish', type: 'float' }
  33342. ]
  33343. } );
  33344. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  33345. const metric = int( metric_immutable ).toVar();
  33346. const jitter = float( jitter_immutable ).toVar();
  33347. const yoff = int( yoff_immutable ).toVar();
  33348. const xoff = int( xoff_immutable ).toVar();
  33349. const y = int( y_immutable ).toVar();
  33350. const x = int( x_immutable ).toVar();
  33351. const p = vec2( p_immutable ).toVar();
  33352. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  33353. const off = vec2( tmp.x, tmp.y ).toVar();
  33354. off.subAssign( 0.5 );
  33355. off.mulAssign( jitter );
  33356. off.addAssign( 0.5 );
  33357. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  33358. const diff = vec2( cellpos.sub( p ) ).toVar();
  33359. If( metric.equal( int( 2 ) ), () => {
  33360. return abs( diff.x ).add( abs( diff.y ) );
  33361. } );
  33362. If( metric.equal( int( 3 ) ), () => {
  33363. return max$1( abs( diff.x ), abs( diff.y ) );
  33364. } );
  33365. return dot( diff, diff );
  33366. } ).setLayout( {
  33367. name: 'mx_worley_distance_0',
  33368. type: 'float',
  33369. inputs: [
  33370. { name: 'p', type: 'vec2' },
  33371. { name: 'x', type: 'int' },
  33372. { name: 'y', type: 'int' },
  33373. { name: 'xoff', type: 'int' },
  33374. { name: 'yoff', type: 'int' },
  33375. { name: 'jitter', type: 'float' },
  33376. { name: 'metric', type: 'int' }
  33377. ]
  33378. } );
  33379. 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 ] ) => {
  33380. const metric = int( metric_immutable ).toVar();
  33381. const jitter = float( jitter_immutable ).toVar();
  33382. const zoff = int( zoff_immutable ).toVar();
  33383. const yoff = int( yoff_immutable ).toVar();
  33384. const xoff = int( xoff_immutable ).toVar();
  33385. const z = int( z_immutable ).toVar();
  33386. const y = int( y_immutable ).toVar();
  33387. const x = int( x_immutable ).toVar();
  33388. const p = vec3( p_immutable ).toVar();
  33389. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  33390. off.subAssign( 0.5 );
  33391. off.mulAssign( jitter );
  33392. off.addAssign( 0.5 );
  33393. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  33394. const diff = vec3( cellpos.sub( p ) ).toVar();
  33395. If( metric.equal( int( 2 ) ), () => {
  33396. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  33397. } );
  33398. If( metric.equal( int( 3 ) ), () => {
  33399. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  33400. } );
  33401. return dot( diff, diff );
  33402. } ).setLayout( {
  33403. name: 'mx_worley_distance_1',
  33404. type: 'float',
  33405. inputs: [
  33406. { name: 'p', type: 'vec3' },
  33407. { name: 'x', type: 'int' },
  33408. { name: 'y', type: 'int' },
  33409. { name: 'z', type: 'int' },
  33410. { name: 'xoff', type: 'int' },
  33411. { name: 'yoff', type: 'int' },
  33412. { name: 'zoff', type: 'int' },
  33413. { name: 'jitter', type: 'float' },
  33414. { name: 'metric', type: 'int' }
  33415. ]
  33416. } );
  33417. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  33418. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33419. const metric = int( metric_immutable ).toVar();
  33420. const jitter = float( jitter_immutable ).toVar();
  33421. const p = vec2( p_immutable ).toVar();
  33422. const X = int().toVar(), Y = int().toVar();
  33423. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  33424. const sqdist = float( 1e6 ).toVar();
  33425. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33426. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33427. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  33428. sqdist.assign( min$1( sqdist, dist ) );
  33429. } );
  33430. } );
  33431. If( metric.equal( int( 0 ) ), () => {
  33432. sqdist.assign( sqrt( sqdist ) );
  33433. } );
  33434. return sqdist;
  33435. } ).setLayout( {
  33436. name: 'mx_worley_noise_float_0',
  33437. type: 'float',
  33438. inputs: [
  33439. { name: 'p', type: 'vec2' },
  33440. { name: 'jitter', type: 'float' },
  33441. { name: 'metric', type: 'int' }
  33442. ]
  33443. } );
  33444. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33445. const metric = int( metric_immutable ).toVar();
  33446. const jitter = float( jitter_immutable ).toVar();
  33447. const p = vec2( p_immutable ).toVar();
  33448. const X = int().toVar(), Y = int().toVar();
  33449. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  33450. const sqdist = vec2( 1e6, 1e6 ).toVar();
  33451. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33452. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33453. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  33454. If( dist.lessThan( sqdist.x ), () => {
  33455. sqdist.y.assign( sqdist.x );
  33456. sqdist.x.assign( dist );
  33457. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33458. sqdist.y.assign( dist );
  33459. } );
  33460. } );
  33461. } );
  33462. If( metric.equal( int( 0 ) ), () => {
  33463. sqdist.assign( sqrt( sqdist ) );
  33464. } );
  33465. return sqdist;
  33466. } ).setLayout( {
  33467. name: 'mx_worley_noise_vec2_0',
  33468. type: 'vec2',
  33469. inputs: [
  33470. { name: 'p', type: 'vec2' },
  33471. { name: 'jitter', type: 'float' },
  33472. { name: 'metric', type: 'int' }
  33473. ]
  33474. } );
  33475. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33476. const metric = int( metric_immutable ).toVar();
  33477. const jitter = float( jitter_immutable ).toVar();
  33478. const p = vec2( p_immutable ).toVar();
  33479. const X = int().toVar(), Y = int().toVar();
  33480. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  33481. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  33482. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33483. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33484. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  33485. If( dist.lessThan( sqdist.x ), () => {
  33486. sqdist.z.assign( sqdist.y );
  33487. sqdist.y.assign( sqdist.x );
  33488. sqdist.x.assign( dist );
  33489. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33490. sqdist.z.assign( sqdist.y );
  33491. sqdist.y.assign( dist );
  33492. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  33493. sqdist.z.assign( dist );
  33494. } );
  33495. } );
  33496. } );
  33497. If( metric.equal( int( 0 ) ), () => {
  33498. sqdist.assign( sqrt( sqdist ) );
  33499. } );
  33500. return sqdist;
  33501. } ).setLayout( {
  33502. name: 'mx_worley_noise_vec3_0',
  33503. type: 'vec3',
  33504. inputs: [
  33505. { name: 'p', type: 'vec2' },
  33506. { name: 'jitter', type: 'float' },
  33507. { name: 'metric', type: 'int' }
  33508. ]
  33509. } );
  33510. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33511. const metric = int( metric_immutable ).toVar();
  33512. const jitter = float( jitter_immutable ).toVar();
  33513. const p = vec3( p_immutable ).toVar();
  33514. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33515. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  33516. const sqdist = float( 1e6 ).toVar();
  33517. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33518. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33519. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  33520. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  33521. sqdist.assign( min$1( sqdist, dist ) );
  33522. } );
  33523. } );
  33524. } );
  33525. If( metric.equal( int( 0 ) ), () => {
  33526. sqdist.assign( sqrt( sqdist ) );
  33527. } );
  33528. return sqdist;
  33529. } ).setLayout( {
  33530. name: 'mx_worley_noise_float_1',
  33531. type: 'float',
  33532. inputs: [
  33533. { name: 'p', type: 'vec3' },
  33534. { name: 'jitter', type: 'float' },
  33535. { name: 'metric', type: 'int' }
  33536. ]
  33537. } );
  33538. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  33539. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33540. const metric = int( metric_immutable ).toVar();
  33541. const jitter = float( jitter_immutable ).toVar();
  33542. const p = vec3( p_immutable ).toVar();
  33543. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33544. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  33545. const sqdist = vec2( 1e6, 1e6 ).toVar();
  33546. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33547. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33548. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  33549. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  33550. If( dist.lessThan( sqdist.x ), () => {
  33551. sqdist.y.assign( sqdist.x );
  33552. sqdist.x.assign( dist );
  33553. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33554. sqdist.y.assign( dist );
  33555. } );
  33556. } );
  33557. } );
  33558. } );
  33559. If( metric.equal( int( 0 ) ), () => {
  33560. sqdist.assign( sqrt( sqdist ) );
  33561. } );
  33562. return sqdist;
  33563. } ).setLayout( {
  33564. name: 'mx_worley_noise_vec2_1',
  33565. type: 'vec2',
  33566. inputs: [
  33567. { name: 'p', type: 'vec3' },
  33568. { name: 'jitter', type: 'float' },
  33569. { name: 'metric', type: 'int' }
  33570. ]
  33571. } );
  33572. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  33573. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33574. const metric = int( metric_immutable ).toVar();
  33575. const jitter = float( jitter_immutable ).toVar();
  33576. const p = vec3( p_immutable ).toVar();
  33577. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33578. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  33579. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  33580. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33581. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33582. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  33583. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  33584. If( dist.lessThan( sqdist.x ), () => {
  33585. sqdist.z.assign( sqdist.y );
  33586. sqdist.y.assign( sqdist.x );
  33587. sqdist.x.assign( dist );
  33588. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33589. sqdist.z.assign( sqdist.y );
  33590. sqdist.y.assign( dist );
  33591. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  33592. sqdist.z.assign( dist );
  33593. } );
  33594. } );
  33595. } );
  33596. } );
  33597. If( metric.equal( int( 0 ) ), () => {
  33598. sqdist.assign( sqrt( sqdist ) );
  33599. } );
  33600. return sqdist;
  33601. } ).setLayout( {
  33602. name: 'mx_worley_noise_vec3_1',
  33603. type: 'vec3',
  33604. inputs: [
  33605. { name: 'p', type: 'vec3' },
  33606. { name: 'jitter', type: 'float' },
  33607. { name: 'metric', type: 'int' }
  33608. ]
  33609. } );
  33610. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  33611. // Unified Noise 2D
  33612. const mx_unifiednoise2d$1 = /*@__PURE__*/ Fn( ( [
  33613. noiseType_immutable, texcoord_immutable, freq_immutable, offset_immutable,
  33614. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  33615. octaves_immutable, lacunarity_immutable, diminish_immutable
  33616. ] ) => {
  33617. const noiseType = int( noiseType_immutable ).toVar();
  33618. const texcoord = vec2( texcoord_immutable ).toVar();
  33619. const freq = vec2( freq_immutable ).toVar();
  33620. const offset = vec2( offset_immutable ).toVar();
  33621. const jitter = float( jitter_immutable ).toVar();
  33622. const outmin = float( outmin_immutable ).toVar();
  33623. const outmax = float( outmax_immutable ).toVar();
  33624. const clampoutput = bool( clampoutput_immutable ).toVar();
  33625. const octaves = int( octaves_immutable ).toVar();
  33626. const lacunarity = float( lacunarity_immutable ).toVar();
  33627. const diminish = float( diminish_immutable ).toVar();
  33628. // Compute input position
  33629. const p = texcoord.mul( freq ).add( offset );
  33630. const result = float( 0.0 ).toVar();
  33631. // Perlin
  33632. If( noiseType.equal( int( 0 ) ), () => {
  33633. result.assign( mx_perlin_noise_vec3( p ) );
  33634. } );
  33635. // Cell
  33636. If( noiseType.equal( int( 1 ) ), () => {
  33637. result.assign( mx_cell_noise_vec3( p ) );
  33638. } );
  33639. // Worley (metric=0 = euclidean)
  33640. If( noiseType.equal( int( 2 ) ), () => {
  33641. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  33642. } );
  33643. // Fractal (use vec3(p, 0.0) for 2D input)
  33644. If( noiseType.equal( int( 3 ) ), () => {
  33645. result.assign( mx_fractal_noise_vec3$1( vec3( p, 0.0 ), octaves, lacunarity, diminish ) );
  33646. } );
  33647. // Remap output to [outmin, outmax]
  33648. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  33649. // Clamp if requested
  33650. If( clampoutput, () => {
  33651. result.assign( clamp( result, outmin, outmax ) );
  33652. } );
  33653. return result;
  33654. } ).setLayout( {
  33655. name: 'mx_unifiednoise2d',
  33656. type: 'float',
  33657. inputs: [
  33658. { name: 'noiseType', type: 'int' },
  33659. { name: 'texcoord', type: 'vec2' },
  33660. { name: 'freq', type: 'vec2' },
  33661. { name: 'offset', type: 'vec2' },
  33662. { name: 'jitter', type: 'float' },
  33663. { name: 'outmin', type: 'float' },
  33664. { name: 'outmax', type: 'float' },
  33665. { name: 'clampoutput', type: 'bool' },
  33666. { name: 'octaves', type: 'int' },
  33667. { name: 'lacunarity', type: 'float' },
  33668. { name: 'diminish', type: 'float' }
  33669. ]
  33670. } );
  33671. // Unified Noise 3D
  33672. const mx_unifiednoise3d$1 = /*@__PURE__*/ Fn( ( [
  33673. noiseType_immutable, position_immutable, freq_immutable, offset_immutable,
  33674. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  33675. octaves_immutable, lacunarity_immutable, diminish_immutable
  33676. ] ) => {
  33677. const noiseType = int( noiseType_immutable ).toVar();
  33678. const position = vec3( position_immutable ).toVar();
  33679. const freq = vec3( freq_immutable ).toVar();
  33680. const offset = vec3( offset_immutable ).toVar();
  33681. const jitter = float( jitter_immutable ).toVar();
  33682. const outmin = float( outmin_immutable ).toVar();
  33683. const outmax = float( outmax_immutable ).toVar();
  33684. const clampoutput = bool( clampoutput_immutable ).toVar();
  33685. const octaves = int( octaves_immutable ).toVar();
  33686. const lacunarity = float( lacunarity_immutable ).toVar();
  33687. const diminish = float( diminish_immutable ).toVar();
  33688. // Compute input position
  33689. const p = position.mul( freq ).add( offset );
  33690. const result = float( 0.0 ).toVar();
  33691. // Perlin
  33692. If( noiseType.equal( int( 0 ) ), () => {
  33693. result.assign( mx_perlin_noise_vec3( p ) );
  33694. } );
  33695. // Cell
  33696. If( noiseType.equal( int( 1 ) ), () => {
  33697. result.assign( mx_cell_noise_vec3( p ) );
  33698. } );
  33699. // Worley (metric=0 = euclidean)
  33700. If( noiseType.equal( int( 2 ) ), () => {
  33701. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  33702. } );
  33703. // Fractal
  33704. If( noiseType.equal( int( 3 ) ), () => {
  33705. result.assign( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) );
  33706. } );
  33707. // Remap output to [outmin, outmax]
  33708. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  33709. // Clamp if requested
  33710. If( clampoutput, () => {
  33711. result.assign( clamp( result, outmin, outmax ) );
  33712. } );
  33713. return result;
  33714. } ).setLayout( {
  33715. name: 'mx_unifiednoise3d',
  33716. type: 'float',
  33717. inputs: [
  33718. { name: 'noiseType', type: 'int' },
  33719. { name: 'position', type: 'vec3' },
  33720. { name: 'freq', type: 'vec3' },
  33721. { name: 'offset', type: 'vec3' },
  33722. { name: 'jitter', type: 'float' },
  33723. { name: 'outmin', type: 'float' },
  33724. { name: 'outmax', type: 'float' },
  33725. { name: 'clampoutput', type: 'bool' },
  33726. { name: 'octaves', type: 'int' },
  33727. { name: 'lacunarity', type: 'float' },
  33728. { name: 'diminish', type: 'float' }
  33729. ]
  33730. } );
  33731. // Three.js Transpiler
  33732. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  33733. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  33734. const s = hsv.y;
  33735. const v = hsv.z;
  33736. const result = vec3().toVar();
  33737. If( s.lessThan( 0.0001 ), () => {
  33738. result.assign( vec3( v, v, v ) );
  33739. } ).Else( () => {
  33740. let h = hsv.x;
  33741. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  33742. const hi = int( trunc( h ) );
  33743. const f = h.sub( float( hi ) );
  33744. const p = v.mul( s.oneMinus() );
  33745. const q = v.mul( s.mul( f ).oneMinus() );
  33746. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  33747. If( hi.equal( int( 0 ) ), () => {
  33748. result.assign( vec3( v, t, p ) );
  33749. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  33750. result.assign( vec3( q, v, p ) );
  33751. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  33752. result.assign( vec3( p, v, t ) );
  33753. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  33754. result.assign( vec3( p, q, v ) );
  33755. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  33756. result.assign( vec3( t, p, v ) );
  33757. } ).Else( () => {
  33758. result.assign( vec3( v, p, q ) );
  33759. } );
  33760. } );
  33761. return result;
  33762. } ).setLayout( {
  33763. name: 'mx_hsvtorgb',
  33764. type: 'vec3',
  33765. inputs: [
  33766. { name: 'hsv', type: 'vec3' }
  33767. ]
  33768. } );
  33769. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  33770. const c = vec3( c_immutable ).toVar();
  33771. const r = float( c.x ).toVar();
  33772. const g = float( c.y ).toVar();
  33773. const b = float( c.z ).toVar();
  33774. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  33775. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  33776. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  33777. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  33778. v.assign( maxcomp );
  33779. If( maxcomp.greaterThan( 0.0 ), () => {
  33780. s.assign( delta.div( maxcomp ) );
  33781. } ).Else( () => {
  33782. s.assign( 0.0 );
  33783. } );
  33784. If( s.lessThanEqual( 0.0 ), () => {
  33785. h.assign( 0.0 );
  33786. } ).Else( () => {
  33787. If( r.greaterThanEqual( maxcomp ), () => {
  33788. h.assign( g.sub( b ).div( delta ) );
  33789. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  33790. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  33791. } ).Else( () => {
  33792. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  33793. } );
  33794. h.mulAssign( 1.0 / 6.0 );
  33795. If( h.lessThan( 0.0 ), () => {
  33796. h.addAssign( 1.0 );
  33797. } );
  33798. } );
  33799. return vec3( h, s, v );
  33800. } ).setLayout( {
  33801. name: 'mx_rgbtohsv',
  33802. type: 'vec3',
  33803. inputs: [
  33804. { name: 'c', type: 'vec3' }
  33805. ]
  33806. } );
  33807. // Three.js Transpiler
  33808. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  33809. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  33810. const color = vec3( color_immutable ).toVar();
  33811. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  33812. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  33813. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  33814. return mix( linSeg, powSeg, isAbove );
  33815. } ).setLayout( {
  33816. name: 'mx_srgb_texture_to_lin_rec709',
  33817. type: 'vec3',
  33818. inputs: [
  33819. { name: 'color', type: 'vec3' }
  33820. ]
  33821. } );
  33822. const mx_aastep = ( threshold, value ) => {
  33823. threshold = float( threshold );
  33824. value = float( value );
  33825. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  33826. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  33827. };
  33828. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  33829. const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' );
  33830. const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' );
  33831. // Bilinear ramp: interpolate between four corners (tl, tr, bl, br) using texcoord.x and texcoord.y
  33832. const mx_ramp4 = (
  33833. valuetl, valuetr, valuebl, valuebr, texcoord = uv$1()
  33834. ) => {
  33835. const u = texcoord.x.clamp();
  33836. const v = texcoord.y.clamp();
  33837. const top = mix( valuetl, valuetr, u );
  33838. const bottom = mix( valuebl, valuebr, u );
  33839. return mix( top, bottom, v );
  33840. };
  33841. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  33842. const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' );
  33843. const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' );
  33844. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  33845. const mx_safepower = ( in1, in2 = 1 ) => {
  33846. in1 = float( in1 );
  33847. return in1.abs().pow( in2 ).mul( in1.sign() );
  33848. };
  33849. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  33850. const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33851. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33852. const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33853. const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => {
  33854. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  33855. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  33856. return noise_vec4.mul( amplitude ).add( pivot );
  33857. };
  33858. 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 );
  33859. 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 );
  33860. const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33861. const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33862. const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33863. const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  33864. 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 );
  33865. 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 );
  33866. 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 );
  33867. 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 );
  33868. // === Moved from MaterialXLoader.js ===
  33869. // Math ops
  33870. const mx_add = ( in1, in2 = float( 0 ) ) => add( in1, in2 );
  33871. const mx_subtract = ( in1, in2 = float( 0 ) ) => sub( in1, in2 );
  33872. const mx_multiply = ( in1, in2 = float( 1 ) ) => mul( in1, in2 );
  33873. const mx_divide = ( in1, in2 = float( 1 ) ) => div( in1, in2 );
  33874. const mx_modulo = ( in1, in2 = float( 1 ) ) => mod( in1, in2 );
  33875. const mx_power = ( in1, in2 = float( 1 ) ) => pow( in1, in2 );
  33876. const mx_atan2 = ( in1 = float( 0 ), in2 = float( 1 ) ) => atan( in1, in2 );
  33877. const mx_timer = () => time;
  33878. const mx_frame = () => frameId;
  33879. const mx_invert = ( in1, amount = float( 1 ) ) => sub( amount, in1 );
  33880. const mx_ifgreater = ( value1, value2, in1, in2 ) => value1.greaterThan( value2 ).mix( in1, in2 );
  33881. const mx_ifgreatereq = ( value1, value2, in1, in2 ) => value1.greaterThanEqual( value2 ).mix( in1, in2 );
  33882. const mx_ifequal = ( value1, value2, in1, in2 ) => value1.equal( value2 ).mix( in1, in2 );
  33883. // Enhanced separate node to support multi-output referencing (outx, outy, outz, outw)
  33884. const mx_separate = ( in1, channelOrOut = null ) => {
  33885. if ( typeof channelOrOut === 'string' ) {
  33886. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  33887. const c = channelOrOut.replace( /^out/, '' ).toLowerCase();
  33888. if ( map[ c ] !== undefined ) return in1.element( map[ c ] );
  33889. }
  33890. if ( typeof channelOrOut === 'number' ) {
  33891. return in1.element( channelOrOut );
  33892. }
  33893. if ( typeof channelOrOut === 'string' && channelOrOut.length === 1 ) {
  33894. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  33895. if ( map[ channelOrOut ] !== undefined ) return in1.element( map[ channelOrOut ] );
  33896. }
  33897. return in1;
  33898. };
  33899. const mx_place2d = (
  33900. texcoord, pivot = vec2( 0.5, 0.5 ), scale = vec2( 1, 1 ), rotate = float( 0 ), offset = vec2( 0, 0 )/*, operationorder = int( 0 )*/
  33901. ) => {
  33902. let uv = texcoord;
  33903. if ( pivot ) uv = uv.sub( pivot );
  33904. if ( scale ) uv = uv.mul( scale );
  33905. if ( rotate ) {
  33906. const rad = rotate.mul( Math.PI / 180.0 );
  33907. const cosR = rad.cos();
  33908. const sinR = rad.sin();
  33909. uv = vec2(
  33910. uv.x.mul( cosR ).sub( uv.y.mul( sinR ) ),
  33911. uv.x.mul( sinR ).add( uv.y.mul( cosR ) )
  33912. );
  33913. }
  33914. if ( pivot ) uv = uv.add( pivot );
  33915. if ( offset ) uv = uv.add( offset );
  33916. return uv;
  33917. };
  33918. const mx_rotate2d = ( input, amount ) => {
  33919. input = vec2( input );
  33920. amount = float( amount );
  33921. const radians = amount.mul( Math.PI / 180.0 );
  33922. return rotate( input, radians );
  33923. };
  33924. const mx_rotate3d = ( input, amount, axis ) => {
  33925. input = vec3( input );
  33926. amount = float( amount );
  33927. axis = vec3( axis );
  33928. const radians = amount.mul( Math.PI / 180.0 );
  33929. const nAxis = axis.normalize();
  33930. const cosA = radians.cos();
  33931. const sinA = radians.sin();
  33932. const oneMinusCosA = float( 1 ).sub( cosA );
  33933. const rot =
  33934. input.mul( cosA )
  33935. .add( nAxis.cross( input ).mul( sinA ) )
  33936. .add( nAxis.mul( nAxis.dot( input ) ).mul( oneMinusCosA ) );
  33937. return rot;
  33938. };
  33939. const mx_heighttonormal = ( input, scale/*, texcoord*/ ) => {
  33940. input = vec3( input );
  33941. scale = float( scale );
  33942. return bumpMap( input, scale );
  33943. };
  33944. /**
  33945. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  33946. *
  33947. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  33948. *
  33949. * ```js
  33950. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  33951. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  33952. * ```
  33953. *
  33954. * @tsl
  33955. * @function
  33956. * @param {Node<vec3>} normal - The normal to correct.
  33957. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  33958. * @param {Node<vec3>} cubePos - The cube position.
  33959. * @return {Node<vec3>} The parallax corrected normal.
  33960. */
  33961. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  33962. const nDir = normalize( normal ).toVar();
  33963. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  33964. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  33965. const rbminmax = vec3().toVar();
  33966. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  33967. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  33968. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  33969. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  33970. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  33971. return boxIntersection.sub( cubePos );
  33972. } );
  33973. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  33974. // normal is assumed to have unit length
  33975. const x = normal.x, y = normal.y, z = normal.z;
  33976. // band 0
  33977. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  33978. // band 1
  33979. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  33980. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  33981. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  33982. // band 2
  33983. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  33984. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  33985. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  33986. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  33987. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  33988. return result;
  33989. } );
  33990. // constants
  33991. var TSL = /*#__PURE__*/Object.freeze({
  33992. __proto__: null,
  33993. BRDF_GGX: BRDF_GGX,
  33994. BRDF_Lambert: BRDF_Lambert,
  33995. BasicPointShadowFilter: BasicPointShadowFilter,
  33996. BasicShadowFilter: BasicShadowFilter,
  33997. Break: Break,
  33998. Const: Const,
  33999. Continue: Continue,
  34000. DFGLUT: DFGLUT,
  34001. D_GGX: D_GGX,
  34002. Discard: Discard,
  34003. EPSILON: EPSILON,
  34004. F_Schlick: F_Schlick,
  34005. Fn: Fn,
  34006. HALF_PI: HALF_PI,
  34007. INFINITY: INFINITY,
  34008. If: If,
  34009. Loop: Loop,
  34010. NodeAccess: NodeAccess,
  34011. NodeShaderStage: NodeShaderStage,
  34012. NodeType: NodeType,
  34013. NodeUpdateType: NodeUpdateType,
  34014. OnBeforeFrameUpdate: OnBeforeFrameUpdate,
  34015. OnBeforeMaterialUpdate: OnBeforeMaterialUpdate,
  34016. OnBeforeObjectUpdate: OnBeforeObjectUpdate,
  34017. OnFrameUpdate: OnFrameUpdate,
  34018. OnMaterialUpdate: OnMaterialUpdate,
  34019. OnObjectUpdate: OnObjectUpdate,
  34020. PCFShadowFilter: PCFShadowFilter,
  34021. PCFSoftShadowFilter: PCFSoftShadowFilter,
  34022. PI: PI,
  34023. PI2: PI2,
  34024. PointShadowFilter: PointShadowFilter,
  34025. Return: Return,
  34026. Schlick_to_F0: Schlick_to_F0,
  34027. ShaderNode: ShaderNode,
  34028. Stack: Stack,
  34029. Switch: Switch,
  34030. TBNViewMatrix: TBNViewMatrix,
  34031. TWO_PI: TWO_PI,
  34032. VSMShadowFilter: VSMShadowFilter,
  34033. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  34034. Var: Var,
  34035. VarIntent: VarIntent,
  34036. abs: abs,
  34037. acesFilmicToneMapping: acesFilmicToneMapping,
  34038. acos: acos,
  34039. acosh: acosh,
  34040. add: add,
  34041. addMethodChaining: addMethodChaining,
  34042. addNodeElement: addNodeElement,
  34043. agxToneMapping: agxToneMapping,
  34044. all: all,
  34045. alphaT: alphaT,
  34046. and: and,
  34047. anisotropy: anisotropy,
  34048. anisotropyB: anisotropyB,
  34049. anisotropyT: anisotropyT,
  34050. any: any,
  34051. append: append,
  34052. array: array,
  34053. asin: asin,
  34054. asinh: asinh,
  34055. assign: assign,
  34056. atan: atan,
  34057. atanh: atanh,
  34058. atomicAdd: atomicAdd,
  34059. atomicAnd: atomicAnd,
  34060. atomicFunc: atomicFunc,
  34061. atomicLoad: atomicLoad,
  34062. atomicMax: atomicMax,
  34063. atomicMin: atomicMin,
  34064. atomicOr: atomicOr,
  34065. atomicStore: atomicStore,
  34066. atomicSub: atomicSub,
  34067. atomicXor: atomicXor,
  34068. attenuationColor: attenuationColor,
  34069. attenuationDistance: attenuationDistance,
  34070. attribute: attribute,
  34071. attributeArray: attributeArray,
  34072. backgroundBlurriness: backgroundBlurriness,
  34073. backgroundIntensity: backgroundIntensity,
  34074. backgroundRotation: backgroundRotation,
  34075. batch: batch,
  34076. bentNormalView: bentNormalView,
  34077. billboarding: billboarding,
  34078. bitAnd: bitAnd,
  34079. bitNot: bitNot,
  34080. bitOr: bitOr,
  34081. bitXor: bitXor,
  34082. bitangentGeometry: bitangentGeometry,
  34083. bitangentLocal: bitangentLocal,
  34084. bitangentView: bitangentView,
  34085. bitangentWorld: bitangentWorld,
  34086. bitcast: bitcast,
  34087. blendBurn: blendBurn,
  34088. blendColor: blendColor,
  34089. blendDodge: blendDodge,
  34090. blendOverlay: blendOverlay,
  34091. blendScreen: blendScreen,
  34092. blur: blur,
  34093. bool: bool,
  34094. buffer: buffer,
  34095. bufferAttribute: bufferAttribute,
  34096. builtin: builtin,
  34097. builtinAOContext: builtinAOContext,
  34098. builtinShadowContext: builtinShadowContext,
  34099. bumpMap: bumpMap,
  34100. bvec2: bvec2,
  34101. bvec3: bvec3,
  34102. bvec4: bvec4,
  34103. bypass: bypass,
  34104. cache: cache,
  34105. call: call,
  34106. cameraFar: cameraFar,
  34107. cameraIndex: cameraIndex,
  34108. cameraNear: cameraNear,
  34109. cameraNormalMatrix: cameraNormalMatrix,
  34110. cameraPosition: cameraPosition,
  34111. cameraProjectionMatrix: cameraProjectionMatrix,
  34112. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  34113. cameraViewMatrix: cameraViewMatrix,
  34114. cameraViewport: cameraViewport,
  34115. cameraWorldMatrix: cameraWorldMatrix,
  34116. cbrt: cbrt,
  34117. cdl: cdl,
  34118. ceil: ceil,
  34119. checker: checker,
  34120. cineonToneMapping: cineonToneMapping,
  34121. clamp: clamp,
  34122. clearcoat: clearcoat,
  34123. clearcoatNormalView: clearcoatNormalView,
  34124. clearcoatRoughness: clearcoatRoughness,
  34125. clipSpace: clipSpace,
  34126. code: code,
  34127. color: color,
  34128. colorSpaceToWorking: colorSpaceToWorking,
  34129. colorToDirection: colorToDirection,
  34130. compute: compute,
  34131. computeKernel: computeKernel,
  34132. computeSkinning: computeSkinning,
  34133. context: context,
  34134. convert: convert,
  34135. convertColorSpace: convertColorSpace,
  34136. convertToTexture: convertToTexture,
  34137. cos: cos,
  34138. cosh: cosh,
  34139. countLeadingZeros: countLeadingZeros,
  34140. countOneBits: countOneBits,
  34141. countTrailingZeros: countTrailingZeros,
  34142. cross: cross,
  34143. cubeTexture: cubeTexture,
  34144. cubeTextureBase: cubeTextureBase,
  34145. dFdx: dFdx,
  34146. dFdy: dFdy,
  34147. dashSize: dashSize,
  34148. debug: debug,
  34149. decrement: decrement,
  34150. decrementBefore: decrementBefore,
  34151. defaultBuildStages: defaultBuildStages,
  34152. defaultShaderStages: defaultShaderStages,
  34153. defined: defined,
  34154. degrees: degrees,
  34155. deltaTime: deltaTime,
  34156. densityFogFactor: densityFogFactor,
  34157. depth: depth,
  34158. depthPass: depthPass,
  34159. determinant: determinant,
  34160. difference: difference,
  34161. diffuseColor: diffuseColor,
  34162. diffuseContribution: diffuseContribution,
  34163. directPointLight: directPointLight,
  34164. directionToColor: directionToColor,
  34165. directionToFaceDirection: directionToFaceDirection,
  34166. dispersion: dispersion,
  34167. disposeShadowMaterial: disposeShadowMaterial,
  34168. distance: distance,
  34169. div: div,
  34170. dot: dot,
  34171. drawIndex: drawIndex,
  34172. dynamicBufferAttribute: dynamicBufferAttribute,
  34173. element: element,
  34174. emissive: emissive,
  34175. equal: equal,
  34176. equirectUV: equirectUV,
  34177. exp: exp,
  34178. exp2: exp2,
  34179. exponentialHeightFogFactor: exponentialHeightFogFactor,
  34180. expression: expression,
  34181. faceDirection: faceDirection,
  34182. faceForward: faceForward,
  34183. faceforward: faceforward,
  34184. float: float,
  34185. floatBitsToInt: floatBitsToInt,
  34186. floatBitsToUint: floatBitsToUint,
  34187. floor: floor,
  34188. fog: fog,
  34189. fract: fract,
  34190. frameGroup: frameGroup,
  34191. frameId: frameId,
  34192. frontFacing: frontFacing,
  34193. fwidth: fwidth,
  34194. gain: gain,
  34195. gapSize: gapSize,
  34196. getConstNodeType: getConstNodeType,
  34197. getCurrentStack: getCurrentStack,
  34198. getDirection: getDirection,
  34199. getDistanceAttenuation: getDistanceAttenuation,
  34200. getGeometryRoughness: getGeometryRoughness,
  34201. getNormalFromDepth: getNormalFromDepth,
  34202. getParallaxCorrectNormal: getParallaxCorrectNormal,
  34203. getRoughness: getRoughness,
  34204. getScreenPosition: getScreenPosition,
  34205. getShIrradianceAt: getShIrradianceAt,
  34206. getShadowMaterial: getShadowMaterial,
  34207. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  34208. getTextureIndex: getTextureIndex,
  34209. getViewPosition: getViewPosition,
  34210. ggxConvolution: ggxConvolution,
  34211. globalId: globalId,
  34212. glsl: glsl,
  34213. glslFn: glslFn,
  34214. grayscale: grayscale,
  34215. greaterThan: greaterThan,
  34216. greaterThanEqual: greaterThanEqual,
  34217. hash: hash,
  34218. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  34219. highpModelViewMatrix: highpModelViewMatrix,
  34220. hue: hue,
  34221. increment: increment,
  34222. incrementBefore: incrementBefore,
  34223. inspector: inspector,
  34224. instance: instance,
  34225. instanceIndex: instanceIndex,
  34226. instancedArray: instancedArray,
  34227. instancedBufferAttribute: instancedBufferAttribute,
  34228. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  34229. instancedMesh: instancedMesh,
  34230. int: int,
  34231. intBitsToFloat: intBitsToFloat,
  34232. interleavedGradientNoise: interleavedGradientNoise,
  34233. inverse: inverse,
  34234. inverseSqrt: inverseSqrt,
  34235. inversesqrt: inversesqrt,
  34236. invocationLocalIndex: invocationLocalIndex,
  34237. invocationSubgroupIndex: invocationSubgroupIndex,
  34238. ior: ior,
  34239. iridescence: iridescence,
  34240. iridescenceIOR: iridescenceIOR,
  34241. iridescenceThickness: iridescenceThickness,
  34242. isolate: isolate,
  34243. ivec2: ivec2,
  34244. ivec3: ivec3,
  34245. ivec4: ivec4,
  34246. js: js,
  34247. label: label,
  34248. length: length,
  34249. lengthSq: lengthSq,
  34250. lessThan: lessThan,
  34251. lessThanEqual: lessThanEqual,
  34252. lightPosition: lightPosition,
  34253. lightProjectionUV: lightProjectionUV,
  34254. lightShadowMatrix: lightShadowMatrix,
  34255. lightTargetDirection: lightTargetDirection,
  34256. lightTargetPosition: lightTargetPosition,
  34257. lightViewPosition: lightViewPosition,
  34258. lightingContext: lightingContext,
  34259. lights: lights,
  34260. linearDepth: linearDepth,
  34261. linearToneMapping: linearToneMapping,
  34262. localId: localId,
  34263. log: log,
  34264. log2: log2,
  34265. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  34266. luminance: luminance,
  34267. mat2: mat2,
  34268. mat3: mat3,
  34269. mat4: mat4,
  34270. matcapUV: matcapUV,
  34271. materialAO: materialAO,
  34272. materialAlphaTest: materialAlphaTest,
  34273. materialAnisotropy: materialAnisotropy,
  34274. materialAnisotropyVector: materialAnisotropyVector,
  34275. materialAttenuationColor: materialAttenuationColor,
  34276. materialAttenuationDistance: materialAttenuationDistance,
  34277. materialClearcoat: materialClearcoat,
  34278. materialClearcoatNormal: materialClearcoatNormal,
  34279. materialClearcoatRoughness: materialClearcoatRoughness,
  34280. materialColor: materialColor,
  34281. materialDispersion: materialDispersion,
  34282. materialEmissive: materialEmissive,
  34283. materialEnvIntensity: materialEnvIntensity,
  34284. materialEnvRotation: materialEnvRotation,
  34285. materialIOR: materialIOR,
  34286. materialIridescence: materialIridescence,
  34287. materialIridescenceIOR: materialIridescenceIOR,
  34288. materialIridescenceThickness: materialIridescenceThickness,
  34289. materialLightMap: materialLightMap,
  34290. materialLineDashOffset: materialLineDashOffset,
  34291. materialLineDashSize: materialLineDashSize,
  34292. materialLineGapSize: materialLineGapSize,
  34293. materialLineScale: materialLineScale,
  34294. materialLineWidth: materialLineWidth,
  34295. materialMetalness: materialMetalness,
  34296. materialNormal: materialNormal,
  34297. materialOpacity: materialOpacity,
  34298. materialPointSize: materialPointSize,
  34299. materialReference: materialReference,
  34300. materialReflectivity: materialReflectivity,
  34301. materialRefractionRatio: materialRefractionRatio,
  34302. materialRotation: materialRotation,
  34303. materialRoughness: materialRoughness,
  34304. materialSheen: materialSheen,
  34305. materialSheenRoughness: materialSheenRoughness,
  34306. materialShininess: materialShininess,
  34307. materialSpecular: materialSpecular,
  34308. materialSpecularColor: materialSpecularColor,
  34309. materialSpecularIntensity: materialSpecularIntensity,
  34310. materialSpecularStrength: materialSpecularStrength,
  34311. materialThickness: materialThickness,
  34312. materialTransmission: materialTransmission,
  34313. max: max$1,
  34314. maxMipLevel: maxMipLevel,
  34315. mediumpModelViewMatrix: mediumpModelViewMatrix,
  34316. metalness: metalness,
  34317. min: min$1,
  34318. mix: mix,
  34319. mixElement: mixElement,
  34320. mod: mod,
  34321. modelDirection: modelDirection,
  34322. modelNormalMatrix: modelNormalMatrix,
  34323. modelPosition: modelPosition,
  34324. modelRadius: modelRadius,
  34325. modelScale: modelScale,
  34326. modelViewMatrix: modelViewMatrix,
  34327. modelViewPosition: modelViewPosition,
  34328. modelViewProjection: modelViewProjection,
  34329. modelWorldMatrix: modelWorldMatrix,
  34330. modelWorldMatrixInverse: modelWorldMatrixInverse,
  34331. morphReference: morphReference,
  34332. mrt: mrt,
  34333. mul: mul,
  34334. mx_aastep: mx_aastep,
  34335. mx_add: mx_add,
  34336. mx_atan2: mx_atan2,
  34337. mx_cell_noise_float: mx_cell_noise_float,
  34338. mx_contrast: mx_contrast,
  34339. mx_divide: mx_divide,
  34340. mx_fractal_noise_float: mx_fractal_noise_float,
  34341. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  34342. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  34343. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  34344. mx_frame: mx_frame,
  34345. mx_heighttonormal: mx_heighttonormal,
  34346. mx_hsvtorgb: mx_hsvtorgb,
  34347. mx_ifequal: mx_ifequal,
  34348. mx_ifgreater: mx_ifgreater,
  34349. mx_ifgreatereq: mx_ifgreatereq,
  34350. mx_invert: mx_invert,
  34351. mx_modulo: mx_modulo,
  34352. mx_multiply: mx_multiply,
  34353. mx_noise_float: mx_noise_float,
  34354. mx_noise_vec3: mx_noise_vec3,
  34355. mx_noise_vec4: mx_noise_vec4,
  34356. mx_place2d: mx_place2d,
  34357. mx_power: mx_power,
  34358. mx_ramp4: mx_ramp4,
  34359. mx_ramplr: mx_ramplr,
  34360. mx_ramptb: mx_ramptb,
  34361. mx_rgbtohsv: mx_rgbtohsv,
  34362. mx_rotate2d: mx_rotate2d,
  34363. mx_rotate3d: mx_rotate3d,
  34364. mx_safepower: mx_safepower,
  34365. mx_separate: mx_separate,
  34366. mx_splitlr: mx_splitlr,
  34367. mx_splittb: mx_splittb,
  34368. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  34369. mx_subtract: mx_subtract,
  34370. mx_timer: mx_timer,
  34371. mx_transform_uv: mx_transform_uv,
  34372. mx_unifiednoise2d: mx_unifiednoise2d,
  34373. mx_unifiednoise3d: mx_unifiednoise3d,
  34374. mx_worley_noise_float: mx_worley_noise_float,
  34375. mx_worley_noise_vec2: mx_worley_noise_vec2,
  34376. mx_worley_noise_vec3: mx_worley_noise_vec3,
  34377. negate: negate,
  34378. neutralToneMapping: neutralToneMapping,
  34379. nodeArray: nodeArray,
  34380. nodeImmutable: nodeImmutable,
  34381. nodeObject: nodeObject,
  34382. nodeObjectIntent: nodeObjectIntent,
  34383. nodeObjects: nodeObjects,
  34384. nodeProxy: nodeProxy,
  34385. nodeProxyIntent: nodeProxyIntent,
  34386. normalFlat: normalFlat,
  34387. normalGeometry: normalGeometry,
  34388. normalLocal: normalLocal,
  34389. normalMap: normalMap,
  34390. normalView: normalView,
  34391. normalViewGeometry: normalViewGeometry,
  34392. normalWorld: normalWorld,
  34393. normalWorldGeometry: normalWorldGeometry,
  34394. normalize: normalize,
  34395. not: not,
  34396. notEqual: notEqual,
  34397. numWorkgroups: numWorkgroups,
  34398. objectDirection: objectDirection,
  34399. objectGroup: objectGroup,
  34400. objectPosition: objectPosition,
  34401. objectRadius: objectRadius,
  34402. objectScale: objectScale,
  34403. objectViewPosition: objectViewPosition,
  34404. objectWorldMatrix: objectWorldMatrix,
  34405. oneMinus: oneMinus,
  34406. or: or,
  34407. orthographicDepthToViewZ: orthographicDepthToViewZ,
  34408. oscSawtooth: oscSawtooth,
  34409. oscSine: oscSine,
  34410. oscSquare: oscSquare,
  34411. oscTriangle: oscTriangle,
  34412. output: output,
  34413. outputStruct: outputStruct,
  34414. overloadingFn: overloadingFn,
  34415. packHalf2x16: packHalf2x16,
  34416. packSnorm2x16: packSnorm2x16,
  34417. packUnorm2x16: packUnorm2x16,
  34418. parabola: parabola,
  34419. parallaxDirection: parallaxDirection,
  34420. parallaxUV: parallaxUV,
  34421. parameter: parameter,
  34422. pass: pass,
  34423. passTexture: passTexture,
  34424. pcurve: pcurve,
  34425. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  34426. pmremTexture: pmremTexture,
  34427. pointShadow: pointShadow,
  34428. pointUV: pointUV,
  34429. pointWidth: pointWidth,
  34430. positionGeometry: positionGeometry,
  34431. positionLocal: positionLocal,
  34432. positionPrevious: positionPrevious,
  34433. positionView: positionView,
  34434. positionViewDirection: positionViewDirection,
  34435. positionWorld: positionWorld,
  34436. positionWorldDirection: positionWorldDirection,
  34437. posterize: posterize,
  34438. pow: pow,
  34439. pow2: pow2,
  34440. pow3: pow3,
  34441. pow4: pow4,
  34442. premultiplyAlpha: premultiplyAlpha,
  34443. property: property,
  34444. quadBroadcast: quadBroadcast,
  34445. quadSwapDiagonal: quadSwapDiagonal,
  34446. quadSwapX: quadSwapX,
  34447. quadSwapY: quadSwapY,
  34448. radians: radians,
  34449. rand: rand,
  34450. range: range,
  34451. rangeFogFactor: rangeFogFactor,
  34452. reciprocal: reciprocal,
  34453. reference: reference,
  34454. referenceBuffer: referenceBuffer,
  34455. reflect: reflect,
  34456. reflectVector: reflectVector,
  34457. reflectView: reflectView,
  34458. reflector: reflector,
  34459. refract: refract,
  34460. refractVector: refractVector,
  34461. refractView: refractView,
  34462. reinhardToneMapping: reinhardToneMapping,
  34463. remap: remap,
  34464. remapClamp: remapClamp,
  34465. renderGroup: renderGroup,
  34466. renderOutput: renderOutput,
  34467. rendererReference: rendererReference,
  34468. replaceDefaultUV: replaceDefaultUV,
  34469. rotate: rotate,
  34470. rotateUV: rotateUV,
  34471. roughness: roughness,
  34472. round: round,
  34473. rtt: rtt,
  34474. sRGBTransferEOTF: sRGBTransferEOTF,
  34475. sRGBTransferOETF: sRGBTransferOETF,
  34476. sample: sample,
  34477. sampler: sampler,
  34478. samplerComparison: samplerComparison,
  34479. saturate: saturate,
  34480. saturation: saturation,
  34481. screenCoordinate: screenCoordinate,
  34482. screenDPR: screenDPR,
  34483. screenSize: screenSize,
  34484. screenUV: screenUV,
  34485. select: select,
  34486. setCurrentStack: setCurrentStack,
  34487. setName: setName,
  34488. shaderStages: shaderStages,
  34489. shadow: shadow,
  34490. shadowPositionWorld: shadowPositionWorld,
  34491. shapeCircle: shapeCircle,
  34492. sharedUniformGroup: sharedUniformGroup,
  34493. sheen: sheen,
  34494. sheenRoughness: sheenRoughness,
  34495. shiftLeft: shiftLeft,
  34496. shiftRight: shiftRight,
  34497. shininess: shininess,
  34498. sign: sign,
  34499. sin: sin,
  34500. sinc: sinc,
  34501. sinh: sinh,
  34502. skinning: skinning,
  34503. smoothstep: smoothstep,
  34504. smoothstepElement: smoothstepElement,
  34505. specularColor: specularColor,
  34506. specularColorBlended: specularColorBlended,
  34507. specularF90: specularF90,
  34508. spherizeUV: spherizeUV,
  34509. split: split,
  34510. spritesheetUV: spritesheetUV,
  34511. sqrt: sqrt,
  34512. stack: stack,
  34513. step: step,
  34514. stepElement: stepElement,
  34515. storage: storage,
  34516. storageBarrier: storageBarrier,
  34517. storageTexture: storageTexture,
  34518. struct: struct,
  34519. sub: sub,
  34520. subBuild: subBuild,
  34521. subgroupAdd: subgroupAdd,
  34522. subgroupAll: subgroupAll,
  34523. subgroupAnd: subgroupAnd,
  34524. subgroupAny: subgroupAny,
  34525. subgroupBallot: subgroupBallot,
  34526. subgroupBroadcast: subgroupBroadcast,
  34527. subgroupBroadcastFirst: subgroupBroadcastFirst,
  34528. subgroupElect: subgroupElect,
  34529. subgroupExclusiveAdd: subgroupExclusiveAdd,
  34530. subgroupExclusiveMul: subgroupExclusiveMul,
  34531. subgroupInclusiveAdd: subgroupInclusiveAdd,
  34532. subgroupInclusiveMul: subgroupInclusiveMul,
  34533. subgroupIndex: subgroupIndex,
  34534. subgroupMax: subgroupMax,
  34535. subgroupMin: subgroupMin,
  34536. subgroupMul: subgroupMul,
  34537. subgroupOr: subgroupOr,
  34538. subgroupShuffle: subgroupShuffle,
  34539. subgroupShuffleDown: subgroupShuffleDown,
  34540. subgroupShuffleUp: subgroupShuffleUp,
  34541. subgroupShuffleXor: subgroupShuffleXor,
  34542. subgroupSize: subgroupSize,
  34543. subgroupXor: subgroupXor,
  34544. tan: tan,
  34545. tangentGeometry: tangentGeometry,
  34546. tangentLocal: tangentLocal,
  34547. tangentView: tangentView,
  34548. tangentWorld: tangentWorld,
  34549. tanh: tanh,
  34550. texture: texture,
  34551. texture3D: texture3D,
  34552. texture3DLevel: texture3DLevel,
  34553. texture3DLoad: texture3DLoad,
  34554. textureBarrier: textureBarrier,
  34555. textureBicubic: textureBicubic,
  34556. textureBicubicLevel: textureBicubicLevel,
  34557. textureCubeUV: textureCubeUV,
  34558. textureLevel: textureLevel,
  34559. textureLoad: textureLoad,
  34560. textureSize: textureSize,
  34561. textureStore: textureStore,
  34562. thickness: thickness,
  34563. time: time,
  34564. toneMapping: toneMapping,
  34565. toneMappingExposure: toneMappingExposure,
  34566. toonOutlinePass: toonOutlinePass,
  34567. transformDirection: transformDirection,
  34568. transformNormal: transformNormal,
  34569. transformNormalToView: transformNormalToView,
  34570. transformedClearcoatNormalView: transformedClearcoatNormalView,
  34571. transformedNormalView: transformedNormalView,
  34572. transformedNormalWorld: transformedNormalWorld,
  34573. transmission: transmission,
  34574. transpose: transpose,
  34575. triNoise3D: triNoise3D,
  34576. triplanarTexture: triplanarTexture,
  34577. triplanarTextures: triplanarTextures,
  34578. trunc: trunc,
  34579. uint: uint,
  34580. uintBitsToFloat: uintBitsToFloat,
  34581. uniform: uniform,
  34582. uniformArray: uniformArray,
  34583. uniformCubeTexture: uniformCubeTexture,
  34584. uniformFlow: uniformFlow,
  34585. uniformGroup: uniformGroup,
  34586. uniformTexture: uniformTexture,
  34587. unpackHalf2x16: unpackHalf2x16,
  34588. unpackNormal: unpackNormal,
  34589. unpackSnorm2x16: unpackSnorm2x16,
  34590. unpackUnorm2x16: unpackUnorm2x16,
  34591. unpremultiplyAlpha: unpremultiplyAlpha,
  34592. userData: userData,
  34593. uv: uv$1,
  34594. uvec2: uvec2,
  34595. uvec3: uvec3,
  34596. uvec4: uvec4,
  34597. varying: varying,
  34598. varyingProperty: varyingProperty,
  34599. vec2: vec2,
  34600. vec3: vec3,
  34601. vec4: vec4,
  34602. vectorComponents: vectorComponents,
  34603. velocity: velocity,
  34604. vertexColor: vertexColor,
  34605. vertexIndex: vertexIndex,
  34606. vertexStage: vertexStage,
  34607. vibrance: vibrance,
  34608. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  34609. viewZToOrthographicDepth: viewZToOrthographicDepth,
  34610. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  34611. viewZToReversedOrthographicDepth: viewZToReversedOrthographicDepth,
  34612. viewZToReversedPerspectiveDepth: viewZToReversedPerspectiveDepth,
  34613. viewport: viewport,
  34614. viewportCoordinate: viewportCoordinate,
  34615. viewportDepthTexture: viewportDepthTexture,
  34616. viewportLinearDepth: viewportLinearDepth,
  34617. viewportMipTexture: viewportMipTexture,
  34618. viewportOpaqueMipTexture: viewportOpaqueMipTexture,
  34619. viewportResolution: viewportResolution,
  34620. viewportSafeUV: viewportSafeUV,
  34621. viewportSharedTexture: viewportSharedTexture,
  34622. viewportSize: viewportSize,
  34623. viewportTexture: viewportTexture,
  34624. viewportUV: viewportUV,
  34625. vogelDiskSample: vogelDiskSample,
  34626. wgsl: wgsl,
  34627. wgslFn: wgslFn,
  34628. workgroupArray: workgroupArray,
  34629. workgroupBarrier: workgroupBarrier,
  34630. workgroupId: workgroupId,
  34631. workingToColorSpace: workingToColorSpace,
  34632. xor: xor
  34633. });
  34634. const _clearColor = /*@__PURE__*/ new Color4();
  34635. /**
  34636. * This renderer module manages the background.
  34637. *
  34638. * @private
  34639. * @augments DataMap
  34640. */
  34641. class Background extends DataMap {
  34642. /**
  34643. * Constructs a new background management component.
  34644. *
  34645. * @param {Renderer} renderer - The renderer.
  34646. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  34647. */
  34648. constructor( renderer, nodes ) {
  34649. super();
  34650. /**
  34651. * The renderer.
  34652. *
  34653. * @type {Renderer}
  34654. */
  34655. this.renderer = renderer;
  34656. /**
  34657. * Renderer component for managing nodes related logic.
  34658. *
  34659. * @type {NodeManager}
  34660. */
  34661. this.nodes = nodes;
  34662. }
  34663. /**
  34664. * Updates the background for the given scene. Depending on how `Scene.background`
  34665. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  34666. * or add a mesh to the render list for rendering the background as a textured plane
  34667. * or skybox.
  34668. *
  34669. * @param {Scene} scene - The scene.
  34670. * @param {RenderList} renderList - The current render list.
  34671. * @param {RenderContext} renderContext - The current render context.
  34672. */
  34673. update( scene, renderList, renderContext ) {
  34674. const renderer = this.renderer;
  34675. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  34676. let forceClear = false;
  34677. if ( background === null ) {
  34678. // no background settings, use clear color configuration from the renderer
  34679. renderer._clearColor.getRGB( _clearColor );
  34680. _clearColor.a = renderer._clearColor.a;
  34681. } else if ( background.isColor === true ) {
  34682. // background is an opaque color
  34683. background.getRGB( _clearColor );
  34684. _clearColor.a = 1;
  34685. forceClear = true;
  34686. } else if ( background.isNode === true ) {
  34687. const sceneData = this.get( scene );
  34688. const backgroundNode = background;
  34689. _clearColor.copy( renderer._clearColor );
  34690. let backgroundMesh = sceneData.backgroundMesh;
  34691. if ( backgroundMesh === undefined ) {
  34692. const backgroundMeshNode = vec4( backgroundNode ).mul( backgroundIntensity ).context( {
  34693. // @TODO: Add Texture2D support using node context
  34694. getUV: () => backgroundRotation.mul( normalWorldGeometry ),
  34695. getTextureLevel: () => backgroundBlurriness
  34696. } );
  34697. // when using orthographic cameras, we must scale the skybox sphere
  34698. // up to exceed the dimensions of the camera's viewing box.
  34699. const isOrtho = cameraProjectionMatrix.element( 3 ).element( 3 ).equal( 1.0 );
  34700. // calculate the orthographic scale
  34701. // projectionMatrix[1][1] is (1 / top). Invert it to get the height and multiply by 3.0
  34702. // (an arbitrary safety factor) to ensure the skybox is large enough to cover the corners
  34703. // of the rectangular screen
  34704. const orthoScale = div( 1.0, cameraProjectionMatrix.element( 1 ).element( 1 ) ).mul( 3.0 );
  34705. // compute vertex position
  34706. const modifiedPosition = isOrtho.select( positionLocal.mul( orthoScale ), positionLocal );
  34707. // by using a w component of 0, the skybox will not translate when the camera moves through the scene
  34708. const viewPosition = modelViewMatrix.mul( vec4( modifiedPosition, 0.0 ) );
  34709. // we force w=1.0 here to prevent the w_clip=0 divide-by-zero error for ortho cameras.
  34710. let viewProj = cameraProjectionMatrix.mul( vec4( viewPosition.xyz, 1.0 ) );
  34711. // force background to far plane so it does not occlude objects
  34712. viewProj = viewProj.setZ( viewProj.w );
  34713. const nodeMaterial = new NodeMaterial();
  34714. nodeMaterial.name = 'Background.material';
  34715. nodeMaterial.side = BackSide;
  34716. nodeMaterial.depthTest = false;
  34717. nodeMaterial.depthWrite = false;
  34718. nodeMaterial.allowOverride = false;
  34719. nodeMaterial.fog = false;
  34720. nodeMaterial.lights = false;
  34721. nodeMaterial.vertexNode = viewProj;
  34722. nodeMaterial.colorNode = backgroundMeshNode;
  34723. sceneData.backgroundMeshNode = backgroundMeshNode;
  34724. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  34725. backgroundMesh.frustumCulled = false;
  34726. backgroundMesh.name = 'Background.mesh';
  34727. function onBackgroundDispose() {
  34728. background.removeEventListener( 'dispose', onBackgroundDispose );
  34729. backgroundMesh.material.dispose();
  34730. backgroundMesh.geometry.dispose();
  34731. }
  34732. background.addEventListener( 'dispose', onBackgroundDispose );
  34733. }
  34734. const backgroundCacheKey = backgroundNode.getCacheKey();
  34735. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  34736. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  34737. sceneData.backgroundMeshNode.needsUpdate = true;
  34738. backgroundMesh.material.needsUpdate = true;
  34739. sceneData.backgroundCacheKey = backgroundCacheKey;
  34740. }
  34741. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  34742. } else {
  34743. error( 'Renderer: Unsupported background configuration.', background );
  34744. }
  34745. //
  34746. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  34747. if ( environmentBlendMode === 'additive' ) {
  34748. _clearColor.set( 0, 0, 0, 1 );
  34749. } else if ( environmentBlendMode === 'alpha-blend' ) {
  34750. _clearColor.set( 0, 0, 0, 0 );
  34751. }
  34752. //
  34753. if ( renderer.autoClear === true || forceClear === true ) {
  34754. const clearColorValue = renderContext.clearColorValue;
  34755. clearColorValue.r = _clearColor.r;
  34756. clearColorValue.g = _clearColor.g;
  34757. clearColorValue.b = _clearColor.b;
  34758. clearColorValue.a = _clearColor.a;
  34759. // premultiply alpha
  34760. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  34761. clearColorValue.r *= clearColorValue.a;
  34762. clearColorValue.g *= clearColorValue.a;
  34763. clearColorValue.b *= clearColorValue.a;
  34764. }
  34765. //
  34766. renderContext.depthClearValue = renderer.getClearDepth();
  34767. renderContext.stencilClearValue = renderer.getClearStencil();
  34768. renderContext.clearColor = renderer.autoClearColor === true;
  34769. renderContext.clearDepth = renderer.autoClearDepth === true;
  34770. renderContext.clearStencil = renderer.autoClearStencil === true;
  34771. } else {
  34772. renderContext.clearColor = false;
  34773. renderContext.clearDepth = false;
  34774. renderContext.clearStencil = false;
  34775. }
  34776. }
  34777. }
  34778. let _id$7 = 0;
  34779. /**
  34780. * A bind group represents a collection of bindings and thus a collection
  34781. * or resources. Bind groups are assigned to pipelines to provide them
  34782. * with the required resources (like uniform buffers or textures).
  34783. *
  34784. * @private
  34785. */
  34786. class BindGroup {
  34787. /**
  34788. * Constructs a new bind group.
  34789. *
  34790. * @param {string} name - The bind group's name.
  34791. * @param {Array<Binding>} bindings - An array of bindings.
  34792. * @param {number} index - The group index.
  34793. */
  34794. constructor( name = '', bindings = [] ) {
  34795. /**
  34796. * The bind group's name.
  34797. *
  34798. * @type {string}
  34799. */
  34800. this.name = name;
  34801. /**
  34802. * An array of bindings.
  34803. *
  34804. * @type {Array<Binding>}
  34805. */
  34806. this.bindings = bindings;
  34807. /**
  34808. * The group's ID.
  34809. *
  34810. * @type {number}
  34811. */
  34812. this.id = _id$7 ++;
  34813. }
  34814. }
  34815. /**
  34816. * This module represents the state of a node builder after it was
  34817. * used to build the nodes for a render object. The state holds the
  34818. * results of the build for further processing in the renderer.
  34819. *
  34820. * Render objects with identical cache keys share the same node builder state.
  34821. *
  34822. * @private
  34823. */
  34824. class NodeBuilderState {
  34825. /**
  34826. * Constructs a new node builder state.
  34827. *
  34828. * @param {string} vertexShader - The native vertex shader code.
  34829. * @param {string} fragmentShader - The native fragment shader code.
  34830. * @param {string} computeShader - The native compute shader code.
  34831. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  34832. * @param {Array<BindGroup>} bindings - An array of bind groups.
  34833. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  34834. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  34835. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  34836. * @param {NodeMaterialObserver} observer - A node material observer.
  34837. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  34838. */
  34839. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  34840. /**
  34841. * The native vertex shader code.
  34842. *
  34843. * @type {string}
  34844. */
  34845. this.vertexShader = vertexShader;
  34846. /**
  34847. * The native fragment shader code.
  34848. *
  34849. * @type {string}
  34850. */
  34851. this.fragmentShader = fragmentShader;
  34852. /**
  34853. * The native compute shader code.
  34854. *
  34855. * @type {string}
  34856. */
  34857. this.computeShader = computeShader;
  34858. /**
  34859. * An array with transform attribute objects.
  34860. * Only relevant when using compute shaders with WebGL 2.
  34861. *
  34862. * @type {Array<Object>}
  34863. */
  34864. this.transforms = transforms;
  34865. /**
  34866. * An array of node attributes representing
  34867. * the attributes of the shaders.
  34868. *
  34869. * @type {Array<NodeAttribute>}
  34870. */
  34871. this.nodeAttributes = nodeAttributes;
  34872. /**
  34873. * An array of bind groups representing the uniform or storage
  34874. * buffers, texture or samplers of the shader.
  34875. *
  34876. * @type {Array<BindGroup>}
  34877. */
  34878. this.bindings = bindings;
  34879. /**
  34880. * An array of nodes that implement their `update()` method.
  34881. *
  34882. * @type {Array<Node>}
  34883. */
  34884. this.updateNodes = updateNodes;
  34885. /**
  34886. * An array of nodes that implement their `updateBefore()` method.
  34887. *
  34888. * @type {Array<Node>}
  34889. */
  34890. this.updateBeforeNodes = updateBeforeNodes;
  34891. /**
  34892. * An array of nodes that implement their `updateAfter()` method.
  34893. *
  34894. * @type {Array<Node>}
  34895. */
  34896. this.updateAfterNodes = updateAfterNodes;
  34897. /**
  34898. * A node material observer.
  34899. *
  34900. * @type {NodeMaterialObserver}
  34901. */
  34902. this.observer = observer;
  34903. /**
  34904. * How often this state is used by render objects.
  34905. *
  34906. * @type {number}
  34907. */
  34908. this.usedTimes = 0;
  34909. }
  34910. /**
  34911. * This method is used to create a array of bind groups based
  34912. * on the existing bind groups of this state. Shared groups are
  34913. * not cloned.
  34914. *
  34915. * @return {Array<BindGroup>} A array of bind groups.
  34916. */
  34917. createBindings() {
  34918. const bindings = [];
  34919. for ( const instanceGroup of this.bindings ) {
  34920. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  34921. if ( shared !== true ) {
  34922. const bindingsGroup = new BindGroup( instanceGroup.name, [] );
  34923. bindings.push( bindingsGroup );
  34924. for ( const instanceBinding of instanceGroup.bindings ) {
  34925. bindingsGroup.bindings.push( instanceBinding.clone() );
  34926. }
  34927. } else {
  34928. bindings.push( instanceGroup );
  34929. }
  34930. }
  34931. return bindings;
  34932. }
  34933. }
  34934. /**
  34935. * {@link NodeBuilder} is going to create instances of this class during the build process
  34936. * of nodes. They represent the final shader attributes that are going to be generated
  34937. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  34938. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  34939. */
  34940. class NodeAttribute {
  34941. /**
  34942. * Constructs a new node attribute.
  34943. *
  34944. * @param {string} name - The name of the attribute.
  34945. * @param {string} type - The type of the attribute.
  34946. * @param {?Node} node - An optional reference to the node.
  34947. */
  34948. constructor( name, type, node = null ) {
  34949. /**
  34950. * This flag can be used for type testing.
  34951. *
  34952. * @type {boolean}
  34953. * @readonly
  34954. * @default true
  34955. */
  34956. this.isNodeAttribute = true;
  34957. /**
  34958. * The name of the attribute.
  34959. *
  34960. * @type {string}
  34961. */
  34962. this.name = name;
  34963. /**
  34964. * The type of the attribute.
  34965. *
  34966. * @type {string}
  34967. */
  34968. this.type = type;
  34969. /**
  34970. * An optional reference to the node.
  34971. *
  34972. * @type {?Node}
  34973. * @default null
  34974. */
  34975. this.node = node;
  34976. }
  34977. }
  34978. /**
  34979. * {@link NodeBuilder} is going to create instances of this class during the build process
  34980. * of nodes. They represent the final shader uniforms that are going to be generated
  34981. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  34982. * for this purpose.
  34983. */
  34984. class NodeUniform {
  34985. /**
  34986. * Constructs a new node uniform.
  34987. *
  34988. * @param {string} name - The name of the uniform.
  34989. * @param {string} type - The type of the uniform.
  34990. * @param {UniformNode} node - An reference to the node.
  34991. */
  34992. constructor( name, type, node ) {
  34993. /**
  34994. * This flag can be used for type testing.
  34995. *
  34996. * @type {boolean}
  34997. * @readonly
  34998. * @default true
  34999. */
  35000. this.isNodeUniform = true;
  35001. /**
  35002. * The name of the uniform.
  35003. *
  35004. * @type {string}
  35005. */
  35006. this.name = name;
  35007. /**
  35008. * The type of the uniform.
  35009. *
  35010. * @type {string}
  35011. */
  35012. this.type = type;
  35013. /**
  35014. * An reference to the node.
  35015. *
  35016. * @type {UniformNode}
  35017. */
  35018. this.node = node;
  35019. }
  35020. /**
  35021. * The value of the uniform node.
  35022. *
  35023. * @type {any}
  35024. */
  35025. get value() {
  35026. return this.node.value;
  35027. }
  35028. set value( val ) {
  35029. this.node.value = val;
  35030. }
  35031. /**
  35032. * The id of the uniform node.
  35033. *
  35034. * @type {number}
  35035. */
  35036. get id() {
  35037. return this.node.id;
  35038. }
  35039. /**
  35040. * The uniform node's group.
  35041. *
  35042. * @type {UniformGroupNode}
  35043. */
  35044. get groupNode() {
  35045. return this.node.groupNode;
  35046. }
  35047. }
  35048. /**
  35049. * {@link NodeBuilder} is going to create instances of this class during the build process
  35050. * of nodes. They represent the final shader variables that are going to be generated
  35051. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  35052. * this purpose.
  35053. */
  35054. class NodeVar {
  35055. /**
  35056. * Constructs a new node variable.
  35057. *
  35058. * @param {string} name - The name of the variable.
  35059. * @param {string} type - The type of the variable.
  35060. * @param {boolean} [readOnly=false] - The read-only flag.
  35061. * @param {?number} [count=null] - The size.
  35062. */
  35063. constructor( name, type, readOnly = false, count = null ) {
  35064. /**
  35065. * This flag can be used for type testing.
  35066. *
  35067. * @type {boolean}
  35068. * @readonly
  35069. * @default true
  35070. */
  35071. this.isNodeVar = true;
  35072. /**
  35073. * The name of the variable.
  35074. *
  35075. * @type {string}
  35076. */
  35077. this.name = name;
  35078. /**
  35079. * The type of the variable.
  35080. *
  35081. * @type {string}
  35082. */
  35083. this.type = type;
  35084. /**
  35085. * The read-only flag.
  35086. *
  35087. * @type {boolean}
  35088. */
  35089. this.readOnly = readOnly;
  35090. /**
  35091. * The size.
  35092. *
  35093. * @type {?number}
  35094. */
  35095. this.count = count;
  35096. }
  35097. }
  35098. /**
  35099. * {@link NodeBuilder} is going to create instances of this class during the build process
  35100. * of nodes. They represent the final shader varyings that are going to be generated
  35101. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  35102. * this purpose.
  35103. *
  35104. * @augments NodeVar
  35105. */
  35106. class NodeVarying extends NodeVar {
  35107. /**
  35108. * Constructs a new node varying.
  35109. *
  35110. * @param {string} name - The name of the varying.
  35111. * @param {string} type - The type of the varying.
  35112. * @param {?string} interpolationType - The interpolation type of the varying.
  35113. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  35114. */
  35115. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  35116. super( name, type );
  35117. /**
  35118. * Whether this varying requires interpolation or not. This property can be used
  35119. * to check if the varying can be optimized for a variable.
  35120. *
  35121. * @type {boolean}
  35122. * @default false
  35123. */
  35124. this.needsInterpolation = false;
  35125. /**
  35126. * This flag can be used for type testing.
  35127. *
  35128. * @type {boolean}
  35129. * @readonly
  35130. * @default true
  35131. */
  35132. this.isNodeVarying = true;
  35133. /**
  35134. * The interpolation type of the varying data.
  35135. *
  35136. * @type {?string}
  35137. * @default null
  35138. */
  35139. this.interpolationType = interpolationType;
  35140. /**
  35141. * The interpolation sampling type of varying data.
  35142. *
  35143. * @type {?string}
  35144. * @default null
  35145. */
  35146. this.interpolationSampling = interpolationSampling;
  35147. }
  35148. }
  35149. /**
  35150. * {@link NodeBuilder} is going to create instances of this class during the build process
  35151. * of nodes. They represent user-defined, native shader code portions that are going to be
  35152. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  35153. * for this purpose.
  35154. */
  35155. class NodeCode {
  35156. /**
  35157. * Constructs a new code node.
  35158. *
  35159. * @param {string} name - The name of the code.
  35160. * @param {string} type - The node type.
  35161. * @param {string} [code=''] - The native shader code.
  35162. */
  35163. constructor( name, type, code = '' ) {
  35164. /**
  35165. * The name of the code.
  35166. *
  35167. * @type {string}
  35168. */
  35169. this.name = name;
  35170. /**
  35171. * The node type.
  35172. *
  35173. * @type {string}
  35174. */
  35175. this.type = type;
  35176. /**
  35177. * The native shader code.
  35178. *
  35179. * @type {string}
  35180. * @default ''
  35181. */
  35182. this.code = code;
  35183. Object.defineProperty( this, 'isNodeCode', { value: true } );
  35184. }
  35185. }
  35186. let _id$6 = 0;
  35187. /**
  35188. * This utility class is used in {@link NodeBuilder} as an internal
  35189. * cache data structure for node data.
  35190. */
  35191. class NodeCache {
  35192. /**
  35193. * Constructs a new node cache.
  35194. *
  35195. * @param {?NodeCache} parent - A reference to a parent cache.
  35196. */
  35197. constructor( parent = null ) {
  35198. /**
  35199. * The id of the cache.
  35200. *
  35201. * @type {number}
  35202. * @readonly
  35203. */
  35204. this.id = _id$6 ++;
  35205. /**
  35206. * A weak map for managing node data.
  35207. *
  35208. * @type {WeakMap<Node, Object>}
  35209. */
  35210. this.nodesData = new WeakMap();
  35211. /**
  35212. * Reference to a parent node cache.
  35213. *
  35214. * @type {?NodeCache}
  35215. * @default null
  35216. */
  35217. this.parent = parent;
  35218. }
  35219. /**
  35220. * Returns the data for the given node.
  35221. *
  35222. * @param {Node} node - The node.
  35223. * @return {?Object} The data for the node.
  35224. */
  35225. getData( node ) {
  35226. let data = this.nodesData.get( node );
  35227. if ( data === undefined && this.parent !== null ) {
  35228. data = this.parent.getData( node );
  35229. }
  35230. return data;
  35231. }
  35232. /**
  35233. * Sets the data for a given node.
  35234. *
  35235. * @param {Node} node - The node.
  35236. * @param {Object} data - The data that should be cached.
  35237. */
  35238. setData( node, data ) {
  35239. this.nodesData.set( node, data );
  35240. }
  35241. }
  35242. class StructType {
  35243. constructor( name, members ) {
  35244. this.name = name;
  35245. this.members = members;
  35246. this.output = false;
  35247. }
  35248. }
  35249. /**
  35250. * Abstract base class for uniforms.
  35251. *
  35252. * @abstract
  35253. * @private
  35254. */
  35255. class Uniform {
  35256. /**
  35257. * Constructs a new uniform.
  35258. *
  35259. * @param {string} name - The uniform's name.
  35260. * @param {any} value - The uniform's value.
  35261. */
  35262. constructor( name, value ) {
  35263. /**
  35264. * The uniform's name.
  35265. *
  35266. * @type {string}
  35267. */
  35268. this.name = name;
  35269. /**
  35270. * The uniform's value.
  35271. *
  35272. * @type {any}
  35273. */
  35274. this.value = value;
  35275. /**
  35276. * Used to build the uniform buffer according to the STD140 layout.
  35277. * Derived uniforms will set this property to a data type specific
  35278. * value.
  35279. *
  35280. * @type {number}
  35281. */
  35282. this.boundary = 0;
  35283. /**
  35284. * The item size. Derived uniforms will set this property to a data
  35285. * type specific value.
  35286. *
  35287. * @type {number}
  35288. */
  35289. this.itemSize = 0;
  35290. /**
  35291. * This property is set by {@link UniformsGroup} and marks
  35292. * the start position in the uniform buffer.
  35293. *
  35294. * @type {number}
  35295. */
  35296. this.offset = 0;
  35297. /**
  35298. * This property is set by {@link UniformsGroup} and marks
  35299. * the index position in the uniform array.
  35300. *
  35301. * @type {number}
  35302. */
  35303. this.index = -1;
  35304. }
  35305. /**
  35306. * Sets the uniform's value.
  35307. *
  35308. * @param {any} value - The value to set.
  35309. */
  35310. setValue( value ) {
  35311. this.value = value;
  35312. }
  35313. /**
  35314. * Returns the uniform's value.
  35315. *
  35316. * @return {any} The value.
  35317. */
  35318. getValue() {
  35319. return this.value;
  35320. }
  35321. }
  35322. /**
  35323. * Represents a Number uniform.
  35324. *
  35325. * @private
  35326. * @augments Uniform
  35327. */
  35328. class NumberUniform extends Uniform {
  35329. /**
  35330. * Constructs a new Number uniform.
  35331. *
  35332. * @param {string} name - The uniform's name.
  35333. * @param {number} value - The uniform's value.
  35334. */
  35335. constructor( name, value = 0 ) {
  35336. super( name, value );
  35337. /**
  35338. * This flag can be used for type testing.
  35339. *
  35340. * @type {boolean}
  35341. * @readonly
  35342. * @default true
  35343. */
  35344. this.isNumberUniform = true;
  35345. this.boundary = 4;
  35346. this.itemSize = 1;
  35347. }
  35348. }
  35349. /**
  35350. * Represents a Vector2 uniform.
  35351. *
  35352. * @private
  35353. * @augments Uniform
  35354. */
  35355. class Vector2Uniform extends Uniform {
  35356. /**
  35357. * Constructs a new Number uniform.
  35358. *
  35359. * @param {string} name - The uniform's name.
  35360. * @param {Vector2} value - The uniform's value.
  35361. */
  35362. constructor( name, value = new Vector2() ) {
  35363. super( name, value );
  35364. /**
  35365. * This flag can be used for type testing.
  35366. *
  35367. * @type {boolean}
  35368. * @readonly
  35369. * @default true
  35370. */
  35371. this.isVector2Uniform = true;
  35372. this.boundary = 8;
  35373. this.itemSize = 2;
  35374. }
  35375. }
  35376. /**
  35377. * Represents a Vector3 uniform.
  35378. *
  35379. * @private
  35380. * @augments Uniform
  35381. */
  35382. class Vector3Uniform extends Uniform {
  35383. /**
  35384. * Constructs a new Number uniform.
  35385. *
  35386. * @param {string} name - The uniform's name.
  35387. * @param {Vector3} value - The uniform's value.
  35388. */
  35389. constructor( name, value = new Vector3() ) {
  35390. super( name, value );
  35391. /**
  35392. * This flag can be used for type testing.
  35393. *
  35394. * @type {boolean}
  35395. * @readonly
  35396. * @default true
  35397. */
  35398. this.isVector3Uniform = true;
  35399. this.boundary = 16;
  35400. this.itemSize = 3;
  35401. }
  35402. }
  35403. /**
  35404. * Represents a Vector4 uniform.
  35405. *
  35406. * @private
  35407. * @augments Uniform
  35408. */
  35409. class Vector4Uniform extends Uniform {
  35410. /**
  35411. * Constructs a new Number uniform.
  35412. *
  35413. * @param {string} name - The uniform's name.
  35414. * @param {Vector4} value - The uniform's value.
  35415. */
  35416. constructor( name, value = new Vector4() ) {
  35417. super( name, value );
  35418. /**
  35419. * This flag can be used for type testing.
  35420. *
  35421. * @type {boolean}
  35422. * @readonly
  35423. * @default true
  35424. */
  35425. this.isVector4Uniform = true;
  35426. this.boundary = 16;
  35427. this.itemSize = 4;
  35428. }
  35429. }
  35430. /**
  35431. * Represents a Color uniform.
  35432. *
  35433. * @private
  35434. * @augments Uniform
  35435. */
  35436. class ColorUniform extends Uniform {
  35437. /**
  35438. * Constructs a new Number uniform.
  35439. *
  35440. * @param {string} name - The uniform's name.
  35441. * @param {Color} value - The uniform's value.
  35442. */
  35443. constructor( name, value = new Color() ) {
  35444. super( name, value );
  35445. /**
  35446. * This flag can be used for type testing.
  35447. *
  35448. * @type {boolean}
  35449. * @readonly
  35450. * @default true
  35451. */
  35452. this.isColorUniform = true;
  35453. this.boundary = 16;
  35454. this.itemSize = 3;
  35455. }
  35456. }
  35457. /**
  35458. * Represents a Matrix2 uniform.
  35459. *
  35460. * @private
  35461. * @augments Uniform
  35462. */
  35463. class Matrix2Uniform extends Uniform {
  35464. /**
  35465. * Constructs a new Number uniform.
  35466. *
  35467. * @param {string} name - The uniform's name.
  35468. * @param {Matrix2} value - The uniform's value.
  35469. */
  35470. constructor( name, value = new Matrix2() ) {
  35471. super( name, value );
  35472. /**
  35473. * This flag can be used for type testing.
  35474. *
  35475. * @type {boolean}
  35476. * @readonly
  35477. * @default true
  35478. */
  35479. this.isMatrix2Uniform = true;
  35480. this.boundary = 8;
  35481. this.itemSize = 4;
  35482. }
  35483. }
  35484. /**
  35485. * Represents a Matrix3 uniform.
  35486. *
  35487. * @private
  35488. * @augments Uniform
  35489. */
  35490. class Matrix3Uniform extends Uniform {
  35491. /**
  35492. * Constructs a new Number uniform.
  35493. *
  35494. * @param {string} name - The uniform's name.
  35495. * @param {Matrix3} value - The uniform's value.
  35496. */
  35497. constructor( name, value = new Matrix3() ) {
  35498. super( name, value );
  35499. /**
  35500. * This flag can be used for type testing.
  35501. *
  35502. * @type {boolean}
  35503. * @readonly
  35504. * @default true
  35505. */
  35506. this.isMatrix3Uniform = true;
  35507. this.boundary = 48;
  35508. this.itemSize = 12;
  35509. }
  35510. }
  35511. /**
  35512. * Represents a Matrix4 uniform.
  35513. *
  35514. * @private
  35515. * @augments Uniform
  35516. */
  35517. class Matrix4Uniform extends Uniform {
  35518. /**
  35519. * Constructs a new Number uniform.
  35520. *
  35521. * @param {string} name - The uniform's name.
  35522. * @param {Matrix4} value - The uniform's value.
  35523. */
  35524. constructor( name, value = new Matrix4() ) {
  35525. super( name, value );
  35526. /**
  35527. * This flag can be used for type testing.
  35528. *
  35529. * @type {boolean}
  35530. * @readonly
  35531. * @default true
  35532. */
  35533. this.isMatrix4Uniform = true;
  35534. this.boundary = 64;
  35535. this.itemSize = 16;
  35536. }
  35537. }
  35538. /**
  35539. * A special form of Number uniform binding type.
  35540. * It's value is managed by a node object.
  35541. *
  35542. * @private
  35543. * @augments NumberUniform
  35544. */
  35545. class NumberNodeUniform extends NumberUniform {
  35546. /**
  35547. * Constructs a new node-based Number uniform.
  35548. *
  35549. * @param {NodeUniform} nodeUniform - The node uniform.
  35550. */
  35551. constructor( nodeUniform ) {
  35552. super( nodeUniform.name, nodeUniform.value );
  35553. /**
  35554. * The node uniform.
  35555. *
  35556. * @type {NodeUniform}
  35557. */
  35558. this.nodeUniform = nodeUniform;
  35559. }
  35560. /**
  35561. * Overwritten to return the value of the node uniform.
  35562. *
  35563. * @return {number} The value.
  35564. */
  35565. getValue() {
  35566. return this.nodeUniform.value;
  35567. }
  35568. /**
  35569. * Returns the node uniform data type.
  35570. *
  35571. * @return {string} The data type.
  35572. */
  35573. getType() {
  35574. return this.nodeUniform.type;
  35575. }
  35576. }
  35577. /**
  35578. * A special form of Vector2 uniform binding type.
  35579. * It's value is managed by a node object.
  35580. *
  35581. * @private
  35582. * @augments Vector2Uniform
  35583. */
  35584. class Vector2NodeUniform extends Vector2Uniform {
  35585. /**
  35586. * Constructs a new node-based Vector2 uniform.
  35587. *
  35588. * @param {NodeUniform} nodeUniform - The node uniform.
  35589. */
  35590. constructor( nodeUniform ) {
  35591. super( nodeUniform.name, nodeUniform.value );
  35592. /**
  35593. * The node uniform.
  35594. *
  35595. * @type {NodeUniform}
  35596. */
  35597. this.nodeUniform = nodeUniform;
  35598. }
  35599. /**
  35600. * Overwritten to return the value of the node uniform.
  35601. *
  35602. * @return {Vector2} The value.
  35603. */
  35604. getValue() {
  35605. return this.nodeUniform.value;
  35606. }
  35607. /**
  35608. * Returns the node uniform data type.
  35609. *
  35610. * @return {string} The data type.
  35611. */
  35612. getType() {
  35613. return this.nodeUniform.type;
  35614. }
  35615. }
  35616. /**
  35617. * A special form of Vector3 uniform binding type.
  35618. * It's value is managed by a node object.
  35619. *
  35620. * @private
  35621. * @augments Vector3Uniform
  35622. */
  35623. class Vector3NodeUniform extends Vector3Uniform {
  35624. /**
  35625. * Constructs a new node-based Vector3 uniform.
  35626. *
  35627. * @param {NodeUniform} nodeUniform - The node uniform.
  35628. */
  35629. constructor( nodeUniform ) {
  35630. super( nodeUniform.name, nodeUniform.value );
  35631. /**
  35632. * The node uniform.
  35633. *
  35634. * @type {NodeUniform}
  35635. */
  35636. this.nodeUniform = nodeUniform;
  35637. }
  35638. /**
  35639. * Overwritten to return the value of the node uniform.
  35640. *
  35641. * @return {Vector3} The value.
  35642. */
  35643. getValue() {
  35644. return this.nodeUniform.value;
  35645. }
  35646. /**
  35647. * Returns the node uniform data type.
  35648. *
  35649. * @return {string} The data type.
  35650. */
  35651. getType() {
  35652. return this.nodeUniform.type;
  35653. }
  35654. }
  35655. /**
  35656. * A special form of Vector4 uniform binding type.
  35657. * It's value is managed by a node object.
  35658. *
  35659. * @private
  35660. * @augments Vector4Uniform
  35661. */
  35662. class Vector4NodeUniform extends Vector4Uniform {
  35663. /**
  35664. * Constructs a new node-based Vector4 uniform.
  35665. *
  35666. * @param {NodeUniform} nodeUniform - The node uniform.
  35667. */
  35668. constructor( nodeUniform ) {
  35669. super( nodeUniform.name, nodeUniform.value );
  35670. /**
  35671. * The node uniform.
  35672. *
  35673. * @type {NodeUniform}
  35674. */
  35675. this.nodeUniform = nodeUniform;
  35676. }
  35677. /**
  35678. * Overwritten to return the value of the node uniform.
  35679. *
  35680. * @return {Vector4} The value.
  35681. */
  35682. getValue() {
  35683. return this.nodeUniform.value;
  35684. }
  35685. /**
  35686. * Returns the node uniform data type.
  35687. *
  35688. * @return {string} The data type.
  35689. */
  35690. getType() {
  35691. return this.nodeUniform.type;
  35692. }
  35693. }
  35694. /**
  35695. * A special form of Color uniform binding type.
  35696. * It's value is managed by a node object.
  35697. *
  35698. * @private
  35699. * @augments ColorUniform
  35700. */
  35701. class ColorNodeUniform extends ColorUniform {
  35702. /**
  35703. * Constructs a new node-based Color uniform.
  35704. *
  35705. * @param {NodeUniform} nodeUniform - The node uniform.
  35706. */
  35707. constructor( nodeUniform ) {
  35708. super( nodeUniform.name, nodeUniform.value );
  35709. /**
  35710. * The node uniform.
  35711. *
  35712. * @type {NodeUniform}
  35713. */
  35714. this.nodeUniform = nodeUniform;
  35715. }
  35716. /**
  35717. * Overwritten to return the value of the node uniform.
  35718. *
  35719. * @return {Color} The value.
  35720. */
  35721. getValue() {
  35722. return this.nodeUniform.value;
  35723. }
  35724. /**
  35725. * Returns the node uniform data type.
  35726. *
  35727. * @return {string} The data type.
  35728. */
  35729. getType() {
  35730. return this.nodeUniform.type;
  35731. }
  35732. }
  35733. /**
  35734. * A special form of Matrix2 uniform binding type.
  35735. * It's value is managed by a node object.
  35736. *
  35737. * @private
  35738. * @augments Matrix2Uniform
  35739. */
  35740. class Matrix2NodeUniform extends Matrix2Uniform {
  35741. /**
  35742. * Constructs a new node-based Matrix2 uniform.
  35743. *
  35744. * @param {NodeUniform} nodeUniform - The node uniform.
  35745. */
  35746. constructor( nodeUniform ) {
  35747. super( nodeUniform.name, nodeUniform.value );
  35748. /**
  35749. * The node uniform.
  35750. *
  35751. * @type {NodeUniform}
  35752. */
  35753. this.nodeUniform = nodeUniform;
  35754. }
  35755. /**
  35756. * Overwritten to return the value of the node uniform.
  35757. *
  35758. * @return {Matrix2} The value.
  35759. */
  35760. getValue() {
  35761. return this.nodeUniform.value;
  35762. }
  35763. /**
  35764. * Returns the node uniform data type.
  35765. *
  35766. * @return {string} The data type.
  35767. */
  35768. getType() {
  35769. return this.nodeUniform.type;
  35770. }
  35771. }
  35772. /**
  35773. * A special form of Matrix3 uniform binding type.
  35774. * It's value is managed by a node object.
  35775. *
  35776. * @private
  35777. * @augments Matrix3Uniform
  35778. */
  35779. class Matrix3NodeUniform extends Matrix3Uniform {
  35780. /**
  35781. * Constructs a new node-based Matrix3 uniform.
  35782. *
  35783. * @param {NodeUniform} nodeUniform - The node uniform.
  35784. */
  35785. constructor( nodeUniform ) {
  35786. super( nodeUniform.name, nodeUniform.value );
  35787. /**
  35788. * The node uniform.
  35789. *
  35790. * @type {NodeUniform}
  35791. */
  35792. this.nodeUniform = nodeUniform;
  35793. }
  35794. /**
  35795. * Overwritten to return the value of the node uniform.
  35796. *
  35797. * @return {Matrix3} The value.
  35798. */
  35799. getValue() {
  35800. return this.nodeUniform.value;
  35801. }
  35802. /**
  35803. * Returns the node uniform data type.
  35804. *
  35805. * @return {string} The data type.
  35806. */
  35807. getType() {
  35808. return this.nodeUniform.type;
  35809. }
  35810. }
  35811. /**
  35812. * A special form of Matrix4 uniform binding type.
  35813. * It's value is managed by a node object.
  35814. *
  35815. * @private
  35816. * @augments Matrix4Uniform
  35817. */
  35818. class Matrix4NodeUniform extends Matrix4Uniform {
  35819. /**
  35820. * Constructs a new node-based Matrix4 uniform.
  35821. *
  35822. * @param {NodeUniform} nodeUniform - The node uniform.
  35823. */
  35824. constructor( nodeUniform ) {
  35825. super( nodeUniform.name, nodeUniform.value );
  35826. /**
  35827. * The node uniform.
  35828. *
  35829. * @type {NodeUniform}
  35830. */
  35831. this.nodeUniform = nodeUniform;
  35832. }
  35833. /**
  35834. * Overwritten to return the value of the node uniform.
  35835. *
  35836. * @return {Matrix4} The value.
  35837. */
  35838. getValue() {
  35839. return this.nodeUniform.value;
  35840. }
  35841. /**
  35842. * Returns the node uniform data type.
  35843. *
  35844. * @return {string} The data type.
  35845. */
  35846. getType() {
  35847. return this.nodeUniform.type;
  35848. }
  35849. }
  35850. let _id$5 = 0;
  35851. const _bindingGroupsCache = new WeakMap();
  35852. const _functionNodeCache = new WeakMap();
  35853. const sharedNodeData = new WeakMap();
  35854. const typeFromArray = new Map( [
  35855. [ Int8Array, 'int' ],
  35856. [ Int16Array, 'int' ],
  35857. [ Int32Array, 'int' ],
  35858. [ Uint8Array, 'uint' ],
  35859. [ Uint16Array, 'uint' ],
  35860. [ Uint32Array, 'uint' ],
  35861. [ Float32Array, 'float' ]
  35862. ] );
  35863. const toFloat = ( value ) => {
  35864. if ( /e/g.test( value ) ) {
  35865. return String( value ).replace( /\+/g, '' );
  35866. } else {
  35867. value = Number( value );
  35868. return value + ( value % 1 ? '' : '.0' );
  35869. }
  35870. };
  35871. /**
  35872. * Base class for builders which generate a shader program based
  35873. * on a 3D object and its node material definition.
  35874. */
  35875. class NodeBuilder {
  35876. /**
  35877. * Constructs a new node builder.
  35878. *
  35879. * @param {Object3D} object - The 3D object.
  35880. * @param {Renderer} renderer - The current renderer.
  35881. * @param {NodeParser} parser - A reference to a node parser.
  35882. */
  35883. constructor( object, renderer, parser ) {
  35884. /**
  35885. * The 3D object.
  35886. *
  35887. * @type {Object3D}
  35888. */
  35889. this.object = object;
  35890. /**
  35891. * The material of the 3D object.
  35892. *
  35893. * @type {?Material}
  35894. */
  35895. this.material = ( object && object.material ) || null;
  35896. /**
  35897. * The geometry of the 3D object.
  35898. *
  35899. * @type {?BufferGeometry}
  35900. */
  35901. this.geometry = ( object && object.geometry ) || null;
  35902. /**
  35903. * The current renderer.
  35904. *
  35905. * @type {Renderer}
  35906. */
  35907. this.renderer = renderer;
  35908. /**
  35909. * A reference to a node parser.
  35910. *
  35911. * @type {NodeParser}
  35912. */
  35913. this.parser = parser;
  35914. /**
  35915. * The scene the 3D object belongs to.
  35916. *
  35917. * @type {?Scene}
  35918. * @default null
  35919. */
  35920. this.scene = null;
  35921. /**
  35922. * The camera the 3D object is rendered with.
  35923. *
  35924. * @type {?Camera}
  35925. * @default null
  35926. */
  35927. this.camera = null;
  35928. /**
  35929. * A list of all nodes the builder is processing
  35930. * for this 3D object.
  35931. *
  35932. * @type {Array<Node>}
  35933. */
  35934. this.nodes = [];
  35935. /**
  35936. * A list of all nodes the builder is processing in sequential order.
  35937. *
  35938. * This is used to determine the update order of nodes, which is important for
  35939. * {@link NodeUpdateType#UPDATE_BEFORE} and {@link NodeUpdateType#UPDATE_AFTER}.
  35940. *
  35941. * @type {Array<Node>}
  35942. */
  35943. this.sequentialNodes = [];
  35944. /**
  35945. * A list of all nodes which {@link Node#update} method should be executed.
  35946. *
  35947. * @type {Array<Node>}
  35948. */
  35949. this.updateNodes = [];
  35950. /**
  35951. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  35952. *
  35953. * @type {Array<Node>}
  35954. */
  35955. this.updateBeforeNodes = [];
  35956. /**
  35957. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  35958. *
  35959. * @type {Array<Node>}
  35960. */
  35961. this.updateAfterNodes = [];
  35962. /**
  35963. * A dictionary that assigns each node to a unique hash.
  35964. *
  35965. * @type {Object<number,Node>}
  35966. */
  35967. this.hashNodes = {};
  35968. /**
  35969. * A reference to a node material observer.
  35970. *
  35971. * @type {?NodeMaterialObserver}
  35972. * @default null
  35973. */
  35974. this.observer = null;
  35975. /**
  35976. * A reference to the current lights node.
  35977. *
  35978. * @type {?LightsNode}
  35979. * @default null
  35980. */
  35981. this.lightsNode = null;
  35982. /**
  35983. * A reference to the current environment node.
  35984. *
  35985. * @type {?Node}
  35986. * @default null
  35987. */
  35988. this.environmentNode = null;
  35989. /**
  35990. * A reference to the current fog node.
  35991. *
  35992. * @type {?Node}
  35993. * @default null
  35994. */
  35995. this.fogNode = null;
  35996. /**
  35997. * The current clipping context.
  35998. *
  35999. * @type {?ClippingContext}
  36000. */
  36001. this.clippingContext = null;
  36002. /**
  36003. * The generated vertex shader.
  36004. *
  36005. * @type {?string}
  36006. */
  36007. this.vertexShader = null;
  36008. /**
  36009. * The generated fragment shader.
  36010. *
  36011. * @type {?string}
  36012. */
  36013. this.fragmentShader = null;
  36014. /**
  36015. * The generated compute shader.
  36016. *
  36017. * @type {?string}
  36018. */
  36019. this.computeShader = null;
  36020. /**
  36021. * Nodes used in the primary flow of code generation.
  36022. *
  36023. * @type {Object<string,Array<Node>>}
  36024. */
  36025. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  36026. /**
  36027. * Nodes code from `.flowNodes`.
  36028. *
  36029. * @type {Object<string,string>}
  36030. */
  36031. this.flowCode = { vertex: '', fragment: '', compute: '' };
  36032. /**
  36033. * This dictionary holds the node uniforms of the builder.
  36034. * The uniforms are maintained in an array for each shader stage.
  36035. *
  36036. * @type {Object}
  36037. */
  36038. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  36039. /**
  36040. * This dictionary holds the output structs of the builder.
  36041. * The structs are maintained in an array for each shader stage.
  36042. *
  36043. * @type {Object}
  36044. */
  36045. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  36046. /**
  36047. * This dictionary holds the types of the builder.
  36048. *
  36049. * @type {Object}
  36050. */
  36051. this.types = { vertex: [], fragment: [], compute: [], index: 0 };
  36052. /**
  36053. * This dictionary holds the bindings for each shader stage.
  36054. *
  36055. * @type {Object}
  36056. */
  36057. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  36058. /**
  36059. * This dictionary maintains the binding indices per bind group.
  36060. *
  36061. * @type {Object}
  36062. */
  36063. this.bindingsIndexes = {};
  36064. /**
  36065. * Reference to the array of bind groups.
  36066. *
  36067. * @type {?Array<BindGroup>}
  36068. */
  36069. this.bindGroups = null;
  36070. /**
  36071. * This array holds the node attributes of this builder
  36072. * created via {@link AttributeNode}.
  36073. *
  36074. * @type {Array<NodeAttribute>}
  36075. */
  36076. this.attributes = [];
  36077. /**
  36078. * This array holds the node attributes of this builder
  36079. * created via {@link BufferAttributeNode}.
  36080. *
  36081. * @type {Array<NodeAttribute>}
  36082. */
  36083. this.bufferAttributes = [];
  36084. /**
  36085. * This array holds the node varyings of this builder.
  36086. *
  36087. * @type {Array<NodeVarying>}
  36088. */
  36089. this.varyings = [];
  36090. /**
  36091. * This dictionary holds the (native) node codes of this builder.
  36092. * The codes are maintained in an array for each shader stage.
  36093. *
  36094. * @type {Object<string,Array<NodeCode>>}
  36095. */
  36096. this.codes = {};
  36097. /**
  36098. * This dictionary holds the node variables of this builder.
  36099. * The variables are maintained in an array for each shader stage.
  36100. * This dictionary is also used to count the number of variables
  36101. * according to their type (const, vars).
  36102. *
  36103. * @type {Object<string,Array<NodeVar>|number>}
  36104. */
  36105. this.vars = {};
  36106. /**
  36107. * This dictionary holds the declarations for each shader stage.
  36108. *
  36109. * @type {Object}
  36110. */
  36111. this.declarations = {};
  36112. /**
  36113. * Current code flow.
  36114. * All code generated in this stack will be stored in `.flow`.
  36115. *
  36116. * @type {{code: string}}
  36117. */
  36118. this.flow = { code: '' };
  36119. /**
  36120. * A chain of nodes.
  36121. * Used to check recursive calls in node-graph.
  36122. *
  36123. * @type {Array<Node>}
  36124. */
  36125. this.chaining = [];
  36126. /**
  36127. * The current stack.
  36128. * This reflects the current process in the code block hierarchy,
  36129. * it is useful to know if the current process is inside a conditional for example.
  36130. *
  36131. * @type {StackNode}
  36132. */
  36133. this.stack = stack();
  36134. /**
  36135. * List of stack nodes.
  36136. * The current stack hierarchy is stored in an array.
  36137. *
  36138. * @type {Array<StackNode>}
  36139. */
  36140. this.stacks = [];
  36141. /**
  36142. * A tab value. Used for shader string generation.
  36143. *
  36144. * @type {string}
  36145. * @default '\t'
  36146. */
  36147. this.tab = '\t';
  36148. /**
  36149. * Reference to the current function node.
  36150. *
  36151. * @type {?FunctionNode}
  36152. * @default null
  36153. */
  36154. this.currentFunctionNode = null;
  36155. /**
  36156. * The builder's context.
  36157. *
  36158. * @type {Object}
  36159. */
  36160. this.context = {
  36161. material: this.material
  36162. };
  36163. /**
  36164. * The builder's cache.
  36165. *
  36166. * @type {NodeCache}
  36167. */
  36168. this.cache = new NodeCache();
  36169. /**
  36170. * Since the {@link NodeBuilder#cache} might be temporarily
  36171. * overwritten by other caches, this member retains the reference
  36172. * to the builder's own cache.
  36173. *
  36174. * @type {NodeCache}
  36175. * @default this.cache
  36176. */
  36177. this.globalCache = this.cache;
  36178. this.flowsData = new WeakMap();
  36179. /**
  36180. * The current shader stage.
  36181. *
  36182. * @type {?('vertex'|'fragment'|'compute'|'any')}
  36183. */
  36184. this.shaderStage = null;
  36185. /**
  36186. * The current build stage.
  36187. *
  36188. * @type {?('setup'|'analyze'|'generate')}
  36189. */
  36190. this.buildStage = null;
  36191. /**
  36192. * The sub-build layers.
  36193. *
  36194. * @type {Array<SubBuildNode>}
  36195. * @default []
  36196. */
  36197. this.subBuildLayers = [];
  36198. /**
  36199. * The active stack nodes.
  36200. *
  36201. * @type {Array<StackNode>}
  36202. */
  36203. this.activeStacks = [];
  36204. /**
  36205. * The current sub-build TSL function(Fn).
  36206. *
  36207. * @type {?string}
  36208. * @default null
  36209. */
  36210. this.subBuildFn = null;
  36211. /**
  36212. * The current TSL function(Fn) call node.
  36213. *
  36214. * @type {?Node}
  36215. * @default null
  36216. */
  36217. this.fnCall = null;
  36218. Object.defineProperty( this, 'id', { value: _id$5 ++ } );
  36219. }
  36220. /**
  36221. * Whether the material is using flat shading or not.
  36222. *
  36223. * @returns {boolean} Whether the material is using flat shading or not.
  36224. */
  36225. isFlatShading() {
  36226. return this.material.flatShading === true || this.geometry.hasAttribute( 'normal' ) === false;
  36227. }
  36228. /**
  36229. * Whether the material is opaque or not.
  36230. *
  36231. * @return {boolean} Whether the material is opaque or not.
  36232. */
  36233. isOpaque() {
  36234. const material = this.material;
  36235. return material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false;
  36236. }
  36237. /**
  36238. * Factory method for creating an instance of {@link RenderTarget} with the given
  36239. * dimensions and options.
  36240. *
  36241. * @param {number} width - The width of the render target.
  36242. * @param {number} height - The height of the render target.
  36243. * @param {Object} options - The options of the render target.
  36244. * @return {RenderTarget} The render target.
  36245. */
  36246. createRenderTarget( width, height, options ) {
  36247. return new RenderTarget( width, height, options );
  36248. }
  36249. /**
  36250. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  36251. * dimensions and options.
  36252. *
  36253. * @param {number} size - The size of the cube render target.
  36254. * @param {Object} options - The options of the cube render target.
  36255. * @return {CubeRenderTarget} The cube render target.
  36256. */
  36257. createCubeRenderTarget( size, options ) {
  36258. return new CubeRenderTarget( size, options );
  36259. }
  36260. /**
  36261. * Whether the given node is included in the internal array of nodes or not.
  36262. *
  36263. * @param {Node} node - The node to test.
  36264. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  36265. */
  36266. includes( node ) {
  36267. return this.nodes.includes( node );
  36268. }
  36269. /**
  36270. * Returns the output struct name which is required by
  36271. * {@link OutputStructNode}.
  36272. *
  36273. * @abstract
  36274. * @return {string} The name of the output struct.
  36275. */
  36276. getOutputStructName() {}
  36277. /**
  36278. * Returns a bind group for the given group name and binding.
  36279. *
  36280. * @private
  36281. * @param {string} groupName - The group name.
  36282. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  36283. * @return {BindGroup} The bind group
  36284. */
  36285. _getBindGroup( groupName, bindings ) {
  36286. const groupNode = bindings[ 0 ].groupNode;
  36287. let sharedGroup = groupNode.shared;
  36288. if ( sharedGroup ) {
  36289. for ( let i = 1; i < bindings.length; i ++ ) {
  36290. if ( groupNode !== bindings[ i ].groupNode ) {
  36291. sharedGroup = false;
  36292. }
  36293. }
  36294. }
  36295. //
  36296. let bindGroup;
  36297. if ( sharedGroup ) {
  36298. let cacheKeyString = '';
  36299. for ( const binding of bindings ) {
  36300. if ( binding.isNodeUniformsGroup ) {
  36301. binding.uniforms.sort( ( a, b ) => a.nodeUniform.node.id - b.nodeUniform.node.id );
  36302. for ( const uniform of binding.uniforms ) {
  36303. cacheKeyString += uniform.nodeUniform.node.id;
  36304. }
  36305. } else {
  36306. cacheKeyString += binding.nodeUniform.id;
  36307. }
  36308. }
  36309. // TODO: Remove this hack ._currentRenderContext
  36310. const currentContext = this.renderer._currentRenderContext || this.renderer; // use renderer as fallback until we have a compute context
  36311. let bindingGroupsCache = _bindingGroupsCache.get( currentContext );
  36312. if ( bindingGroupsCache === undefined ) {
  36313. bindingGroupsCache = new Map();
  36314. _bindingGroupsCache.set( currentContext, bindingGroupsCache );
  36315. }
  36316. //
  36317. const cacheKey = hashString( cacheKeyString );
  36318. bindGroup = bindingGroupsCache.get( cacheKey );
  36319. if ( bindGroup === undefined ) {
  36320. bindGroup = new BindGroup( groupName, bindings );
  36321. bindingGroupsCache.set( cacheKey, bindGroup );
  36322. }
  36323. } else {
  36324. bindGroup = new BindGroup( groupName, bindings );
  36325. }
  36326. return bindGroup;
  36327. }
  36328. /**
  36329. * Returns an array of node uniform groups for the given group name and shader stage.
  36330. *
  36331. * @param {string} groupName - The group name.
  36332. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36333. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  36334. */
  36335. getBindGroupArray( groupName, shaderStage ) {
  36336. const bindings = this.bindings[ shaderStage ];
  36337. let bindGroup = bindings[ groupName ];
  36338. if ( bindGroup === undefined ) {
  36339. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  36340. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  36341. }
  36342. bindings[ groupName ] = bindGroup = [];
  36343. }
  36344. return bindGroup;
  36345. }
  36346. /**
  36347. * Returns a list bindings of all shader stages separated by groups.
  36348. *
  36349. * @return {Array<BindGroup>} The list of bindings.
  36350. */
  36351. getBindings() {
  36352. let bindingsGroups = this.bindGroups;
  36353. if ( bindingsGroups === null ) {
  36354. const groups = {};
  36355. const bindings = this.bindings;
  36356. for ( const shaderStage of shaderStages ) {
  36357. for ( const groupName in bindings[ shaderStage ] ) {
  36358. const uniforms = bindings[ shaderStage ][ groupName ];
  36359. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  36360. for ( const uniform of uniforms ) {
  36361. if ( groupUniforms.includes( uniform ) === false ) {
  36362. groupUniforms.push( uniform );
  36363. }
  36364. }
  36365. }
  36366. }
  36367. bindingsGroups = [];
  36368. for ( const groupName in groups ) {
  36369. const group = groups[ groupName ];
  36370. const bindingsGroup = this._getBindGroup( groupName, group );
  36371. bindingsGroups.push( bindingsGroup );
  36372. }
  36373. this.bindGroups = bindingsGroups;
  36374. }
  36375. return bindingsGroups;
  36376. }
  36377. /**
  36378. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  36379. */
  36380. sortBindingGroups() {
  36381. const bindingsGroups = this.getBindings();
  36382. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  36383. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  36384. const bindingGroup = bindingsGroups[ i ];
  36385. this.bindingsIndexes[ bindingGroup.name ].group = i;
  36386. }
  36387. }
  36388. /**
  36389. * The builder maintains each node in a hash-based dictionary.
  36390. * This method sets the given node (value) with the given hash (key) into this dictionary.
  36391. *
  36392. * @param {Node} node - The node to add.
  36393. * @param {number} hash - The hash of the node.
  36394. */
  36395. setHashNode( node, hash ) {
  36396. this.hashNodes[ hash ] = node;
  36397. }
  36398. /**
  36399. * Adds a node to this builder.
  36400. *
  36401. * @param {Node} node - The node to add.
  36402. */
  36403. addNode( node ) {
  36404. if ( this.nodes.includes( node ) === false ) {
  36405. this.nodes.push( node );
  36406. this.setHashNode( node, node.getHash( this ) );
  36407. }
  36408. }
  36409. /**
  36410. * It is used to add Nodes that will be used as FRAME and RENDER events,
  36411. * and need to follow a certain sequence in the calls to work correctly.
  36412. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  36413. *
  36414. * @param {Node} node - The node to add.
  36415. */
  36416. addSequentialNode( node ) {
  36417. const updateBeforeType = node.getUpdateBeforeType();
  36418. const updateAfterType = node.getUpdateAfterType();
  36419. if ( updateBeforeType !== NodeUpdateType.NONE || updateAfterType !== NodeUpdateType.NONE ) {
  36420. if ( this.sequentialNodes.includes( node ) === false ) {
  36421. this.sequentialNodes.push( node );
  36422. }
  36423. }
  36424. }
  36425. /**
  36426. * Checks the update types of nodes
  36427. */
  36428. buildUpdateNodes() {
  36429. for ( const node of this.nodes ) {
  36430. const updateType = node.getUpdateType();
  36431. if ( updateType !== NodeUpdateType.NONE ) {
  36432. this.updateNodes.push( node );
  36433. }
  36434. }
  36435. for ( const node of this.sequentialNodes ) {
  36436. const updateBeforeType = node.getUpdateBeforeType();
  36437. const updateAfterType = node.getUpdateAfterType();
  36438. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  36439. this.updateBeforeNodes.push( node );
  36440. }
  36441. if ( updateAfterType !== NodeUpdateType.NONE ) {
  36442. this.updateAfterNodes.push( node );
  36443. }
  36444. }
  36445. }
  36446. /**
  36447. * A reference the current node which is the
  36448. * last node in the chain of nodes.
  36449. *
  36450. * @type {Node}
  36451. */
  36452. get currentNode() {
  36453. return this.chaining[ this.chaining.length - 1 ];
  36454. }
  36455. /**
  36456. * Whether the given texture is filtered or not.
  36457. *
  36458. * @param {Texture} texture - The texture to check.
  36459. * @return {boolean} Whether the given texture is filtered or not.
  36460. */
  36461. isFilteredTexture( texture ) {
  36462. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  36463. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  36464. }
  36465. /**
  36466. * Returns the maximum number of bytes available for uniform buffers.
  36467. *
  36468. * @return {number} The maximum number of bytes available for uniform buffers.
  36469. */
  36470. getUniformBufferLimit() {
  36471. return this.renderer.backend.capabilities.getUniformBufferLimit();
  36472. }
  36473. /**
  36474. * Adds the given node to the internal node chain.
  36475. * This is used to check recursive calls in node-graph.
  36476. *
  36477. * @param {Node} node - The node to add.
  36478. */
  36479. addChain( node ) {
  36480. /*
  36481. if ( this.chaining.indexOf( node ) !== - 1 ) {
  36482. warn( 'Recursive node: ', node );
  36483. }
  36484. */
  36485. this.chaining.push( node );
  36486. }
  36487. /**
  36488. * Removes the given node from the internal node chain.
  36489. *
  36490. * @param {Node} node - The node to remove.
  36491. */
  36492. removeChain( node ) {
  36493. const lastChain = this.chaining.pop();
  36494. if ( lastChain !== node ) {
  36495. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  36496. }
  36497. }
  36498. /**
  36499. * Returns the native shader method name for a given generic name. E.g.
  36500. * the method name `textureDimensions` matches the WGSL name but must be
  36501. * resolved to `textureSize` in GLSL.
  36502. *
  36503. * @abstract
  36504. * @param {string} method - The method name to resolve.
  36505. * @return {string} The resolved method name.
  36506. */
  36507. getMethod( method ) {
  36508. return method;
  36509. }
  36510. /**
  36511. * Returns the native snippet for a ternary operation. E.g. GLSL would output
  36512. * a ternary op as `cond ? x : y` whereas WGSL would output it as `select(y, x, cond)`
  36513. *
  36514. * @abstract
  36515. * @param {string} condSnippet - The condition determining which expression gets resolved.
  36516. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  36517. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  36518. * @return {string} The resolved method name.
  36519. */
  36520. getTernary( /* condSnippet, ifSnippet, elseSnippet*/ ) {
  36521. return null;
  36522. }
  36523. /**
  36524. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  36525. *
  36526. * @param {number} hash - The hash of the node.
  36527. * @return {Node} The found node.
  36528. */
  36529. getNodeFromHash( hash ) {
  36530. return this.hashNodes[ hash ];
  36531. }
  36532. /**
  36533. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  36534. *
  36535. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  36536. * @param {Node} node - The node to add.
  36537. * @return {Node} The node.
  36538. */
  36539. addFlow( shaderStage, node ) {
  36540. this.flowNodes[ shaderStage ].push( node );
  36541. return node;
  36542. }
  36543. /**
  36544. * Sets builder's context.
  36545. *
  36546. * @param {Object} context - The context to set.
  36547. */
  36548. setContext( context ) {
  36549. this.context = context;
  36550. }
  36551. /**
  36552. * Returns the builder's current context.
  36553. *
  36554. * @return {Object} The builder's current context.
  36555. */
  36556. getContext() {
  36557. return this.context;
  36558. }
  36559. /**
  36560. * Adds context data to the builder's current context.
  36561. *
  36562. * @param {Object} context - The context to add.
  36563. * @return {Object} The previous context.
  36564. */
  36565. addContext( context ) {
  36566. const previousContext = this.getContext();
  36567. this.setContext( { ...this.context, ...context } );
  36568. return previousContext;
  36569. }
  36570. /**
  36571. * Gets a context used in shader construction that can be shared across different materials.
  36572. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  36573. *
  36574. * @return {Object} The builder's current context without material.
  36575. */
  36576. getSharedContext() {
  36577. const context = { ...this.context };
  36578. delete context.material;
  36579. delete context.getUV;
  36580. delete context.getOutput;
  36581. delete context.getTextureLevel;
  36582. delete context.getAO;
  36583. delete context.getShadow;
  36584. return context;
  36585. }
  36586. /**
  36587. * Sets builder's cache.
  36588. *
  36589. * @param {NodeCache} cache - The cache to set.
  36590. */
  36591. setCache( cache ) {
  36592. this.cache = cache;
  36593. }
  36594. /**
  36595. * Returns the builder's current cache.
  36596. *
  36597. * @return {NodeCache} The builder's current cache.
  36598. */
  36599. getCache() {
  36600. return this.cache;
  36601. }
  36602. /**
  36603. * Returns a cache for the given node.
  36604. *
  36605. * @param {Node} node - The node.
  36606. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  36607. * @return {NodeCache} The cache.
  36608. */
  36609. getCacheFromNode( node, parent = true ) {
  36610. const data = this.getDataFromNode( node );
  36611. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  36612. return data.cache;
  36613. }
  36614. /**
  36615. * Whether the requested feature is available or not.
  36616. *
  36617. * @abstract
  36618. * @param {string} name - The requested feature.
  36619. * @return {boolean} Whether the requested feature is supported or not.
  36620. */
  36621. isAvailable( /*name*/ ) {
  36622. return false;
  36623. }
  36624. /**
  36625. * Returns the vertexIndex input variable as a native shader string.
  36626. *
  36627. * @abstract
  36628. * @return {string} The instanceIndex shader string.
  36629. */
  36630. getVertexIndex() {
  36631. warn( 'Abstract function.' );
  36632. }
  36633. /**
  36634. * Contextually returns either the vertex stage instance index builtin
  36635. * or the linearized index of an compute invocation within a grid of workgroups.
  36636. *
  36637. * @abstract
  36638. * @return {string} The instanceIndex shader string.
  36639. */
  36640. getInstanceIndex() {
  36641. warn( 'Abstract function.' );
  36642. }
  36643. /**
  36644. * Returns the drawIndex input variable as a native shader string.
  36645. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  36646. *
  36647. * @abstract
  36648. * @return {?string} The drawIndex shader string.
  36649. */
  36650. getDrawIndex() {
  36651. warn( 'Abstract function.' );
  36652. }
  36653. /**
  36654. * Returns the frontFacing input variable as a native shader string.
  36655. *
  36656. * @abstract
  36657. * @return {string} The frontFacing shader string.
  36658. */
  36659. getFrontFacing() {
  36660. warn( 'Abstract function.' );
  36661. }
  36662. /**
  36663. * Returns the fragCoord input variable as a native shader string.
  36664. *
  36665. * @abstract
  36666. * @return {string} The fragCoord shader string.
  36667. */
  36668. getFragCoord() {
  36669. warn( 'Abstract function.' );
  36670. }
  36671. /**
  36672. * Whether to flip texture data along its vertical axis or not. WebGL needs
  36673. * this method evaluate to `true`, WebGPU to `false`.
  36674. *
  36675. * @abstract
  36676. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  36677. */
  36678. isFlipY() {
  36679. return false;
  36680. }
  36681. /**
  36682. * Calling this method increases the usage count for the given node by one.
  36683. *
  36684. * @param {Node} node - The node to increase the usage count for.
  36685. * @return {number} The updated usage count.
  36686. */
  36687. increaseUsage( node ) {
  36688. const nodeData = this.getDataFromNode( node );
  36689. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  36690. return nodeData.usageCount;
  36691. }
  36692. /**
  36693. * Generates a texture sample shader string for the given texture data.
  36694. *
  36695. * @abstract
  36696. * @param {Texture} texture - The texture.
  36697. * @param {string} textureProperty - The texture property name.
  36698. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  36699. * @return {string} The generated shader string.
  36700. */
  36701. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  36702. warn( 'Abstract function.' );
  36703. }
  36704. /**
  36705. * Generates a texture LOD shader string for the given texture data.
  36706. *
  36707. * @abstract
  36708. * @param {Texture} texture - The texture.
  36709. * @param {string} textureProperty - The texture property name.
  36710. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  36711. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  36712. * @param {string} levelSnippet - Snippet defining the mip level.
  36713. * @return {string} The generated shader string.
  36714. */
  36715. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  36716. warn( 'Abstract function.' );
  36717. }
  36718. /**
  36719. * Generates the array declaration string.
  36720. *
  36721. * @param {string} type - The type.
  36722. * @param {?number} [count] - The count.
  36723. * @return {string} The generated value as a shader string.
  36724. */
  36725. generateArrayDeclaration( type, count ) {
  36726. return this.getType( type ) + '[ ' + count + ' ]';
  36727. }
  36728. /**
  36729. * Generates the array shader string for the given type and value.
  36730. *
  36731. * @param {string} type - The type.
  36732. * @param {?number} [count] - The count.
  36733. * @param {?Array<Node>} [values=null] - The default values.
  36734. * @return {string} The generated value as a shader string.
  36735. */
  36736. generateArray( type, count, values = null ) {
  36737. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  36738. for ( let i = 0; i < count; i ++ ) {
  36739. const value = values ? values[ i ] : null;
  36740. if ( value !== null ) {
  36741. snippet += value.build( this, type );
  36742. } else {
  36743. snippet += this.generateConst( type );
  36744. }
  36745. if ( i < count - 1 ) snippet += ', ';
  36746. }
  36747. snippet += ' )';
  36748. return snippet;
  36749. }
  36750. /**
  36751. * Generates the struct shader string.
  36752. *
  36753. * @param {string} type - The type.
  36754. * @param {Array<Object>} [membersLayout] - The count.
  36755. * @param {?Array<Node>} [values=null] - The default values.
  36756. * @return {string} The generated value as a shader string.
  36757. */
  36758. generateStruct( type, membersLayout, values = null ) {
  36759. const snippets = [];
  36760. for ( const member of membersLayout ) {
  36761. const { name, type } = member;
  36762. if ( values && values[ name ] && values[ name ].isNode ) {
  36763. snippets.push( values[ name ].build( this, type ) );
  36764. } else {
  36765. snippets.push( this.generateConst( type ) );
  36766. }
  36767. }
  36768. return type + '( ' + snippets.join( ', ' ) + ' )';
  36769. }
  36770. /**
  36771. * Generates the shader string for the given type and value.
  36772. *
  36773. * @param {string} type - The type.
  36774. * @param {?any} [value=null] - The value.
  36775. * @return {string} The generated value as a shader string.
  36776. */
  36777. generateConst( type, value = null ) {
  36778. if ( value === null ) {
  36779. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  36780. else if ( type === 'bool' ) value = false;
  36781. else if ( type === 'color' ) value = new Color();
  36782. else if ( type === 'vec2' || type === 'uvec2' || type === 'ivec2' ) value = new Vector2();
  36783. else if ( type === 'vec3' || type === 'uvec3' || type === 'ivec3' ) value = new Vector3();
  36784. else if ( type === 'vec4' || type === 'uvec4' || type === 'ivec4' ) value = new Vector4();
  36785. }
  36786. if ( type === 'float' ) return toFloat( value );
  36787. if ( type === 'int' ) return `${ Math.round( value ) }`;
  36788. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  36789. if ( type === 'bool' ) return value ? 'true' : 'false';
  36790. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  36791. const typeLength = this.getTypeLength( type );
  36792. const componentType = this.getComponentType( type );
  36793. const generateConst = value => this.generateConst( componentType, value );
  36794. if ( typeLength === 2 ) {
  36795. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  36796. } else if ( typeLength === 3 ) {
  36797. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  36798. } else if ( typeLength === 4 && type !== 'mat2' ) {
  36799. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  36800. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  36801. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  36802. } else if ( typeLength > 4 ) {
  36803. return `${ this.getType( type ) }()`;
  36804. }
  36805. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  36806. }
  36807. /**
  36808. * It might be necessary to convert certain data types to different ones
  36809. * so this method can be used to hide the conversion.
  36810. *
  36811. * @param {string} type - The type.
  36812. * @return {string} The updated type.
  36813. */
  36814. getType( type ) {
  36815. if ( type === 'color' ) return 'vec3';
  36816. return type;
  36817. }
  36818. /**
  36819. * Whether the given attribute name is defined in the geometry or not.
  36820. *
  36821. * @param {string} name - The attribute name.
  36822. * @return {boolean} Whether the given attribute name is defined in the geometry.
  36823. */
  36824. hasGeometryAttribute( name ) {
  36825. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  36826. }
  36827. /**
  36828. * Returns a node attribute for the given name and type.
  36829. *
  36830. * @param {string} name - The attribute's name.
  36831. * @param {string} type - The attribute's type.
  36832. * @return {NodeAttribute} The node attribute.
  36833. */
  36834. getAttribute( name, type ) {
  36835. const attributes = this.attributes;
  36836. // find attribute
  36837. for ( const attribute of attributes ) {
  36838. if ( attribute.name === name ) {
  36839. return attribute;
  36840. }
  36841. }
  36842. // create a new if no exist
  36843. const attribute = new NodeAttribute( name, type );
  36844. this.registerDeclaration( attribute );
  36845. attributes.push( attribute );
  36846. return attribute;
  36847. }
  36848. /**
  36849. * Returns for the given node and shader stage the property name for the shader.
  36850. *
  36851. * @param {Node} node - The node.
  36852. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36853. * @return {string} The property name.
  36854. */
  36855. getPropertyName( node/*, shaderStage*/ ) {
  36856. return node.name;
  36857. }
  36858. /**
  36859. * Whether the given type is a vector type or not.
  36860. *
  36861. * @param {string} type - The type to check.
  36862. * @return {boolean} Whether the given type is a vector type or not.
  36863. */
  36864. isVector( type ) {
  36865. return /vec\d/.test( type );
  36866. }
  36867. /**
  36868. * Whether the given type is a matrix type or not.
  36869. *
  36870. * @param {string} type - The type to check.
  36871. * @return {boolean} Whether the given type is a matrix type or not.
  36872. */
  36873. isMatrix( type ) {
  36874. return /mat\d/.test( type );
  36875. }
  36876. /**
  36877. * Whether the given type is a reference type or not.
  36878. *
  36879. * @param {string} type - The type to check.
  36880. * @return {boolean} Whether the given type is a reference type or not.
  36881. */
  36882. isReference( type ) {
  36883. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  36884. }
  36885. /**
  36886. * Checks if the given texture requires a manual conversion to the working color space.
  36887. *
  36888. * @abstract
  36889. * @param {Texture} texture - The texture to check.
  36890. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  36891. */
  36892. needsToWorkingColorSpace( /*texture*/ ) {
  36893. return false;
  36894. }
  36895. /**
  36896. * Returns the component type of a given texture.
  36897. *
  36898. * @param {Texture} texture - The texture.
  36899. * @return {string} The component type.
  36900. */
  36901. getComponentTypeFromTexture( texture ) {
  36902. const type = texture.type;
  36903. if ( texture.isDataTexture ) {
  36904. if ( type === IntType ) return 'int';
  36905. if ( type === UnsignedIntType ) return 'uint';
  36906. }
  36907. return 'float';
  36908. }
  36909. /**
  36910. * Returns the element type for a given type.
  36911. *
  36912. * @param {string} type - The type.
  36913. * @return {string} The element type.
  36914. */
  36915. getElementType( type ) {
  36916. if ( type === 'mat2' ) return 'vec2';
  36917. if ( type === 'mat3' ) return 'vec3';
  36918. if ( type === 'mat4' ) return 'vec4';
  36919. return this.getComponentType( type );
  36920. }
  36921. /**
  36922. * Returns the component type for a given type.
  36923. *
  36924. * @param {string} type - The type.
  36925. * @return {string} The component type.
  36926. */
  36927. getComponentType( type ) {
  36928. type = this.getVectorType( type );
  36929. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  36930. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  36931. if ( componentType === null ) return null;
  36932. if ( componentType[ 1 ] === 'b' ) return 'bool';
  36933. if ( componentType[ 1 ] === 'i' ) return 'int';
  36934. if ( componentType[ 1 ] === 'u' ) return 'uint';
  36935. return 'float';
  36936. }
  36937. /**
  36938. * Returns the vector type for a given type.
  36939. *
  36940. * @param {string} type - The type.
  36941. * @return {string} The vector type.
  36942. */
  36943. getVectorType( type ) {
  36944. if ( type === 'color' ) return 'vec3';
  36945. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  36946. return type;
  36947. }
  36948. /**
  36949. * Returns the data type for the given the length and component type.
  36950. *
  36951. * @param {number} length - The length.
  36952. * @param {string} [componentType='float'] - The component type.
  36953. * @return {string} The type.
  36954. */
  36955. getTypeFromLength( length, componentType = 'float' ) {
  36956. if ( length === 1 ) return componentType;
  36957. let baseType = getTypeFromLength( length );
  36958. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  36959. // fix edge case for mat2x2 being same size as vec4
  36960. if ( /mat2/.test( componentType ) === true ) {
  36961. baseType = baseType.replace( 'vec', 'mat' );
  36962. }
  36963. return prefix + baseType;
  36964. }
  36965. /**
  36966. * Returns the type for a given typed array.
  36967. *
  36968. * @param {TypedArray} array - The typed array.
  36969. * @return {string} The type.
  36970. */
  36971. getTypeFromArray( array ) {
  36972. return typeFromArray.get( array.constructor );
  36973. }
  36974. /**
  36975. * Returns the type is an integer type.
  36976. *
  36977. * @param {string} type - The type.
  36978. * @return {boolean} Whether the type is an integer type or not.
  36979. */
  36980. isInteger( type ) {
  36981. return /int|uint|(i|u)vec/.test( type );
  36982. }
  36983. /**
  36984. * Returns the type for a given buffer attribute.
  36985. *
  36986. * @param {BufferAttribute} attribute - The buffer attribute.
  36987. * @return {string} The type.
  36988. */
  36989. getTypeFromAttribute( attribute ) {
  36990. let dataAttribute = attribute;
  36991. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  36992. const array = dataAttribute.array;
  36993. const itemSize = attribute.itemSize;
  36994. const normalized = attribute.normalized;
  36995. let arrayType;
  36996. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  36997. arrayType = this.getTypeFromArray( array );
  36998. }
  36999. return this.getTypeFromLength( itemSize, arrayType );
  37000. }
  37001. /**
  37002. * Returns the length for the given data type.
  37003. *
  37004. * @param {string} type - The data type.
  37005. * @return {number} The length.
  37006. */
  37007. getTypeLength( type ) {
  37008. const vecType = this.getVectorType( type );
  37009. const vecNum = /vec([2-4])/.exec( vecType );
  37010. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  37011. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  37012. if ( /mat2/.test( type ) === true ) return 4;
  37013. if ( /mat3/.test( type ) === true ) return 9;
  37014. if ( /mat4/.test( type ) === true ) return 16;
  37015. return 0;
  37016. }
  37017. /**
  37018. * Returns the vector type for a given matrix type.
  37019. *
  37020. * @param {string} type - The matrix type.
  37021. * @return {string} The vector type.
  37022. */
  37023. getVectorFromMatrix( type ) {
  37024. return type.replace( 'mat', 'vec' );
  37025. }
  37026. /**
  37027. * For a given type this method changes the component type to the
  37028. * given value. E.g. `vec4` should be changed to the new component type
  37029. * `uint` which results in `uvec4`.
  37030. *
  37031. * @param {string} type - The type.
  37032. * @param {string} newComponentType - The new component type.
  37033. * @return {string} The new type.
  37034. */
  37035. changeComponentType( type, newComponentType ) {
  37036. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  37037. }
  37038. /**
  37039. * Returns the integer type pendant for the given type.
  37040. *
  37041. * @param {string} type - The type.
  37042. * @return {string} The integer type.
  37043. */
  37044. getIntegerType( type ) {
  37045. const componentType = this.getComponentType( type );
  37046. if ( componentType === 'int' || componentType === 'uint' ) return type;
  37047. return this.changeComponentType( type, 'int' );
  37048. }
  37049. /**
  37050. * Adds an active stack to the internal stack.
  37051. *
  37052. * @param {StackNode} stack - The stack node to add.
  37053. */
  37054. setActiveStack( stack ) {
  37055. this.activeStacks.push( stack );
  37056. }
  37057. /**
  37058. * Removes the active stack from the internal stack.
  37059. *
  37060. * @param {StackNode} stack - The stack node to remove.
  37061. */
  37062. removeActiveStack( stack ) {
  37063. if ( this.activeStacks[ this.activeStacks.length - 1 ] === stack ) {
  37064. this.activeStacks.pop();
  37065. } else {
  37066. throw new Error( 'NodeBuilder: Invalid active stack removal.' );
  37067. }
  37068. }
  37069. /**
  37070. * Returns the active stack.
  37071. *
  37072. * @return {StackNode} The active stack.
  37073. */
  37074. getActiveStack() {
  37075. return this.activeStacks[ this.activeStacks.length - 1 ];
  37076. }
  37077. /**
  37078. * Returns the base stack.
  37079. *
  37080. * @return {StackNode} The base stack.
  37081. */
  37082. getBaseStack() {
  37083. return this.activeStacks[ 0 ];
  37084. }
  37085. /**
  37086. * Adds a stack node to the internal stack.
  37087. *
  37088. * @return {StackNode} The added stack node.
  37089. */
  37090. addStack() {
  37091. this.stack = stack( this.stack );
  37092. const previousStack = getCurrentStack();
  37093. this.stacks.push( previousStack );
  37094. setCurrentStack( this.stack );
  37095. return this.stack;
  37096. }
  37097. /**
  37098. * Removes the last stack node from the internal stack.
  37099. *
  37100. * @return {StackNode} The removed stack node.
  37101. */
  37102. removeStack() {
  37103. const lastStack = this.stack;
  37104. for ( const node of lastStack.nodes ) {
  37105. const nodeData = this.getDataFromNode( node );
  37106. nodeData.stack = lastStack;
  37107. }
  37108. this.stack = lastStack.parent;
  37109. setCurrentStack( this.stacks.pop() );
  37110. return lastStack;
  37111. }
  37112. /**
  37113. * The builder maintains (cached) data for each node during the building process. This method
  37114. * can be used to get these data for a specific shader stage and cache.
  37115. *
  37116. * @param {Node} node - The node to get the data for.
  37117. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  37118. * @param {?NodeCache} cache - An optional cache.
  37119. * @return {Object} The node data.
  37120. */
  37121. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  37122. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  37123. let nodeData = cache.getData( node );
  37124. if ( nodeData === undefined ) {
  37125. nodeData = {};
  37126. cache.setData( node, nodeData );
  37127. }
  37128. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  37129. //
  37130. let data = nodeData[ shaderStage ];
  37131. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  37132. const subBuild = this.getClosestSubBuild( subBuilds );
  37133. if ( subBuild ) {
  37134. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  37135. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  37136. data.subBuilds = subBuilds;
  37137. }
  37138. return data;
  37139. }
  37140. /**
  37141. * Returns the properties for the given node and shader stage.
  37142. *
  37143. * Properties are typically used within a build stage to reference a node's
  37144. * child node or nodes manually assigned to the properties in a separate build stage.
  37145. * A typical usage pattern for defining nodes manually would be assigning dependency nodes
  37146. * to the current node's properties in the setup stage and building those properties in the generate stage.
  37147. *
  37148. * @param {Node} node - The node to get the properties for.
  37149. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  37150. * @return {Object} The node properties.
  37151. */
  37152. getNodeProperties( node, shaderStage = 'any' ) {
  37153. const nodeData = this.getDataFromNode( node, shaderStage );
  37154. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  37155. }
  37156. /**
  37157. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  37158. *
  37159. * @param {BufferAttributeNode} node - The buffer attribute node.
  37160. * @param {string} type - The node type.
  37161. * @param {?string} [name=null] - The name of the buffer attribute.
  37162. * @return {NodeAttribute} The node attribute.
  37163. */
  37164. getBufferAttributeFromNode( node, type, name = null ) {
  37165. const nodeData = this.getDataFromNode( node, 'vertex' );
  37166. let bufferAttribute = nodeData.bufferAttribute;
  37167. if ( bufferAttribute === undefined ) {
  37168. const index = this.uniforms.index ++;
  37169. if ( name === null ) {
  37170. name = 'nodeAttribute' + index;
  37171. }
  37172. bufferAttribute = new NodeAttribute( name, type, node );
  37173. this.bufferAttributes.push( bufferAttribute );
  37174. nodeData.bufferAttribute = bufferAttribute;
  37175. }
  37176. return bufferAttribute;
  37177. }
  37178. /**
  37179. * Returns an instance of {@link StructType} for the given struct name and shader stage
  37180. * or null if not found.
  37181. *
  37182. * @param {string} name - The name of the struct.
  37183. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  37184. * @return {?StructType} The struct type or null if not found.
  37185. */
  37186. getStructTypeNode( name, shaderStage = this.shaderStage ) {
  37187. return this.types[ shaderStage ][ name ] || null;
  37188. }
  37189. /**
  37190. * Returns an instance of {@link StructType} for the given output struct node.
  37191. *
  37192. * @param {OutputStructNode} node - The output struct node.
  37193. * @param {Array<Object>} membersLayout - The output struct types.
  37194. * @param {?string} [name=null] - The name of the struct.
  37195. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  37196. * @return {StructType} The struct type attribute.
  37197. */
  37198. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  37199. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  37200. let structType = nodeData.structType;
  37201. if ( structType === undefined ) {
  37202. const index = this.structs.index ++;
  37203. if ( name === null ) name = 'StructType' + index;
  37204. structType = new StructType( name, membersLayout );
  37205. this.structs[ shaderStage ].push( structType );
  37206. this.types[ shaderStage ][ name ] = node;
  37207. nodeData.structType = structType;
  37208. }
  37209. return structType;
  37210. }
  37211. /**
  37212. * Returns an instance of {@link StructType} for the given output struct node.
  37213. *
  37214. * @param {OutputStructNode} node - The output struct node.
  37215. * @param {Array<Object>} membersLayout - The output struct types.
  37216. * @return {StructType} The struct type attribute.
  37217. */
  37218. getOutputStructTypeFromNode( node, membersLayout ) {
  37219. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  37220. structType.output = true;
  37221. return structType;
  37222. }
  37223. /**
  37224. * Returns an instance of {@link NodeUniform} for the given uniform node.
  37225. *
  37226. * @param {UniformNode} node - The uniform node.
  37227. * @param {string} type - The uniform type.
  37228. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  37229. * @param {?string} name - The name of the uniform.
  37230. * @return {NodeUniform} The node uniform.
  37231. */
  37232. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  37233. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  37234. let nodeUniform = nodeData.uniform;
  37235. if ( nodeUniform === undefined ) {
  37236. const index = this.uniforms.index ++;
  37237. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  37238. this.uniforms[ shaderStage ].push( nodeUniform );
  37239. this.registerDeclaration( nodeUniform );
  37240. nodeData.uniform = nodeUniform;
  37241. }
  37242. return nodeUniform;
  37243. }
  37244. /**
  37245. * Returns an instance of {@link NodeVar} for the given variable node.
  37246. *
  37247. * @param {VarNode} node - The variable node.
  37248. * @param {?string} name - The variable's name.
  37249. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  37250. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  37251. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  37252. *
  37253. * @return {NodeVar} The node variable.
  37254. */
  37255. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  37256. const nodeData = this.getDataFromNode( node, shaderStage );
  37257. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  37258. let nodeVar = nodeData[ subBuildVariable ];
  37259. if ( nodeVar === undefined ) {
  37260. const idNS = readOnly ? '_const' : '_var';
  37261. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  37262. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  37263. if ( name === null ) {
  37264. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  37265. this.vars[ idNS ] ++;
  37266. }
  37267. //
  37268. if ( subBuildVariable !== 'variable' ) {
  37269. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  37270. }
  37271. //
  37272. const count = node.getArrayCount( this );
  37273. nodeVar = new NodeVar( name, type, readOnly, count );
  37274. if ( ! readOnly ) {
  37275. vars.push( nodeVar );
  37276. }
  37277. this.registerDeclaration( nodeVar );
  37278. nodeData[ subBuildVariable ] = nodeVar;
  37279. }
  37280. return nodeVar;
  37281. }
  37282. /**
  37283. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  37284. *
  37285. * @param {Node} node - The varying node.
  37286. * @return {boolean} Returns true if deterministic.
  37287. */
  37288. isDeterministic( node ) {
  37289. if ( node.isMathNode ) {
  37290. return this.isDeterministic( node.aNode ) &&
  37291. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  37292. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  37293. } else if ( node.isOperatorNode ) {
  37294. return this.isDeterministic( node.aNode ) &&
  37295. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  37296. } else if ( node.isArrayNode ) {
  37297. if ( node.values !== null ) {
  37298. for ( const n of node.values ) {
  37299. if ( ! this.isDeterministic( n ) ) {
  37300. return false;
  37301. }
  37302. }
  37303. }
  37304. return true;
  37305. } else if ( node.isConstNode ) {
  37306. return true;
  37307. }
  37308. return false;
  37309. }
  37310. /**
  37311. * Returns an instance of {@link NodeVarying} for the given varying node.
  37312. *
  37313. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  37314. * @param {?string} name - The varying's name.
  37315. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  37316. * @param {?string} interpolationType - The interpolation type of the varying.
  37317. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  37318. * @return {NodeVar} The node varying.
  37319. */
  37320. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  37321. const nodeData = this.getDataFromNode( node, 'any' );
  37322. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  37323. let nodeVarying = nodeData[ subBuildVarying ];
  37324. if ( nodeVarying === undefined ) {
  37325. const varyings = this.varyings;
  37326. const index = varyings.length;
  37327. if ( name === null ) name = 'nodeVarying' + index;
  37328. //
  37329. if ( subBuildVarying !== 'varying' ) {
  37330. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  37331. }
  37332. //
  37333. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  37334. varyings.push( nodeVarying );
  37335. this.registerDeclaration( nodeVarying );
  37336. nodeData[ subBuildVarying ] = nodeVarying;
  37337. }
  37338. return nodeVarying;
  37339. }
  37340. /**
  37341. * Registers a node declaration in the current shader stage.
  37342. *
  37343. * @param {Object} node - The node to be registered.
  37344. */
  37345. registerDeclaration( node ) {
  37346. const shaderStage = this.shaderStage;
  37347. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  37348. const property = this.getPropertyName( node );
  37349. let index = 1;
  37350. let name = property;
  37351. // Automatically renames the property if the name is already in use.
  37352. while ( declarations[ name ] !== undefined ) {
  37353. name = property + '_' + index ++;
  37354. }
  37355. if ( index > 1 ) {
  37356. node.name = name;
  37357. warn( `TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  37358. }
  37359. declarations[ name ] = node;
  37360. }
  37361. /**
  37362. * Returns an instance of {@link NodeCode} for the given code node.
  37363. *
  37364. * @param {CodeNode} node - The code node.
  37365. * @param {string} type - The node type.
  37366. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  37367. * @return {NodeCode} The node code.
  37368. */
  37369. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  37370. const nodeData = this.getDataFromNode( node );
  37371. let nodeCode = nodeData.code;
  37372. if ( nodeCode === undefined ) {
  37373. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  37374. const index = codes.length;
  37375. nodeCode = new NodeCode( 'nodeCode' + index, type );
  37376. codes.push( nodeCode );
  37377. nodeData.code = nodeCode;
  37378. }
  37379. return nodeCode;
  37380. }
  37381. /**
  37382. * Adds a code flow based on the code-block hierarchy.
  37383. * This is used so that code-blocks like If,Else create their variables locally if the Node
  37384. * is only used inside one of these conditionals in the current shader stage.
  37385. *
  37386. * @param {Node} node - The node to add.
  37387. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  37388. */
  37389. addFlowCodeHierarchy( node, nodeBlock ) {
  37390. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  37391. let needsFlowCode = true;
  37392. let nodeBlockHierarchy = nodeBlock;
  37393. while ( nodeBlockHierarchy ) {
  37394. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  37395. needsFlowCode = false;
  37396. break;
  37397. }
  37398. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  37399. }
  37400. if ( needsFlowCode ) {
  37401. for ( const flowCode of flowCodes ) {
  37402. this.addLineFlowCode( flowCode );
  37403. }
  37404. }
  37405. }
  37406. /**
  37407. * Add a inline-code to the current flow code-block.
  37408. *
  37409. * @param {Node} node - The node to add.
  37410. * @param {string} code - The code to add.
  37411. * @param {Node} nodeBlock - Current ConditionalNode
  37412. */
  37413. addLineFlowCodeBlock( node, code, nodeBlock ) {
  37414. const nodeData = this.getDataFromNode( node );
  37415. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  37416. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  37417. flowCodes.push( code );
  37418. codeBlock.set( nodeBlock, true );
  37419. }
  37420. /**
  37421. * Add a inline-code to the current flow.
  37422. *
  37423. * @param {string} code - The code to add.
  37424. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  37425. * @return {NodeBuilder} A reference to this node builder.
  37426. */
  37427. addLineFlowCode( code, node = null ) {
  37428. if ( code === '' ) return this;
  37429. if ( node !== null && this.context.nodeBlock ) {
  37430. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  37431. }
  37432. code = this.tab + code;
  37433. if ( ! /;\s*$/.test( code ) ) {
  37434. code = code + ';\n';
  37435. }
  37436. this.flow.code += code;
  37437. return this;
  37438. }
  37439. /**
  37440. * Adds a code to the current code flow.
  37441. *
  37442. * @param {string} code - Shader code.
  37443. * @return {NodeBuilder} A reference to this node builder.
  37444. */
  37445. addFlowCode( code ) {
  37446. this.flow.code += code;
  37447. return this;
  37448. }
  37449. /**
  37450. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  37451. * Typically used in codes with If,Else.
  37452. *
  37453. * @return {NodeBuilder} A reference to this node builder.
  37454. */
  37455. addFlowTab() {
  37456. this.tab += '\t';
  37457. return this;
  37458. }
  37459. /**
  37460. * Removes a tab.
  37461. *
  37462. * @return {NodeBuilder} A reference to this node builder.
  37463. */
  37464. removeFlowTab() {
  37465. this.tab = this.tab.slice( 0, -1 );
  37466. return this;
  37467. }
  37468. /**
  37469. * Gets the current flow data based on a Node.
  37470. *
  37471. * @param {Node} node - Node that the flow was started.
  37472. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37473. * @return {Object} The flow data.
  37474. */
  37475. getFlowData( node/*, shaderStage*/ ) {
  37476. return this.flowsData.get( node );
  37477. }
  37478. /**
  37479. * Executes the node flow based on a root node to generate the final shader code.
  37480. *
  37481. * @param {Node} node - The node to execute.
  37482. * @return {Object} The code flow.
  37483. */
  37484. flowNode( node ) {
  37485. const output = node.getNodeType( this );
  37486. const flowData = this.flowChildNode( node, output );
  37487. this.flowsData.set( node, flowData );
  37488. return flowData;
  37489. }
  37490. /**
  37491. * Includes a node in the current function node.
  37492. *
  37493. * @param {Node} node - The node to include.
  37494. * @returns {void}
  37495. */
  37496. addInclude( node ) {
  37497. if ( this.currentFunctionNode !== null ) {
  37498. this.currentFunctionNode.includes.push( node );
  37499. }
  37500. }
  37501. /**
  37502. * Returns the native shader operator name for a given generic name.
  37503. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  37504. *
  37505. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  37506. * @return {FunctionNode} The build function node.
  37507. */
  37508. buildFunctionNode( shaderNode ) {
  37509. const backend = this.renderer.backend;
  37510. let cache = _functionNodeCache.get( backend );
  37511. if ( cache === undefined ) {
  37512. cache = new WeakMap();
  37513. _functionNodeCache.set( backend, cache );
  37514. }
  37515. let fn = cache.get( shaderNode );
  37516. if ( fn === undefined ) {
  37517. fn = new FunctionNode();
  37518. const previous = this.currentFunctionNode;
  37519. this.currentFunctionNode = fn;
  37520. fn.code = this.buildFunctionCode( shaderNode );
  37521. this.currentFunctionNode = previous;
  37522. cache.set( shaderNode, fn );
  37523. }
  37524. return fn;
  37525. }
  37526. /**
  37527. * Generates a code flow based on a TSL function: Fn().
  37528. *
  37529. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  37530. * @return {Object}
  37531. */
  37532. flowShaderNode( shaderNode ) {
  37533. const layout = shaderNode.layout;
  37534. const inputs = {
  37535. [ Symbol.iterator ]() {
  37536. let index = 0;
  37537. const values = Object.values( this );
  37538. return {
  37539. next: () => ( {
  37540. value: values[ index ],
  37541. done: index ++ >= values.length
  37542. } )
  37543. };
  37544. }
  37545. };
  37546. for ( const input of layout.inputs ) {
  37547. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  37548. }
  37549. //
  37550. shaderNode.layout = null;
  37551. const callNode = shaderNode.call( inputs );
  37552. const flowData = this.flowStagesNode( callNode, layout.type );
  37553. shaderNode.layout = layout;
  37554. return flowData;
  37555. }
  37556. /**
  37557. * Executes the node in a specific build stage.
  37558. *
  37559. * This function can be used to arbitrarily execute the specified build stage
  37560. * outside of the standard build process. For instance, if a node's type depends
  37561. * on properties created by the 'setup' stage, then flowBuildStage(node, 'setup')
  37562. * can be used to execute the setup build stage and access its generated nodes
  37563. * before the standard build process begins.
  37564. *
  37565. * @param {Node} node - The node to execute.
  37566. * @param {string} buildStage - The build stage to execute the node in.
  37567. * @param {?(Node|string)} [output=null] - Expected output type. For example 'vec3'.
  37568. * @return {?(Node|string)} The result of the node build.
  37569. */
  37570. flowBuildStage( node, buildStage, output = null ) {
  37571. const previousBuildStage = this.getBuildStage();
  37572. this.setBuildStage( buildStage );
  37573. const result = node.build( this, output );
  37574. this.setBuildStage( previousBuildStage );
  37575. return result;
  37576. }
  37577. /**
  37578. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  37579. *
  37580. * @param {Node} node - The node to execute.
  37581. * @param {?string} output - Expected output type. For example 'vec3'.
  37582. * @return {Object}
  37583. */
  37584. flowStagesNode( node, output = null ) {
  37585. const previousFlow = this.flow;
  37586. const previousVars = this.vars;
  37587. const previousDeclarations = this.declarations;
  37588. const previousCache = this.cache;
  37589. const previousBuildStage = this.buildStage;
  37590. const previousStack = this.stack;
  37591. const flow = {
  37592. code: ''
  37593. };
  37594. this.flow = flow;
  37595. this.vars = {};
  37596. this.declarations = {};
  37597. this.cache = new NodeCache();
  37598. this.stack = stack();
  37599. for ( const buildStage of defaultBuildStages ) {
  37600. this.setBuildStage( buildStage );
  37601. flow.result = node.build( this, output );
  37602. }
  37603. flow.vars = this.getVars( this.shaderStage );
  37604. this.flow = previousFlow;
  37605. this.vars = previousVars;
  37606. this.declarations = previousDeclarations;
  37607. this.cache = previousCache;
  37608. this.stack = previousStack;
  37609. this.setBuildStage( previousBuildStage );
  37610. return flow;
  37611. }
  37612. /**
  37613. * Returns the native shader operator name for a given generic name.
  37614. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  37615. *
  37616. * @abstract
  37617. * @param {string} op - The operator name to resolve.
  37618. * @return {?string} The resolved operator name.
  37619. */
  37620. getFunctionOperator( /* op */ ) {
  37621. return null;
  37622. }
  37623. /**
  37624. * Builds the given shader node.
  37625. *
  37626. * @abstract
  37627. * @param {ShaderNodeInternal} shaderNode - The shader node.
  37628. * @return {string} The function code.
  37629. */
  37630. buildFunctionCode( /* shaderNode */ ) {
  37631. warn( 'Abstract function.' );
  37632. }
  37633. /**
  37634. * Generates a code flow based on a child Node.
  37635. *
  37636. * @param {Node} node - The node to execute.
  37637. * @param {?string} output - Expected output type. For example 'vec3'.
  37638. * @return {Object} The code flow.
  37639. */
  37640. flowChildNode( node, output = null ) {
  37641. const previousFlow = this.flow;
  37642. const flow = {
  37643. code: ''
  37644. };
  37645. this.flow = flow;
  37646. flow.result = node.build( this, output );
  37647. this.flow = previousFlow;
  37648. return flow;
  37649. }
  37650. /**
  37651. * Executes a flow of code in a different stage.
  37652. *
  37653. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  37654. * return the value in fragment-stage even if it is being executed in an input fragment.
  37655. *
  37656. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37657. * @param {Node} node - The node to execute.
  37658. * @param {?string} output - Expected output type. For example 'vec3'.
  37659. * @param {?string} propertyName - The property name to assign the result.
  37660. * @return {?(Object|Node)} The code flow or node.build() result.
  37661. */
  37662. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  37663. const previousTab = this.tab;
  37664. const previousCache = this.cache;
  37665. const previousShaderStage = this.shaderStage;
  37666. const previousContext = this.context;
  37667. this.setShaderStage( shaderStage );
  37668. const context = { ...this.context };
  37669. delete context.nodeBlock;
  37670. this.cache = this.globalCache;
  37671. this.tab = '\t';
  37672. this.context = context;
  37673. let result = null;
  37674. if ( this.buildStage === 'generate' ) {
  37675. const flowData = this.flowChildNode( node, output );
  37676. if ( propertyName !== null ) {
  37677. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  37678. }
  37679. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  37680. result = flowData;
  37681. } else {
  37682. result = node.build( this );
  37683. }
  37684. this.setShaderStage( previousShaderStage );
  37685. this.cache = previousCache;
  37686. this.tab = previousTab;
  37687. this.context = previousContext;
  37688. return result;
  37689. }
  37690. /**
  37691. * Returns an array holding all node attributes of this node builder.
  37692. *
  37693. * @return {Array<NodeAttribute>} The node attributes of this builder.
  37694. */
  37695. getAttributesArray() {
  37696. return this.attributes.concat( this.bufferAttributes );
  37697. }
  37698. /**
  37699. * Returns the attribute definitions as a shader string for the given shader stage.
  37700. *
  37701. * @abstract
  37702. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37703. * @return {string} The attribute code section.
  37704. */
  37705. getAttributes( /*shaderStage*/ ) {
  37706. warn( 'Abstract function.' );
  37707. }
  37708. /**
  37709. * Returns the varying definitions as a shader string for the given shader stage.
  37710. *
  37711. * @abstract
  37712. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37713. * @return {string} The varying code section.
  37714. */
  37715. getVaryings( /*shaderStage*/ ) {
  37716. warn( 'Abstract function.' );
  37717. }
  37718. /**
  37719. * Returns a single variable definition as a shader string for the given variable type and name.
  37720. *
  37721. * @param {string} type - The variable's type.
  37722. * @param {string} name - The variable's name.
  37723. * @param {?number} [count=null] - The array length.
  37724. * @return {string} The shader string.
  37725. */
  37726. getVar( type, name, count = null ) {
  37727. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  37728. }
  37729. /**
  37730. * Returns the variable definitions as a shader string for the given shader stage.
  37731. *
  37732. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37733. * @param {boolean} [global=false] - Whether the variables are global.
  37734. * @return {string} The variable code section.
  37735. */
  37736. getVars( shaderStage, global = false ) {
  37737. const snippets = [];
  37738. const vars = this.vars[ shaderStage ];
  37739. if ( vars !== undefined ) {
  37740. for ( const variable of vars ) {
  37741. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  37742. }
  37743. }
  37744. return snippets.join( global ? '\n' : '\n\t' );
  37745. }
  37746. /**
  37747. * Returns the uniform definitions as a shader string for the given shader stage.
  37748. *
  37749. * @abstract
  37750. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37751. * @return {string} The uniform code section.
  37752. */
  37753. getUniforms( /*shaderStage*/ ) {
  37754. warn( 'Abstract function.' );
  37755. }
  37756. /**
  37757. * Returns the native code definitions as a shader string for the given shader stage.
  37758. *
  37759. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37760. * @return {string} The native code section.
  37761. */
  37762. getCodes( shaderStage ) {
  37763. const codes = this.codes[ shaderStage ];
  37764. let code = '';
  37765. if ( codes !== undefined ) {
  37766. for ( const nodeCode of codes ) {
  37767. code += nodeCode.code + '\n';
  37768. }
  37769. }
  37770. return code;
  37771. }
  37772. /**
  37773. * Returns the hash of this node builder.
  37774. *
  37775. * @return {string} The hash.
  37776. */
  37777. getHash() {
  37778. return this.vertexShader + this.fragmentShader + this.computeShader;
  37779. }
  37780. /**
  37781. * Sets the current shader stage.
  37782. *
  37783. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  37784. */
  37785. setShaderStage( shaderStage ) {
  37786. this.shaderStage = shaderStage;
  37787. }
  37788. /**
  37789. * Returns the current shader stage.
  37790. *
  37791. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  37792. */
  37793. getShaderStage() {
  37794. return this.shaderStage;
  37795. }
  37796. /**
  37797. * Sets the current build stage.
  37798. *
  37799. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  37800. */
  37801. setBuildStage( buildStage ) {
  37802. this.buildStage = buildStage;
  37803. }
  37804. /**
  37805. * Returns the current build stage.
  37806. *
  37807. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  37808. */
  37809. getBuildStage() {
  37810. return this.buildStage;
  37811. }
  37812. /**
  37813. * Controls the code build of the shader stages.
  37814. *
  37815. * @abstract
  37816. */
  37817. buildCode() {
  37818. warn( 'Abstract function.' );
  37819. }
  37820. /**
  37821. * Returns the current sub-build layer.
  37822. *
  37823. * @return {SubBuildNode} The current sub-build layers.
  37824. */
  37825. get subBuild() {
  37826. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  37827. }
  37828. /**
  37829. * Adds a sub-build layer to the node builder.
  37830. *
  37831. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  37832. */
  37833. addSubBuild( subBuild ) {
  37834. this.subBuildLayers.push( subBuild );
  37835. }
  37836. /**
  37837. * Removes the last sub-build layer from the node builder.
  37838. *
  37839. * @return {SubBuildNode} The removed sub-build layer.
  37840. */
  37841. removeSubBuild() {
  37842. return this.subBuildLayers.pop();
  37843. }
  37844. /**
  37845. * Returns the closest sub-build layer for the given data.
  37846. *
  37847. * @param {Node|Set<string>|Array<string>} data - The data to get the closest sub-build layer from.
  37848. * @return {?string} The closest sub-build name or null if none found.
  37849. */
  37850. getClosestSubBuild( data ) {
  37851. let subBuilds;
  37852. if ( data && data.isNode ) {
  37853. if ( data.isShaderCallNodeInternal ) {
  37854. subBuilds = data.shaderNode.subBuilds;
  37855. } else if ( data.isStackNode ) {
  37856. subBuilds = [ data.subBuild ];
  37857. } else {
  37858. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  37859. }
  37860. } else if ( data instanceof Set ) {
  37861. subBuilds = [ ...data ];
  37862. } else {
  37863. subBuilds = data;
  37864. }
  37865. if ( ! subBuilds ) return null;
  37866. const subBuildLayers = this.subBuildLayers;
  37867. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  37868. const subBuild = subBuilds[ i ];
  37869. if ( subBuildLayers.includes( subBuild ) ) {
  37870. return subBuild;
  37871. }
  37872. }
  37873. return null;
  37874. }
  37875. /**
  37876. * Returns the output node of a sub-build layer.
  37877. *
  37878. * @param {Node} node - The node to get the output from.
  37879. * @return {string} The output node name.
  37880. */
  37881. getSubBuildOutput( node ) {
  37882. return this.getSubBuildProperty( 'outputNode', node );
  37883. }
  37884. /**
  37885. * Returns the sub-build property name for the given property and node.
  37886. *
  37887. * @param {string} [property=''] - The property name.
  37888. * @param {?Node} [node=null] - The node to get the sub-build from.
  37889. * @return {string} The sub-build property name.
  37890. */
  37891. getSubBuildProperty( property = '', node = null ) {
  37892. let subBuild;
  37893. if ( node !== null ) {
  37894. subBuild = this.getClosestSubBuild( node );
  37895. } else {
  37896. subBuild = this.subBuildFn;
  37897. }
  37898. let result;
  37899. if ( subBuild ) {
  37900. result = property ? ( subBuild + '_' + property ) : subBuild;
  37901. } else {
  37902. result = property;
  37903. }
  37904. return result;
  37905. }
  37906. /**
  37907. * Prebuild the node builder.
  37908. */
  37909. prebuild() {
  37910. const { object, renderer, material } = this;
  37911. // < renderer.contextNode >
  37912. if ( renderer.contextNode.isContextNode === true ) {
  37913. this.context = { ...this.context, ...renderer.contextNode.getFlowContextData() };
  37914. } else {
  37915. error( 'NodeBuilder: "renderer.contextNode" must be an instance of `context()`.' );
  37916. }
  37917. // < material.contextNode >
  37918. if ( material && material.contextNode ) {
  37919. if ( material.contextNode.isContextNode === true ) {
  37920. this.context = { ...this.context, ...material.contextNode.getFlowContextData() };
  37921. } else {
  37922. error( 'NodeBuilder: "material.contextNode" must be an instance of `context()`.' );
  37923. }
  37924. }
  37925. // < nodeMaterial >
  37926. if ( material !== null ) {
  37927. let nodeMaterial = renderer.library.fromMaterial( material );
  37928. if ( nodeMaterial === null ) {
  37929. error( `NodeBuilder: Material "${ material.type }" is not compatible.` );
  37930. nodeMaterial = new NodeMaterial();
  37931. }
  37932. nodeMaterial.build( this );
  37933. } else {
  37934. this.addFlow( 'compute', object );
  37935. }
  37936. }
  37937. /**
  37938. * Central build method which controls the build for the given object.
  37939. *
  37940. * @return {NodeBuilder} A reference to this node builder.
  37941. */
  37942. build() {
  37943. this.prebuild();
  37944. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  37945. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  37946. // generate() -> stage 3: generate shader
  37947. for ( const buildStage of defaultBuildStages ) {
  37948. this.setBuildStage( buildStage );
  37949. if ( this.context.position && this.context.position.isNode ) {
  37950. this.flowNodeFromShaderStage( 'vertex', this.context.position );
  37951. }
  37952. for ( const shaderStage of shaderStages ) {
  37953. this.setShaderStage( shaderStage );
  37954. const flowNodes = this.flowNodes[ shaderStage ];
  37955. for ( const node of flowNodes ) {
  37956. if ( buildStage === 'generate' ) {
  37957. this.flowNode( node );
  37958. } else {
  37959. node.build( this );
  37960. }
  37961. }
  37962. }
  37963. }
  37964. this.setBuildStage( null );
  37965. this.setShaderStage( null );
  37966. // stage 4: build code for a specific output
  37967. this.buildCode();
  37968. this.buildUpdateNodes();
  37969. return this;
  37970. }
  37971. /**
  37972. * Async version of build() that yields to main thread between shader stages.
  37973. * Use this in compileAsync() to prevent blocking the main thread.
  37974. *
  37975. * @return {Promise<NodeBuilder>} A promise that resolves to this node builder.
  37976. */
  37977. async buildAsync() {
  37978. this.prebuild();
  37979. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  37980. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  37981. // generate() -> stage 3: generate shader
  37982. for ( const buildStage of defaultBuildStages ) {
  37983. this.setBuildStage( buildStage );
  37984. if ( this.context.position && this.context.position.isNode ) {
  37985. this.flowNodeFromShaderStage( 'vertex', this.context.position );
  37986. }
  37987. for ( const shaderStage of shaderStages ) {
  37988. this.setShaderStage( shaderStage );
  37989. const flowNodes = this.flowNodes[ shaderStage ];
  37990. for ( const node of flowNodes ) {
  37991. if ( buildStage === 'generate' ) {
  37992. this.flowNode( node );
  37993. } else {
  37994. node.build( this );
  37995. }
  37996. }
  37997. // Yield to main thread after each shader stage to prevent blocking
  37998. await yieldToMain();
  37999. }
  38000. }
  38001. this.setBuildStage( null );
  38002. this.setShaderStage( null );
  38003. // stage 4: build code for a specific output
  38004. this.buildCode();
  38005. this.buildUpdateNodes();
  38006. return this;
  38007. }
  38008. /**
  38009. * Returns shared data object for the given node.
  38010. *
  38011. * @param {Node} node - The node to get shared data from.
  38012. * @return {Object} The shared data.
  38013. */
  38014. getSharedDataFromNode( node ) {
  38015. let data = sharedNodeData.get( node );
  38016. if ( data === undefined ) {
  38017. data = {};
  38018. }
  38019. return data;
  38020. }
  38021. /**
  38022. * Returns a uniform representation which is later used for UBO generation and rendering.
  38023. *
  38024. * @param {NodeUniform} uniformNode - The uniform node.
  38025. * @param {string} type - The requested type.
  38026. * @return {Uniform} The uniform.
  38027. */
  38028. getNodeUniform( uniformNode, type ) {
  38029. const nodeData = this.getSharedDataFromNode( uniformNode );
  38030. let node = nodeData.cache;
  38031. if ( node === undefined ) {
  38032. if ( type === 'float' || type === 'int' || type === 'uint' ) node = new NumberNodeUniform( uniformNode );
  38033. else if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) node = new Vector2NodeUniform( uniformNode );
  38034. else if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) node = new Vector3NodeUniform( uniformNode );
  38035. else if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) node = new Vector4NodeUniform( uniformNode );
  38036. else if ( type === 'color' ) node = new ColorNodeUniform( uniformNode );
  38037. else if ( type === 'mat2' ) node = new Matrix2NodeUniform( uniformNode );
  38038. else if ( type === 'mat3' ) node = new Matrix3NodeUniform( uniformNode );
  38039. else if ( type === 'mat4' ) node = new Matrix4NodeUniform( uniformNode );
  38040. else {
  38041. throw new Error( `Uniform "${ type }" not implemented.` );
  38042. }
  38043. nodeData.cache = node;
  38044. }
  38045. return node;
  38046. }
  38047. /**
  38048. * Formats the given shader snippet from a given type into another one. E.g.
  38049. * this method might be used to convert a simple float string `"1.0"` into a
  38050. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  38051. *
  38052. * @param {string} snippet - The shader snippet.
  38053. * @param {string} fromType - The source type.
  38054. * @param {string} toType - The target type.
  38055. * @return {string} The updated shader string.
  38056. */
  38057. format( snippet, fromType, toType ) {
  38058. fromType = this.getVectorType( fromType );
  38059. toType = this.getVectorType( toType );
  38060. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  38061. return snippet;
  38062. }
  38063. const fromTypeLength = this.getTypeLength( fromType );
  38064. const toTypeLength = this.getTypeLength( toType );
  38065. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  38066. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  38067. }
  38068. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  38069. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  38070. }
  38071. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  38072. // @TODO: ignore for now
  38073. return snippet;
  38074. }
  38075. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  38076. // @TODO: ignore for now
  38077. return snippet;
  38078. }
  38079. if ( fromTypeLength === toTypeLength ) {
  38080. return `${ this.getType( toType ) }( ${ snippet } )`;
  38081. }
  38082. if ( fromTypeLength > toTypeLength ) {
  38083. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  38084. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  38085. }
  38086. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  38087. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  38088. }
  38089. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  38090. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  38091. }
  38092. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  38093. // convert a number value to vector type, e.g:
  38094. // vec3( 1u ) -> vec3( float( 1u ) )
  38095. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  38096. }
  38097. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  38098. }
  38099. /**
  38100. * Returns a signature with the engine's current revision.
  38101. *
  38102. * @return {string} The signature.
  38103. */
  38104. getSignature() {
  38105. return `// Three.js r${ REVISION } - Node System\n`;
  38106. }
  38107. /**
  38108. * Returns `true` if data from the previous frame are required. Relevant
  38109. * when computing motion vectors with {@link VelocityNode}.
  38110. *
  38111. * @return {boolean} Whether data from the previous frame are required or not.
  38112. */
  38113. needsPreviousData() {
  38114. const mrt = this.renderer.getMRT();
  38115. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( this.object ).useVelocity === true;
  38116. }
  38117. }
  38118. /**
  38119. * Management class for updating nodes. The module tracks metrics like
  38120. * the elapsed time, delta time, the render and frame ID to correctly
  38121. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  38122. * and {@link Node#updateAfter} depending on the node's configuration.
  38123. */
  38124. class NodeFrame {
  38125. /**
  38126. * Constructs a new node fame.
  38127. */
  38128. constructor() {
  38129. /**
  38130. * The elapsed time in seconds.
  38131. *
  38132. * @type {number}
  38133. * @default 0
  38134. */
  38135. this.time = 0;
  38136. /**
  38137. * The delta time in seconds.
  38138. *
  38139. * @type {number}
  38140. * @default 0
  38141. */
  38142. this.deltaTime = 0;
  38143. /**
  38144. * The frame ID.
  38145. *
  38146. * @type {number}
  38147. * @default 0
  38148. */
  38149. this.frameId = 0;
  38150. /**
  38151. * The render ID.
  38152. *
  38153. * @type {number}
  38154. * @default 0
  38155. */
  38156. this.renderId = 0;
  38157. /**
  38158. * Used to control the {@link Node#update} call.
  38159. *
  38160. * @type {WeakMap<Node, Object>}
  38161. */
  38162. this.updateMap = new WeakMap();
  38163. /**
  38164. * Used to control the {@link Node#updateBefore} call.
  38165. *
  38166. * @type {WeakMap<Node, Object>}
  38167. */
  38168. this.updateBeforeMap = new WeakMap();
  38169. /**
  38170. * Used to control the {@link Node#updateAfter} call.
  38171. *
  38172. * @type {WeakMap<Node, Object>}
  38173. */
  38174. this.updateAfterMap = new WeakMap();
  38175. /**
  38176. * A reference to the current renderer.
  38177. *
  38178. * @type {?Renderer}
  38179. * @default null
  38180. */
  38181. this.renderer = null;
  38182. /**
  38183. * A reference to the current material.
  38184. *
  38185. * @type {?Material}
  38186. * @default null
  38187. */
  38188. this.material = null;
  38189. /**
  38190. * A reference to the current camera.
  38191. *
  38192. * @type {?Camera}
  38193. * @default null
  38194. */
  38195. this.camera = null;
  38196. /**
  38197. * A reference to the current 3D object.
  38198. *
  38199. * @type {?Object3D}
  38200. * @default null
  38201. */
  38202. this.object = null;
  38203. /**
  38204. * A reference to the current scene.
  38205. *
  38206. * @type {?Scene}
  38207. * @default null
  38208. */
  38209. this.scene = null;
  38210. }
  38211. /**
  38212. * Returns a dictionary for a given node and update map which
  38213. * is used to correctly call node update methods per frame or render.
  38214. *
  38215. * @private
  38216. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  38217. * @param {Node} nodeRef - The reference to the current node.
  38218. * @return {Object<string,WeakMap<Object, number>>} The dictionary.
  38219. */
  38220. _getMaps( referenceMap, nodeRef ) {
  38221. let maps = referenceMap.get( nodeRef );
  38222. if ( maps === undefined ) {
  38223. maps = {
  38224. renderId: 0,
  38225. frameId: 0,
  38226. };
  38227. referenceMap.set( nodeRef, maps );
  38228. }
  38229. return maps;
  38230. }
  38231. /**
  38232. * This method executes the {@link Node#updateBefore} for the given node.
  38233. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  38234. * is only executed once per frame, render or object depending on the update
  38235. * type.
  38236. *
  38237. * @param {Node} node - The node that should be updated.
  38238. */
  38239. updateBeforeNode( node ) {
  38240. const updateType = node.getUpdateBeforeType();
  38241. const reference = node.updateReference( this );
  38242. if ( updateType === NodeUpdateType.FRAME ) {
  38243. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  38244. if ( nodeUpdateBeforeMap.frameId !== this.frameId ) {
  38245. const previousFrameId = nodeUpdateBeforeMap.frameId;
  38246. nodeUpdateBeforeMap.frameId = this.frameId;
  38247. if ( node.updateBefore( this ) === false ) {
  38248. nodeUpdateBeforeMap.frameId = previousFrameId;
  38249. }
  38250. }
  38251. } else if ( updateType === NodeUpdateType.RENDER ) {
  38252. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  38253. if ( nodeUpdateBeforeMap.renderId !== this.renderId ) {
  38254. const previousRenderId = nodeUpdateBeforeMap.renderId;
  38255. nodeUpdateBeforeMap.renderId = this.renderId;
  38256. if ( node.updateBefore( this ) === false ) {
  38257. nodeUpdateBeforeMap.renderId = previousRenderId;
  38258. }
  38259. }
  38260. } else if ( updateType === NodeUpdateType.OBJECT ) {
  38261. node.updateBefore( this );
  38262. }
  38263. }
  38264. /**
  38265. * This method executes the {@link Node#updateAfter} for the given node.
  38266. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  38267. * is only executed once per frame, render or object depending on the update
  38268. * type.
  38269. *
  38270. * @param {Node} node - The node that should be updated.
  38271. */
  38272. updateAfterNode( node ) {
  38273. const updateType = node.getUpdateAfterType();
  38274. const reference = node.updateReference( this );
  38275. if ( updateType === NodeUpdateType.FRAME ) {
  38276. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  38277. if ( nodeUpdateAfterMap.frameId !== this.frameId ) {
  38278. if ( node.updateAfter( this ) !== false ) {
  38279. nodeUpdateAfterMap.frameId = this.frameId;
  38280. }
  38281. }
  38282. } else if ( updateType === NodeUpdateType.RENDER ) {
  38283. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  38284. if ( nodeUpdateAfterMap.renderId !== this.renderId ) {
  38285. if ( node.updateAfter( this ) !== false ) {
  38286. nodeUpdateAfterMap.renderId = this.renderId;
  38287. }
  38288. }
  38289. } else if ( updateType === NodeUpdateType.OBJECT ) {
  38290. node.updateAfter( this );
  38291. }
  38292. }
  38293. /**
  38294. * This method executes the {@link Node#update} for the given node.
  38295. * It makes sure {@link Node#updateType} is honored meaning the update
  38296. * is only executed once per frame, render or object depending on the update
  38297. * type.
  38298. *
  38299. * @param {Node} node - The node that should be updated.
  38300. */
  38301. updateNode( node ) {
  38302. const updateType = node.getUpdateType();
  38303. const reference = node.updateReference( this );
  38304. if ( updateType === NodeUpdateType.FRAME ) {
  38305. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  38306. if ( nodeUpdateMap.frameId !== this.frameId ) {
  38307. if ( node.update( this ) !== false ) {
  38308. nodeUpdateMap.frameId = this.frameId;
  38309. }
  38310. }
  38311. } else if ( updateType === NodeUpdateType.RENDER ) {
  38312. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  38313. if ( nodeUpdateMap.renderId !== this.renderId ) {
  38314. if ( node.update( this ) !== false ) {
  38315. nodeUpdateMap.renderId = this.renderId;
  38316. }
  38317. }
  38318. } else if ( updateType === NodeUpdateType.OBJECT ) {
  38319. node.update( this );
  38320. }
  38321. }
  38322. /**
  38323. * Updates the internal state of the node frame. This method is
  38324. * called by the renderer in its internal animation loop.
  38325. */
  38326. update() {
  38327. this.frameId ++;
  38328. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  38329. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  38330. this.lastTime = performance.now();
  38331. this.time += this.deltaTime;
  38332. }
  38333. }
  38334. /**
  38335. * Describes the input of a {@link NodeFunction}.
  38336. */
  38337. class NodeFunctionInput {
  38338. /**
  38339. * Constructs a new node function input.
  38340. *
  38341. * @param {string} type - The input type.
  38342. * @param {string} name - The input name.
  38343. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  38344. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  38345. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  38346. */
  38347. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  38348. /**
  38349. * The input type.
  38350. *
  38351. * @type {string}
  38352. */
  38353. this.type = type;
  38354. /**
  38355. * The input name.
  38356. *
  38357. * @type {string}
  38358. */
  38359. this.name = name;
  38360. /**
  38361. * If the input is an Array, count will be the length.
  38362. *
  38363. * @type {?number}
  38364. * @default null
  38365. */
  38366. this.count = count;
  38367. /**
  38368. *The parameter qualifier (only relevant for GLSL).
  38369. *
  38370. * @type {('in'|'out'|'inout')}
  38371. * @default ''
  38372. */
  38373. this.qualifier = qualifier;
  38374. /**
  38375. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  38376. *
  38377. * @type {boolean}
  38378. * @default false
  38379. */
  38380. this.isConst = isConst;
  38381. }
  38382. }
  38383. NodeFunctionInput.isNodeFunctionInput = true;
  38384. /**
  38385. * Module for representing ambient lights as nodes.
  38386. *
  38387. * @augments AnalyticLightNode
  38388. */
  38389. class AmbientLightNode extends AnalyticLightNode {
  38390. static get type() {
  38391. return 'AmbientLightNode';
  38392. }
  38393. /**
  38394. * Constructs a new ambient light node.
  38395. *
  38396. * @param {?AmbientLight} [light=null] - The ambient light source.
  38397. */
  38398. constructor( light = null ) {
  38399. super( light );
  38400. }
  38401. setup( { context } ) {
  38402. context.irradiance.addAssign( this.colorNode );
  38403. }
  38404. }
  38405. /**
  38406. * Module for representing directional lights as nodes.
  38407. *
  38408. * @augments AnalyticLightNode
  38409. */
  38410. class DirectionalLightNode extends AnalyticLightNode {
  38411. static get type() {
  38412. return 'DirectionalLightNode';
  38413. }
  38414. /**
  38415. * Constructs a new directional light node.
  38416. *
  38417. * @param {?DirectionalLight} [light=null] - The directional light source.
  38418. */
  38419. constructor( light = null ) {
  38420. super( light );
  38421. }
  38422. setupDirect() {
  38423. const lightColor = this.colorNode;
  38424. const lightDirection = lightTargetDirection( this.light );
  38425. return { lightDirection, lightColor };
  38426. }
  38427. }
  38428. /**
  38429. * Module for representing hemisphere lights as nodes.
  38430. *
  38431. * @augments AnalyticLightNode
  38432. */
  38433. class HemisphereLightNode extends AnalyticLightNode {
  38434. static get type() {
  38435. return 'HemisphereLightNode';
  38436. }
  38437. /**
  38438. * Constructs a new hemisphere light node.
  38439. *
  38440. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  38441. */
  38442. constructor( light = null ) {
  38443. super( light );
  38444. /**
  38445. * Uniform node representing the light's position.
  38446. *
  38447. * @type {UniformNode<vec3>}
  38448. */
  38449. this.lightPositionNode = lightPosition( light );
  38450. /**
  38451. * A node representing the light's direction.
  38452. *
  38453. * @type {Node<vec3>}
  38454. */
  38455. this.lightDirectionNode = this.lightPositionNode.normalize();
  38456. /**
  38457. * Uniform node representing the light's ground color.
  38458. *
  38459. * @type {UniformNode<vec3>}
  38460. */
  38461. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  38462. }
  38463. /**
  38464. * Overwritten to updated hemisphere light specific uniforms.
  38465. *
  38466. * @param {NodeFrame} frame - A reference to the current node frame.
  38467. */
  38468. update( frame ) {
  38469. const { light } = this;
  38470. super.update( frame );
  38471. this.lightPositionNode.object3d = light;
  38472. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  38473. }
  38474. setup( builder ) {
  38475. const { colorNode, groundColorNode, lightDirectionNode } = this;
  38476. const dotNL = normalWorld.dot( lightDirectionNode );
  38477. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  38478. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  38479. builder.context.irradiance.addAssign( irradiance );
  38480. }
  38481. }
  38482. /**
  38483. * Module for representing spot lights as nodes.
  38484. *
  38485. * @augments AnalyticLightNode
  38486. */
  38487. class SpotLightNode extends AnalyticLightNode {
  38488. static get type() {
  38489. return 'SpotLightNode';
  38490. }
  38491. /**
  38492. * Constructs a new spot light node.
  38493. *
  38494. * @param {?SpotLight} [light=null] - The spot light source.
  38495. */
  38496. constructor( light = null ) {
  38497. super( light );
  38498. /**
  38499. * Uniform node representing the cone cosine.
  38500. *
  38501. * @type {UniformNode<float>}
  38502. */
  38503. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  38504. /**
  38505. * Uniform node representing the penumbra cosine.
  38506. *
  38507. * @type {UniformNode<float>}
  38508. */
  38509. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  38510. /**
  38511. * Uniform node representing the cutoff distance.
  38512. *
  38513. * @type {UniformNode<float>}
  38514. */
  38515. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  38516. /**
  38517. * Uniform node representing the decay exponent.
  38518. *
  38519. * @type {UniformNode<float>}
  38520. */
  38521. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  38522. /**
  38523. * Uniform node representing the light color.
  38524. *
  38525. * @type {UniformNode<Color>}
  38526. */
  38527. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  38528. }
  38529. /**
  38530. * Overwritten to updated spot light specific uniforms.
  38531. *
  38532. * @param {NodeFrame} frame - A reference to the current node frame.
  38533. */
  38534. update( frame ) {
  38535. super.update( frame );
  38536. const { light } = this;
  38537. this.coneCosNode.value = Math.cos( light.angle );
  38538. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  38539. this.cutoffDistanceNode.value = light.distance;
  38540. this.decayExponentNode.value = light.decay;
  38541. }
  38542. /**
  38543. * Computes the spot attenuation for the given angle.
  38544. *
  38545. * @param {NodeBuilder} builder - The node builder.
  38546. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  38547. * @return {Node<float>} The spot attenuation.
  38548. */
  38549. getSpotAttenuation( builder, angleCosine ) {
  38550. const { coneCosNode, penumbraCosNode } = this;
  38551. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  38552. }
  38553. getLightCoord( builder ) {
  38554. const properties = builder.getNodeProperties( this );
  38555. let projectionUV = properties.projectionUV;
  38556. if ( projectionUV === undefined ) {
  38557. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  38558. properties.projectionUV = projectionUV;
  38559. }
  38560. return projectionUV;
  38561. }
  38562. setupDirect( builder ) {
  38563. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  38564. const lightVector = this.getLightVector( builder );
  38565. const lightDirection = lightVector.normalize();
  38566. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  38567. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  38568. const lightDistance = lightVector.length();
  38569. const lightAttenuation = getDistanceAttenuation( {
  38570. lightDistance,
  38571. cutoffDistance: cutoffDistanceNode,
  38572. decayExponent: decayExponentNode
  38573. } );
  38574. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  38575. let projected, lightCoord;
  38576. if ( light.colorNode ) {
  38577. lightCoord = this.getLightCoord( builder );
  38578. projected = light.colorNode( lightCoord );
  38579. } else if ( light.map ) {
  38580. lightCoord = this.getLightCoord( builder );
  38581. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  38582. }
  38583. if ( projected ) {
  38584. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  38585. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  38586. }
  38587. return { lightColor, lightDirection };
  38588. }
  38589. }
  38590. /**
  38591. * An IES version of the default spot light node.
  38592. *
  38593. * @augments SpotLightNode
  38594. */
  38595. class IESSpotLightNode extends SpotLightNode {
  38596. static get type() {
  38597. return 'IESSpotLightNode';
  38598. }
  38599. /**
  38600. * Constructs a new IES spot light node.
  38601. *
  38602. * @param {?SpotLight} [light=null] - The spot light source.
  38603. */
  38604. constructor( light = null ) {
  38605. super( light );
  38606. /**
  38607. * The texture node representing the IES texture.
  38608. *
  38609. * @type {?TextureNode}
  38610. * @default null
  38611. */
  38612. this._iesTextureNode = null;
  38613. }
  38614. /**
  38615. * Overwrites the default implementation to compute an IES conform spot attenuation.
  38616. *
  38617. * @param {NodeBuilder} builder - The node builder.
  38618. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  38619. * @return {Node<float>} The spot attenuation.
  38620. */
  38621. getSpotAttenuation( builder, angleCosine ) {
  38622. const iesMap = this.light.iesMap;
  38623. let spotAttenuation = null;
  38624. if ( iesMap && iesMap.isTexture === true ) {
  38625. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  38626. this._iesTextureNode = texture( iesMap, vec2( angle, 0 ), 0 );
  38627. spotAttenuation = this._iesTextureNode.r;
  38628. } else {
  38629. spotAttenuation = super.getSpotAttenuation( builder, angleCosine );
  38630. }
  38631. return spotAttenuation;
  38632. }
  38633. /**
  38634. * Overwritten to update the IES spot light texture.
  38635. *
  38636. * @param {NodeFrame} frame - A reference to the current node frame.
  38637. */
  38638. update( frame ) {
  38639. super.update( frame );
  38640. if ( this._iesTextureNode !== null && this.light.iesMap ) {
  38641. this._iesTextureNode.value = this.light.iesMap;
  38642. }
  38643. }
  38644. }
  38645. /**
  38646. * Module for representing light probes as nodes.
  38647. *
  38648. * @augments AnalyticLightNode
  38649. */
  38650. class LightProbeNode extends AnalyticLightNode {
  38651. static get type() {
  38652. return 'LightProbeNode';
  38653. }
  38654. /**
  38655. * Constructs a new light probe node.
  38656. *
  38657. * @param {?LightProbe} [light=null] - The light probe.
  38658. */
  38659. constructor( light = null ) {
  38660. super( light );
  38661. const array = [];
  38662. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  38663. /**
  38664. * Light probe represented as a uniform of spherical harmonics.
  38665. *
  38666. * @type {UniformArrayNode}
  38667. */
  38668. this.lightProbe = uniformArray( array );
  38669. }
  38670. /**
  38671. * Overwritten to updated light probe specific uniforms.
  38672. *
  38673. * @param {NodeFrame} frame - A reference to the current node frame.
  38674. */
  38675. update( frame ) {
  38676. const { light } = this;
  38677. super.update( frame );
  38678. //
  38679. for ( let i = 0; i < 9; i ++ ) {
  38680. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  38681. }
  38682. }
  38683. setup( builder ) {
  38684. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  38685. builder.context.irradiance.addAssign( irradiance );
  38686. }
  38687. }
  38688. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  38689. const d = p.abs().sub( b );
  38690. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  38691. } );
  38692. /**
  38693. * An implementation of a projector light node.
  38694. *
  38695. * @augments SpotLightNode
  38696. */
  38697. class ProjectorLightNode extends SpotLightNode {
  38698. static get type() {
  38699. return 'ProjectorLightNode';
  38700. }
  38701. update( frame ) {
  38702. super.update( frame );
  38703. const light = this.light;
  38704. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  38705. if ( light.aspect === null ) {
  38706. let aspect = 1;
  38707. if ( light.map !== null ) {
  38708. aspect = light.map.width / light.map.height;
  38709. }
  38710. light.shadow.aspect = aspect;
  38711. } else {
  38712. light.shadow.aspect = light.aspect;
  38713. }
  38714. }
  38715. /**
  38716. * Overwrites the default implementation to compute projection attenuation.
  38717. *
  38718. * @param {NodeBuilder} builder - The node builder.
  38719. * @return {Node<float>} The spot attenuation.
  38720. */
  38721. getSpotAttenuation( builder ) {
  38722. const attenuation = float( 0 );
  38723. const penumbraCos = this.penumbraCosNode;
  38724. // compute the fragment's position in the light's clip space
  38725. const spotLightCoord = lightShadowMatrix( this.light ).mul( builder.context.positionWorld || positionWorld );
  38726. // the sign of w determines whether the current fragment is in front or behind the light.
  38727. // to avoid a back-projection, it's important to only compute an attenuation if w is positive
  38728. If( spotLightCoord.w.greaterThan( 0 ), () => {
  38729. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  38730. const boxDist = sdBox( projectionUV.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  38731. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  38732. attenuation.assign( saturate( boxDist.mul( -2 ).mul( angleFactor ) ) );
  38733. } );
  38734. return attenuation;
  38735. }
  38736. }
  38737. const _matrix41 = /*@__PURE__*/ new Matrix4();
  38738. const _matrix42 = /*@__PURE__*/ new Matrix4();
  38739. let _ltcLib = null;
  38740. /**
  38741. * Module for representing rect area lights as nodes.
  38742. *
  38743. * @augments AnalyticLightNode
  38744. */
  38745. class RectAreaLightNode extends AnalyticLightNode {
  38746. static get type() {
  38747. return 'RectAreaLightNode';
  38748. }
  38749. /**
  38750. * Constructs a new rect area light node.
  38751. *
  38752. * @param {?RectAreaLight} [light=null] - The rect area light source.
  38753. */
  38754. constructor( light = null ) {
  38755. super( light );
  38756. /**
  38757. * Uniform node representing the half height of the are light.
  38758. *
  38759. * @type {UniformNode<vec3>}
  38760. */
  38761. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  38762. /**
  38763. * Uniform node representing the half width of the are light.
  38764. *
  38765. * @type {UniformNode<vec3>}
  38766. */
  38767. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  38768. /**
  38769. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  38770. * relies on `viewMatrix` which might vary per render call.
  38771. *
  38772. * @type {string}
  38773. * @default 'render'
  38774. */
  38775. this.updateType = NodeUpdateType.RENDER;
  38776. }
  38777. /**
  38778. * Overwritten to updated rect area light specific uniforms.
  38779. *
  38780. * @param {NodeFrame} frame - A reference to the current node frame.
  38781. */
  38782. update( frame ) {
  38783. super.update( frame );
  38784. const { light } = this;
  38785. const viewMatrix = frame.camera.matrixWorldInverse;
  38786. _matrix42.identity();
  38787. _matrix41.copy( light.matrixWorld );
  38788. _matrix41.premultiply( viewMatrix );
  38789. _matrix42.extractRotation( _matrix41 );
  38790. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  38791. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  38792. this.halfWidth.value.applyMatrix4( _matrix42 );
  38793. this.halfHeight.value.applyMatrix4( _matrix42 );
  38794. }
  38795. setupDirectRectArea( builder ) {
  38796. let ltc_1, ltc_2;
  38797. if ( builder.isAvailable( 'float32Filterable' ) ) {
  38798. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  38799. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  38800. } else {
  38801. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  38802. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  38803. }
  38804. const { colorNode, light } = this;
  38805. const lightPosition = lightViewPosition( light );
  38806. return {
  38807. lightColor: colorNode,
  38808. lightPosition,
  38809. halfWidth: this.halfWidth,
  38810. halfHeight: this.halfHeight,
  38811. ltc_1,
  38812. ltc_2
  38813. };
  38814. }
  38815. /**
  38816. * Used to configure the internal BRDF approximation texture data.
  38817. *
  38818. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  38819. */
  38820. static setLTC( ltc ) {
  38821. _ltcLib = ltc;
  38822. }
  38823. }
  38824. /**
  38825. * Base class for node parsers. A derived parser must be implemented
  38826. * for each supported native shader language.
  38827. */
  38828. class NodeParser {
  38829. /**
  38830. * The method parses the given native code an returns a node function.
  38831. *
  38832. * @abstract
  38833. * @param {string} source - The native shader code.
  38834. * @return {NodeFunction} A node function.
  38835. */
  38836. parseFunction( /*source*/ ) {
  38837. warn( 'Abstract function.' );
  38838. }
  38839. }
  38840. /**
  38841. * Base class for node functions. A derived module must be implemented
  38842. * for each supported native shader language. Similar to other `Node*` modules,
  38843. * this class is only relevant during the building process and not used
  38844. * in user-level code.
  38845. */
  38846. class NodeFunction {
  38847. /**
  38848. * Constructs a new node function.
  38849. *
  38850. * @param {string} type - The node type. This type is the return type of the node function.
  38851. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  38852. * @param {string} [name=''] - The function's name.
  38853. * @param {string} [precision=''] - The precision qualifier.
  38854. */
  38855. constructor( type, inputs, name = '', precision = '' ) {
  38856. /**
  38857. * The node type. This type is the return type of the node function.
  38858. *
  38859. * @type {string}
  38860. */
  38861. this.type = type;
  38862. /**
  38863. * The function's inputs.
  38864. *
  38865. * @type {Array<NodeFunctionInput>}
  38866. */
  38867. this.inputs = inputs;
  38868. /**
  38869. * The name of the uniform.
  38870. *
  38871. * @type {string}
  38872. * @default ''
  38873. */
  38874. this.name = name;
  38875. /**
  38876. * The precision qualifier.
  38877. *
  38878. * @type {string}
  38879. * @default ''
  38880. */
  38881. this.precision = precision;
  38882. }
  38883. /**
  38884. * This method returns the native code of the node function.
  38885. *
  38886. * @abstract
  38887. * @param {string} name - The function's name.
  38888. * @return {string} A shader code.
  38889. */
  38890. getCode( /*name = this.name*/ ) {
  38891. warn( 'Abstract function.' );
  38892. }
  38893. }
  38894. NodeFunction.isNodeFunction = true;
  38895. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  38896. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  38897. const pragmaMain = '#pragma main';
  38898. const parse$1 = ( source ) => {
  38899. source = source.trim();
  38900. const pragmaMainIndex = source.indexOf( pragmaMain );
  38901. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  38902. const declaration = mainCode.match( declarationRegexp$1 );
  38903. if ( declaration !== null && declaration.length === 5 ) {
  38904. // tokenizer
  38905. const inputsCode = declaration[ 4 ];
  38906. const propsMatches = [];
  38907. let nameMatch = null;
  38908. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  38909. propsMatches.push( nameMatch );
  38910. }
  38911. // parser
  38912. const inputs = [];
  38913. let i = 0;
  38914. while ( i < propsMatches.length ) {
  38915. const isConst = propsMatches[ i ][ 0 ] === 'const';
  38916. if ( isConst === true ) {
  38917. i ++;
  38918. }
  38919. let qualifier = propsMatches[ i ][ 0 ];
  38920. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  38921. i ++;
  38922. } else {
  38923. qualifier = '';
  38924. }
  38925. const type = propsMatches[ i ++ ][ 0 ];
  38926. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  38927. if ( Number.isNaN( count ) === false ) i ++;
  38928. else count = null;
  38929. const name = propsMatches[ i ++ ][ 0 ];
  38930. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  38931. }
  38932. //
  38933. const blockCode = mainCode.substring( declaration[ 0 ].length );
  38934. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  38935. const type = declaration[ 2 ];
  38936. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  38937. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  38938. return {
  38939. type,
  38940. inputs,
  38941. name,
  38942. precision,
  38943. inputsCode,
  38944. blockCode,
  38945. headerCode
  38946. };
  38947. } else {
  38948. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  38949. }
  38950. };
  38951. /**
  38952. * This class represents a GLSL node function.
  38953. *
  38954. * @augments NodeFunction
  38955. */
  38956. class GLSLNodeFunction extends NodeFunction {
  38957. /**
  38958. * Constructs a new GLSL node function.
  38959. *
  38960. * @param {string} source - The GLSL source.
  38961. */
  38962. constructor( source ) {
  38963. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  38964. super( type, inputs, name, precision );
  38965. this.inputsCode = inputsCode;
  38966. this.blockCode = blockCode;
  38967. this.headerCode = headerCode;
  38968. }
  38969. /**
  38970. * This method returns the GLSL code of the node function.
  38971. *
  38972. * @param {string} [name=this.name] - The function's name.
  38973. * @return {string} The shader code.
  38974. */
  38975. getCode( name = this.name ) {
  38976. let code;
  38977. const blockCode = this.blockCode;
  38978. if ( blockCode !== '' ) {
  38979. const { type, inputsCode, headerCode, precision } = this;
  38980. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  38981. if ( precision !== '' ) {
  38982. declarationCode = `${ precision } ${ declarationCode }`;
  38983. }
  38984. code = headerCode + declarationCode + blockCode;
  38985. } else {
  38986. // interface function
  38987. code = '';
  38988. }
  38989. return code;
  38990. }
  38991. }
  38992. /**
  38993. * A GLSL node parser.
  38994. *
  38995. * @augments NodeParser
  38996. */
  38997. class GLSLNodeParser extends NodeParser {
  38998. /**
  38999. * The method parses the given GLSL code an returns a node function.
  39000. *
  39001. * @param {string} source - The GLSL code.
  39002. * @return {GLSLNodeFunction} A node function.
  39003. */
  39004. parseFunction( source ) {
  39005. return new GLSLNodeFunction( source );
  39006. }
  39007. }
  39008. const _chainKeys$1 = [];
  39009. const _cacheKeyValues = [];
  39010. // Dedicated uniform for output pass array layer selection
  39011. // This is separate from cameraIndex to avoid the sharedUniformGroup complexity
  39012. const _outputLayerIndex = /*@__PURE__*/ uniform( 0, 'int' ).setGroup( renderGroup );
  39013. /**
  39014. * This renderer module manages node-related objects and is the
  39015. * primary interface between the renderer and the node system.
  39016. *
  39017. * @private
  39018. * @augments DataMap
  39019. */
  39020. class NodeManager extends DataMap {
  39021. /**
  39022. * Constructs a new nodes management component.
  39023. *
  39024. * @param {Renderer} renderer - The renderer.
  39025. * @param {Backend} backend - The renderer's backend.
  39026. */
  39027. constructor( renderer, backend ) {
  39028. super();
  39029. /**
  39030. * The renderer.
  39031. *
  39032. * @type {Renderer}
  39033. */
  39034. this.renderer = renderer;
  39035. /**
  39036. * The renderer's backend.
  39037. *
  39038. * @type {Backend}
  39039. */
  39040. this.backend = backend;
  39041. /**
  39042. * The node frame.
  39043. *
  39044. * @type {Renderer}
  39045. */
  39046. this.nodeFrame = new NodeFrame();
  39047. /**
  39048. * A cache for managing node builder states.
  39049. *
  39050. * @type {Map<number,NodeBuilderState>}
  39051. */
  39052. this.nodeBuilderCache = new Map();
  39053. /**
  39054. * A cache for managing data cache key data.
  39055. *
  39056. * @type {ChainMap}
  39057. */
  39058. this.callHashCache = new ChainMap();
  39059. /**
  39060. * A cache for managing node uniforms group data.
  39061. *
  39062. * @type {ChainMap}
  39063. */
  39064. this.groupsData = new ChainMap();
  39065. /**
  39066. * Queue for pending async builds to limit concurrent compilation.
  39067. *
  39068. * @private
  39069. * @type {Array<Function>}
  39070. */
  39071. this._buildQueue = [];
  39072. /**
  39073. * Whether an async build is currently in progress.
  39074. *
  39075. * @private
  39076. * @type {boolean}
  39077. */
  39078. this._buildInProgress = false;
  39079. /**
  39080. * A cache for managing node objects of
  39081. * scene properties like fog or environments.
  39082. *
  39083. * @type {Object<string,WeakMap>}
  39084. */
  39085. this.cacheLib = {};
  39086. }
  39087. /**
  39088. * Returns `true` if the given node uniforms group must be updated or not.
  39089. *
  39090. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  39091. * @return {boolean} Whether the node uniforms group requires an update or not.
  39092. */
  39093. updateGroup( nodeUniformsGroup ) {
  39094. const groupNode = nodeUniformsGroup.groupNode;
  39095. _chainKeys$1[ 0 ] = groupNode;
  39096. _chainKeys$1[ 1 ] = nodeUniformsGroup;
  39097. let groupData = this.groupsData.get( _chainKeys$1 );
  39098. if ( groupData === undefined ) this.groupsData.set( _chainKeys$1, groupData = {} );
  39099. _chainKeys$1[ 0 ] = null;
  39100. _chainKeys$1[ 1 ] = null;
  39101. if ( groupData.version !== groupNode.version ) {
  39102. groupData.version = groupNode.version;
  39103. return true;
  39104. }
  39105. return false;
  39106. }
  39107. /**
  39108. * Returns the cache key for the given render object.
  39109. *
  39110. * @param {RenderObject} renderObject - The render object.
  39111. * @return {number} The cache key.
  39112. */
  39113. getForRenderCacheKey( renderObject ) {
  39114. return renderObject.initialCacheKey;
  39115. }
  39116. /**
  39117. * Creates a node builder configured for the given render object and material.
  39118. *
  39119. * @private
  39120. * @param {RenderObject} renderObject - The render object.
  39121. * @param {Material} material - The material to use.
  39122. * @return {NodeBuilder} The configured node builder.
  39123. */
  39124. _createNodeBuilder( renderObject, material ) {
  39125. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  39126. nodeBuilder.scene = renderObject.scene;
  39127. nodeBuilder.material = material;
  39128. nodeBuilder.camera = renderObject.camera;
  39129. nodeBuilder.context.material = material;
  39130. nodeBuilder.lightsNode = renderObject.lightsNode;
  39131. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  39132. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  39133. nodeBuilder.clippingContext = renderObject.clippingContext;
  39134. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  39135. nodeBuilder.enableMultiview();
  39136. }
  39137. return nodeBuilder;
  39138. }
  39139. /**
  39140. * Returns a node builder state for the given render object.
  39141. *
  39142. * @param {RenderObject} renderObject - The render object.
  39143. * @param {boolean} [useAsync=false] - Whether to use async build with yielding.
  39144. * @return {NodeBuilderState|Promise<NodeBuilderState>} The node builder state (or Promise if async).
  39145. */
  39146. getForRender( renderObject, useAsync = false ) {
  39147. const renderObjectData = this.get( renderObject );
  39148. let nodeBuilderState = renderObjectData.nodeBuilderState;
  39149. if ( nodeBuilderState === undefined ) {
  39150. const { nodeBuilderCache } = this;
  39151. const cacheKey = this.getForRenderCacheKey( renderObject );
  39152. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  39153. if ( nodeBuilderState === undefined ) {
  39154. const buildNodeBuilder = async () => {
  39155. let nodeBuilder = this._createNodeBuilder( renderObject, renderObject.material );
  39156. try {
  39157. if ( useAsync ) {
  39158. await nodeBuilder.buildAsync();
  39159. } else {
  39160. nodeBuilder.build();
  39161. }
  39162. } catch ( e ) {
  39163. nodeBuilder = this._createNodeBuilder( renderObject, new NodeMaterial() );
  39164. if ( useAsync ) {
  39165. await nodeBuilder.buildAsync();
  39166. } else {
  39167. nodeBuilder.build();
  39168. }
  39169. error( 'TSL: ' + e );
  39170. }
  39171. return nodeBuilder;
  39172. };
  39173. if ( useAsync ) {
  39174. return buildNodeBuilder().then( ( nodeBuilder ) => {
  39175. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  39176. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  39177. nodeBuilderState.usedTimes ++;
  39178. renderObjectData.nodeBuilderState = nodeBuilderState;
  39179. return nodeBuilderState;
  39180. } );
  39181. } else {
  39182. // Synchronous path - call buildNodeBuilder but don't await
  39183. let nodeBuilder = this._createNodeBuilder( renderObject, renderObject.material );
  39184. try {
  39185. nodeBuilder.build();
  39186. } catch ( e ) {
  39187. nodeBuilder = this._createNodeBuilder( renderObject, new NodeMaterial() );
  39188. nodeBuilder.build();
  39189. let stackTrace = e.stackTrace;
  39190. if ( ! stackTrace && e.stack ) {
  39191. // Capture stack trace for JavaScript errors
  39192. stackTrace = new StackTrace( e.stack );
  39193. }
  39194. error( 'TSL: ' + e, stackTrace );
  39195. }
  39196. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  39197. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  39198. }
  39199. }
  39200. nodeBuilderState.usedTimes ++;
  39201. renderObjectData.nodeBuilderState = nodeBuilderState;
  39202. }
  39203. return nodeBuilderState;
  39204. }
  39205. /**
  39206. * Async version of getForRender() that yields to main thread during build.
  39207. * Use this in compileAsync() to prevent blocking the main thread.
  39208. *
  39209. * @param {RenderObject} renderObject - The render object.
  39210. * @return {Promise<NodeBuilderState>} A promise that resolves to the node builder state.
  39211. */
  39212. getForRenderAsync( renderObject ) {
  39213. const result = this.getForRender( renderObject, true );
  39214. // Ensure we always return a Promise (cache hit returns nodeBuilderState directly)
  39215. if ( result.then ) {
  39216. return result;
  39217. }
  39218. return Promise.resolve( result );
  39219. }
  39220. /**
  39221. * Returns nodeBuilderState if ready, null if pending async build.
  39222. * Queues async build on first call for cache miss.
  39223. * Use this in render() path to enable non-blocking compilation.
  39224. *
  39225. * @param {RenderObject} renderObject - The render object.
  39226. * @return {?NodeBuilderState} The node builder state, or null if still building.
  39227. */
  39228. getForRenderDeferred( renderObject ) {
  39229. const renderObjectData = this.get( renderObject );
  39230. // Already built for this renderObject
  39231. if ( renderObjectData.nodeBuilderState !== undefined ) {
  39232. return renderObjectData.nodeBuilderState;
  39233. }
  39234. // Check cache with stable key
  39235. const cacheKey = this.getForRenderCacheKey( renderObject );
  39236. const nodeBuilderState = this.nodeBuilderCache.get( cacheKey );
  39237. if ( nodeBuilderState !== undefined ) {
  39238. // Cache hit - use it
  39239. nodeBuilderState.usedTimes ++;
  39240. renderObjectData.nodeBuilderState = nodeBuilderState;
  39241. return nodeBuilderState;
  39242. }
  39243. // Cache miss - check if async build already queued
  39244. if ( renderObjectData.pendingBuild !== true ) {
  39245. // Mark as pending and add to build queue
  39246. renderObjectData.pendingBuild = true;
  39247. this._buildQueue.push( () => {
  39248. return this.getForRenderAsync( renderObject ).then( () => {
  39249. renderObjectData.pendingBuild = false;
  39250. } );
  39251. } );
  39252. // Start processing queue if not already running
  39253. this._processBuildQueue();
  39254. }
  39255. return null; // Not ready
  39256. }
  39257. /**
  39258. * Processes the build queue one item at a time.
  39259. * This ensures builds don't all run simultaneously and freeze the main thread.
  39260. *
  39261. * @private
  39262. */
  39263. _processBuildQueue() {
  39264. if ( this._buildInProgress || this._buildQueue.length === 0 ) {
  39265. return;
  39266. }
  39267. this._buildInProgress = true;
  39268. const buildFn = this._buildQueue.shift();
  39269. buildFn().then( () => {
  39270. this._buildInProgress = false;
  39271. // Process next item in queue
  39272. this._processBuildQueue();
  39273. } );
  39274. }
  39275. /**
  39276. * Deletes the given object from the internal data map
  39277. *
  39278. * @param {any} object - The object to delete.
  39279. * @return {?Object} The deleted dictionary.
  39280. */
  39281. delete( object ) {
  39282. if ( object.isRenderObject ) {
  39283. const nodeBuilderState = this.get( object ).nodeBuilderState;
  39284. if ( nodeBuilderState !== undefined ) {
  39285. nodeBuilderState.usedTimes --;
  39286. if ( nodeBuilderState.usedTimes === 0 ) {
  39287. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  39288. }
  39289. }
  39290. }
  39291. return super.delete( object );
  39292. }
  39293. /**
  39294. * Returns a node builder state for the given compute node.
  39295. *
  39296. * @param {Node} computeNode - The compute node.
  39297. * @return {NodeBuilderState} The node builder state.
  39298. */
  39299. getForCompute( computeNode ) {
  39300. const computeData = this.get( computeNode );
  39301. let nodeBuilderState = computeData.nodeBuilderState;
  39302. if ( nodeBuilderState === undefined || computeData.version !== computeNode.version ) {
  39303. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  39304. nodeBuilder.build();
  39305. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  39306. computeData.nodeBuilderState = nodeBuilderState;
  39307. computeData.version = computeNode.version;
  39308. }
  39309. return nodeBuilderState;
  39310. }
  39311. /**
  39312. * Creates a node builder state for the given node builder.
  39313. *
  39314. * @private
  39315. * @param {NodeBuilder} nodeBuilder - The node builder.
  39316. * @return {NodeBuilderState} The node builder state.
  39317. */
  39318. _createNodeBuilderState( nodeBuilder ) {
  39319. return new NodeBuilderState(
  39320. nodeBuilder.vertexShader,
  39321. nodeBuilder.fragmentShader,
  39322. nodeBuilder.computeShader,
  39323. nodeBuilder.getAttributesArray(),
  39324. nodeBuilder.getBindings(),
  39325. nodeBuilder.updateNodes,
  39326. nodeBuilder.updateBeforeNodes,
  39327. nodeBuilder.updateAfterNodes,
  39328. nodeBuilder.observer,
  39329. nodeBuilder.transforms
  39330. );
  39331. }
  39332. /**
  39333. * Returns an environment node for the current configured
  39334. * scene environment.
  39335. *
  39336. * @param {Scene} scene - The scene.
  39337. * @return {Node} A node representing the current scene environment.
  39338. */
  39339. getEnvironmentNode( scene ) {
  39340. this.updateEnvironment( scene );
  39341. let environmentNode = null;
  39342. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  39343. environmentNode = scene.environmentNode;
  39344. } else {
  39345. const sceneData = this.get( scene );
  39346. if ( sceneData.environmentNode ) {
  39347. environmentNode = sceneData.environmentNode;
  39348. }
  39349. }
  39350. return environmentNode;
  39351. }
  39352. /**
  39353. * Returns a background node for the current configured
  39354. * scene background.
  39355. *
  39356. * @param {Scene} scene - The scene.
  39357. * @return {Node} A node representing the current scene background.
  39358. */
  39359. getBackgroundNode( scene ) {
  39360. this.updateBackground( scene );
  39361. let backgroundNode = null;
  39362. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  39363. backgroundNode = scene.backgroundNode;
  39364. } else {
  39365. const sceneData = this.get( scene );
  39366. if ( sceneData.backgroundNode ) {
  39367. backgroundNode = sceneData.backgroundNode;
  39368. }
  39369. }
  39370. return backgroundNode;
  39371. }
  39372. /**
  39373. * Returns a fog node for the current configured scene fog.
  39374. *
  39375. * @param {Scene} scene - The scene.
  39376. * @return {Node} A node representing the current scene fog.
  39377. */
  39378. getFogNode( scene ) {
  39379. this.updateFog( scene );
  39380. return scene.fogNode || this.get( scene ).fogNode || null;
  39381. }
  39382. /**
  39383. * Returns a cache key for the given scene and lights node.
  39384. * This key is used by `RenderObject` as a part of the dynamic
  39385. * cache key (a key that must be checked every time the render
  39386. * objects is drawn).
  39387. *
  39388. * @param {Scene} scene - The scene.
  39389. * @param {LightsNode} lightsNode - The lights node.
  39390. * @return {number} The cache key.
  39391. */
  39392. getCacheKey( scene, lightsNode ) {
  39393. _chainKeys$1[ 0 ] = scene;
  39394. _chainKeys$1[ 1 ] = lightsNode;
  39395. const callId = this.renderer.info.calls;
  39396. const cacheKeyData = this.callHashCache.get( _chainKeys$1 ) || {};
  39397. if ( cacheKeyData.callId !== callId ) {
  39398. const environmentNode = this.getEnvironmentNode( scene );
  39399. const fogNode = this.getFogNode( scene );
  39400. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  39401. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  39402. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  39403. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  39404. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  39405. _cacheKeyValues.push( this.renderer.shadowMap.type );
  39406. cacheKeyData.callId = callId;
  39407. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  39408. this.callHashCache.set( _chainKeys$1, cacheKeyData );
  39409. _cacheKeyValues.length = 0;
  39410. }
  39411. _chainKeys$1[ 0 ] = null;
  39412. _chainKeys$1[ 1 ] = null;
  39413. return cacheKeyData.cacheKey;
  39414. }
  39415. /**
  39416. * A boolean that indicates whether tone mapping should be enabled
  39417. * or not.
  39418. *
  39419. * @type {boolean}
  39420. */
  39421. get isToneMappingState() {
  39422. return this.renderer.getRenderTarget() ? false : true;
  39423. }
  39424. /**
  39425. * If a scene background is configured, this method makes sure to
  39426. * represent the background with a corresponding node-based implementation.
  39427. *
  39428. * @param {Scene} scene - The scene.
  39429. */
  39430. updateBackground( scene ) {
  39431. const sceneData = this.get( scene );
  39432. const background = scene.background;
  39433. if ( background ) {
  39434. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  39435. if ( sceneData.background !== background || forceUpdate ) {
  39436. const backgroundNode = this.getCacheNode( 'background', background, () => {
  39437. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  39438. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  39439. return pmremTexture( background );
  39440. } else {
  39441. let envMap;
  39442. if ( background.isCubeTexture === true ) {
  39443. envMap = cubeTexture( background );
  39444. } else {
  39445. envMap = texture( background );
  39446. }
  39447. return cubeMapNode( envMap );
  39448. }
  39449. } else if ( background.isTexture === true ) {
  39450. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  39451. } else if ( background.isColor !== true ) {
  39452. error( 'WebGPUNodes: Unsupported background configuration.', background );
  39453. }
  39454. }, forceUpdate );
  39455. sceneData.backgroundNode = backgroundNode;
  39456. sceneData.background = background;
  39457. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  39458. }
  39459. } else if ( sceneData.backgroundNode ) {
  39460. delete sceneData.backgroundNode;
  39461. delete sceneData.background;
  39462. }
  39463. }
  39464. /**
  39465. * This method is part of the caching of nodes which are used to represents the
  39466. * scene's background, fog or environment.
  39467. *
  39468. * @param {string} type - The type of object to cache.
  39469. * @param {Object} object - The object.
  39470. * @param {Function} callback - A callback that produces a node representation for the given object.
  39471. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  39472. * @return {Node} The node representation.
  39473. */
  39474. getCacheNode( type, object, callback, forceUpdate = false ) {
  39475. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  39476. let node = nodeCache.get( object );
  39477. if ( node === undefined || forceUpdate ) {
  39478. node = callback();
  39479. nodeCache.set( object, node );
  39480. }
  39481. return node;
  39482. }
  39483. /**
  39484. * If a scene fog is configured, this method makes sure to
  39485. * represent the fog with a corresponding node-based implementation.
  39486. *
  39487. * @param {Scene} scene - The scene.
  39488. */
  39489. updateFog( scene ) {
  39490. const sceneData = this.get( scene );
  39491. const sceneFog = scene.fog;
  39492. if ( sceneFog ) {
  39493. if ( sceneData.fog !== sceneFog ) {
  39494. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  39495. if ( sceneFog.isFogExp2 ) {
  39496. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  39497. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  39498. return fog( color, densityFogFactor( density ) );
  39499. } else if ( sceneFog.isFog ) {
  39500. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  39501. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  39502. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  39503. return fog( color, rangeFogFactor( near, far ) );
  39504. } else {
  39505. error( 'Renderer: Unsupported fog configuration.', sceneFog );
  39506. }
  39507. } );
  39508. sceneData.fogNode = fogNode;
  39509. sceneData.fog = sceneFog;
  39510. }
  39511. } else {
  39512. delete sceneData.fogNode;
  39513. delete sceneData.fog;
  39514. }
  39515. }
  39516. /**
  39517. * If a scene environment is configured, this method makes sure to
  39518. * represent the environment with a corresponding node-based implementation.
  39519. *
  39520. * @param {Scene} scene - The scene.
  39521. */
  39522. updateEnvironment( scene ) {
  39523. const sceneData = this.get( scene );
  39524. const environment = scene.environment;
  39525. if ( environment ) {
  39526. if ( sceneData.environment !== environment ) {
  39527. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  39528. if ( environment.isCubeTexture === true ) {
  39529. return cubeTexture( environment );
  39530. } else if ( environment.isTexture === true ) {
  39531. return texture( environment );
  39532. } else {
  39533. error( 'Nodes: Unsupported environment configuration.', environment );
  39534. }
  39535. } );
  39536. sceneData.environmentNode = environmentNode;
  39537. sceneData.environment = environment;
  39538. }
  39539. } else if ( sceneData.environmentNode ) {
  39540. delete sceneData.environmentNode;
  39541. delete sceneData.environment;
  39542. }
  39543. }
  39544. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  39545. const nodeFrame = this.nodeFrame;
  39546. nodeFrame.renderer = renderer;
  39547. nodeFrame.scene = scene;
  39548. nodeFrame.object = object;
  39549. nodeFrame.camera = camera;
  39550. nodeFrame.material = material;
  39551. return nodeFrame;
  39552. }
  39553. getNodeFrameForRender( renderObject ) {
  39554. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  39555. }
  39556. /**
  39557. * Returns the current output cache key.
  39558. *
  39559. * @return {string} The output cache key.
  39560. */
  39561. getOutputCacheKey() {
  39562. const renderer = this.renderer;
  39563. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  39564. }
  39565. /**
  39566. * Returns a node that represents the output configuration (tone mapping and
  39567. * color space) for the current target.
  39568. *
  39569. * @param {Texture} outputTarget - The output target.
  39570. * @return {Node} The output node.
  39571. */
  39572. getOutputNode( outputTarget ) {
  39573. const renderer = this.renderer;
  39574. let output;
  39575. if ( outputTarget.isArrayTexture ) {
  39576. if ( this.backend.isWebGLBackend ) {
  39577. output = texture( outputTarget, screenUV ).depth( builtin( 'gl_ViewID_OVR' ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  39578. } else {
  39579. output = texture( outputTarget, screenUV ).depth( _outputLayerIndex ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  39580. }
  39581. } else {
  39582. output = texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  39583. }
  39584. return output;
  39585. }
  39586. /**
  39587. * Sets the output layer index for array texture output pass.
  39588. * This should be called before each layer render during the output pass.
  39589. *
  39590. * @param {number} index - The layer index.
  39591. */
  39592. setOutputLayerIndex( index ) {
  39593. _outputLayerIndex.value = index;
  39594. }
  39595. /**
  39596. * Triggers the call of `updateBefore()` methods
  39597. * for all nodes of the given render object.
  39598. *
  39599. * @param {RenderObject} renderObject - The render object.
  39600. */
  39601. updateBefore( renderObject ) {
  39602. const nodeBuilder = renderObject.getNodeBuilderState();
  39603. for ( const node of nodeBuilder.updateBeforeNodes ) {
  39604. // update frame state for each node
  39605. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  39606. }
  39607. }
  39608. /**
  39609. * Triggers the call of `updateAfter()` methods
  39610. * for all nodes of the given render object.
  39611. *
  39612. * @param {RenderObject} renderObject - The render object.
  39613. */
  39614. updateAfter( renderObject ) {
  39615. const nodeBuilder = renderObject.getNodeBuilderState();
  39616. for ( const node of nodeBuilder.updateAfterNodes ) {
  39617. // update frame state for each node
  39618. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  39619. }
  39620. }
  39621. /**
  39622. * Triggers the call of `update()` methods
  39623. * for all nodes of the given compute node.
  39624. *
  39625. * @param {Node} computeNode - The compute node.
  39626. */
  39627. updateForCompute( computeNode ) {
  39628. const nodeFrame = this.getNodeFrame();
  39629. const nodeBuilder = this.getForCompute( computeNode );
  39630. for ( const node of nodeBuilder.updateNodes ) {
  39631. nodeFrame.updateNode( node );
  39632. }
  39633. }
  39634. /**
  39635. * Triggers the call of `update()` methods
  39636. * for all nodes of the given render object.
  39637. *
  39638. * @param {RenderObject} renderObject - The render object.
  39639. */
  39640. updateForRender( renderObject ) {
  39641. const nodeFrame = this.getNodeFrameForRender( renderObject );
  39642. const nodeBuilder = renderObject.getNodeBuilderState();
  39643. for ( const node of nodeBuilder.updateNodes ) {
  39644. nodeFrame.updateNode( node );
  39645. }
  39646. }
  39647. /**
  39648. * Returns `true` if the given render object requires a refresh.
  39649. *
  39650. * @param {RenderObject} renderObject - The render object.
  39651. * @return {boolean} Whether the given render object requires a refresh or not.
  39652. */
  39653. needsRefresh( renderObject ) {
  39654. const nodeFrame = this.getNodeFrameForRender( renderObject );
  39655. const monitor = renderObject.getMonitor();
  39656. return monitor.needsRefresh( renderObject, nodeFrame );
  39657. }
  39658. /**
  39659. * Frees the internal resources.
  39660. */
  39661. dispose() {
  39662. super.dispose();
  39663. this.nodeFrame = new NodeFrame();
  39664. this.nodeBuilderCache = new Map();
  39665. this.cacheLib = {};
  39666. }
  39667. }
  39668. const _plane = /*@__PURE__*/ new Plane();
  39669. /**
  39670. * Represents the state that is used to perform clipping via clipping planes.
  39671. * There is a default clipping context for each render context. When the
  39672. * scene holds instances of `ClippingGroup`, there will be a context for each
  39673. * group.
  39674. *
  39675. * @private
  39676. */
  39677. class ClippingContext {
  39678. /**
  39679. * Constructs a new clipping context.
  39680. *
  39681. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  39682. */
  39683. constructor( parentContext = null ) {
  39684. /**
  39685. * The clipping context's version.
  39686. *
  39687. * @type {number}
  39688. * @readonly
  39689. */
  39690. this.version = 0;
  39691. /**
  39692. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  39693. *
  39694. * @type {?boolean}
  39695. * @default null
  39696. */
  39697. this.clipIntersection = null;
  39698. /**
  39699. * The clipping context's cache key.
  39700. *
  39701. * @type {string}
  39702. */
  39703. this.cacheKey = '';
  39704. /**
  39705. * Whether the shadow pass is active or not.
  39706. *
  39707. * @type {boolean}
  39708. * @default false
  39709. */
  39710. this.shadowPass = false;
  39711. /**
  39712. * The view normal matrix.
  39713. *
  39714. * @type {Matrix3}
  39715. */
  39716. this.viewNormalMatrix = new Matrix3();
  39717. /**
  39718. * Internal cache for maintaining clipping contexts.
  39719. *
  39720. * @type {WeakMap<ClippingGroup,ClippingContext>}
  39721. */
  39722. this.clippingGroupContexts = new WeakMap();
  39723. /**
  39724. * The intersection planes.
  39725. *
  39726. * @type {Array<Vector4>}
  39727. */
  39728. this.intersectionPlanes = [];
  39729. /**
  39730. * The intersection planes.
  39731. *
  39732. * @type {Array<Vector4>}
  39733. */
  39734. this.unionPlanes = [];
  39735. /**
  39736. * The version of the clipping context's parent context.
  39737. *
  39738. * @type {?number}
  39739. * @readonly
  39740. */
  39741. this.parentVersion = null;
  39742. if ( parentContext !== null ) {
  39743. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  39744. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  39745. this.shadowPass = parentContext.shadowPass;
  39746. this.viewMatrix = parentContext.viewMatrix;
  39747. }
  39748. }
  39749. /**
  39750. * Projects the given source clipping planes and writes the result into the
  39751. * destination array.
  39752. *
  39753. * @param {Array<Plane>} source - The source clipping planes.
  39754. * @param {Array<Vector4>} destination - The destination.
  39755. * @param {number} offset - The offset.
  39756. */
  39757. projectPlanes( source, destination, offset ) {
  39758. const l = source.length;
  39759. for ( let i = 0; i < l; i ++ ) {
  39760. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  39761. const v = destination[ offset + i ];
  39762. const normal = _plane.normal;
  39763. v.x = - normal.x;
  39764. v.y = - normal.y;
  39765. v.z = - normal.z;
  39766. v.w = _plane.constant;
  39767. }
  39768. }
  39769. /**
  39770. * Updates the root clipping context of a scene.
  39771. *
  39772. * @param {Scene} scene - The scene.
  39773. * @param {Camera} camera - The camera that is used to render the scene.
  39774. */
  39775. updateGlobal( scene, camera ) {
  39776. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  39777. this.viewMatrix = camera.matrixWorldInverse;
  39778. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  39779. }
  39780. /**
  39781. * Updates the clipping context.
  39782. *
  39783. * @param {ClippingContext} parentContext - The parent context.
  39784. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  39785. */
  39786. update( parentContext, clippingGroup ) {
  39787. let update = false;
  39788. if ( parentContext.version !== this.parentVersion ) {
  39789. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  39790. this.unionPlanes = Array.from( parentContext.unionPlanes );
  39791. this.parentVersion = parentContext.version;
  39792. }
  39793. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  39794. this.clipIntersection = clippingGroup.clipIntersection;
  39795. if ( this.clipIntersection ) {
  39796. this.unionPlanes.length = parentContext.unionPlanes.length;
  39797. } else {
  39798. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  39799. }
  39800. }
  39801. const srcClippingPlanes = clippingGroup.clippingPlanes;
  39802. const l = srcClippingPlanes.length;
  39803. let dstClippingPlanes;
  39804. let offset;
  39805. if ( this.clipIntersection ) {
  39806. dstClippingPlanes = this.intersectionPlanes;
  39807. offset = parentContext.intersectionPlanes.length;
  39808. } else {
  39809. dstClippingPlanes = this.unionPlanes;
  39810. offset = parentContext.unionPlanes.length;
  39811. }
  39812. if ( dstClippingPlanes.length !== offset + l ) {
  39813. dstClippingPlanes.length = offset + l;
  39814. for ( let i = 0; i < l; i ++ ) {
  39815. dstClippingPlanes[ offset + i ] = new Vector4();
  39816. }
  39817. update = true;
  39818. }
  39819. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  39820. if ( update ) {
  39821. this.version ++;
  39822. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  39823. }
  39824. }
  39825. /**
  39826. * Returns a clipping context for the given clipping group.
  39827. *
  39828. * @param {ClippingGroup} clippingGroup - The clipping group.
  39829. * @return {ClippingContext} The clipping context.
  39830. */
  39831. getGroupContext( clippingGroup ) {
  39832. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  39833. let context = this.clippingGroupContexts.get( clippingGroup );
  39834. if ( context === undefined ) {
  39835. context = new ClippingContext( this );
  39836. this.clippingGroupContexts.set( clippingGroup, context );
  39837. }
  39838. context.update( this, clippingGroup );
  39839. return context;
  39840. }
  39841. /**
  39842. * The count of union clipping planes.
  39843. *
  39844. * @type {number}
  39845. * @readonly
  39846. */
  39847. get unionClippingCount() {
  39848. return this.unionPlanes.length;
  39849. }
  39850. }
  39851. /**
  39852. * This module is used to represent render bundles inside the renderer
  39853. * for further processing.
  39854. *
  39855. * @private
  39856. */
  39857. class RenderBundle {
  39858. /**
  39859. * Constructs a new bundle group.
  39860. *
  39861. * @param {BundleGroup} bundleGroup - The bundle group.
  39862. * @param {Camera} camera - The camera the bundle group is rendered with.
  39863. * @param {RenderContext} renderContext - The render context the bundle is rendered with.
  39864. */
  39865. constructor( bundleGroup, camera, renderContext ) {
  39866. this.bundleGroup = bundleGroup;
  39867. this.camera = camera;
  39868. this.renderContext = renderContext;
  39869. }
  39870. }
  39871. const _chainKeys = [];
  39872. /**
  39873. * This renderer module manages render bundles.
  39874. *
  39875. * @private
  39876. */
  39877. class RenderBundles {
  39878. /**
  39879. * Constructs a new render bundle management component.
  39880. */
  39881. constructor() {
  39882. /**
  39883. * A chain map for maintaining the render bundles.
  39884. *
  39885. * @type {ChainMap}
  39886. */
  39887. this.bundles = new ChainMap();
  39888. }
  39889. /**
  39890. * Returns a render bundle for the given bundle group and camera.
  39891. *
  39892. * @param {BundleGroup} bundleGroup - The bundle group.
  39893. * @param {Camera} camera - The camera the bundle group is rendered with.
  39894. * @param {RenderContext} renderContext - The render context the bundle is rendered with.
  39895. * @return {RenderBundle} The render bundle.
  39896. */
  39897. get( bundleGroup, camera, renderContext ) {
  39898. const bundles = this.bundles;
  39899. _chainKeys[ 0 ] = bundleGroup;
  39900. _chainKeys[ 1 ] = camera;
  39901. _chainKeys[ 2 ] = renderContext;
  39902. let bundle = bundles.get( _chainKeys );
  39903. if ( bundle === undefined ) {
  39904. bundle = new RenderBundle( bundleGroup, camera, renderContext );
  39905. bundles.set( _chainKeys, bundle );
  39906. }
  39907. _chainKeys[ 0 ] = null;
  39908. _chainKeys[ 1 ] = null;
  39909. _chainKeys[ 2 ] = null;
  39910. return bundle;
  39911. }
  39912. /**
  39913. * Frees all internal resources.
  39914. */
  39915. dispose() {
  39916. this.bundles = new ChainMap();
  39917. }
  39918. }
  39919. /**
  39920. * The purpose of a node library is to assign node implementations
  39921. * to existing library features. In `WebGPURenderer` lights, materials
  39922. * which are not based on `NodeMaterial` as well as tone mapping techniques
  39923. * are implemented with node-based modules.
  39924. *
  39925. * @private
  39926. */
  39927. class NodeLibrary {
  39928. /**
  39929. * Constructs a new node library.
  39930. */
  39931. constructor() {
  39932. /**
  39933. * A weak map that maps lights to light nodes.
  39934. *
  39935. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  39936. */
  39937. this.lightNodes = new WeakMap();
  39938. /**
  39939. * A map that maps materials to node materials.
  39940. *
  39941. * @type {Map<string,NodeMaterial.constructor>}
  39942. */
  39943. this.materialNodes = new Map();
  39944. /**
  39945. * A map that maps tone mapping techniques (constants)
  39946. * to tone mapping node functions.
  39947. *
  39948. * @type {Map<number,Function>}
  39949. */
  39950. this.toneMappingNodes = new Map();
  39951. }
  39952. /**
  39953. * Returns a matching node material instance for the given material object.
  39954. *
  39955. * This method also assigns/copies the properties of the given material object
  39956. * to the node material. This is done to make sure the current material
  39957. * configuration carries over to the node version.
  39958. *
  39959. * @param {Material} material - A material.
  39960. * @return {NodeMaterial} The corresponding node material.
  39961. */
  39962. fromMaterial( material ) {
  39963. if ( material.isNodeMaterial ) return material;
  39964. let nodeMaterial = null;
  39965. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  39966. if ( nodeMaterialClass !== null ) {
  39967. nodeMaterial = new nodeMaterialClass();
  39968. for ( const key in material ) {
  39969. nodeMaterial[ key ] = material[ key ];
  39970. }
  39971. }
  39972. return nodeMaterial;
  39973. }
  39974. /**
  39975. * Adds a tone mapping node function for a tone mapping technique (constant).
  39976. *
  39977. * @param {Function} toneMappingNode - The tone mapping node function.
  39978. * @param {number} toneMapping - The tone mapping.
  39979. */
  39980. addToneMapping( toneMappingNode, toneMapping ) {
  39981. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  39982. }
  39983. /**
  39984. * Returns a tone mapping node function for a tone mapping technique (constant).
  39985. *
  39986. * @param {number} toneMapping - The tone mapping.
  39987. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  39988. */
  39989. getToneMappingFunction( toneMapping ) {
  39990. return this.toneMappingNodes.get( toneMapping ) || null;
  39991. }
  39992. /**
  39993. * Returns a node material class definition for a material type.
  39994. *
  39995. * @param {string} materialType - The material type.
  39996. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  39997. */
  39998. getMaterialNodeClass( materialType ) {
  39999. return this.materialNodes.get( materialType ) || null;
  40000. }
  40001. /**
  40002. * Adds a node material class definition for a given material type.
  40003. *
  40004. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  40005. * @param {string} materialClassType - The material type.
  40006. */
  40007. addMaterial( materialNodeClass, materialClassType ) {
  40008. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  40009. }
  40010. /**
  40011. * Returns a light node class definition for a light class definition.
  40012. *
  40013. * @param {Light.constructor} light - The light class definition.
  40014. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  40015. */
  40016. getLightNodeClass( light ) {
  40017. return this.lightNodes.get( light ) || null;
  40018. }
  40019. /**
  40020. * Adds a light node class definition for a given light class definition.
  40021. *
  40022. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  40023. * @param {Light.constructor} lightClass - The light class definition.
  40024. */
  40025. addLight( lightNodeClass, lightClass ) {
  40026. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  40027. }
  40028. /**
  40029. * Adds a node class definition for the given type to the provided type library.
  40030. *
  40031. * @param {Node.constructor} nodeClass - The node class definition.
  40032. * @param {number|string} type - The object type.
  40033. * @param {Map<number|string,Node.constructor>} library - The type library.
  40034. */
  40035. addType( nodeClass, type, library ) {
  40036. if ( library.has( type ) ) {
  40037. warn( `Redefinition of node ${ type }` );
  40038. return;
  40039. }
  40040. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  40041. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  40042. library.set( type, nodeClass );
  40043. }
  40044. /**
  40045. * Adds a node class definition for the given class definition to the provided type library.
  40046. *
  40047. * @param {Node.constructor} nodeClass - The node class definition.
  40048. * @param {Node.constructor} baseClass - The class definition.
  40049. * @param {WeakMap<Node.constructor, Node.constructor>} library - The type library.
  40050. */
  40051. addClass( nodeClass, baseClass, library ) {
  40052. if ( library.has( baseClass ) ) {
  40053. warn( `Redefinition of node ${ baseClass.name }` );
  40054. return;
  40055. }
  40056. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  40057. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  40058. library.set( baseClass, nodeClass );
  40059. }
  40060. }
  40061. const _defaultLights = /*@__PURE__*/ new LightsNode();
  40062. const _weakMap = /*@__PURE__*/ new WeakMap();
  40063. /**
  40064. * This renderer module manages the lights nodes which are unique
  40065. * per scene and camera combination.
  40066. *
  40067. * The lights node itself is later configured in the render list
  40068. * with the actual lights from the scene.
  40069. *
  40070. * @private
  40071. */
  40072. class Lighting {
  40073. /**
  40074. * Creates a new lights node for the given array of lights.
  40075. *
  40076. * @param {Array<Light>} lights - The render object.
  40077. * @return {LightsNode} The lights node.
  40078. */
  40079. createNode( lights = [] ) {
  40080. return new LightsNode().setLights( lights );
  40081. }
  40082. /**
  40083. * Returns a lights node for the given scene and camera.
  40084. *
  40085. * @param {Scene} scene - The scene.
  40086. * @param {Camera} camera - The camera.
  40087. * @return {LightsNode} The lights node.
  40088. */
  40089. getNode( scene ) {
  40090. // ignore post-processing
  40091. if ( scene.isQuadMesh ) return _defaultLights;
  40092. let node = _weakMap.get( scene );
  40093. if ( node === undefined ) {
  40094. node = this.createNode();
  40095. _weakMap.set( scene, node );
  40096. }
  40097. return node;
  40098. }
  40099. }
  40100. /**
  40101. * A special type of render target that is used when rendering
  40102. * with the WebXR Device API.
  40103. *
  40104. * @private
  40105. * @augments RenderTarget
  40106. */
  40107. class XRRenderTarget extends RenderTarget {
  40108. /**
  40109. * Constructs a new XR render target.
  40110. *
  40111. * @param {number} [width=1] - The width of the render target.
  40112. * @param {number} [height=1] - The height of the render target.
  40113. * @param {Object} [options={}] - The configuration options.
  40114. */
  40115. constructor( width = 1, height = 1, options = {} ) {
  40116. super( width, height, options );
  40117. /**
  40118. * This flag can be used for type testing.
  40119. *
  40120. * @type {boolean}
  40121. * @readonly
  40122. * @default true
  40123. */
  40124. this.isXRRenderTarget = true;
  40125. /**
  40126. * Whether the attachments of the render target
  40127. * are defined by external textures. This flag is
  40128. * set to `true` when using the WebXR Layers API.
  40129. *
  40130. * @private
  40131. * @type {boolean}
  40132. * @default false
  40133. */
  40134. this._hasExternalTextures = false;
  40135. /**
  40136. * Whether a depth buffer should automatically be allocated
  40137. * for this XR render target or not.
  40138. *
  40139. * Allocating a depth buffer is the default behavior of XR render
  40140. * targets. However, when using the WebXR Layers API, this flag
  40141. * must be set to `false` when the `ignoreDepthValues` property of
  40142. * the projection layers evaluates to `false`.
  40143. *
  40144. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  40145. *
  40146. * @private
  40147. * @type {boolean}
  40148. * @default true
  40149. */
  40150. this._autoAllocateDepthBuffer = true;
  40151. /**
  40152. * Whether this render target is associated with a XRWebGLLayer.
  40153. *
  40154. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  40155. * this means that you don't have access to its bound color,
  40156. * stencil and depth buffers. We need to handle this framebuffer
  40157. * differently since its textures are always bound.
  40158. *
  40159. * @private
  40160. * @type {boolean}
  40161. * @default false
  40162. * */
  40163. this._isOpaqueFramebuffer = false;
  40164. }
  40165. copy( source ) {
  40166. super.copy( source );
  40167. this._hasExternalTextures = source._hasExternalTextures;
  40168. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  40169. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  40170. return this;
  40171. }
  40172. }
  40173. const _cameraLPos = /*@__PURE__*/ new Vector3();
  40174. const _cameraRPos = /*@__PURE__*/ new Vector3();
  40175. const _contextNodeLib = /*@__PURE__*/ new WeakMap();
  40176. /**
  40177. * The XR manager is built on top of the WebXR Device API to
  40178. * manage XR sessions with `WebGPURenderer`.
  40179. *
  40180. * XR is currently only supported with a WebGL 2 backend.
  40181. *
  40182. * @augments EventDispatcher
  40183. */
  40184. class XRManager extends EventDispatcher {
  40185. /**
  40186. * Constructs a new XR manager.
  40187. *
  40188. * @param {Renderer} renderer - The renderer.
  40189. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  40190. */
  40191. constructor( renderer, multiview = false ) {
  40192. super();
  40193. /**
  40194. * This flag globally enables XR rendering.
  40195. *
  40196. * @type {boolean}
  40197. * @default false
  40198. */
  40199. this.enabled = false;
  40200. /**
  40201. * Whether the XR device is currently presenting or not.
  40202. *
  40203. * @type {boolean}
  40204. * @default false
  40205. * @readonly
  40206. */
  40207. this.isPresenting = false;
  40208. /**
  40209. * Whether the XR camera should automatically be updated or not.
  40210. *
  40211. * @type {boolean}
  40212. * @default true
  40213. */
  40214. this.cameraAutoUpdate = true;
  40215. /**
  40216. * The renderer.
  40217. *
  40218. * @private
  40219. * @type {Renderer}
  40220. */
  40221. this._renderer = renderer;
  40222. // camera
  40223. /**
  40224. * Represents the camera for the left eye.
  40225. *
  40226. * @private
  40227. * @type {PerspectiveCamera}
  40228. */
  40229. this._cameraL = new PerspectiveCamera();
  40230. this._cameraL.viewport = new Vector4();
  40231. /**
  40232. * Represents the camera for the right eye.
  40233. *
  40234. * @private
  40235. * @type {PerspectiveCamera}
  40236. */
  40237. this._cameraR = new PerspectiveCamera();
  40238. this._cameraR.viewport = new Vector4();
  40239. /**
  40240. * A list of cameras used for rendering the XR views.
  40241. *
  40242. * @private
  40243. * @type {Array<Camera>}
  40244. */
  40245. this._cameras = [ this._cameraL, this._cameraR ];
  40246. /**
  40247. * The main XR camera.
  40248. *
  40249. * @private
  40250. * @type {ArrayCamera}
  40251. */
  40252. this._cameraXR = new ArrayCamera();
  40253. /**
  40254. * The current near value of the XR camera.
  40255. *
  40256. * @private
  40257. * @type {?number}
  40258. * @default null
  40259. */
  40260. this._currentDepthNear = null;
  40261. /**
  40262. * The current far value of the XR camera.
  40263. *
  40264. * @private
  40265. * @type {?number}
  40266. * @default null
  40267. */
  40268. this._currentDepthFar = null;
  40269. /**
  40270. * A list of WebXR controllers requested by the application.
  40271. *
  40272. * @private
  40273. * @type {Array<WebXRController>}
  40274. */
  40275. this._controllers = [];
  40276. /**
  40277. * A list of XR input source. Each input source belongs to
  40278. * an instance of WebXRController.
  40279. *
  40280. * @private
  40281. * @type {Array<XRInputSource?>}
  40282. */
  40283. this._controllerInputSources = [];
  40284. /**
  40285. * The XR render target that represents the rendering destination
  40286. * during an active XR session.
  40287. *
  40288. * @private
  40289. * @type {?RenderTarget}
  40290. * @default null
  40291. */
  40292. this._xrRenderTarget = null;
  40293. /**
  40294. * An array holding all the non-projection layers
  40295. *
  40296. * @private
  40297. * @type {Array<Object>}
  40298. * @default []
  40299. */
  40300. this._layers = [];
  40301. /**
  40302. * Whether the XR session uses layers.
  40303. *
  40304. * @private
  40305. * @type {boolean}
  40306. * @default false
  40307. */
  40308. this._sessionUsesLayers = false;
  40309. /**
  40310. * Whether the device supports binding gl objects.
  40311. *
  40312. * @private
  40313. * @type {boolean}
  40314. * @readonly
  40315. */
  40316. this._supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  40317. /**
  40318. * Helper function to create native WebXR Layer.
  40319. *
  40320. * @private
  40321. * @type {Function}
  40322. */
  40323. this._createXRLayer = createXRLayer.bind( this );
  40324. /**
  40325. * The current WebGL context.
  40326. *
  40327. * @private
  40328. * @type {?WebGL2RenderingContext}
  40329. * @default null
  40330. */
  40331. this._gl = null;
  40332. /**
  40333. * The current animation context.
  40334. *
  40335. * @private
  40336. * @type {?Window}
  40337. * @default null
  40338. */
  40339. this._currentAnimationContext = null;
  40340. /**
  40341. * The current animation loop.
  40342. *
  40343. * @private
  40344. * @type {?Function}
  40345. * @default null
  40346. */
  40347. this._currentAnimationLoop = null;
  40348. /**
  40349. * The current pixel ratio.
  40350. *
  40351. * @private
  40352. * @type {?number}
  40353. * @default null
  40354. */
  40355. this._currentPixelRatio = null;
  40356. /**
  40357. * The current size of the renderer's canvas
  40358. * in logical pixel unit.
  40359. *
  40360. * @private
  40361. * @type {Vector2}
  40362. */
  40363. this._currentSize = new Vector2();
  40364. /**
  40365. * The default event listener for handling events inside a XR session.
  40366. *
  40367. * @private
  40368. * @type {Function}
  40369. */
  40370. this._onSessionEvent = onSessionEvent.bind( this );
  40371. /**
  40372. * The event listener for handling the end of a XR session.
  40373. *
  40374. * @private
  40375. * @type {Function}
  40376. */
  40377. this._onSessionEnd = onSessionEnd.bind( this );
  40378. /**
  40379. * The event listener for handling the `inputsourceschange` event.
  40380. *
  40381. * @private
  40382. * @type {Function}
  40383. */
  40384. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  40385. /**
  40386. * The animation loop which is used as a replacement for the default
  40387. * animation loop of the application. It is only used when a XR session
  40388. * is active.
  40389. *
  40390. * @private
  40391. * @type {Function}
  40392. */
  40393. this._onAnimationFrame = onAnimationFrame.bind( this );
  40394. /**
  40395. * The current XR reference space.
  40396. *
  40397. * @private
  40398. * @type {?XRReferenceSpace}
  40399. * @default null
  40400. */
  40401. this._referenceSpace = null;
  40402. /**
  40403. * The current XR reference space type.
  40404. *
  40405. * @private
  40406. * @type {XRReferenceSpaceType}
  40407. * @default 'local-floor'
  40408. */
  40409. this._referenceSpaceType = 'local-floor';
  40410. /**
  40411. * A custom reference space defined by the application.
  40412. *
  40413. * @private
  40414. * @type {?XRReferenceSpace}
  40415. * @default null
  40416. */
  40417. this._customReferenceSpace = null;
  40418. /**
  40419. * The framebuffer scale factor.
  40420. *
  40421. * @private
  40422. * @type {number}
  40423. * @default 1
  40424. */
  40425. this._framebufferScaleFactor = 1;
  40426. /**
  40427. * The foveation factor.
  40428. *
  40429. * @private
  40430. * @type {number}
  40431. * @default 1
  40432. */
  40433. this._foveation = 1.0;
  40434. /**
  40435. * A reference to the current XR session.
  40436. *
  40437. * @private
  40438. * @type {?XRSession}
  40439. * @default null
  40440. */
  40441. this._session = null;
  40442. /**
  40443. * A reference to the current XR base layer.
  40444. *
  40445. * @private
  40446. * @type {?XRWebGLLayer}
  40447. * @default null
  40448. */
  40449. this._glBaseLayer = null;
  40450. /**
  40451. * A reference to the current XR binding.
  40452. *
  40453. * @private
  40454. * @type {?XRWebGLBinding}
  40455. * @default null
  40456. */
  40457. this._glBinding = null;
  40458. /**
  40459. * A reference to the current XR projection layer.
  40460. *
  40461. * @private
  40462. * @type {?XRProjectionLayer}
  40463. * @default null
  40464. */
  40465. this._glProjLayer = null;
  40466. /**
  40467. * A reference to the current XR frame.
  40468. *
  40469. * @private
  40470. * @type {?XRFrame}
  40471. * @default null
  40472. */
  40473. this._xrFrame = null;
  40474. /**
  40475. * Whether the browser supports the APIs necessary to use XRProjectionLayers.
  40476. *
  40477. * Note: this does not represent XRSession explicitly requesting
  40478. * `'layers'` as a feature - see `_sessionUsesLayers` and #30112
  40479. *
  40480. * @private
  40481. * @type {boolean}
  40482. * @readonly
  40483. */
  40484. this._supportsLayers = ( this._supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  40485. /**
  40486. * Whether the usage of multiview has been requested by the application or not.
  40487. *
  40488. * @private
  40489. * @type {boolean}
  40490. * @default false
  40491. * @readonly
  40492. */
  40493. this._useMultiviewIfPossible = multiview;
  40494. /**
  40495. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  40496. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  40497. *
  40498. * @private
  40499. * @type {boolean}
  40500. * @readonly
  40501. */
  40502. this._useMultiview = false;
  40503. }
  40504. /**
  40505. * Returns an instance of `THREE.Group` that represents the transformation
  40506. * of a XR controller in target ray space. The requested controller is defined
  40507. * by the given index.
  40508. *
  40509. * @param {number} index - The index of the XR controller.
  40510. * @return {Group} A group that represents the controller's transformation.
  40511. */
  40512. getController( index ) {
  40513. const controller = this._getController( index );
  40514. return controller.getTargetRaySpace();
  40515. }
  40516. /**
  40517. * Returns an instance of `THREE.Group` that represents the transformation
  40518. * of a XR controller in grip space. The requested controller is defined
  40519. * by the given index.
  40520. *
  40521. * @param {number} index - The index of the XR controller.
  40522. * @return {Group} A group that represents the controller's transformation.
  40523. */
  40524. getControllerGrip( index ) {
  40525. const controller = this._getController( index );
  40526. return controller.getGripSpace();
  40527. }
  40528. /**
  40529. * Returns an instance of `THREE.Group` that represents the transformation
  40530. * of a XR controller in hand space. The requested controller is defined
  40531. * by the given index.
  40532. *
  40533. * @param {number} index - The index of the XR controller.
  40534. * @return {Group} A group that represents the controller's transformation.
  40535. */
  40536. getHand( index ) {
  40537. const controller = this._getController( index );
  40538. return controller.getHandSpace();
  40539. }
  40540. /**
  40541. * Returns the foveation value.
  40542. *
  40543. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  40544. */
  40545. getFoveation() {
  40546. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  40547. return undefined;
  40548. }
  40549. return this._foveation;
  40550. }
  40551. /**
  40552. * Sets the foveation value.
  40553. *
  40554. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  40555. * and `1` means maximum foveation (the edges render at lower resolution).
  40556. */
  40557. setFoveation( foveation ) {
  40558. this._foveation = foveation;
  40559. if ( this._glProjLayer !== null ) {
  40560. this._glProjLayer.fixedFoveation = foveation;
  40561. }
  40562. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  40563. this._glBaseLayer.fixedFoveation = foveation;
  40564. }
  40565. }
  40566. /**
  40567. * Returns the framebuffer scale factor.
  40568. *
  40569. * @return {number} The framebuffer scale factor.
  40570. */
  40571. getFramebufferScaleFactor() {
  40572. return this._framebufferScaleFactor;
  40573. }
  40574. /**
  40575. * Sets the framebuffer scale factor.
  40576. *
  40577. * This method can not be used during a XR session.
  40578. *
  40579. * @param {number} factor - The framebuffer scale factor.
  40580. */
  40581. setFramebufferScaleFactor( factor ) {
  40582. this._framebufferScaleFactor = factor;
  40583. if ( this.isPresenting === true ) {
  40584. warn( 'XRManager: Cannot change framebuffer scale while presenting.' );
  40585. }
  40586. }
  40587. /**
  40588. * Returns the reference space type.
  40589. *
  40590. * @return {XRReferenceSpaceType} The reference space type.
  40591. */
  40592. getReferenceSpaceType() {
  40593. return this._referenceSpaceType;
  40594. }
  40595. /**
  40596. * Sets the reference space type.
  40597. *
  40598. * This method can not be used during a XR session.
  40599. *
  40600. * @param {XRReferenceSpaceType} type - The reference space type.
  40601. */
  40602. setReferenceSpaceType( type ) {
  40603. this._referenceSpaceType = type;
  40604. if ( this.isPresenting === true ) {
  40605. warn( 'XRManager: Cannot change reference space type while presenting.' );
  40606. }
  40607. }
  40608. /**
  40609. * Returns the XR reference space.
  40610. *
  40611. * @return {XRReferenceSpace} The XR reference space.
  40612. */
  40613. getReferenceSpace() {
  40614. return this._customReferenceSpace || this._referenceSpace;
  40615. }
  40616. /**
  40617. * Sets a custom XR reference space.
  40618. *
  40619. * @param {XRReferenceSpace} space - The XR reference space.
  40620. */
  40621. setReferenceSpace( space ) {
  40622. this._customReferenceSpace = space;
  40623. }
  40624. /**
  40625. * Returns the XR camera.
  40626. *
  40627. * @return {ArrayCamera} The XR camera.
  40628. */
  40629. getCamera() {
  40630. return this._cameraXR;
  40631. }
  40632. /**
  40633. * Returns the environment blend mode from the current XR session.
  40634. *
  40635. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  40636. */
  40637. getEnvironmentBlendMode() {
  40638. if ( this._session !== null ) {
  40639. return this._session.environmentBlendMode;
  40640. }
  40641. }
  40642. /**
  40643. * Returns the current base layer.
  40644. *
  40645. * This is an `XRProjectionLayer` when the targeted XR device supports the
  40646. * WebXR Layers API, or an `XRWebGLLayer` otherwise.
  40647. *
  40648. * @return {?(XRWebGLLayer|XRProjectionLayer)} The XR base layer.
  40649. */
  40650. getBaseLayer() {
  40651. return this._glProjLayer !== null ? this._glProjLayer : this._glBaseLayer;
  40652. }
  40653. /**
  40654. * Returns the current XR binding.
  40655. *
  40656. * Creates a new binding if needed and the browser is
  40657. * capable of doing so.
  40658. *
  40659. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  40660. */
  40661. getBinding() {
  40662. if ( this._glBinding === null && this._supportsGlBinding ) {
  40663. this._glBinding = new XRWebGLBinding( this._session, this._gl );
  40664. }
  40665. return this._glBinding;
  40666. }
  40667. /**
  40668. * Applies WebXR fixed foveation to the internal post-processing render target
  40669. * used by the first XR render pass before compositing into a projection layer.
  40670. *
  40671. * Browser-side `XRWebGLBinding.foveateBoundTexture()` failures are treated as
  40672. * non-fatal so they do not interrupt rendering.
  40673. *
  40674. * @param {RenderTarget} renderTarget - The internal render target.
  40675. */
  40676. foveateBoundTexture( renderTarget ) {
  40677. if ( renderTarget.isPostProcessingRenderTarget !== true ) return;
  40678. if ( this.isPresenting !== true ) return;
  40679. if ( this._glProjLayer === null ) return;
  40680. const backend = this._renderer.backend;
  40681. if ( backend === undefined || backend.isWebGLBackend !== true ) return;
  40682. if ( backend.state === null ) return;
  40683. const outputRenderTarget = this._renderer.getOutputRenderTarget();
  40684. if ( outputRenderTarget === null || outputRenderTarget.isXRRenderTarget !== true ) return;
  40685. const glBinding = this.getBinding();
  40686. if ( glBinding === null || typeof glBinding.foveateBoundTexture !== 'function' ) return;
  40687. this._renderer._textures.updateRenderTarget( renderTarget );
  40688. const { textureGPU, glTextureType } = backend.get( renderTarget.texture );
  40689. if ( textureGPU === undefined || glTextureType === undefined ) return;
  40690. if ( renderTarget._xrFoveationTextureGPU === textureGPU ) return;
  40691. renderTarget._xrFoveationTextureGPU = textureGPU;
  40692. backend.state.bindTexture( glTextureType, textureGPU );
  40693. try {
  40694. glBinding.foveateBoundTexture( glTextureType, this.getFoveation() );
  40695. } catch ( error ) {
  40696. warnOnce( `XRManager: Unable to foveate bound XR post-processing texture. ${error.name}: ${error.message}` );
  40697. } finally {
  40698. backend.state.unbindTexture();
  40699. }
  40700. }
  40701. /**
  40702. * Returns the current XR frame.
  40703. *
  40704. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  40705. */
  40706. getFrame() {
  40707. return this._xrFrame;
  40708. }
  40709. /**
  40710. * Returns `true` if the engine renders to a multiview target.
  40711. *
  40712. * @return {boolean} Whether the engine renders to a multiview render target or not.
  40713. */
  40714. useMultiview() {
  40715. return this._useMultiview;
  40716. }
  40717. /**
  40718. * This method can be used in XR applications to create a quadratic layer that presents a separate
  40719. * rendered scene.
  40720. *
  40721. * @param {number} width - The width of the layer plane in world units.
  40722. * @param {number} height - The height of the layer plane in world units.
  40723. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  40724. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  40725. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  40726. * @param {number} pixelheight - The height of the layer's render target in pixels.
  40727. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  40728. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  40729. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  40730. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  40731. */
  40732. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  40733. const geometry = new PlaneGeometry( width, height );
  40734. const renderTarget = new XRRenderTarget(
  40735. pixelwidth,
  40736. pixelheight,
  40737. {
  40738. format: RGBAFormat,
  40739. type: UnsignedByteType,
  40740. depthTexture: new DepthTexture(
  40741. pixelwidth,
  40742. pixelheight,
  40743. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  40744. undefined,
  40745. undefined,
  40746. undefined,
  40747. undefined,
  40748. undefined,
  40749. undefined,
  40750. attributes.stencil ? DepthStencilFormat : DepthFormat
  40751. ),
  40752. stencilBuffer: attributes.stencil,
  40753. resolveDepthBuffer: false,
  40754. resolveStencilBuffer: false
  40755. } );
  40756. renderTarget._autoAllocateDepthBuffer = true;
  40757. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  40758. material.map = renderTarget.texture;
  40759. material.map.offset.y = 1;
  40760. material.map.repeat.y = -1;
  40761. const plane = new Mesh( geometry, material );
  40762. plane.position.copy( translation );
  40763. plane.quaternion.copy( quaternion );
  40764. const layer = {
  40765. type: 'quad',
  40766. width: width,
  40767. height: height,
  40768. translation: translation,
  40769. quaternion: quaternion,
  40770. pixelwidth: pixelwidth,
  40771. pixelheight: pixelheight,
  40772. plane: plane,
  40773. material: material,
  40774. rendercall: rendercall,
  40775. renderTarget: renderTarget };
  40776. this._layers.push( layer );
  40777. if ( this._session !== null ) {
  40778. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  40779. layer.plane.material.blending = CustomBlending;
  40780. layer.plane.material.blendEquation = AddEquation;
  40781. layer.plane.material.blendSrc = ZeroFactor;
  40782. layer.plane.material.blendDst = ZeroFactor;
  40783. layer.xrlayer = this._createXRLayer( layer );
  40784. const xrlayers = this._session.renderState.layers;
  40785. xrlayers.unshift( layer.xrlayer );
  40786. this._session.updateRenderState( { layers: xrlayers } );
  40787. } else {
  40788. renderTarget.isXRRenderTarget = false;
  40789. }
  40790. return plane;
  40791. }
  40792. /**
  40793. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  40794. * rendered scene.
  40795. *
  40796. * @param {number} radius - The radius of the cylinder in world units.
  40797. * @param {number} centralAngle - The central angle of the cylinder in radians.
  40798. * @param {number} aspectratio - The aspect ratio.
  40799. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  40800. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  40801. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  40802. * @param {number} pixelheight - The height of the layer's render target in pixels.
  40803. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  40804. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  40805. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  40806. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  40807. */
  40808. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  40809. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  40810. const renderTarget = new XRRenderTarget(
  40811. pixelwidth,
  40812. pixelheight,
  40813. {
  40814. format: RGBAFormat,
  40815. type: UnsignedByteType,
  40816. depthTexture: new DepthTexture(
  40817. pixelwidth,
  40818. pixelheight,
  40819. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  40820. undefined,
  40821. undefined,
  40822. undefined,
  40823. undefined,
  40824. undefined,
  40825. undefined,
  40826. attributes.stencil ? DepthStencilFormat : DepthFormat
  40827. ),
  40828. stencilBuffer: attributes.stencil,
  40829. resolveDepthBuffer: false,
  40830. resolveStencilBuffer: false
  40831. } );
  40832. renderTarget._autoAllocateDepthBuffer = true;
  40833. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  40834. material.map = renderTarget.texture;
  40835. material.map.offset.y = 1;
  40836. material.map.repeat.y = -1;
  40837. const plane = new Mesh( geometry, material );
  40838. plane.position.copy( translation );
  40839. plane.quaternion.copy( quaternion );
  40840. const layer = {
  40841. type: 'cylinder',
  40842. radius: radius,
  40843. centralAngle: centralAngle,
  40844. aspectratio: aspectratio,
  40845. translation: translation,
  40846. quaternion: quaternion,
  40847. pixelwidth: pixelwidth,
  40848. pixelheight: pixelheight,
  40849. plane: plane,
  40850. material: material,
  40851. rendercall: rendercall,
  40852. renderTarget: renderTarget };
  40853. this._layers.push( layer );
  40854. if ( this._session !== null ) {
  40855. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  40856. layer.plane.material.blending = CustomBlending;
  40857. layer.plane.material.blendEquation = AddEquation;
  40858. layer.plane.material.blendSrc = ZeroFactor;
  40859. layer.plane.material.blendDst = ZeroFactor;
  40860. layer.xrlayer = this._createXRLayer( layer );
  40861. const xrlayers = this._session.renderState.layers;
  40862. xrlayers.unshift( layer.xrlayer );
  40863. this._session.updateRenderState( { layers: xrlayers } );
  40864. } else {
  40865. renderTarget.isXRRenderTarget = false;
  40866. }
  40867. return plane;
  40868. }
  40869. /**
  40870. * Renders the XR layers that have been previously added to the scene.
  40871. *
  40872. * This method is usually called in your animation loop before rendering
  40873. * the actual scene via `renderer.render( scene, camera );`.
  40874. */
  40875. renderLayers( ) {
  40876. const translationObject = new Vector3();
  40877. const quaternionObject = new Quaternion();
  40878. const renderer = this._renderer;
  40879. const wasPresenting = this.isPresenting;
  40880. this.isPresenting = false;
  40881. const rendererSize = new Vector2();
  40882. renderer.getSize( rendererSize );
  40883. const currentRenderTarget = renderer.getRenderTarget();
  40884. for ( const layer of this._layers ) {
  40885. layer.renderTarget.isXRRenderTarget = this._session !== null;
  40886. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  40887. const currentContextNode = renderer.contextNode;
  40888. let contextNode;
  40889. if ( layer.renderTarget.isXRRenderTarget && this._sessionUsesLayers ) {
  40890. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  40891. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  40892. renderer.backend.setXRRenderTargetTextures(
  40893. layer.renderTarget,
  40894. glSubImage.colorTexture,
  40895. undefined );
  40896. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  40897. contextNode = _contextNodeLib.get( currentContextNode );
  40898. if ( contextNode === undefined ) {
  40899. // Apply ToneMapping and OutputColorSpace directly in the material shader
  40900. contextNode = currentContextNode.context( {
  40901. getOutput: ( outputNode ) => {
  40902. return renderOutput( outputNode, renderer.toneMapping, renderer.outputColorSpace );
  40903. }
  40904. } );
  40905. _contextNodeLib.set( currentContextNode, contextNode );
  40906. }
  40907. } else {
  40908. contextNode = currentContextNode;
  40909. }
  40910. renderer.contextNode = contextNode;
  40911. renderer.setRenderTarget( layer.renderTarget );
  40912. layer.rendercall();
  40913. renderer.contextNode = currentContextNode;
  40914. }
  40915. renderer.setRenderTarget( currentRenderTarget );
  40916. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  40917. this.isPresenting = wasPresenting;
  40918. }
  40919. /**
  40920. * Returns the current XR session.
  40921. *
  40922. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  40923. */
  40924. getSession() {
  40925. return this._session;
  40926. }
  40927. /**
  40928. * After a XR session has been requested usually with one of the `*Button` modules, it
  40929. * is injected into the renderer with this method. This method triggers the start of
  40930. * the actual XR rendering.
  40931. *
  40932. * @async
  40933. * @param {XRSession} session - The XR session to set.
  40934. * @return {Promise} A Promise that resolves when the session has been set.
  40935. */
  40936. async setSession( session ) {
  40937. const renderer = this._renderer;
  40938. const backend = renderer.backend;
  40939. this._gl = renderer.getContext();
  40940. const gl = this._gl;
  40941. const attributes = gl.getContextAttributes();
  40942. this._session = session;
  40943. if ( session !== null ) {
  40944. if ( backend.isWebGPUBackend === true ) throw new Error( 'THREE.XRManager: XR is currently not supported with a WebGPU backend. Use WebGL by passing "{ forceWebGL: true }" to the constructor of the renderer.' );
  40945. session.addEventListener( 'select', this._onSessionEvent );
  40946. session.addEventListener( 'selectstart', this._onSessionEvent );
  40947. session.addEventListener( 'selectend', this._onSessionEvent );
  40948. session.addEventListener( 'squeeze', this._onSessionEvent );
  40949. session.addEventListener( 'squeezestart', this._onSessionEvent );
  40950. session.addEventListener( 'squeezeend', this._onSessionEvent );
  40951. session.addEventListener( 'end', this._onSessionEnd );
  40952. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  40953. await backend.makeXRCompatible();
  40954. this._currentPixelRatio = renderer.getPixelRatio();
  40955. renderer.getSize( this._currentSize );
  40956. this._currentAnimationContext = renderer._animation.getContext();
  40957. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  40958. renderer._animation.stop();
  40959. //
  40960. if ( this._supportsLayers === true ) {
  40961. // default path using XRProjectionLayer
  40962. let depthFormat = null;
  40963. let depthType = null;
  40964. let glDepthFormat = null;
  40965. if ( renderer.depth ) {
  40966. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  40967. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  40968. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  40969. }
  40970. const projectionlayerInit = {
  40971. colorFormat: gl.RGBA8,
  40972. depthFormat: glDepthFormat,
  40973. scaleFactor: this._framebufferScaleFactor,
  40974. clearOnAccess: false
  40975. };
  40976. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  40977. projectionlayerInit.textureType = 'texture-array';
  40978. this._useMultiview = true;
  40979. }
  40980. this._glBinding = this.getBinding();
  40981. const glProjLayer = this._glBinding.createProjectionLayer( projectionlayerInit );
  40982. const layersArray = [ glProjLayer ];
  40983. this._glProjLayer = glProjLayer;
  40984. renderer.setPixelRatio( 1 );
  40985. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  40986. const depth = this._useMultiview ? 2 : 1;
  40987. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  40988. this._xrRenderTarget = new XRRenderTarget(
  40989. glProjLayer.textureWidth,
  40990. glProjLayer.textureHeight,
  40991. {
  40992. format: RGBAFormat,
  40993. type: UnsignedByteType,
  40994. colorSpace: renderer.outputColorSpace,
  40995. depthTexture: depthTexture,
  40996. stencilBuffer: renderer.stencil,
  40997. samples: attributes.antialias ? 4 : 0,
  40998. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  40999. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  41000. depth: this._useMultiview ? 2 : 1,
  41001. multiview: this._useMultiview
  41002. } );
  41003. this._xrRenderTarget._hasExternalTextures = true;
  41004. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  41005. this._sessionUsesLayers = session.enabledFeatures.includes( 'layers' );
  41006. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  41007. if ( this._sessionUsesLayers ) {
  41008. // switch layers to native
  41009. for ( const layer of this._layers ) {
  41010. // change material so it "punches" out a hole to show the XR Layer.
  41011. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  41012. layer.plane.material.blending = CustomBlending;
  41013. layer.plane.material.blendEquation = AddEquation;
  41014. layer.plane.material.blendSrc = ZeroFactor;
  41015. layer.plane.material.blendDst = ZeroFactor;
  41016. layer.xrlayer = this._createXRLayer( layer );
  41017. layersArray.unshift( layer.xrlayer );
  41018. }
  41019. }
  41020. session.updateRenderState( { layers: layersArray } );
  41021. } else {
  41022. // fallback to XRWebGLLayer
  41023. const layerInit = {
  41024. antialias: renderer.currentSamples > 0,
  41025. alpha: true,
  41026. depth: renderer.depth,
  41027. stencil: renderer.stencil,
  41028. framebufferScaleFactor: this.getFramebufferScaleFactor()
  41029. };
  41030. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  41031. this._glBaseLayer = glBaseLayer;
  41032. session.updateRenderState( { baseLayer: glBaseLayer } );
  41033. renderer.setPixelRatio( 1 );
  41034. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  41035. this._xrRenderTarget = new XRRenderTarget(
  41036. glBaseLayer.framebufferWidth,
  41037. glBaseLayer.framebufferHeight,
  41038. {
  41039. format: RGBAFormat,
  41040. type: UnsignedByteType,
  41041. colorSpace: renderer.outputColorSpace,
  41042. stencilBuffer: renderer.stencil,
  41043. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  41044. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  41045. }
  41046. );
  41047. this._xrRenderTarget._isOpaqueFramebuffer = true;
  41048. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  41049. }
  41050. //
  41051. this.setFoveation( this.getFoveation() );
  41052. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  41053. renderer._animation.setContext( session );
  41054. renderer._animation.start();
  41055. this.isPresenting = true;
  41056. this.dispatchEvent( { type: 'sessionstart' } );
  41057. }
  41058. }
  41059. /**
  41060. * This method is called by the renderer per frame and updates the XR camera
  41061. * and it sub cameras based on the given camera. The given camera is the "user"
  41062. * camera created on application level and used for non-XR rendering.
  41063. *
  41064. * @param {PerspectiveCamera} camera - The camera.
  41065. */
  41066. updateCamera( camera ) {
  41067. const session = this._session;
  41068. if ( session === null ) return;
  41069. const depthNear = camera.near;
  41070. const depthFar = camera.far;
  41071. const cameraXR = this._cameraXR;
  41072. const cameraL = this._cameraL;
  41073. const cameraR = this._cameraR;
  41074. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  41075. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  41076. cameraXR.isMultiViewCamera = this._useMultiview;
  41077. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  41078. // Note that the new renderState won't apply until the next frame. See #18320
  41079. session.updateRenderState( {
  41080. depthNear: cameraXR.near,
  41081. depthFar: cameraXR.far
  41082. } );
  41083. this._currentDepthNear = cameraXR.near;
  41084. this._currentDepthFar = cameraXR.far;
  41085. }
  41086. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  41087. cameraXR.layers.mask = camera.layers.mask | 0b110;
  41088. cameraL.layers.mask = cameraXR.layers.mask & -5;
  41089. cameraR.layers.mask = cameraXR.layers.mask & -3;
  41090. const parent = camera.parent;
  41091. const cameras = cameraXR.cameras;
  41092. updateCamera( cameraXR, parent );
  41093. for ( let i = 0; i < cameras.length; i ++ ) {
  41094. updateCamera( cameras[ i ], parent );
  41095. }
  41096. // update projection matrix for proper view frustum culling
  41097. if ( cameras.length === 2 ) {
  41098. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  41099. } else {
  41100. // assume single camera setup (AR)
  41101. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  41102. }
  41103. // update user camera and its children
  41104. updateUserCamera( camera, cameraXR, parent );
  41105. }
  41106. /**
  41107. * Returns a WebXR controller for the given controller index.
  41108. *
  41109. * @private
  41110. * @param {number} index - The controller index.
  41111. * @return {WebXRController} The XR controller.
  41112. */
  41113. _getController( index ) {
  41114. let controller = this._controllers[ index ];
  41115. if ( controller === undefined ) {
  41116. controller = new WebXRController();
  41117. this._controllers[ index ] = controller;
  41118. }
  41119. return controller;
  41120. }
  41121. }
  41122. /**
  41123. * Assumes 2 cameras that are parallel and share an X-axis, and that
  41124. * the cameras' projection and world matrices have already been set.
  41125. * And that near and far planes are identical for both cameras.
  41126. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  41127. *
  41128. * @param {ArrayCamera} camera - The camera to update.
  41129. * @param {PerspectiveCamera} cameraL - The left camera.
  41130. * @param {PerspectiveCamera} cameraR - The right camera.
  41131. */
  41132. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  41133. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  41134. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  41135. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  41136. const projL = cameraL.projectionMatrix.elements;
  41137. const projR = cameraR.projectionMatrix.elements;
  41138. // VR systems will have identical far and near planes, and
  41139. // most likely identical top and bottom frustum extents.
  41140. // Use the left camera for these values.
  41141. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  41142. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  41143. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  41144. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  41145. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  41146. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  41147. const left = near * leftFov;
  41148. const right = near * rightFov;
  41149. // Calculate the new camera's position offset from the
  41150. // left camera. xOffset should be roughly half `ipd`.
  41151. const zOffset = ipd / ( - leftFov + rightFov );
  41152. const xOffset = zOffset * - leftFov;
  41153. // TODO: Better way to apply this offset?
  41154. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  41155. camera.translateX( xOffset );
  41156. camera.translateZ( zOffset );
  41157. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  41158. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  41159. // Check if the projection uses an infinite far plane.
  41160. if ( projL[ 10 ] === -1 ) {
  41161. // Use the projection matrix from the left eye.
  41162. // The camera offset is sufficient to include the view volumes
  41163. // of both eyes (assuming symmetric projections).
  41164. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  41165. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  41166. } else {
  41167. // Find the union of the frustum values of the cameras and scale
  41168. // the values so that the near plane's position does not change in world space,
  41169. // although must now be relative to the new union camera.
  41170. const near2 = near + zOffset;
  41171. const far2 = far + zOffset;
  41172. const left2 = left - xOffset;
  41173. const right2 = right + ( ipd - xOffset );
  41174. const top2 = topFov * far / far2 * near2;
  41175. const bottom2 = bottomFov * far / far2 * near2;
  41176. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  41177. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  41178. }
  41179. }
  41180. /**
  41181. * Updates the world matrices for the given camera based on the parent 3D object.
  41182. *
  41183. * @inner
  41184. * @param {Camera} camera - The camera to update.
  41185. * @param {Object3D} parent - The parent 3D object.
  41186. */
  41187. function updateCamera( camera, parent ) {
  41188. if ( parent === null ) {
  41189. camera.matrixWorld.copy( camera.matrix );
  41190. } else {
  41191. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  41192. }
  41193. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  41194. }
  41195. /**
  41196. * Updates the given camera with the transformation of the XR camera and parent object.
  41197. *
  41198. * @inner
  41199. * @param {Camera} camera - The camera to update.
  41200. * @param {ArrayCamera} cameraXR - The XR camera.
  41201. * @param {Object3D} parent - The parent 3D object.
  41202. */
  41203. function updateUserCamera( camera, cameraXR, parent ) {
  41204. if ( parent === null ) {
  41205. camera.matrix.copy( cameraXR.matrixWorld );
  41206. } else {
  41207. camera.matrix.copy( parent.matrixWorld );
  41208. camera.matrix.invert();
  41209. camera.matrix.multiply( cameraXR.matrixWorld );
  41210. }
  41211. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  41212. camera.updateMatrixWorld( true );
  41213. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  41214. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  41215. if ( camera.isPerspectiveCamera ) {
  41216. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  41217. camera.zoom = 1;
  41218. }
  41219. }
  41220. function onSessionEvent( event ) {
  41221. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  41222. if ( controllerIndex === -1 ) {
  41223. return;
  41224. }
  41225. const controller = this._controllers[ controllerIndex ];
  41226. if ( controller !== undefined ) {
  41227. const referenceSpace = this.getReferenceSpace();
  41228. controller.update( event.inputSource, event.frame, referenceSpace );
  41229. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  41230. }
  41231. }
  41232. function onSessionEnd() {
  41233. const session = this._session;
  41234. const renderer = this._renderer;
  41235. session.removeEventListener( 'select', this._onSessionEvent );
  41236. session.removeEventListener( 'selectstart', this._onSessionEvent );
  41237. session.removeEventListener( 'selectend', this._onSessionEvent );
  41238. session.removeEventListener( 'squeeze', this._onSessionEvent );
  41239. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  41240. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  41241. session.removeEventListener( 'end', this._onSessionEnd );
  41242. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  41243. for ( let i = 0; i < this._controllers.length; i ++ ) {
  41244. const inputSource = this._controllerInputSources[ i ];
  41245. if ( inputSource === null ) continue;
  41246. this._controllerInputSources[ i ] = null;
  41247. this._controllers[ i ].disconnect( inputSource );
  41248. }
  41249. this._currentDepthNear = null;
  41250. this._currentDepthFar = null;
  41251. // restore framebuffer/rendering state
  41252. renderer._resetXRState();
  41253. this._session = null;
  41254. this._xrRenderTarget = null;
  41255. this._glBinding = null;
  41256. this._glBaseLayer = null;
  41257. this._glProjLayer = null;
  41258. // switch layers back to emulated
  41259. if ( this._sessionUsesLayers === true ) {
  41260. for ( const layer of this._layers ) {
  41261. // Recreate layer render target to reset state
  41262. layer.renderTarget = new XRRenderTarget(
  41263. layer.pixelwidth,
  41264. layer.pixelheight,
  41265. {
  41266. format: RGBAFormat,
  41267. type: UnsignedByteType,
  41268. depthTexture: new DepthTexture(
  41269. layer.pixelwidth,
  41270. layer.pixelheight,
  41271. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  41272. undefined,
  41273. undefined,
  41274. undefined,
  41275. undefined,
  41276. undefined,
  41277. undefined,
  41278. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  41279. ),
  41280. stencilBuffer: layer.stencilBuffer,
  41281. resolveDepthBuffer: false,
  41282. resolveStencilBuffer: false
  41283. } );
  41284. layer.renderTarget.isXRRenderTarget = false;
  41285. layer.plane.material = layer.material;
  41286. layer.material.map = layer.renderTarget.texture;
  41287. layer.material.map.offset.y = 1;
  41288. layer.material.map.repeat.y = -1;
  41289. delete layer.xrlayer;
  41290. }
  41291. }
  41292. //
  41293. this.isPresenting = false;
  41294. this._useMultiview = false;
  41295. renderer._animation.stop();
  41296. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  41297. renderer._animation.setContext( this._currentAnimationContext );
  41298. renderer._animation.start();
  41299. renderer.setPixelRatio( this._currentPixelRatio );
  41300. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  41301. this.dispatchEvent( { type: 'sessionend' } );
  41302. }
  41303. function onInputSourcesChange( event ) {
  41304. const controllers = this._controllers;
  41305. const controllerInputSources = this._controllerInputSources;
  41306. // Notify disconnected
  41307. for ( let i = 0; i < event.removed.length; i ++ ) {
  41308. const inputSource = event.removed[ i ];
  41309. const index = controllerInputSources.indexOf( inputSource );
  41310. if ( index >= 0 ) {
  41311. controllerInputSources[ index ] = null;
  41312. controllers[ index ].disconnect( inputSource );
  41313. }
  41314. }
  41315. // Notify connected
  41316. for ( let i = 0; i < event.added.length; i ++ ) {
  41317. const inputSource = event.added[ i ];
  41318. let controllerIndex = controllerInputSources.indexOf( inputSource );
  41319. if ( controllerIndex === -1 ) {
  41320. // Assign input source a controller that currently has no input source
  41321. for ( let i = 0; i < controllers.length; i ++ ) {
  41322. if ( i >= controllerInputSources.length ) {
  41323. controllerInputSources.push( inputSource );
  41324. controllerIndex = i;
  41325. break;
  41326. } else if ( controllerInputSources[ i ] === null ) {
  41327. controllerInputSources[ i ] = inputSource;
  41328. controllerIndex = i;
  41329. break;
  41330. }
  41331. }
  41332. // If all controllers do currently receive input we ignore new ones
  41333. if ( controllerIndex === -1 ) break;
  41334. }
  41335. const controller = controllers[ controllerIndex ];
  41336. if ( controller ) {
  41337. controller.connect( inputSource );
  41338. }
  41339. }
  41340. }
  41341. // Creation method for native WebXR layers
  41342. function createXRLayer( layer ) {
  41343. if ( layer.type === 'quad' ) {
  41344. return this._glBinding.createQuadLayer( {
  41345. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  41346. width: layer.width / 2,
  41347. height: layer.height / 2,
  41348. space: this._referenceSpace,
  41349. viewPixelWidth: layer.pixelwidth,
  41350. viewPixelHeight: layer.pixelheight,
  41351. clearOnAccess: false
  41352. } );
  41353. } else {
  41354. return this._glBinding.createCylinderLayer( {
  41355. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  41356. radius: layer.radius,
  41357. centralAngle: layer.centralAngle,
  41358. aspectRatio: layer.aspectRatio,
  41359. space: this._referenceSpace,
  41360. viewPixelWidth: layer.pixelwidth,
  41361. viewPixelHeight: layer.pixelheight,
  41362. clearOnAccess: false
  41363. } );
  41364. }
  41365. }
  41366. // Animation Loop
  41367. function onAnimationFrame( time, frame ) {
  41368. if ( frame === undefined ) return;
  41369. const cameraXR = this._cameraXR;
  41370. const renderer = this._renderer;
  41371. const backend = renderer.backend;
  41372. const glBaseLayer = this._glBaseLayer;
  41373. const referenceSpace = this.getReferenceSpace();
  41374. const pose = frame.getViewerPose( referenceSpace );
  41375. this._xrFrame = frame;
  41376. if ( pose !== null ) {
  41377. const views = pose.views;
  41378. if ( this._glBaseLayer !== null ) {
  41379. backend.setXRTarget( glBaseLayer.framebuffer );
  41380. }
  41381. let cameraXRNeedsUpdate = false;
  41382. // check if it's necessary to rebuild cameraXR's camera list
  41383. if ( views.length !== cameraXR.cameras.length ) {
  41384. cameraXR.cameras.length = 0;
  41385. cameraXRNeedsUpdate = true;
  41386. }
  41387. for ( let i = 0; i < views.length; i ++ ) {
  41388. const view = views[ i ];
  41389. let viewport;
  41390. if ( this._supportsLayers === true ) {
  41391. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  41392. viewport = glSubImage.viewport;
  41393. // For side-by-side projection, we only produce a single texture for both eyes.
  41394. if ( i === 0 ) {
  41395. backend.setXRRenderTargetTextures(
  41396. this._xrRenderTarget,
  41397. glSubImage.colorTexture,
  41398. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  41399. );
  41400. }
  41401. } else {
  41402. viewport = glBaseLayer.getViewport( view );
  41403. }
  41404. let camera = this._cameras[ i ];
  41405. if ( camera === undefined ) {
  41406. camera = new PerspectiveCamera();
  41407. camera.layers.enable( i );
  41408. camera.viewport = new Vector4();
  41409. this._cameras[ i ] = camera;
  41410. }
  41411. camera.matrix.fromArray( view.transform.matrix );
  41412. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  41413. camera.projectionMatrix.fromArray( view.projectionMatrix );
  41414. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  41415. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  41416. if ( i === 0 ) {
  41417. cameraXR.matrix.copy( camera.matrix );
  41418. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  41419. }
  41420. if ( cameraXRNeedsUpdate === true ) {
  41421. cameraXR.cameras.push( camera );
  41422. }
  41423. }
  41424. renderer.setOutputRenderTarget( this._xrRenderTarget );
  41425. const frameBufferTarget = renderer._getFrameBufferTarget();
  41426. renderer.xr.foveateBoundTexture( frameBufferTarget );
  41427. }
  41428. //
  41429. for ( let i = 0; i < this._controllers.length; i ++ ) {
  41430. const inputSource = this._controllerInputSources[ i ];
  41431. const controller = this._controllers[ i ];
  41432. if ( inputSource !== null && controller !== undefined ) {
  41433. controller.update( inputSource, frame, referenceSpace );
  41434. }
  41435. }
  41436. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  41437. if ( frame.detectedPlanes ) {
  41438. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  41439. }
  41440. this._xrFrame = null;
  41441. }
  41442. /**
  41443. * CanvasTarget is a class that represents the final output destination of the renderer.
  41444. *
  41445. * @augments EventDispatcher
  41446. */
  41447. class CanvasTarget extends EventDispatcher {
  41448. /**
  41449. * Constructs a new CanvasTarget.
  41450. *
  41451. * @param {HTMLCanvasElement|OffscreenCanvas} domElement - The canvas element to render to.
  41452. */
  41453. constructor( domElement ) {
  41454. super();
  41455. /**
  41456. * A reference to the canvas element the renderer is drawing to.
  41457. * This value of this property will automatically be created by
  41458. * the renderer.
  41459. *
  41460. * @type {HTMLCanvasElement|OffscreenCanvas}
  41461. */
  41462. this.domElement = domElement;
  41463. /**
  41464. * The renderer's pixel ratio.
  41465. *
  41466. * @private
  41467. * @type {number}
  41468. * @default 1
  41469. */
  41470. this._pixelRatio = 1;
  41471. /**
  41472. * The width of the renderer's default framebuffer in logical pixel unit.
  41473. *
  41474. * @private
  41475. * @type {number}
  41476. */
  41477. this._width = this.domElement.width;
  41478. /**
  41479. * The height of the renderer's default framebuffer in logical pixel unit.
  41480. *
  41481. * @private
  41482. * @type {number}
  41483. */
  41484. this._height = this.domElement.height;
  41485. /**
  41486. * The viewport of the renderer in logical pixel unit.
  41487. *
  41488. * @private
  41489. * @type {Vector4}
  41490. */
  41491. this._viewport = new Vector4( 0, 0, this._width, this._height );
  41492. /**
  41493. * The scissor rectangle of the renderer in logical pixel unit.
  41494. *
  41495. * @private
  41496. * @type {Vector4}
  41497. */
  41498. this._scissor = new Vector4( 0, 0, this._width, this._height );
  41499. /**
  41500. * Whether the scissor test should be enabled or not.
  41501. *
  41502. * @private
  41503. * @type {boolean}
  41504. */
  41505. this._scissorTest = false;
  41506. /**
  41507. * The color texture of the default framebuffer.
  41508. *
  41509. * @type {FramebufferTexture}
  41510. */
  41511. this.colorTexture = new FramebufferTexture();
  41512. /**
  41513. * The depth texture of the default framebuffer.
  41514. *
  41515. * @type {DepthTexture}
  41516. */
  41517. this.depthTexture = new DepthTexture();
  41518. }
  41519. /**
  41520. * Returns the pixel ratio.
  41521. *
  41522. * @return {number} The pixel ratio.
  41523. */
  41524. getPixelRatio() {
  41525. return this._pixelRatio;
  41526. }
  41527. /**
  41528. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  41529. *
  41530. * @param {Vector2} target - The method writes the result in this target object.
  41531. * @return {Vector2} The drawing buffer size.
  41532. */
  41533. getDrawingBufferSize( target ) {
  41534. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  41535. }
  41536. /**
  41537. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  41538. *
  41539. * @param {Vector2} target - The method writes the result in this target object.
  41540. * @return {Vector2} The renderer's size in logical pixels.
  41541. */
  41542. getSize( target ) {
  41543. return target.set( this._width, this._height );
  41544. }
  41545. /**
  41546. * Sets the given pixel ratio and resizes the canvas if necessary.
  41547. *
  41548. * @param {number} [value=1] - The pixel ratio.
  41549. */
  41550. setPixelRatio( value = 1 ) {
  41551. if ( this._pixelRatio === value ) return;
  41552. this._pixelRatio = value;
  41553. this.setSize( this._width, this._height, false );
  41554. }
  41555. /**
  41556. * This method allows to define the drawing buffer size by specifying
  41557. * width, height and pixel ratio all at once. The size of the drawing
  41558. * buffer is computed with this formula:
  41559. * ```js
  41560. * size.x = width * pixelRatio;
  41561. * size.y = height * pixelRatio;
  41562. * ```
  41563. *
  41564. * @param {number} width - The width in logical pixels.
  41565. * @param {number} height - The height in logical pixels.
  41566. * @param {number} pixelRatio - The pixel ratio.
  41567. */
  41568. setDrawingBufferSize( width, height, pixelRatio ) {
  41569. // Renderer can't be resized while presenting in XR.
  41570. if ( this.xr && this.xr.isPresenting ) return;
  41571. this._width = width;
  41572. this._height = height;
  41573. this._pixelRatio = pixelRatio;
  41574. this.domElement.width = Math.floor( width * pixelRatio );
  41575. this.domElement.height = Math.floor( height * pixelRatio );
  41576. this.setViewport( 0, 0, width, height );
  41577. this._dispatchResize();
  41578. }
  41579. /**
  41580. * Sets the size of the renderer.
  41581. *
  41582. * @param {number} width - The width in logical pixels.
  41583. * @param {number} height - The height in logical pixels.
  41584. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  41585. */
  41586. setSize( width, height, updateStyle = true ) {
  41587. // Renderer can't be resized while presenting in XR.
  41588. if ( this.xr && this.xr.isPresenting ) return;
  41589. this._width = width;
  41590. this._height = height;
  41591. this.domElement.width = Math.floor( width * this._pixelRatio );
  41592. this.domElement.height = Math.floor( height * this._pixelRatio );
  41593. if ( updateStyle === true ) {
  41594. this.domElement.style.width = width + 'px';
  41595. this.domElement.style.height = height + 'px';
  41596. }
  41597. this.setViewport( 0, 0, width, height );
  41598. this._dispatchResize();
  41599. }
  41600. /**
  41601. * Returns the scissor rectangle.
  41602. *
  41603. * @param {Vector4} target - The method writes the result in this target object.
  41604. * @return {Vector4} The scissor rectangle.
  41605. */
  41606. getScissor( target ) {
  41607. const scissor = this._scissor;
  41608. target.x = scissor.x;
  41609. target.y = scissor.y;
  41610. target.width = scissor.width;
  41611. target.height = scissor.height;
  41612. return target;
  41613. }
  41614. /**
  41615. * Defines the scissor rectangle.
  41616. *
  41617. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  41618. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  41619. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  41620. * @param {number} width - The width of the scissor box in logical pixel unit.
  41621. * @param {number} height - The height of the scissor box in logical pixel unit.
  41622. */
  41623. setScissor( x, y, width, height ) {
  41624. const scissor = this._scissor;
  41625. if ( x.isVector4 ) {
  41626. scissor.copy( x );
  41627. } else {
  41628. scissor.set( x, y, width, height );
  41629. }
  41630. }
  41631. /**
  41632. * Returns the scissor test value.
  41633. *
  41634. * @return {boolean} Whether the scissor test should be enabled or not.
  41635. */
  41636. getScissorTest() {
  41637. return this._scissorTest;
  41638. }
  41639. /**
  41640. * Defines the scissor test.
  41641. *
  41642. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  41643. */
  41644. setScissorTest( boolean ) {
  41645. this._scissorTest = boolean;
  41646. }
  41647. /**
  41648. * Returns the viewport definition.
  41649. *
  41650. * @param {Vector4} target - The method writes the result in this target object.
  41651. * @return {Vector4} The viewport definition.
  41652. */
  41653. getViewport( target ) {
  41654. return target.copy( this._viewport );
  41655. }
  41656. /**
  41657. * Defines the viewport.
  41658. *
  41659. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  41660. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  41661. * @param {number} width - The width of the viewport in logical pixel unit.
  41662. * @param {number} height - The height of the viewport in logical pixel unit.
  41663. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  41664. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  41665. */
  41666. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  41667. const viewport = this._viewport;
  41668. if ( x.isVector4 ) {
  41669. viewport.copy( x );
  41670. } else {
  41671. viewport.set( x, y, width, height );
  41672. }
  41673. viewport.minDepth = minDepth;
  41674. viewport.maxDepth = maxDepth;
  41675. }
  41676. /**
  41677. * Dispatches the resize event.
  41678. *
  41679. * @private
  41680. */
  41681. _dispatchResize() {
  41682. this.dispatchEvent( { type: 'resize' } );
  41683. }
  41684. /**
  41685. * Frees the GPU-related resources allocated by this instance. Call this
  41686. * method whenever this instance is no longer used in your app.
  41687. *
  41688. * @fires RenderTarget#dispose
  41689. */
  41690. dispose() {
  41691. this.dispatchEvent( { type: 'dispose' } );
  41692. }
  41693. }
  41694. const _scene = /*@__PURE__*/ new Scene();
  41695. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  41696. const _screen = /*@__PURE__*/ new Vector4();
  41697. const _frustum = /*@__PURE__*/ new Frustum();
  41698. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  41699. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  41700. const _vector4 = /*@__PURE__*/ new Vector4();
  41701. const _shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  41702. /**
  41703. * Base class for renderers.
  41704. */
  41705. class Renderer {
  41706. /**
  41707. * Renderer options.
  41708. *
  41709. * @typedef {Object} Renderer~Options
  41710. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  41711. * @property {boolean} [reversedDepthBuffer=false] - Whether reversed depth buffer is enabled or not.
  41712. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  41713. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  41714. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  41715. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  41716. * @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
  41717. * to overwrite the default.
  41718. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  41719. * @property {number} [outputBufferType=HalfFloatType] - Defines the type of output buffers. The default `HalfFloatType` is recommend for best
  41720. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  41721. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  41722. */
  41723. /**
  41724. * Constructs a new renderer.
  41725. *
  41726. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  41727. * @param {Renderer~Options} [parameters] - The configuration parameter.
  41728. */
  41729. constructor( backend, parameters = {} ) {
  41730. /**
  41731. * This flag can be used for type testing.
  41732. *
  41733. * @type {boolean}
  41734. * @readonly
  41735. * @default true
  41736. */
  41737. this.isRenderer = true;
  41738. //
  41739. const {
  41740. logarithmicDepthBuffer = false,
  41741. reversedDepthBuffer = false,
  41742. alpha = true,
  41743. depth = true,
  41744. stencil = false,
  41745. antialias = false,
  41746. samples = 0,
  41747. getFallback = null,
  41748. outputBufferType = HalfFloatType,
  41749. multiview = false
  41750. } = parameters;
  41751. /**
  41752. * A reference to the current backend.
  41753. *
  41754. * @type {Backend}
  41755. */
  41756. this.backend = backend;
  41757. /**
  41758. * Whether the renderer should automatically clear the current rendering target
  41759. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  41760. * or the current bound render target (custom framebuffer).
  41761. *
  41762. * @type {boolean}
  41763. * @default true
  41764. */
  41765. this.autoClear = true;
  41766. /**
  41767. * When `autoClear` is set to `true`, this property defines whether the renderer
  41768. * should clear the color buffer.
  41769. *
  41770. * @type {boolean}
  41771. * @default true
  41772. */
  41773. this.autoClearColor = true;
  41774. /**
  41775. * When `autoClear` is set to `true`, this property defines whether the renderer
  41776. * should clear the depth buffer.
  41777. *
  41778. * @type {boolean}
  41779. * @default true
  41780. */
  41781. this.autoClearDepth = true;
  41782. /**
  41783. * When `autoClear` is set to `true`, this property defines whether the renderer
  41784. * should clear the stencil buffer.
  41785. *
  41786. * @type {boolean}
  41787. * @default true
  41788. */
  41789. this.autoClearStencil = true;
  41790. /**
  41791. * Whether the default framebuffer should be transparent or opaque.
  41792. *
  41793. * @type {boolean}
  41794. * @default true
  41795. */
  41796. this.alpha = alpha;
  41797. /**
  41798. * Whether logarithmic depth buffer is enabled or not.
  41799. *
  41800. * @type {boolean}
  41801. * @default false
  41802. * @readonly
  41803. */
  41804. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  41805. /**
  41806. * Whether reversed depth buffer is enabled or not.
  41807. *
  41808. * @type {boolean}
  41809. * @default false
  41810. * @readonly
  41811. */
  41812. this.reversedDepthBuffer = reversedDepthBuffer;
  41813. /**
  41814. * Defines the output color space of the renderer.
  41815. *
  41816. * @type {string}
  41817. * @default SRGBColorSpace
  41818. */
  41819. this.outputColorSpace = SRGBColorSpace;
  41820. /**
  41821. * Defines the tone mapping of the renderer.
  41822. *
  41823. * @type {number}
  41824. * @default NoToneMapping
  41825. */
  41826. this.toneMapping = NoToneMapping;
  41827. /**
  41828. * Defines the tone mapping exposure.
  41829. *
  41830. * @type {number}
  41831. * @default 1
  41832. */
  41833. this.toneMappingExposure = 1.0;
  41834. /**
  41835. * Whether the renderer should sort its render lists or not.
  41836. *
  41837. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  41838. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  41839. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  41840. * e.g. manually determining each object's rendering order.
  41841. *
  41842. * @type {boolean}
  41843. * @default true
  41844. */
  41845. this.sortObjects = true;
  41846. /**
  41847. * Whether the default framebuffer should have a depth buffer or not.
  41848. *
  41849. * @type {boolean}
  41850. * @default true
  41851. */
  41852. this.depth = depth;
  41853. /**
  41854. * Whether the default framebuffer should have a stencil buffer or not.
  41855. *
  41856. * @type {boolean}
  41857. * @default false
  41858. */
  41859. this.stencil = stencil;
  41860. /**
  41861. * Holds a series of statistical information about the GPU memory
  41862. * and the rendering process. Useful for debugging and monitoring.
  41863. *
  41864. * @type {Info}
  41865. */
  41866. this.info = new Info();
  41867. /**
  41868. * A global context node that stores override nodes for specific transformations or calculations.
  41869. * These nodes can be used to replace default behavior in the rendering pipeline.
  41870. *
  41871. * @type {ContextNode}
  41872. * @property {Object} value - The context value object.
  41873. */
  41874. this.contextNode = context();
  41875. /**
  41876. * The node library defines how certain library objects like materials, lights
  41877. * or tone mapping functions are mapped to node types. This is required since
  41878. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  41879. * be part of the scene graph, they are internally represented as nodes for
  41880. * further processing.
  41881. *
  41882. * @type {NodeLibrary}
  41883. */
  41884. this.library = new NodeLibrary();
  41885. /**
  41886. * A map-like data structure for managing lights.
  41887. *
  41888. * @type {Lighting}
  41889. */
  41890. this.lighting = new Lighting();
  41891. // internals
  41892. /**
  41893. * The number of MSAA samples.
  41894. *
  41895. * @private
  41896. * @type {number}
  41897. * @default 0
  41898. */
  41899. this._samples = samples || ( antialias === true ) ? 4 : 0;
  41900. /**
  41901. * OnCanvasTargetResize callback function.
  41902. *
  41903. * @private
  41904. * @type {Function}
  41905. */
  41906. this._onCanvasTargetResize = this._onCanvasTargetResize.bind( this );
  41907. /**
  41908. * The canvas target for rendering.
  41909. *
  41910. * @private
  41911. * @type {CanvasTarget}
  41912. */
  41913. this._canvasTarget = new CanvasTarget( backend.getDomElement() );
  41914. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  41915. this._canvasTarget.isDefaultCanvasTarget = true;
  41916. /**
  41917. * The inspector provides information about the internal renderer state.
  41918. *
  41919. * @private
  41920. * @type {InspectorBase}
  41921. */
  41922. this._inspector = new InspectorBase();
  41923. this._inspector.setRenderer( this );
  41924. /**
  41925. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  41926. *
  41927. * @private
  41928. * @type {?Function}
  41929. */
  41930. this._getFallback = getFallback;
  41931. /**
  41932. * A reference to a renderer module for managing shader attributes.
  41933. *
  41934. * @private
  41935. * @type {?Attributes}
  41936. * @default null
  41937. */
  41938. this._attributes = null;
  41939. /**
  41940. * A reference to a renderer module for managing geometries.
  41941. *
  41942. * @private
  41943. * @type {?Geometries}
  41944. * @default null
  41945. */
  41946. this._geometries = null;
  41947. /**
  41948. * A reference to a renderer module for managing node related logic.
  41949. *
  41950. * @private
  41951. * @type {?NodeManager}
  41952. * @default null
  41953. */
  41954. this._nodes = null;
  41955. /**
  41956. * A reference to a renderer module for managing the internal animation loop.
  41957. *
  41958. * @private
  41959. * @type {?Animation}
  41960. * @default null
  41961. */
  41962. this._animation = null;
  41963. /**
  41964. * A reference to a renderer module for managing shader program bindings.
  41965. *
  41966. * @private
  41967. * @type {?Bindings}
  41968. * @default null
  41969. */
  41970. this._bindings = null;
  41971. /**
  41972. * A reference to a renderer module for managing render objects.
  41973. *
  41974. * @private
  41975. * @type {?RenderObjects}
  41976. * @default null
  41977. */
  41978. this._objects = null;
  41979. /**
  41980. * A reference to a renderer module for managing render and compute pipelines.
  41981. *
  41982. * @private
  41983. * @type {?Pipelines}
  41984. * @default null
  41985. */
  41986. this._pipelines = null;
  41987. /**
  41988. * A reference to a renderer module for managing render bundles.
  41989. *
  41990. * @private
  41991. * @type {?RenderBundles}
  41992. * @default null
  41993. */
  41994. this._bundles = null;
  41995. /**
  41996. * A reference to a renderer module for managing render lists.
  41997. *
  41998. * @private
  41999. * @type {?RenderLists}
  42000. * @default null
  42001. */
  42002. this._renderLists = null;
  42003. /**
  42004. * A reference to a renderer module for managing render contexts.
  42005. *
  42006. * @private
  42007. * @type {?RenderContexts}
  42008. * @default null
  42009. */
  42010. this._renderContexts = null;
  42011. /**
  42012. * A reference to a renderer module for managing textures.
  42013. *
  42014. * @private
  42015. * @type {?Textures}
  42016. * @default null
  42017. */
  42018. this._textures = null;
  42019. /**
  42020. * A reference to a renderer module for backgrounds.
  42021. *
  42022. * @private
  42023. * @type {?Background}
  42024. * @default null
  42025. */
  42026. this._background = null;
  42027. /**
  42028. * Cache for the fullscreen quad.
  42029. * This fullscreen quad is used for internal render passes
  42030. * like the tone mapping and color space output pass.
  42031. *
  42032. * @private
  42033. * @type {Map<Texture,QuadMesh>}
  42034. */
  42035. this._quadCache = new Map();
  42036. /**
  42037. * A reference to the current render context.
  42038. *
  42039. * @private
  42040. * @type {?RenderContext}
  42041. * @default null
  42042. */
  42043. this._currentRenderContext = null;
  42044. /**
  42045. * A custom sort function for the opaque render list.
  42046. *
  42047. * @private
  42048. * @type {?Function}
  42049. * @default null
  42050. */
  42051. this._opaqueSort = null;
  42052. /**
  42053. * A custom sort function for the transparent render list.
  42054. *
  42055. * @private
  42056. * @type {?Function}
  42057. * @default null
  42058. */
  42059. this._transparentSort = null;
  42060. /**
  42061. * Cache of framebuffer targets per canvas target.
  42062. *
  42063. * @private
  42064. * @type {Map<CanvasTarget, RenderTarget>}
  42065. */
  42066. this._frameBufferTargets = new Map();
  42067. const alphaClear = this.alpha === true ? 0 : 1;
  42068. /**
  42069. * The clear color value.
  42070. *
  42071. * @private
  42072. * @type {Color4}
  42073. */
  42074. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  42075. /**
  42076. * The clear depth value.
  42077. *
  42078. * @private
  42079. * @type {number}
  42080. * @default 1
  42081. */
  42082. this._clearDepth = 1;
  42083. /**
  42084. * The clear stencil value.
  42085. *
  42086. * @private
  42087. * @type {number}
  42088. * @default 0
  42089. */
  42090. this._clearStencil = 0;
  42091. /**
  42092. * The current render target.
  42093. *
  42094. * @private
  42095. * @type {?RenderTarget}
  42096. * @default null
  42097. */
  42098. this._renderTarget = null;
  42099. /**
  42100. * The active cube face.
  42101. *
  42102. * @private
  42103. * @type {number}
  42104. * @default 0
  42105. */
  42106. this._activeCubeFace = 0;
  42107. /**
  42108. * The active mipmap level.
  42109. *
  42110. * @private
  42111. * @type {number}
  42112. * @default 0
  42113. */
  42114. this._activeMipmapLevel = 0;
  42115. /**
  42116. * The current output render target.
  42117. *
  42118. * @private
  42119. * @type {?RenderTarget}
  42120. * @default null
  42121. */
  42122. this._outputRenderTarget = null;
  42123. /**
  42124. * The MRT setting.
  42125. *
  42126. * @private
  42127. * @type {?MRTNode}
  42128. * @default null
  42129. */
  42130. this._mrt = null;
  42131. /**
  42132. * This function defines how a render object is going
  42133. * to be rendered.
  42134. *
  42135. * @private
  42136. * @type {?Function}
  42137. * @default null
  42138. */
  42139. this._renderObjectFunction = null;
  42140. /**
  42141. * Used to keep track of the current render object function.
  42142. *
  42143. * @private
  42144. * @type {?Function}
  42145. * @default null
  42146. */
  42147. this._currentRenderObjectFunction = null;
  42148. /**
  42149. * Used to keep track of the current render bundle.
  42150. *
  42151. * @private
  42152. * @type {?RenderBundle}
  42153. * @default null
  42154. */
  42155. this._currentRenderBundle = null;
  42156. /**
  42157. * Next to `_renderObjectFunction()`, this function provides another hook
  42158. * for influencing the render process of a render object. It is meant for internal
  42159. * use and only relevant for `compileAsync()` right now. Instead of using
  42160. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  42161. * a different function might be used which performs no draw but just the node
  42162. * and pipeline updates.
  42163. *
  42164. * @private
  42165. * @type {Function}
  42166. */
  42167. this._handleObjectFunction = this._renderObjectDirect;
  42168. /**
  42169. * Indicates whether the device has been lost or not. In WebGL terms, the device
  42170. * lost is considered as a context lost. When this is set to `true`, rendering
  42171. * isn't possible anymore.
  42172. *
  42173. * @private
  42174. * @type {boolean}
  42175. * @default false
  42176. */
  42177. this._isDeviceLost = false;
  42178. /**
  42179. * A callback function that defines what should happen when a device/context lost occurs.
  42180. *
  42181. * @type {Function}
  42182. */
  42183. this.onDeviceLost = this._onDeviceLost;
  42184. /**
  42185. * A callback function that defines what should happen when an uncaptured
  42186. * backend error is reported (e.g. a WebGPU validation/out-of-memory/internal
  42187. * error raised outside an error scope). Applications can override this to
  42188. * surface errors in their own UI without letting them escalate to a device
  42189. * loss. The default implementation logs to the console.
  42190. *
  42191. * @type {Function}
  42192. */
  42193. this.onError = this._onError;
  42194. /**
  42195. * Defines the type of output buffers. The default `HalfFloatType` is recommend for
  42196. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  42197. * This will reduce rendering quality though.
  42198. *
  42199. * @private
  42200. * @type {number}
  42201. * @default HalfFloatType
  42202. */
  42203. this._outputBufferType = outputBufferType;
  42204. /**
  42205. * A cache for shadow nodes per material
  42206. *
  42207. * @private
  42208. * @type {WeakMap<Material, Object>}
  42209. */
  42210. this._cacheShadowNodes = new WeakMap();
  42211. /**
  42212. * Whether the renderer has been initialized or not.
  42213. *
  42214. * @private
  42215. * @type {boolean}
  42216. * @default false
  42217. */
  42218. this._initialized = false;
  42219. /**
  42220. * The call depth of the renderer. Counts the number of
  42221. * nested render calls.
  42222. *
  42223. * @private
  42224. * @type {number}
  42225. * @default - 1
  42226. */
  42227. this._callDepth = -1;
  42228. /**
  42229. * A reference to the promise which initializes the renderer.
  42230. *
  42231. * @private
  42232. * @type {?Promise<this>}
  42233. * @default null
  42234. */
  42235. this._initPromise = null;
  42236. /**
  42237. * An array of compilation promises which are used in `compileAsync()`.
  42238. *
  42239. * @private
  42240. * @type {?Array<Promise>}
  42241. * @default null
  42242. */
  42243. this._compilationPromises = null;
  42244. /**
  42245. * Whether the renderer should render transparent render objects or not.
  42246. *
  42247. * @type {boolean}
  42248. * @default true
  42249. */
  42250. this.transparent = true;
  42251. /**
  42252. * Whether the renderer should render opaque render objects or not.
  42253. *
  42254. * @type {boolean}
  42255. * @default true
  42256. */
  42257. this.opaque = true;
  42258. /**
  42259. * Shadow map configuration
  42260. * @typedef {Object} ShadowMapConfig
  42261. * @property {boolean} enabled - Whether to globally enable shadows or not.
  42262. * @property {boolean} transmitted - Whether to enable light transmission through non-opaque materials.
  42263. * @property {number} type - The shadow map type.
  42264. */
  42265. /**
  42266. * The renderer's shadow configuration.
  42267. *
  42268. * @type {ShadowMapConfig}
  42269. */
  42270. this.shadowMap = {
  42271. enabled: false,
  42272. transmitted: false,
  42273. type: PCFShadowMap
  42274. };
  42275. /**
  42276. * XR configuration.
  42277. * @typedef {Object} XRConfig
  42278. * @property {boolean} enabled - Whether to globally enable XR or not.
  42279. */
  42280. /**
  42281. * The renderer's XR manager.
  42282. *
  42283. * @type {XRManager}
  42284. */
  42285. this.xr = new XRManager( this, multiview );
  42286. /**
  42287. * Debug configuration.
  42288. * @typedef {Object} DebugConfig
  42289. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  42290. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  42291. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  42292. */
  42293. /**
  42294. * The renderer's debug configuration.
  42295. *
  42296. * @type {DebugConfig}
  42297. */
  42298. this.debug = {
  42299. checkShaderErrors: true,
  42300. onShaderError: null,
  42301. getShaderAsync: async ( scene, camera, object ) => {
  42302. await this.compileAsync( scene, camera );
  42303. const renderList = this._renderLists.get( scene, camera );
  42304. const renderContext = this._renderContexts.get( this._renderTarget, this._mrt );
  42305. const material = scene.overrideMaterial || object.material;
  42306. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  42307. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  42308. return { fragmentShader, vertexShader };
  42309. }
  42310. };
  42311. }
  42312. /**
  42313. * Initializes the renderer so it is ready for usage.
  42314. *
  42315. * @async
  42316. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  42317. */
  42318. async init() {
  42319. if ( this._initPromise !== null ) {
  42320. return this._initPromise;
  42321. }
  42322. this._initPromise = new Promise( async ( resolve, reject ) => {
  42323. let backend = this.backend;
  42324. try {
  42325. await backend.init( this );
  42326. } catch ( error ) {
  42327. if ( this._getFallback !== null ) {
  42328. // try the fallback
  42329. try {
  42330. this.backend = backend = this._getFallback( error );
  42331. await backend.init( this );
  42332. } catch ( error ) {
  42333. reject( error );
  42334. return;
  42335. }
  42336. } else {
  42337. reject( error );
  42338. return;
  42339. }
  42340. }
  42341. this._nodes = new NodeManager( this, backend );
  42342. this._animation = new Animation( this, this._nodes, this.info );
  42343. this._attributes = new Attributes( backend, this.info );
  42344. this._background = new Background( this, this._nodes );
  42345. this._geometries = new Geometries( this._attributes, this.info );
  42346. this._textures = new Textures( this, backend, this.info );
  42347. this._pipelines = new Pipelines( backend, this._nodes, this.info );
  42348. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  42349. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  42350. this._renderLists = new RenderLists( this.lighting );
  42351. this._bundles = new RenderBundles();
  42352. this._renderContexts = new RenderContexts( this );
  42353. //
  42354. this._animation.start();
  42355. this._initialized = true;
  42356. //
  42357. this._inspector.init();
  42358. //
  42359. resolve( this );
  42360. } );
  42361. return this._initPromise;
  42362. }
  42363. /**
  42364. * A reference to the canvas element the renderer is drawing to.
  42365. * This value of this property will automatically be created by
  42366. * the renderer.
  42367. *
  42368. * @type {HTMLCanvasElement|OffscreenCanvas}
  42369. */
  42370. get domElement() {
  42371. return this._canvasTarget.domElement;
  42372. }
  42373. /**
  42374. * The coordinate system of the renderer. The value of this property
  42375. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  42376. * `THREE.WebGPUCoordinateSystem`.
  42377. *
  42378. * @readonly
  42379. * @type {number}
  42380. */
  42381. get coordinateSystem() {
  42382. return this.backend.coordinateSystem;
  42383. }
  42384. /**
  42385. * Compiles all materials in the given scene. This can be useful to avoid a
  42386. * phenomenon which is called "shader compilation stutter", which occurs when
  42387. * rendering an object with a new shader for the first time.
  42388. *
  42389. * If you want to add a 3D object to an existing scene, use the third optional
  42390. * parameter for applying the target scene. Note that the (target) scene's lighting
  42391. * and environment must be configured before calling this method.
  42392. *
  42393. * @async
  42394. * @param {Object3D} scene - The scene or 3D object to precompile.
  42395. * @param {Camera} camera - The camera that is used to render the scene.
  42396. * @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.
  42397. * @return {Promise} A Promise that resolves when the compile has been finished.
  42398. */
  42399. async compileAsync( scene, camera, targetScene = null ) {
  42400. if ( this._isDeviceLost === true ) return;
  42401. if ( this._initialized === false ) await this.init();
  42402. // preserve render tree
  42403. const nodeFrame = this._nodes.nodeFrame;
  42404. const previousRenderId = nodeFrame.renderId;
  42405. const previousRenderContext = this._currentRenderContext;
  42406. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  42407. const previousHandleObjectFunction = this._handleObjectFunction;
  42408. const previousCompilationPromises = this._compilationPromises;
  42409. //
  42410. if ( targetScene === null ) targetScene = scene;
  42411. // Use the actual scene for caching when compiling individual objects
  42412. // This ensures cache keys match between compileAsync and render
  42413. const sceneRef = ( scene.isScene === true ) ? scene : ( targetScene.isScene === true ) ? targetScene : _scene;
  42414. // Match render()'s logic: use frameBufferTarget when needsFrameBufferTarget is true
  42415. const useFrameBufferTarget = this.needsFrameBufferTarget && this._renderTarget === null;
  42416. const renderTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : ( this._renderTarget || this._outputRenderTarget );
  42417. const renderContext = this._renderContexts.get( renderTarget, this._mrt );
  42418. const activeMipmapLevel = this._activeMipmapLevel;
  42419. const compilationPromises = [];
  42420. this._currentRenderContext = renderContext;
  42421. this._currentRenderObjectFunction = this.renderObject;
  42422. this._handleObjectFunction = this._createObjectPipeline;
  42423. this._compilationPromises = compilationPromises;
  42424. nodeFrame.renderId ++;
  42425. //
  42426. nodeFrame.update();
  42427. //
  42428. renderContext.depth = this.depth;
  42429. renderContext.stencil = this.stencil;
  42430. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  42431. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  42432. //
  42433. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  42434. //
  42435. // Use sceneRef for render list to ensure lightsNode matches between compileAsync and render
  42436. const renderList = this._renderLists.get( sceneRef, camera );
  42437. renderList.begin();
  42438. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  42439. // include lights from target scene
  42440. if ( targetScene !== scene ) {
  42441. targetScene.traverseVisible( function ( object ) {
  42442. if ( object.isLight && object.layers.test( camera.layers ) ) {
  42443. renderList.pushLight( object );
  42444. }
  42445. } );
  42446. }
  42447. renderList.finish();
  42448. //
  42449. if ( renderTarget !== null ) {
  42450. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  42451. const renderTargetData = this._textures.get( renderTarget );
  42452. renderContext.textures = renderTargetData.textures;
  42453. renderContext.depthTexture = renderTargetData.depthTexture;
  42454. } else {
  42455. renderContext.textures = null;
  42456. renderContext.depthTexture = null;
  42457. }
  42458. //
  42459. if ( targetScene !== scene ) {
  42460. this._background.update( targetScene, renderList, renderContext );
  42461. } else {
  42462. this._background.update( sceneRef, renderList, renderContext );
  42463. }
  42464. // process render lists - _createObjectPipeline will push async promises to _compilationPromises
  42465. const opaqueObjects = renderList.opaque;
  42466. const transparentObjects = renderList.transparent;
  42467. const transparentDoublePassObjects = renderList.transparentDoublePass;
  42468. const lightsNode = renderList.lightsNode;
  42469. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  42470. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  42471. // restore render tree
  42472. nodeFrame.renderId = previousRenderId;
  42473. this._currentRenderContext = previousRenderContext;
  42474. this._currentRenderObjectFunction = previousRenderObjectFunction;
  42475. this._handleObjectFunction = previousHandleObjectFunction;
  42476. this._compilationPromises = previousCompilationPromises;
  42477. // Process compilation work items sequentially to avoid freezing
  42478. // Yields between objects to keep animation smooth
  42479. for ( const item of compilationPromises ) {
  42480. const renderObject = this._objects.get( item.object, item.material, item.scene, item.camera, item.lightsNode, item.renderContext, item.clippingContext, item.passId );
  42481. renderObject.drawRange = item.object.geometry.drawRange;
  42482. renderObject.group = item.group;
  42483. this._geometries.updateForRender( renderObject );
  42484. // Use async node building to yield to main thread
  42485. await this._nodes.getForRenderAsync( renderObject );
  42486. this._nodes.updateBefore( renderObject );
  42487. this._nodes.updateForRender( renderObject );
  42488. this._bindings.updateForRender( renderObject );
  42489. // Wait for pipeline creation
  42490. const pipelinePromises = [];
  42491. this._pipelines.getForRender( renderObject, pipelinePromises );
  42492. if ( pipelinePromises.length > 0 ) {
  42493. await Promise.all( pipelinePromises );
  42494. }
  42495. this._nodes.updateAfter( renderObject );
  42496. // Yield between objects to allow animation frames
  42497. await yieldToMain();
  42498. }
  42499. }
  42500. /**
  42501. * Renders the scene in an async fashion.
  42502. *
  42503. * @async
  42504. * @deprecated
  42505. * @param {Object3D} scene - The scene or 3D object to render.
  42506. * @param {Camera} camera - The camera.
  42507. * @return {Promise} A Promise that resolves when the render has been finished.
  42508. */
  42509. async renderAsync( scene, camera ) {
  42510. warnOnce( 'Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42511. await this.init();
  42512. this.render( scene, camera );
  42513. }
  42514. /**
  42515. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  42516. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  42517. *
  42518. * @async
  42519. * @deprecated
  42520. * @return {Promise} A Promise that resolves when synchronization has been finished.
  42521. */
  42522. async waitForGPU() {
  42523. error( 'Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.' );
  42524. }
  42525. //
  42526. set inspector( value ) {
  42527. if ( this._inspector !== null ) {
  42528. this._inspector.setRenderer( null );
  42529. }
  42530. this._inspector = value;
  42531. this._inspector.setRenderer( this );
  42532. }
  42533. /**
  42534. * The inspector instance. The inspector can be any class that extends from `InspectorBase`.
  42535. *
  42536. * @type {InspectorBase}
  42537. */
  42538. get inspector() {
  42539. return this._inspector;
  42540. }
  42541. /**
  42542. * Enables or disables high precision for model-view and normal-view matrices.
  42543. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  42544. *
  42545. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  42546. *
  42547. * @param {boolean} value - Whether to enable or disable high precision.
  42548. * @type {boolean}
  42549. */
  42550. set highPrecision( value ) {
  42551. const contextNodeData = this.contextNode.value;
  42552. if ( value === true ) {
  42553. contextNodeData.modelViewMatrix = highpModelViewMatrix;
  42554. contextNodeData.modelNormalViewMatrix = highpModelNormalViewMatrix;
  42555. } else if ( this.highPrecision ) {
  42556. delete contextNodeData.modelViewMatrix;
  42557. delete contextNodeData.modelNormalViewMatrix;
  42558. }
  42559. }
  42560. /**
  42561. * Returns whether high precision is enabled or not.
  42562. *
  42563. * @return {boolean} Whether high precision is enabled or not.
  42564. * @type {boolean}
  42565. */
  42566. get highPrecision() {
  42567. const contextNodeData = this.contextNode.value;
  42568. return contextNodeData.modelViewMatrix === highpModelViewMatrix && contextNodeData.modelNormalViewMatrix === highpModelNormalViewMatrix;
  42569. }
  42570. /**
  42571. * Sets the given MRT configuration.
  42572. *
  42573. * @param {MRTNode} mrt - The MRT node to set.
  42574. * @return {Renderer} A reference to this renderer.
  42575. */
  42576. setMRT( mrt ) {
  42577. this._mrt = mrt;
  42578. return this;
  42579. }
  42580. /**
  42581. * Returns the MRT configuration.
  42582. *
  42583. * @return {MRTNode} The MRT configuration.
  42584. */
  42585. getMRT() {
  42586. return this._mrt;
  42587. }
  42588. /**
  42589. * Returns the output buffer type.
  42590. *
  42591. * @return {number} The output buffer type.
  42592. */
  42593. getOutputBufferType() {
  42594. return this._outputBufferType;
  42595. }
  42596. /**
  42597. * Returns the output buffer type.
  42598. *
  42599. * @deprecated since r182. Use `.getOutputBufferType()` instead.
  42600. * @return {number} The output buffer type.
  42601. */
  42602. getColorBufferType() { // @deprecated, r182
  42603. warnOnce( 'Renderer: ".getColorBufferType()" has been renamed to ".getOutputBufferType()".' );
  42604. return this.getOutputBufferType();
  42605. }
  42606. /**
  42607. * Default implementation of the device lost callback.
  42608. *
  42609. * @private
  42610. * @param {Object} info - Information about the context lost.
  42611. */
  42612. _onDeviceLost( info ) {
  42613. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  42614. if ( info.reason ) {
  42615. errorMessage += `\nReason: ${info.reason}`;
  42616. }
  42617. error( errorMessage );
  42618. this._isDeviceLost = true;
  42619. }
  42620. /**
  42621. * Default implementation of the uncaptured backend error callback.
  42622. *
  42623. * @private
  42624. * @param {Object} info - Information about the uncaptured error.
  42625. */
  42626. _onError( info ) {
  42627. let errorMessage = `WebGPURenderer: Uncaptured ${ info.api } ${ info.type }`;
  42628. if ( info.message ) {
  42629. errorMessage += `: ${ info.message }`;
  42630. }
  42631. error( errorMessage );
  42632. }
  42633. /**
  42634. * Renders the given render bundle.
  42635. *
  42636. * @private
  42637. * @param {Object} bundle - Render bundle data.
  42638. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  42639. * @param {LightsNode} lightsNode - The lights node.
  42640. */
  42641. _renderBundle( bundle, sceneRef, lightsNode ) {
  42642. const { bundleGroup, camera, renderList } = bundle;
  42643. const renderContext = this._currentRenderContext;
  42644. //
  42645. const renderBundle = this._bundles.get( bundleGroup, camera, renderContext );
  42646. const renderBundleData = this.backend.get( renderBundle );
  42647. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  42648. const renderBundleNeedsUpdate = needsUpdate || renderBundleData.bundleGPU === undefined;
  42649. if ( renderBundleNeedsUpdate ) {
  42650. this.backend.beginBundle( renderContext );
  42651. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  42652. renderBundleData.renderObjects = [];
  42653. }
  42654. this._currentRenderBundle = renderBundle;
  42655. const {
  42656. transparentDoublePass: transparentDoublePassObjects,
  42657. transparent: transparentObjects,
  42658. opaque: opaqueObjects
  42659. } = renderList;
  42660. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  42661. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  42662. this._currentRenderBundle = null;
  42663. //
  42664. this.backend.finishBundle( renderContext, renderBundle );
  42665. renderBundleData.version = bundleGroup.version;
  42666. } else {
  42667. const { renderObjects } = renderBundleData;
  42668. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  42669. const renderObject = renderObjects[ i ];
  42670. if ( this._nodes.needsRefresh( renderObject ) ) {
  42671. this._nodes.updateBefore( renderObject );
  42672. this._nodes.updateForRender( renderObject );
  42673. this._bindings.updateForRender( renderObject );
  42674. this._nodes.updateAfter( renderObject );
  42675. }
  42676. }
  42677. }
  42678. this.backend.addBundle( renderContext, renderBundle );
  42679. }
  42680. /**
  42681. * Renders the scene or 3D object with the given camera. This method can only be called
  42682. * if the renderer has been initialized. When using `render()` inside an animation loop,
  42683. * it's guaranteed the renderer will be initialized. The animation loop must be defined
  42684. * with {@link Renderer#setAnimationLoop} though.
  42685. *
  42686. * For all other use cases (like when using on-demand rendering), you must call
  42687. * {@link Renderer#init} before rendering.
  42688. *
  42689. * The target of the method is the default framebuffer (meaning the canvas)
  42690. * or alternatively a render target when specified via `setRenderTarget()`.
  42691. *
  42692. * @param {Object3D} scene - The scene or 3D object to render.
  42693. * @param {Camera} camera - The camera to render the scene with.
  42694. */
  42695. render( scene, camera ) {
  42696. if ( this._initialized === false ) {
  42697. throw new Error( 'Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.' );
  42698. }
  42699. this._renderScene( scene, camera );
  42700. }
  42701. /**
  42702. * Returns whether the renderer has been initialized or not.
  42703. *
  42704. * @readonly
  42705. * @return {boolean} Whether the renderer has been initialized or not.
  42706. */
  42707. get initialized() {
  42708. return this._initialized;
  42709. }
  42710. _renderOutputLayers( quad, renderTarget ) {
  42711. if ( renderTarget.texture.isArrayTexture !== true || renderTarget.texture.image.depth <= 1 ) {
  42712. this._renderScene( quad, quad.camera, false );
  42713. return;
  42714. }
  42715. const currentActiveCubeFace = this._activeCubeFace;
  42716. try {
  42717. for ( let layer = 0; layer < renderTarget.texture.image.depth; layer ++ ) {
  42718. this._nodes.setOutputLayerIndex( layer );
  42719. this._activeCubeFace = layer;
  42720. this._renderScene( quad, quad.camera, false );
  42721. }
  42722. } finally {
  42723. this._nodes.setOutputLayerIndex( 0 );
  42724. this._activeCubeFace = currentActiveCubeFace;
  42725. }
  42726. }
  42727. /**
  42728. * Returns an internal render target which is used when computing the output tone mapping
  42729. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  42730. * pass and not inline to achieve more correct results.
  42731. *
  42732. * @private
  42733. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  42734. */
  42735. _getFrameBufferTarget() {
  42736. const { currentToneMapping, currentColorSpace } = this;
  42737. const useToneMapping = currentToneMapping !== NoToneMapping;
  42738. const useColorSpace = currentColorSpace !== ColorManagement.workingColorSpace;
  42739. if ( useToneMapping === false && useColorSpace === false ) return null;
  42740. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  42741. const { depth, stencil } = this;
  42742. // TODO: Unify CanvasTarget and OutputRenderTarget
  42743. const target = this._outputRenderTarget || this._canvasTarget;
  42744. let frameBufferTarget = this._frameBufferTargets.get( target );
  42745. if ( frameBufferTarget === undefined ) {
  42746. frameBufferTarget = new RenderTarget( width, height, {
  42747. depthBuffer: depth,
  42748. stencilBuffer: stencil,
  42749. type: this._outputBufferType,
  42750. format: RGBAFormat,
  42751. colorSpace: ColorManagement.workingColorSpace,
  42752. generateMipmaps: false,
  42753. minFilter: LinearFilter,
  42754. magFilter: LinearFilter,
  42755. samples: this.samples
  42756. } );
  42757. frameBufferTarget.isPostProcessingRenderTarget = true;
  42758. const dispose = () => {
  42759. target.removeEventListener( 'dispose', dispose );
  42760. frameBufferTarget.dispose();
  42761. this._frameBufferTargets.delete( target );
  42762. };
  42763. target.addEventListener( 'dispose', dispose );
  42764. this._frameBufferTargets.set( target, frameBufferTarget );
  42765. }
  42766. const outputRenderTarget = this.getOutputRenderTarget();
  42767. frameBufferTarget.depthBuffer = depth;
  42768. frameBufferTarget.stencilBuffer = stencil;
  42769. if ( outputRenderTarget !== null ) {
  42770. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  42771. } else {
  42772. frameBufferTarget.setSize( width, height, 1 );
  42773. }
  42774. // RenderTarget || CanvasTarget
  42775. const viewport = this._outputRenderTarget ? this._outputRenderTarget.viewport : target._viewport;
  42776. const scissor = this._outputRenderTarget ? this._outputRenderTarget.scissor : target._scissor;
  42777. const pixelRatio = this._outputRenderTarget ? 1 : target._pixelRatio;
  42778. const scissorTest = this._outputRenderTarget ? this._outputRenderTarget.scissorTest : target._scissorTest;
  42779. frameBufferTarget.viewport.copy( viewport );
  42780. frameBufferTarget.scissor.copy( scissor );
  42781. frameBufferTarget.viewport.multiplyScalar( pixelRatio );
  42782. frameBufferTarget.scissor.multiplyScalar( pixelRatio );
  42783. frameBufferTarget.scissorTest = scissorTest;
  42784. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  42785. frameBufferTarget.useArrayDepthTexture = outputRenderTarget !== null ? outputRenderTarget.useArrayDepthTexture : false;
  42786. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  42787. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  42788. return frameBufferTarget;
  42789. }
  42790. /**
  42791. * Renders the scene or 3D object with the given camera.
  42792. *
  42793. * @private
  42794. * @param {Object3D} scene - The scene or 3D object to render.
  42795. * @param {Camera} camera - The camera to render the scene with.
  42796. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  42797. * @return {RenderContext} The current render context.
  42798. */
  42799. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  42800. if ( this._isDeviceLost === true ) return;
  42801. //
  42802. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  42803. // preserve render tree
  42804. const nodeFrame = this._nodes.nodeFrame;
  42805. const previousRenderId = nodeFrame.renderId;
  42806. const previousRenderContext = this._currentRenderContext;
  42807. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  42808. const previousHandleObjectFunction = this._handleObjectFunction;
  42809. //
  42810. this._callDepth ++;
  42811. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  42812. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  42813. const activeCubeFace = this._activeCubeFace;
  42814. const activeMipmapLevel = this._activeMipmapLevel;
  42815. //
  42816. let renderTarget;
  42817. if ( frameBufferTarget !== null ) {
  42818. renderTarget = frameBufferTarget;
  42819. this.setRenderTarget( renderTarget );
  42820. } else {
  42821. renderTarget = outputRenderTarget;
  42822. }
  42823. // make sure a new render target has correct default depth values
  42824. if ( renderTarget !== null && renderTarget.depthBuffer === true ) {
  42825. const renderTargetData = this._textures.get( renderTarget );
  42826. if ( renderTargetData.depthInitialized !== true ) {
  42827. // we need a single manual clear if auto clear depth is disabled
  42828. if ( this.autoClear === false || ( this.autoClear === true && this.autoClearDepth === false ) ) {
  42829. this.clearDepth();
  42830. }
  42831. renderTargetData.depthInitialized = true;
  42832. }
  42833. }
  42834. //
  42835. const renderContext = this._renderContexts.get( renderTarget, this._mrt, this._callDepth );
  42836. this._currentRenderContext = renderContext;
  42837. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  42838. this._handleObjectFunction = this._renderObjectDirect;
  42839. //
  42840. this.info.calls ++;
  42841. this.info.render.calls ++;
  42842. this.info.render.frameCalls ++;
  42843. nodeFrame.renderId = this.info.calls;
  42844. //
  42845. this.backend.updateTimeStampUID( renderContext );
  42846. this.inspector.beginRender( this.backend.getTimestampUID( renderContext ), scene, camera, renderTarget );
  42847. //
  42848. const xr = this.xr;
  42849. if ( xr.isPresenting === false ) {
  42850. let projectionMatrixNeedsUpdate = false;
  42851. // reversed depth
  42852. if ( this.reversedDepthBuffer === true && camera.reversedDepth !== true ) {
  42853. camera._reversedDepth = true;
  42854. if ( camera.isArrayCamera ) {
  42855. for ( const subCamera of camera.cameras ) {
  42856. subCamera._reversedDepth = true;
  42857. }
  42858. }
  42859. projectionMatrixNeedsUpdate = true;
  42860. }
  42861. // WebGPU/WebGL coordinate system
  42862. const coordinateSystem = this.coordinateSystem;
  42863. if ( camera.coordinateSystem !== coordinateSystem ) {
  42864. camera.coordinateSystem = coordinateSystem;
  42865. if ( camera.isArrayCamera ) {
  42866. for ( const subCamera of camera.cameras ) {
  42867. subCamera.coordinateSystem = coordinateSystem;
  42868. }
  42869. }
  42870. projectionMatrixNeedsUpdate = true;
  42871. }
  42872. // camera update
  42873. if ( projectionMatrixNeedsUpdate === true ) {
  42874. camera.updateProjectionMatrix();
  42875. if ( camera.isArrayCamera ) {
  42876. for ( const subCamera of camera.cameras ) {
  42877. subCamera.updateProjectionMatrix();
  42878. }
  42879. }
  42880. }
  42881. }
  42882. //
  42883. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  42884. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  42885. if ( xr.enabled === true && xr.isPresenting === true ) {
  42886. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  42887. camera = xr.getCamera(); // use XR camera for rendering
  42888. }
  42889. //
  42890. const canvasTarget = this._canvasTarget;
  42891. let viewport = canvasTarget._viewport;
  42892. let scissor = canvasTarget._scissor;
  42893. let pixelRatio = canvasTarget._pixelRatio;
  42894. if ( renderTarget !== null ) {
  42895. viewport = renderTarget.viewport;
  42896. scissor = renderTarget.scissor;
  42897. pixelRatio = 1;
  42898. }
  42899. this.getDrawingBufferSize( _drawingBufferSize );
  42900. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  42901. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  42902. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  42903. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  42904. renderContext.viewportValue.width >>= activeMipmapLevel;
  42905. renderContext.viewportValue.height >>= activeMipmapLevel;
  42906. renderContext.viewportValue.minDepth = minDepth;
  42907. renderContext.viewportValue.maxDepth = maxDepth;
  42908. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  42909. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  42910. renderContext.scissor = canvasTarget._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  42911. renderContext.scissorValue.width >>= activeMipmapLevel;
  42912. renderContext.scissorValue.height >>= activeMipmapLevel;
  42913. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  42914. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  42915. //
  42916. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  42917. //
  42918. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  42919. if ( ! camera.isArrayCamera ) {
  42920. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  42921. frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  42922. }
  42923. const renderList = this._renderLists.get( scene, camera );
  42924. renderList.begin();
  42925. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  42926. renderList.finish();
  42927. if ( this.sortObjects === true ) {
  42928. renderList.sort( this._opaqueSort, this._transparentSort );
  42929. }
  42930. //
  42931. if ( renderTarget !== null ) {
  42932. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  42933. const renderTargetData = this._textures.get( renderTarget );
  42934. renderContext.textures = renderTargetData.textures;
  42935. renderContext.depthTexture = renderTargetData.depthTexture;
  42936. renderContext.width = renderTargetData.width;
  42937. renderContext.height = renderTargetData.height;
  42938. renderContext.renderTarget = renderTarget;
  42939. renderContext.depth = renderTarget.depthBuffer;
  42940. renderContext.stencil = renderTarget.stencilBuffer;
  42941. } else {
  42942. renderContext.textures = null;
  42943. renderContext.depthTexture = null;
  42944. renderContext.width = _drawingBufferSize.width;
  42945. renderContext.height = _drawingBufferSize.height;
  42946. renderContext.depth = this.depth;
  42947. renderContext.stencil = this.stencil;
  42948. }
  42949. renderContext.width >>= activeMipmapLevel;
  42950. renderContext.height >>= activeMipmapLevel;
  42951. renderContext.activeCubeFace = activeCubeFace;
  42952. renderContext.activeMipmapLevel = activeMipmapLevel;
  42953. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  42954. //
  42955. renderContext.scissorValue.max( _vector4.set( 0, 0, 0, 0 ) );
  42956. if ( renderContext.scissorValue.x + renderContext.scissorValue.width > renderContext.width ) {
  42957. renderContext.scissorValue.width = Math.max( renderContext.width - renderContext.scissorValue.x, 0 );
  42958. }
  42959. if ( renderContext.scissorValue.y + renderContext.scissorValue.height > renderContext.height ) {
  42960. renderContext.scissorValue.height = Math.max( renderContext.height - renderContext.scissorValue.y, 0 );
  42961. }
  42962. //
  42963. this._background.update( sceneRef, renderList, renderContext );
  42964. //
  42965. renderContext.camera = camera;
  42966. this.backend.beginRender( renderContext );
  42967. // process render lists
  42968. const {
  42969. bundles,
  42970. lightsNode,
  42971. transparentDoublePass: transparentDoublePassObjects,
  42972. transparent: transparentObjects,
  42973. opaque: opaqueObjects
  42974. } = renderList;
  42975. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  42976. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  42977. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  42978. // finish render pass
  42979. this.backend.finishRender( renderContext );
  42980. // restore render tree
  42981. nodeFrame.renderId = previousRenderId;
  42982. this._currentRenderContext = previousRenderContext;
  42983. this._currentRenderObjectFunction = previousRenderObjectFunction;
  42984. this._handleObjectFunction = previousHandleObjectFunction;
  42985. //
  42986. this._callDepth --;
  42987. if ( frameBufferTarget !== null ) {
  42988. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  42989. this._renderOutput( renderTarget );
  42990. }
  42991. //
  42992. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  42993. //
  42994. this.inspector.finishRender( this.backend.getTimestampUID( renderContext ) );
  42995. //
  42996. return renderContext;
  42997. }
  42998. _setXRLayerSize( width, height ) {
  42999. // TODO: Find a better solution to resize the canvas when in XR.
  43000. this._canvasTarget._width = width;
  43001. this._canvasTarget._height = height;
  43002. this.setViewport( 0, 0, width, height );
  43003. }
  43004. /**
  43005. * The output pass performs tone mapping and color space conversion.
  43006. *
  43007. * @private
  43008. * @param {RenderTarget} renderTarget - The current render target.
  43009. */
  43010. _renderOutput( renderTarget ) {
  43011. const cacheKey = this._nodes.getOutputCacheKey();
  43012. let quadData = this._quadCache.get( renderTarget.texture );
  43013. let quad;
  43014. if ( quadData === undefined ) {
  43015. quad = new QuadMesh( new NodeMaterial() );
  43016. quad.name = 'Output Color Transform';
  43017. quad.material.name = 'outputColorTransform';
  43018. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  43019. quadData = {
  43020. quad,
  43021. cacheKey
  43022. };
  43023. this._quadCache.set( renderTarget.texture, quadData );
  43024. // dispose logic
  43025. const dispose = () => {
  43026. quad.material.dispose();
  43027. this._quadCache.delete( renderTarget.texture );
  43028. renderTarget.texture.removeEventListener( 'dispose', dispose );
  43029. };
  43030. renderTarget.texture.addEventListener( 'dispose', dispose );
  43031. } else {
  43032. quad = quadData.quad;
  43033. if ( quadData.cacheKey !== cacheKey ) {
  43034. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  43035. quad.material.needsUpdate = true;
  43036. quadData.cacheKey = cacheKey;
  43037. }
  43038. }
  43039. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  43040. const currentAutoClear = this.autoClear;
  43041. const currentXR = this.xr.enabled;
  43042. this.autoClear = false;
  43043. this.xr.enabled = false;
  43044. this._renderOutputLayers( quad, renderTarget );
  43045. this.autoClear = currentAutoClear;
  43046. this.xr.enabled = currentXR;
  43047. }
  43048. /**
  43049. * Returns the maximum available anisotropy for texture filtering.
  43050. *
  43051. * @return {number} The maximum available anisotropy.
  43052. */
  43053. getMaxAnisotropy() {
  43054. return this.backend.capabilities.getMaxAnisotropy();
  43055. }
  43056. /**
  43057. * Returns the active cube face.
  43058. *
  43059. * @return {number} The active cube face.
  43060. */
  43061. getActiveCubeFace() {
  43062. return this._activeCubeFace;
  43063. }
  43064. /**
  43065. * Returns the active mipmap level.
  43066. *
  43067. * @return {number} The active mipmap level.
  43068. */
  43069. getActiveMipmapLevel() {
  43070. return this._activeMipmapLevel;
  43071. }
  43072. /**
  43073. * Applications are advised to always define the animation loop
  43074. * with this method and not manually with `requestAnimationFrame()`
  43075. * for best compatibility.
  43076. *
  43077. * @async
  43078. * @param {?onAnimationCallback} callback - The application's animation loop.
  43079. * @return {Promise} A Promise that resolves when the set has been executed.
  43080. */
  43081. async setAnimationLoop( callback ) {
  43082. if ( this._initialized === false ) await this.init();
  43083. this._animation.setAnimationLoop( callback );
  43084. }
  43085. /**
  43086. * Returns the current animation loop callback.
  43087. *
  43088. * @return {?Function} The current animation loop callback.
  43089. */
  43090. getAnimationLoop() {
  43091. return this._animation.getAnimationLoop();
  43092. }
  43093. /**
  43094. * Can be used to transfer buffer data from a storage buffer attribute
  43095. * from the GPU to the CPU in context of compute shaders.
  43096. *
  43097. * @async
  43098. * @param {BufferAttribute} attribute - The storage buffer attribute to read frm.
  43099. * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute.
  43100. * @param {number} offset - The storage buffer attribute.
  43101. * @param {number} count - The offset from which to start reading the
  43102. * @return {Promise<ArrayBuffer|ReadbackBuffer>} A promise that resolves with the buffer data when the data are ready.
  43103. */
  43104. async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) {
  43105. // tally the memory for this readback buffer
  43106. if ( target !== null && target.isReadbackBuffer ) {
  43107. if ( this.info.memoryMap.has( target ) === false ) {
  43108. this.info.createReadbackBuffer( target );
  43109. const disposeInfo = () => {
  43110. target.removeEventListener( 'dispose', disposeInfo );
  43111. this.info.destroyReadbackBuffer( target );
  43112. };
  43113. target.addEventListener( 'dispose', disposeInfo );
  43114. }
  43115. }
  43116. if ( offset % 4 !== 0 || ( count > 0 && count % 4 !== 0 ) ) {
  43117. throw new Error( 'THREE.Renderer: "getArrayBufferAsync()" offset and count must be a multiple of 4.' );
  43118. }
  43119. return await this.backend.getArrayBufferAsync( attribute, target, offset, count );
  43120. }
  43121. /**
  43122. * Returns the rendering context.
  43123. *
  43124. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  43125. */
  43126. getContext() {
  43127. return this.backend.getContext();
  43128. }
  43129. /**
  43130. * Returns the pixel ratio.
  43131. *
  43132. * @return {number} The pixel ratio.
  43133. */
  43134. getPixelRatio() {
  43135. return this._canvasTarget.getPixelRatio();
  43136. }
  43137. /**
  43138. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  43139. *
  43140. * @param {Vector2} target - The method writes the result in this target object.
  43141. * @return {Vector2} The drawing buffer size.
  43142. */
  43143. getDrawingBufferSize( target ) {
  43144. return this._canvasTarget.getDrawingBufferSize( target );
  43145. }
  43146. /**
  43147. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  43148. *
  43149. * @param {Vector2} target - The method writes the result in this target object.
  43150. * @return {Vector2} The renderer's size in logical pixels.
  43151. */
  43152. getSize( target ) {
  43153. return this._canvasTarget.getSize( target );
  43154. }
  43155. /**
  43156. * Sets the given pixel ratio and resizes the canvas if necessary.
  43157. *
  43158. * @param {number} [value=1] - The pixel ratio.
  43159. */
  43160. setPixelRatio( value = 1 ) {
  43161. this._canvasTarget.setPixelRatio( value );
  43162. }
  43163. /**
  43164. * This method allows to define the drawing buffer size by specifying
  43165. * width, height and pixel ratio all at once. The size of the drawing
  43166. * buffer is computed with this formula:
  43167. * ```js
  43168. * size.x = width * pixelRatio;
  43169. * size.y = height * pixelRatio;
  43170. * ```
  43171. *
  43172. * @param {number} width - The width in logical pixels.
  43173. * @param {number} height - The height in logical pixels.
  43174. * @param {number} pixelRatio - The pixel ratio.
  43175. */
  43176. setDrawingBufferSize( width, height, pixelRatio ) {
  43177. // Renderer can't be resized while presenting in XR.
  43178. if ( this.xr && this.xr.isPresenting ) return;
  43179. this._canvasTarget.setDrawingBufferSize( width, height, pixelRatio );
  43180. }
  43181. /**
  43182. * Sets the size of the renderer.
  43183. *
  43184. * @param {number} width - The width in logical pixels.
  43185. * @param {number} height - The height in logical pixels.
  43186. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  43187. */
  43188. setSize( width, height, updateStyle = true ) {
  43189. // Renderer can't be resized while presenting in XR.
  43190. if ( this.xr && this.xr.isPresenting ) return;
  43191. this._canvasTarget.setSize( width, height, updateStyle );
  43192. }
  43193. /**
  43194. * Defines a manual sort function for the opaque render list.
  43195. * Pass `null` to use the default sort.
  43196. *
  43197. * @param {Function} method - The sort function.
  43198. */
  43199. setOpaqueSort( method ) {
  43200. this._opaqueSort = method;
  43201. }
  43202. /**
  43203. * Defines a manual sort function for the transparent render list.
  43204. * Pass `null` to use the default sort.
  43205. *
  43206. * @param {Function} method - The sort function.
  43207. */
  43208. setTransparentSort( method ) {
  43209. this._transparentSort = method;
  43210. }
  43211. /**
  43212. * Returns the scissor rectangle.
  43213. *
  43214. * @param {Vector4} target - The method writes the result in this target object.
  43215. * @return {Vector4} The scissor rectangle.
  43216. */
  43217. getScissor( target ) {
  43218. return this._canvasTarget.getScissor( target );
  43219. }
  43220. /**
  43221. * Defines the scissor rectangle.
  43222. *
  43223. * @param {number | Vector4} x - The horizontal coordinate for the upper left corner of the box in logical pixel unit.
  43224. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  43225. * @param {number} y - The vertical coordinate for the upper left corner of the box in logical pixel unit.
  43226. * @param {number} width - The width of the scissor box in logical pixel unit.
  43227. * @param {number} height - The height of the scissor box in logical pixel unit.
  43228. */
  43229. setScissor( x, y, width, height ) {
  43230. this._canvasTarget.setScissor( x, y, width, height );
  43231. }
  43232. /**
  43233. * Returns the scissor test value.
  43234. *
  43235. * @return {boolean} Whether the scissor test should be enabled or not.
  43236. */
  43237. getScissorTest() {
  43238. return this._canvasTarget.getScissorTest();
  43239. }
  43240. /**
  43241. * Defines the scissor test.
  43242. *
  43243. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  43244. */
  43245. setScissorTest( boolean ) {
  43246. this._canvasTarget.setScissorTest( boolean );
  43247. // TODO: Move it to CanvasTarget event listener.
  43248. this.backend.setScissorTest( boolean );
  43249. }
  43250. /**
  43251. * Returns the viewport definition.
  43252. *
  43253. * @param {Vector4} target - The method writes the result in this target object.
  43254. * @return {Vector4} The viewport definition.
  43255. */
  43256. getViewport( target ) {
  43257. return this._canvasTarget.getViewport( target );
  43258. }
  43259. /**
  43260. * Defines the viewport.
  43261. *
  43262. * @param {number | Vector4} x - The horizontal coordinate for the upper left corner of the viewport origin in logical pixel unit.
  43263. * @param {number} y - The vertical coordinate for the upper left corner of the viewport origin in logical pixel unit.
  43264. * @param {number} width - The width of the viewport in logical pixel unit.
  43265. * @param {number} height - The height of the viewport in logical pixel unit.
  43266. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  43267. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  43268. */
  43269. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  43270. this._canvasTarget.setViewport( x, y, width, height, minDepth, maxDepth );
  43271. }
  43272. /**
  43273. * Returns the clear color.
  43274. *
  43275. * @param {Color} target - The method writes the result in this target object.
  43276. * @return {Color} The clear color.
  43277. */
  43278. getClearColor( target ) {
  43279. return target.copy( this._clearColor );
  43280. }
  43281. /**
  43282. * Defines the clear color and optionally the clear alpha.
  43283. *
  43284. * @param {Color} color - The clear color.
  43285. * @param {number} [alpha=1] - The clear alpha.
  43286. */
  43287. setClearColor( color, alpha = 1 ) {
  43288. this._clearColor.set( color );
  43289. this._clearColor.a = alpha;
  43290. }
  43291. /**
  43292. * Returns the clear alpha.
  43293. *
  43294. * @return {number} The clear alpha.
  43295. */
  43296. getClearAlpha() {
  43297. return this._clearColor.a;
  43298. }
  43299. /**
  43300. * Defines the clear alpha.
  43301. *
  43302. * @param {number} alpha - The clear alpha.
  43303. */
  43304. setClearAlpha( alpha ) {
  43305. this._clearColor.a = alpha;
  43306. }
  43307. /**
  43308. * Returns the clear depth.
  43309. *
  43310. * @return {number} The clear depth.
  43311. */
  43312. getClearDepth() {
  43313. return ( this.reversedDepthBuffer === true ) ? 1 - this._clearDepth : this._clearDepth;
  43314. }
  43315. /**
  43316. * Defines the clear depth.
  43317. *
  43318. * @param {number} depth - The clear depth.
  43319. */
  43320. setClearDepth( depth ) {
  43321. this._clearDepth = depth;
  43322. }
  43323. /**
  43324. * Returns the clear stencil.
  43325. *
  43326. * @return {number} The clear stencil.
  43327. */
  43328. getClearStencil() {
  43329. return this._clearStencil;
  43330. }
  43331. /**
  43332. * Defines the clear stencil.
  43333. *
  43334. * @param {number} stencil - The clear stencil.
  43335. */
  43336. setClearStencil( stencil ) {
  43337. this._clearStencil = stencil;
  43338. }
  43339. /**
  43340. * This method performs an occlusion query for the given 3D object.
  43341. * It returns `true` if the given 3D object is fully occluded by other
  43342. * 3D objects in the scene.
  43343. *
  43344. * @param {Object3D} object - The 3D object to test.
  43345. * @return {boolean} Whether the 3D object is fully occluded or not.
  43346. */
  43347. isOccluded( object ) {
  43348. const renderContext = this._currentRenderContext;
  43349. return renderContext && this.backend.isOccluded( renderContext, object );
  43350. }
  43351. /**
  43352. * Performs a manual clear operation. This method ignores `autoClear` properties.
  43353. *
  43354. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  43355. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  43356. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  43357. */
  43358. clear( color = true, depth = true, stencil = true ) {
  43359. if ( this._initialized === false ) {
  43360. throw new Error( 'Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  43361. }
  43362. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  43363. let renderContext = null;
  43364. if ( renderTarget !== null ) {
  43365. this._textures.updateRenderTarget( renderTarget );
  43366. const renderTargetData = this._textures.get( renderTarget );
  43367. renderContext = this._renderContexts.get( renderTarget, null, -1 ); // using - 1 for the call depth to get a render context for the clear operation
  43368. renderContext.textures = renderTargetData.textures;
  43369. renderContext.depthTexture = renderTargetData.depthTexture;
  43370. renderContext.width = renderTargetData.width;
  43371. renderContext.height = renderTargetData.height;
  43372. renderContext.renderTarget = renderTarget;
  43373. renderContext.depth = renderTarget.depthBuffer;
  43374. renderContext.stencil = renderTarget.stencilBuffer;
  43375. // #30329
  43376. const color = this.backend.getClearColor();
  43377. renderContext.clearColorValue.r = color.r;
  43378. renderContext.clearColorValue.g = color.g;
  43379. renderContext.clearColorValue.b = color.b;
  43380. renderContext.clearColorValue.a = color.a;
  43381. renderContext.clearDepthValue = this.getClearDepth();
  43382. renderContext.clearStencilValue = this.getClearStencil();
  43383. renderContext.activeCubeFace = this.getActiveCubeFace();
  43384. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  43385. if ( renderTarget.depthBuffer === true ) renderTargetData.depthInitialized = true;
  43386. }
  43387. this.backend.clear( color, depth, stencil, renderContext );
  43388. if ( renderTarget !== null && this._renderTarget === null ) {
  43389. this._renderOutput( renderTarget );
  43390. }
  43391. }
  43392. /**
  43393. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  43394. */
  43395. clearColor() {
  43396. this.clear( true, false, false );
  43397. }
  43398. /**
  43399. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  43400. */
  43401. clearDepth() {
  43402. this.clear( false, true, false );
  43403. }
  43404. /**
  43405. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  43406. */
  43407. clearStencil() {
  43408. this.clear( false, false, true );
  43409. }
  43410. /**
  43411. * Async version of {@link Renderer#clear}.
  43412. *
  43413. * @async
  43414. * @deprecated
  43415. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  43416. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  43417. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  43418. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  43419. */
  43420. async clearAsync( color = true, depth = true, stencil = true ) {
  43421. warnOnce( 'Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  43422. await this.init();
  43423. this.clear( color, depth, stencil );
  43424. }
  43425. /**
  43426. * Async version of {@link Renderer#clearColor}.
  43427. *
  43428. * @async
  43429. * @deprecated
  43430. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  43431. */
  43432. async clearColorAsync() {
  43433. warnOnce( 'Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  43434. this.clear( true, false, false );
  43435. }
  43436. /**
  43437. * Async version of {@link Renderer#clearDepth}.
  43438. *
  43439. * @async
  43440. * @deprecated
  43441. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  43442. */
  43443. async clearDepthAsync() {
  43444. warnOnce( 'Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  43445. this.clear( false, true, false );
  43446. }
  43447. /**
  43448. * Async version of {@link Renderer#clearStencil}.
  43449. *
  43450. * @async
  43451. * @deprecated
  43452. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  43453. */
  43454. async clearStencilAsync() {
  43455. warnOnce( 'Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  43456. this.clear( false, false, true );
  43457. }
  43458. /**
  43459. * Returns `true` if a framebuffer target is needed to perform tone mapping or color space conversion.
  43460. * If this is the case, the renderer allocates an internal render target for that purpose.
  43461. *
  43462. */
  43463. get needsFrameBufferTarget() {
  43464. const useToneMapping = this.currentToneMapping !== NoToneMapping;
  43465. const useColorSpace = this.currentColorSpace !== ColorManagement.workingColorSpace;
  43466. return useToneMapping || useColorSpace;
  43467. }
  43468. /**
  43469. * The number of samples used for multi-sample anti-aliasing (MSAA).
  43470. *
  43471. * @type {number}
  43472. * @default 0
  43473. */
  43474. get samples() {
  43475. return this._samples;
  43476. }
  43477. /**
  43478. * The current number of samples used for multi-sample anti-aliasing (MSAA).
  43479. *
  43480. * When rendering to a custom render target, the number of samples of that render target is used.
  43481. * If the renderer needs an internal framebuffer target for tone mapping or color space conversion,
  43482. * the number of samples is set to 0.
  43483. *
  43484. * @type {number}
  43485. */
  43486. get currentSamples() {
  43487. let samples = this._samples;
  43488. if ( this._renderTarget !== null ) {
  43489. samples = this._renderTarget.samples;
  43490. } else if ( this.needsFrameBufferTarget ) {
  43491. samples = 0;
  43492. }
  43493. return samples;
  43494. }
  43495. /**
  43496. * The current tone mapping of the renderer. When not producing screen output,
  43497. * the tone mapping is always `NoToneMapping`.
  43498. *
  43499. * @type {number}
  43500. */
  43501. get currentToneMapping() {
  43502. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  43503. }
  43504. /**
  43505. * The current color space of the renderer. When not producing screen output,
  43506. * the color space is always the working color space.
  43507. *
  43508. * @type {string}
  43509. */
  43510. get currentColorSpace() {
  43511. return this.isOutputTarget ? this.outputColorSpace : ColorManagement.workingColorSpace;
  43512. }
  43513. /**
  43514. * Returns `true` if the rendering settings are set to screen output.
  43515. *
  43516. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  43517. */
  43518. get isOutputTarget() {
  43519. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  43520. }
  43521. /**
  43522. * Frees all internal resources of the renderer. Call this method if the renderer
  43523. * is no longer in use by your app.
  43524. */
  43525. dispose() {
  43526. if ( this._initialized === true ) {
  43527. this.info.dispose();
  43528. this.backend.dispose();
  43529. this._animation.dispose();
  43530. this._objects.dispose();
  43531. this._geometries.dispose();
  43532. this._pipelines.dispose();
  43533. this._nodes.dispose();
  43534. this._bindings.dispose();
  43535. this._renderLists.dispose();
  43536. this._renderContexts.dispose();
  43537. this._textures.dispose();
  43538. for ( const canvasTarget of this._frameBufferTargets.keys() ) {
  43539. canvasTarget.dispose();
  43540. }
  43541. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  43542. if ( queryPool !== null ) queryPool.dispose();
  43543. } );
  43544. }
  43545. this.setRenderTarget( null );
  43546. this.setAnimationLoop( null );
  43547. }
  43548. /**
  43549. * Sets the given render target. Calling this method means the renderer does not
  43550. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  43551. * Use `null` as the first argument to reset the state.
  43552. *
  43553. * @param {?RenderTarget} renderTarget - The render target to set.
  43554. * @param {number} [activeCubeFace=0] - The active cube face.
  43555. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  43556. */
  43557. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  43558. this._renderTarget = renderTarget;
  43559. this._activeCubeFace = activeCubeFace;
  43560. this._activeMipmapLevel = activeMipmapLevel;
  43561. }
  43562. /**
  43563. * Returns the current render target.
  43564. *
  43565. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  43566. */
  43567. getRenderTarget() {
  43568. return this._renderTarget;
  43569. }
  43570. /**
  43571. * Sets the output render target for the renderer.
  43572. *
  43573. * @param {?RenderTarget} renderTarget - The render target to set as the output target.
  43574. */
  43575. setOutputRenderTarget( renderTarget ) {
  43576. this._outputRenderTarget = renderTarget;
  43577. }
  43578. /**
  43579. * Returns the current output target.
  43580. *
  43581. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  43582. */
  43583. getOutputRenderTarget() {
  43584. return this._outputRenderTarget;
  43585. }
  43586. /**
  43587. * Sets the canvas target. The canvas target manages the HTML canvas
  43588. * or the offscreen canvas the renderer draws into.
  43589. *
  43590. * @param {CanvasTarget} canvasTarget - The canvas target.
  43591. */
  43592. setCanvasTarget( canvasTarget ) {
  43593. this._canvasTarget.removeEventListener( 'resize', this._onCanvasTargetResize );
  43594. this._canvasTarget = canvasTarget;
  43595. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  43596. }
  43597. /**
  43598. * Returns the current canvas target.
  43599. *
  43600. * @return {CanvasTarget} The current canvas target.
  43601. */
  43602. getCanvasTarget() {
  43603. return this._canvasTarget;
  43604. }
  43605. /**
  43606. * Resets the renderer to the initial state before WebXR started.
  43607. *
  43608. * @private
  43609. */
  43610. _resetXRState() {
  43611. this.backend.setXRTarget( null );
  43612. this.setOutputRenderTarget( null );
  43613. this.setRenderTarget( null );
  43614. for ( const canvasTarget of this._frameBufferTargets.keys() ) {
  43615. canvasTarget.dispose();
  43616. }
  43617. }
  43618. /**
  43619. * Callback for {@link Renderer#setRenderObjectFunction}.
  43620. *
  43621. * @callback renderObjectFunction
  43622. * @param {Object3D} object - The 3D object.
  43623. * @param {Scene} scene - The scene the 3D object belongs to.
  43624. * @param {Camera} camera - The camera the object should be rendered with.
  43625. * @param {BufferGeometry} geometry - The object's geometry.
  43626. * @param {Material} material - The object's material.
  43627. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  43628. * @param {LightsNode} lightsNode - The current lights node.
  43629. * @param {ClippingContext} clippingContext - The clipping context.
  43630. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  43631. */
  43632. /**
  43633. * Sets the given render object function. Calling this method overwrites the default implementation
  43634. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  43635. * if you want to modify the way objects are rendered. For example you can define things like "every
  43636. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  43637. * The custom function must always call `renderObject()` in its implementation.
  43638. *
  43639. * Use `null` as the first argument to reset the state.
  43640. *
  43641. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  43642. */
  43643. setRenderObjectFunction( renderObjectFunction ) {
  43644. this._renderObjectFunction = renderObjectFunction;
  43645. }
  43646. /**
  43647. * Returns the current render object function.
  43648. *
  43649. * @return {?Function} The current render object function. Returns `null` if no function is set.
  43650. */
  43651. getRenderObjectFunction() {
  43652. return this._renderObjectFunction;
  43653. }
  43654. /**
  43655. * Execute a single or an array of compute nodes. This method can only be called
  43656. * if the renderer has been initialized.
  43657. *
  43658. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  43659. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  43660. * - A single number representing count, or
  43661. * - An array [x, y, z] representing dispatch size, or
  43662. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  43663. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  43664. */
  43665. compute( computeNodes, dispatchSize = null ) {
  43666. if ( this._isDeviceLost === true ) return;
  43667. if ( this._initialized === false ) {
  43668. warn( 'Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  43669. return this.computeAsync( computeNodes, dispatchSize );
  43670. }
  43671. //
  43672. const nodeFrame = this._nodes.nodeFrame;
  43673. const previousRenderId = nodeFrame.renderId;
  43674. //
  43675. this.info.calls ++;
  43676. this.info.compute.calls ++;
  43677. this.info.compute.frameCalls ++;
  43678. nodeFrame.renderId = this.info.calls;
  43679. //
  43680. this.backend.updateTimeStampUID( computeNodes );
  43681. this.inspector.beginCompute( this.backend.getTimestampUID( computeNodes ), computeNodes );
  43682. //
  43683. const backend = this.backend;
  43684. const pipelines = this._pipelines;
  43685. const bindings = this._bindings;
  43686. const nodes = this._nodes;
  43687. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  43688. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  43689. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  43690. }
  43691. backend.beginCompute( computeNodes );
  43692. for ( const computeNode of computeList ) {
  43693. // onInit
  43694. if ( pipelines.has( computeNode ) === false ) {
  43695. const dispose = () => {
  43696. computeNode.removeEventListener( 'dispose', dispose );
  43697. pipelines.delete( computeNode );
  43698. bindings.deleteForCompute( computeNode );
  43699. nodes.delete( computeNode );
  43700. };
  43701. computeNode.addEventListener( 'dispose', dispose );
  43702. //
  43703. const onInitFn = computeNode.onInitFunction;
  43704. if ( onInitFn !== null ) {
  43705. onInitFn.call( computeNode, { renderer: this } );
  43706. }
  43707. }
  43708. nodes.updateForCompute( computeNode );
  43709. bindings.updateForCompute( computeNode );
  43710. const computeBindings = bindings.getForCompute( computeNode );
  43711. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  43712. backend.compute( computeNodes, computeNode, computeBindings, computePipeline, dispatchSize );
  43713. }
  43714. backend.finishCompute( computeNodes );
  43715. //
  43716. nodeFrame.renderId = previousRenderId;
  43717. //
  43718. this.inspector.finishCompute( this.backend.getTimestampUID( computeNodes ) );
  43719. }
  43720. /**
  43721. * Execute a single or an array of compute nodes.
  43722. *
  43723. * @async
  43724. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  43725. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  43726. * - A single number representing count, or
  43727. * - An array [x, y, z] representing dispatch size, or
  43728. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  43729. * @return {Promise} A Promise that resolve when the compute has finished.
  43730. */
  43731. async computeAsync( computeNodes, dispatchSize = null ) {
  43732. if ( this._initialized === false ) await this.init();
  43733. this.compute( computeNodes, dispatchSize );
  43734. }
  43735. /**
  43736. * Checks if the given feature is supported by the selected backend.
  43737. *
  43738. * @async
  43739. * @deprecated
  43740. * @param {string} name - The feature's name.
  43741. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  43742. */
  43743. async hasFeatureAsync( name ) {
  43744. warnOnce( 'Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  43745. await this.init();
  43746. return this.hasFeature( name );
  43747. }
  43748. async resolveTimestampsAsync( type = 'render' ) {
  43749. if ( this._initialized === false ) await this.init();
  43750. return this.backend.resolveTimestampsAsync( type );
  43751. }
  43752. /**
  43753. * Checks if the given feature is supported by the selected backend. If the
  43754. * renderer has not been initialized, this method always returns `false`.
  43755. *
  43756. * @param {string} name - The feature's name.
  43757. * @return {boolean} Whether the feature is supported or not.
  43758. */
  43759. hasFeature( name ) {
  43760. if ( this._initialized === false ) {
  43761. throw new Error( 'Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  43762. }
  43763. return this.backend.hasFeature( name );
  43764. }
  43765. /**
  43766. * Returns `true` when the renderer has been initialized.
  43767. *
  43768. * @return {boolean} Whether the renderer has been initialized or not.
  43769. */
  43770. hasInitialized() {
  43771. return this._initialized;
  43772. }
  43773. /**
  43774. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  43775. * (which can cause noticeable lags due to decode and GPU upload overhead).
  43776. *
  43777. * @async
  43778. * @deprecated
  43779. * @param {Texture} texture - The texture.
  43780. * @return {Promise} A Promise that resolves when the texture has been initialized.
  43781. */
  43782. async initTextureAsync( texture ) {
  43783. warnOnce( 'Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  43784. await this.init();
  43785. this.initTexture( texture );
  43786. }
  43787. /**
  43788. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  43789. * (which can cause noticeable lags due to decode and GPU upload overhead).
  43790. *
  43791. * This method can only be used if the renderer has been initialized.
  43792. *
  43793. * @param {Texture} texture - The texture.
  43794. */
  43795. initTexture( texture ) {
  43796. if ( this._initialized === false ) {
  43797. throw new Error( 'Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  43798. }
  43799. this._textures.updateTexture( texture );
  43800. }
  43801. /**
  43802. * Initializes the given render target.
  43803. *
  43804. * @param {RenderTarget} renderTarget - The render target to intialize.
  43805. */
  43806. initRenderTarget( renderTarget ) {
  43807. if ( this._initialized === false ) {
  43808. throw new Error( 'Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  43809. }
  43810. this._textures.updateRenderTarget( renderTarget );
  43811. const renderTargetData = this._textures.get( renderTarget );
  43812. const renderContext = this._renderContexts.get( renderTarget );
  43813. renderContext.textures = renderTargetData.textures;
  43814. renderContext.depthTexture = renderTargetData.depthTexture;
  43815. renderContext.width = renderTargetData.width;
  43816. renderContext.height = renderTargetData.height;
  43817. renderContext.renderTarget = renderTarget;
  43818. renderContext.depth = renderTarget.depthBuffer;
  43819. renderContext.stencil = renderTarget.stencilBuffer;
  43820. this.backend.initRenderTarget( renderContext );
  43821. }
  43822. /**
  43823. * Copies the current bound framebuffer into the given texture.
  43824. *
  43825. * @param {FramebufferTexture} framebufferTexture - The texture.
  43826. * @param {?(Vector2|Vector4)} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  43827. */
  43828. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  43829. if ( rectangle !== null ) {
  43830. if ( rectangle.isVector2 ) {
  43831. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  43832. } else if ( rectangle.isVector4 ) {
  43833. rectangle = _vector4.copy( rectangle ).floor();
  43834. } else {
  43835. error( 'Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  43836. return;
  43837. }
  43838. } else {
  43839. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  43840. }
  43841. //
  43842. let renderContext = this._currentRenderContext;
  43843. let renderTarget;
  43844. if ( renderContext !== null ) {
  43845. renderTarget = renderContext.renderTarget;
  43846. } else {
  43847. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  43848. if ( renderTarget !== null ) {
  43849. this._textures.updateRenderTarget( renderTarget );
  43850. renderContext = this._textures.get( renderTarget );
  43851. }
  43852. }
  43853. //
  43854. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  43855. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  43856. this._inspector.copyFramebufferToTexture( framebufferTexture );
  43857. }
  43858. /**
  43859. * Copies data of the given source texture into a destination texture.
  43860. *
  43861. * @param {Texture} srcTexture - The source texture.
  43862. * @param {Texture} dstTexture - The destination texture.
  43863. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  43864. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  43865. * @param {number} [srcLevel=0] - The source mip level to copy from.
  43866. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  43867. */
  43868. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  43869. this._textures.updateTexture( srcTexture );
  43870. this._textures.updateTexture( dstTexture );
  43871. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  43872. this._inspector.copyTextureToTexture( srcTexture, dstTexture );
  43873. }
  43874. /**
  43875. * Reads pixel data from the given render target.
  43876. *
  43877. * @async
  43878. * @param {RenderTarget} renderTarget - The render target to read from.
  43879. * @param {number} x - The `x` coordinate of the copy region's origin.
  43880. * @param {number} y - The `y` coordinate of the copy region's origin.
  43881. * @param {number} width - The width of the copy region.
  43882. * @param {number} height - The height of the copy region.
  43883. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  43884. * @param {number} [faceIndex=0] - The active cube face index.
  43885. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  43886. */
  43887. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  43888. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  43889. }
  43890. /**
  43891. * Analyzes the given 3D object's hierarchy and builds render lists from the
  43892. * processed hierarchy.
  43893. *
  43894. * @private
  43895. * @param {Object3D} object - The 3D object to process (usually a scene).
  43896. * @param {Camera} camera - The camera the object is rendered with.
  43897. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  43898. * @param {RenderList} renderList - The current render list.
  43899. * @param {ClippingContext} clippingContext - The current clipping context.
  43900. */
  43901. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  43902. if ( object.visible === false ) return;
  43903. const visible = object.layers.test( camera.layers );
  43904. if ( visible ) {
  43905. if ( object.isGroup ) {
  43906. groupOrder = object.renderOrder;
  43907. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  43908. } else if ( object.isLOD ) {
  43909. if ( object.autoUpdate === true ) object.update( camera );
  43910. } else if ( object.isLight ) {
  43911. renderList.pushLight( object );
  43912. } else if ( object.isSprite ) {
  43913. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  43914. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  43915. if ( this.sortObjects === true ) {
  43916. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  43917. }
  43918. const { geometry, material } = object;
  43919. if ( material.visible ) {
  43920. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  43921. }
  43922. }
  43923. } else if ( object.isLineLoop ) {
  43924. error( 'Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  43925. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  43926. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  43927. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  43928. const { geometry, material } = object;
  43929. if ( this.sortObjects === true ) {
  43930. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  43931. _vector4
  43932. .copy( geometry.boundingSphere.center )
  43933. .applyMatrix4( object.matrixWorld )
  43934. .applyMatrix4( _projScreenMatrix );
  43935. }
  43936. if ( Array.isArray( material ) ) {
  43937. const groups = geometry.groups;
  43938. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  43939. const group = groups[ i ];
  43940. const groupMaterial = material[ group.materialIndex ];
  43941. if ( groupMaterial && groupMaterial.visible ) {
  43942. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  43943. }
  43944. }
  43945. } else if ( material.visible ) {
  43946. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  43947. }
  43948. }
  43949. }
  43950. }
  43951. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  43952. const baseRenderList = renderList;
  43953. // replace render list
  43954. renderList = this._renderLists.get( object, camera );
  43955. renderList.begin();
  43956. baseRenderList.pushBundle( {
  43957. bundleGroup: object,
  43958. camera,
  43959. renderList,
  43960. } );
  43961. renderList.finish();
  43962. }
  43963. const children = object.children;
  43964. for ( let i = 0, l = children.length; i < l; i ++ ) {
  43965. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  43966. }
  43967. }
  43968. /**
  43969. * Renders the given render bundles.
  43970. *
  43971. * @private
  43972. * @param {Array<Object>} bundles - Array with render bundle data.
  43973. * @param {Scene} sceneRef - The scene the render bundles belong to.
  43974. * @param {LightsNode} lightsNode - The current lights node.
  43975. */
  43976. _renderBundles( bundles, sceneRef, lightsNode ) {
  43977. for ( const bundle of bundles ) {
  43978. this._renderBundle( bundle, sceneRef, lightsNode );
  43979. }
  43980. }
  43981. /**
  43982. * Renders the transparent objects from the given render lists.
  43983. *
  43984. * @private
  43985. * @param {Array<Object>} renderList - The transparent render list.
  43986. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  43987. * @param {Camera} camera - The camera the render list should be rendered with.
  43988. * @param {Scene} scene - The scene the render list belongs to.
  43989. * @param {LightsNode} lightsNode - The current lights node.
  43990. */
  43991. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  43992. if ( doublePassList.length > 0 ) {
  43993. // render back side
  43994. for ( const { material } of doublePassList ) {
  43995. material.side = BackSide;
  43996. }
  43997. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  43998. // render front side
  43999. for ( const { material } of doublePassList ) {
  44000. material.side = FrontSide;
  44001. }
  44002. this._renderObjects( renderList, camera, scene, lightsNode );
  44003. // restore
  44004. for ( const { material } of doublePassList ) {
  44005. material.side = DoubleSide;
  44006. }
  44007. } else {
  44008. this._renderObjects( renderList, camera, scene, lightsNode );
  44009. }
  44010. }
  44011. /**
  44012. * Renders the objects from the given render list.
  44013. *
  44014. * @private
  44015. * @param {Array<Object>} renderList - The render list.
  44016. * @param {Camera} camera - The camera the render list should be rendered with.
  44017. * @param {Scene} scene - The scene the render list belongs to.
  44018. * @param {LightsNode} lightsNode - The current lights node.
  44019. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  44020. */
  44021. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  44022. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  44023. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  44024. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  44025. }
  44026. }
  44027. /**
  44028. * Retrieves shadow nodes for the given material. This is used to setup shadow passes.
  44029. * The result is cached per material and updated when the material's version changes.
  44030. *
  44031. * @private
  44032. * @param {Material} material
  44033. * @returns {Object} - The shadow nodes for the material.
  44034. */
  44035. _getShadowNodes( material ) {
  44036. const version = material.version;
  44037. let cache = this._cacheShadowNodes.get( material );
  44038. if ( cache === undefined || cache.version !== version ) {
  44039. const hasMap = material.map !== null;
  44040. const hasColorNode = material.colorNode && material.colorNode.isNode;
  44041. const hasCastShadowNode = material.castShadowNode && material.castShadowNode.isNode;
  44042. const hasMaskNode = ( material.maskShadowNode && material.maskShadowNode.isNode ) || ( material.maskNode && material.maskNode.isNode );
  44043. let positionNode = null;
  44044. let colorNode = null;
  44045. let depthNode = null;
  44046. if ( hasMap || hasColorNode || hasCastShadowNode || hasMaskNode ) {
  44047. let shadowRGB;
  44048. let shadowAlpha;
  44049. if ( hasCastShadowNode ) {
  44050. shadowRGB = material.castShadowNode.rgb;
  44051. shadowAlpha = material.castShadowNode.a;
  44052. if ( this.shadowMap.transmitted !== true ) {
  44053. warnOnce( 'Renderer: `shadowMap.transmitted` needs to be set to `true` when using `material.castShadowNode`.' );
  44054. }
  44055. } else {
  44056. shadowRGB = vec3( 0 );
  44057. shadowAlpha = float( 1 );
  44058. }
  44059. if ( hasMap ) {
  44060. shadowAlpha = shadowAlpha.mul( reference( 'map', 'texture', material ).a );
  44061. }
  44062. if ( hasColorNode ) {
  44063. shadowAlpha = shadowAlpha.mul( material.colorNode.a );
  44064. }
  44065. colorNode = vec4( shadowRGB, shadowAlpha );
  44066. if ( hasMaskNode ) {
  44067. const maskNode = material.maskShadowNode || material.maskNode;
  44068. colorNode = Fn( ( [ color ] ) => {
  44069. maskNode.not().discard();
  44070. return color;
  44071. } )( colorNode );
  44072. }
  44073. }
  44074. if ( material.depthNode && material.depthNode.isNode ) {
  44075. depthNode = material.depthNode;
  44076. }
  44077. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  44078. positionNode = material.castShadowPositionNode;
  44079. } else if ( material.positionNode && material.positionNode.isNode ) {
  44080. positionNode = material.positionNode;
  44081. }
  44082. cache = {
  44083. version,
  44084. colorNode,
  44085. depthNode,
  44086. positionNode
  44087. };
  44088. this._cacheShadowNodes.set( material, cache );
  44089. }
  44090. return cache;
  44091. }
  44092. /**
  44093. * This method represents the default render object function that manages the render lifecycle
  44094. * of the object.
  44095. *
  44096. * @param {Object3D} object - The 3D object.
  44097. * @param {Scene} scene - The scene the 3D object belongs to.
  44098. * @param {Camera} camera - The camera the object should be rendered with.
  44099. * @param {BufferGeometry} geometry - The object's geometry.
  44100. * @param {Material} material - The object's material.
  44101. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  44102. * @param {LightsNode} lightsNode - The current lights node.
  44103. * @param {?ClippingContext} clippingContext - The clipping context.
  44104. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  44105. */
  44106. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  44107. let materialOverride = false;
  44108. let materialColorNode;
  44109. let materialDepthNode;
  44110. let materialPositionNode;
  44111. let materialSide;
  44112. //
  44113. object.onBeforeRender( this, scene, camera, geometry, material, group );
  44114. //
  44115. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  44116. const overrideMaterial = scene.overrideMaterial;
  44117. materialOverride = true;
  44118. // store original nodes
  44119. materialColorNode = ( overrideMaterial.isNodeMaterial ) ? overrideMaterial.colorNode : null;
  44120. materialDepthNode = ( overrideMaterial.isNodeMaterial ) ? overrideMaterial.depthNode : null;
  44121. materialPositionNode = ( overrideMaterial.isNodeMaterial ) ? overrideMaterial.positionNode : null;
  44122. materialSide = scene.overrideMaterial.side;
  44123. if ( material.positionNode && material.positionNode.isNode ) {
  44124. overrideMaterial.positionNode = material.positionNode;
  44125. }
  44126. overrideMaterial.alphaTest = material.alphaTest;
  44127. overrideMaterial.alphaMap = material.alphaMap;
  44128. overrideMaterial.transparent = material.transparent || material.transmission > 0 ||
  44129. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  44130. ( material.backdropNode && material.backdropNode.isNode );
  44131. if ( overrideMaterial.isShadowPassMaterial ) {
  44132. const { colorNode, depthNode, positionNode } = this._getShadowNodes( material );
  44133. if ( this.shadowMap.type === VSMShadowMap ) {
  44134. overrideMaterial.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  44135. } else {
  44136. overrideMaterial.side = ( material.shadowSide !== null ) ? material.shadowSide : _shadowSide[ material.side ];
  44137. }
  44138. if ( colorNode !== null ) overrideMaterial.colorNode = colorNode;
  44139. if ( depthNode !== null ) overrideMaterial.depthNode = depthNode;
  44140. if ( positionNode !== null ) overrideMaterial.positionNode = positionNode;
  44141. }
  44142. material = overrideMaterial;
  44143. }
  44144. //
  44145. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  44146. material.side = BackSide;
  44147. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  44148. material.side = FrontSide;
  44149. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  44150. material.side = DoubleSide;
  44151. } else {
  44152. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  44153. }
  44154. //
  44155. if ( materialOverride ) {
  44156. scene.overrideMaterial.colorNode = materialColorNode;
  44157. scene.overrideMaterial.depthNode = materialDepthNode;
  44158. scene.overrideMaterial.positionNode = materialPositionNode;
  44159. scene.overrideMaterial.side = materialSide;
  44160. }
  44161. //
  44162. object.onAfterRender( this, scene, camera, geometry, material, group );
  44163. }
  44164. /**
  44165. * Checks if the given compatibility is supported by the selected backend.
  44166. *
  44167. * @param {string} name - The compatibility's name.
  44168. * @return {boolean} Whether the compatibility is supported or not.
  44169. */
  44170. hasCompatibility( name ) {
  44171. if ( this._initialized === false ) {
  44172. throw new Error( 'Renderer: .hasCompatibility() called before the backend is initialized. Use "await renderer.init();" before using this method.' );
  44173. }
  44174. return this.backend.hasCompatibility( name );
  44175. }
  44176. /**
  44177. * This method represents the default `_handleObjectFunction` implementation which creates
  44178. * a render object from the given data and performs the draw command with the selected backend.
  44179. *
  44180. * @private
  44181. * @param {Object3D} object - The 3D object.
  44182. * @param {Material} material - The object's material.
  44183. * @param {Scene} scene - The scene the 3D object belongs to.
  44184. * @param {Camera} camera - The camera the object should be rendered with.
  44185. * @param {LightsNode} lightsNode - The current lights node.
  44186. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  44187. * @param {ClippingContext} clippingContext - The clipping context.
  44188. * @param {string} [passId] - An optional ID for identifying the pass.
  44189. */
  44190. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  44191. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  44192. renderObject.drawRange = object.geometry.drawRange;
  44193. renderObject.group = group;
  44194. if ( this._currentRenderBundle !== null ) {
  44195. const renderBundleData = this.backend.get( this._currentRenderBundle );
  44196. renderBundleData.renderObjects.push( renderObject );
  44197. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  44198. }
  44199. //
  44200. const needsRefresh = this._nodes.needsRefresh( renderObject );
  44201. if ( needsRefresh ) {
  44202. this._nodes.updateBefore( renderObject );
  44203. this._geometries.updateForRender( renderObject );
  44204. this._nodes.updateForRender( renderObject );
  44205. this._bindings.updateForRender( renderObject );
  44206. }
  44207. this._pipelines.updateForRender( renderObject );
  44208. //
  44209. if ( this._pipelines.isReady( renderObject ) ) {
  44210. this.backend.draw( renderObject, this.info );
  44211. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  44212. }
  44213. }
  44214. /**
  44215. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  44216. * Used in `compileAsync()`.
  44217. *
  44218. * @private
  44219. * @param {Object3D} object - The 3D object.
  44220. * @param {Material} material - The object's material.
  44221. * @param {Scene} scene - The scene the 3D object belongs to.
  44222. * @param {Camera} camera - The camera the object should be rendered with.
  44223. * @param {LightsNode} lightsNode - The current lights node.
  44224. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  44225. * @param {ClippingContext} clippingContext - The clipping context.
  44226. * @param {string} [passId] - An optional ID for identifying the pass.
  44227. */
  44228. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  44229. // If in async compilation mode, queue the work for sequential execution
  44230. if ( this._compilationPromises !== null ) {
  44231. // Store work items instead of promises - will be processed sequentially
  44232. this._compilationPromises.push( {
  44233. object,
  44234. material,
  44235. scene,
  44236. camera,
  44237. lightsNode,
  44238. group,
  44239. clippingContext,
  44240. passId,
  44241. renderContext: this._currentRenderContext
  44242. } );
  44243. return;
  44244. }
  44245. // Sync path
  44246. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  44247. renderObject.drawRange = object.geometry.drawRange;
  44248. renderObject.group = group;
  44249. //
  44250. this._nodes.updateBefore( renderObject );
  44251. this._geometries.updateForRender( renderObject );
  44252. this._nodes.updateForRender( renderObject );
  44253. this._bindings.updateForRender( renderObject );
  44254. this._pipelines.getForRender( renderObject, this._compilationPromises );
  44255. this._nodes.updateAfter( renderObject );
  44256. }
  44257. /**
  44258. * Callback when the canvas has been resized.
  44259. *
  44260. * @private
  44261. */
  44262. _onCanvasTargetResize() {
  44263. if ( this._initialized ) this.backend.updateSize();
  44264. }
  44265. /**
  44266. * Alias for `compileAsync()`.
  44267. *
  44268. * @method
  44269. * @param {Object3D} scene - The scene or 3D object to precompile.
  44270. * @param {Camera} camera - The camera that is used to render the scene.
  44271. * @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.
  44272. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  44273. */
  44274. get compile() {
  44275. return this.compileAsync;
  44276. }
  44277. }
  44278. /**
  44279. * A binding represents the connection between a resource (like a texture, sampler
  44280. * or uniform buffer) and the resource definition in a shader stage.
  44281. *
  44282. * This module is an abstract base class for all concrete bindings types.
  44283. *
  44284. * @abstract
  44285. * @private
  44286. */
  44287. class Binding {
  44288. /**
  44289. * Constructs a new binding.
  44290. *
  44291. * @param {string} [name=''] - The binding's name.
  44292. */
  44293. constructor( name = '' ) {
  44294. /**
  44295. * The binding's name.
  44296. *
  44297. * @type {string}
  44298. */
  44299. this.name = name;
  44300. /**
  44301. * A bitmask that defines in what shader stages the
  44302. * binding's resource is accessible.
  44303. *
  44304. * @type {number}
  44305. */
  44306. this.visibility = 0;
  44307. }
  44308. /**
  44309. * Makes sure binding's resource is visible for the given shader stage.
  44310. *
  44311. * @param {number} visibility - The shader stage.
  44312. */
  44313. setVisibility( visibility ) {
  44314. this.visibility |= visibility;
  44315. }
  44316. /**
  44317. * The shader stages in which the binding's resource is visible.
  44318. *
  44319. * @return {number} The visibility bitmask.
  44320. */
  44321. getVisibility() {
  44322. return this.visibility;
  44323. }
  44324. /**
  44325. * Clones the binding.
  44326. *
  44327. * @return {Binding} The cloned binding.
  44328. */
  44329. clone() {
  44330. return Object.assign( new this.constructor(), this );
  44331. }
  44332. }
  44333. /**
  44334. * This function is usually called with the length in bytes of an array buffer.
  44335. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  44336. *
  44337. * @function
  44338. * @param {number} floatLength - The buffer length.
  44339. * @return {number} The padded length.
  44340. */
  44341. function getFloatLength( floatLength ) {
  44342. // ensure chunk size alignment (STD140 layout)
  44343. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  44344. }
  44345. /**
  44346. * Represents a buffer binding type.
  44347. *
  44348. * @private
  44349. * @abstract
  44350. * @augments Binding
  44351. */
  44352. class Buffer extends Binding {
  44353. /**
  44354. * Constructs a new buffer.
  44355. *
  44356. * @param {string} name - The buffer's name.
  44357. * @param {TypedArray} [buffer=null] - The buffer.
  44358. */
  44359. constructor( name, buffer = null ) {
  44360. super( name );
  44361. /**
  44362. * This flag can be used for type testing.
  44363. *
  44364. * @type {boolean}
  44365. * @readonly
  44366. * @default true
  44367. */
  44368. this.isBuffer = true;
  44369. /**
  44370. * The bytes per element.
  44371. *
  44372. * @type {number}
  44373. */
  44374. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  44375. /**
  44376. * A reference to the internal buffer.
  44377. *
  44378. * @private
  44379. * @type {TypedArray}
  44380. */
  44381. this._buffer = buffer;
  44382. /**
  44383. * An array of update ranges.
  44384. *
  44385. * @private
  44386. * @type {Array<{start: number, count: number}>}
  44387. */
  44388. this._updateRanges = [];
  44389. }
  44390. /**
  44391. * The array of update ranges.
  44392. *
  44393. * @type {Array<{start: number, count: number}>}
  44394. */
  44395. get updateRanges() {
  44396. return this._updateRanges;
  44397. }
  44398. /**
  44399. * Adds an update range.
  44400. *
  44401. * @param {number} start - The start index.
  44402. * @param {number} count - The number of elements.
  44403. */
  44404. addUpdateRange( start, count ) {
  44405. this.updateRanges.push( { start, count } );
  44406. }
  44407. /**
  44408. * Clears all update ranges.
  44409. */
  44410. clearUpdateRanges() {
  44411. this.updateRanges.length = 0;
  44412. }
  44413. /**
  44414. * The buffer's byte length.
  44415. *
  44416. * @type {number}
  44417. * @readonly
  44418. */
  44419. get byteLength() {
  44420. return getFloatLength( this._buffer.byteLength );
  44421. }
  44422. /**
  44423. * A reference to the internal buffer.
  44424. *
  44425. * @type {Float32Array}
  44426. * @readonly
  44427. */
  44428. get buffer() {
  44429. return this._buffer;
  44430. }
  44431. /**
  44432. * Updates the binding.
  44433. *
  44434. * @return {boolean} Whether the buffer has been updated and must be
  44435. * uploaded to the GPU.
  44436. */
  44437. update() {
  44438. return true;
  44439. }
  44440. /**
  44441. * Releases the buffer.
  44442. */
  44443. release() {
  44444. this._buffer = null;
  44445. }
  44446. }
  44447. /**
  44448. * Represents a uniform buffer binding type.
  44449. *
  44450. * @private
  44451. * @augments Buffer
  44452. */
  44453. class UniformBuffer extends Buffer {
  44454. /**
  44455. * Constructs a new uniform buffer.
  44456. *
  44457. * @param {string} name - The buffer's name.
  44458. * @param {TypedArray} [buffer=null] - The buffer.
  44459. */
  44460. constructor( name, buffer = null ) {
  44461. super( name, buffer );
  44462. /**
  44463. * This flag can be used for type testing.
  44464. *
  44465. * @type {boolean}
  44466. * @readonly
  44467. * @default true
  44468. */
  44469. this.isUniformBuffer = true;
  44470. }
  44471. }
  44472. let _id$4 = 0;
  44473. /**
  44474. * A special form of uniform buffer binding type.
  44475. * It's buffer value is managed by a node object.
  44476. *
  44477. * @private
  44478. * @augments UniformBuffer
  44479. */
  44480. class NodeUniformBuffer extends UniformBuffer {
  44481. /**
  44482. * Constructs a new node-based uniform buffer.
  44483. *
  44484. * @param {BufferNode} nodeUniform - The uniform buffer node.
  44485. * @param {UniformGroupNode} groupNode - The uniform group node.
  44486. */
  44487. constructor( nodeUniform, groupNode ) {
  44488. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  44489. /**
  44490. * The uniform buffer node.
  44491. *
  44492. * @type {BufferNode}
  44493. */
  44494. this.nodeUniform = nodeUniform;
  44495. /**
  44496. * The uniform group node.
  44497. *
  44498. * @type {UniformGroupNode}
  44499. */
  44500. this.groupNode = groupNode;
  44501. /**
  44502. * This flag can be used for type testing.
  44503. *
  44504. * @type {boolean}
  44505. * @readonly
  44506. * @default true
  44507. */
  44508. this.isNodeUniformBuffer = true;
  44509. }
  44510. /**
  44511. * The array of update ranges.
  44512. *
  44513. * @param {Array<{start: number, count: number}>} value - The update ranges.
  44514. */
  44515. set updateRanges( value ) {
  44516. this.nodeUniform.updateRanges = value;
  44517. }
  44518. /**
  44519. * The array of update ranges.
  44520. *
  44521. * @type {Array<{start: number, count: number}>}
  44522. */
  44523. get updateRanges() {
  44524. return this.nodeUniform.updateRanges;
  44525. }
  44526. /**
  44527. * Adds a range of data in the data array to be updated on the GPU.
  44528. *
  44529. * @param {number} start - Position at which to start update.
  44530. * @param {number} count - The number of components to update.
  44531. */
  44532. addUpdateRange( start, count ) {
  44533. this.nodeUniform.addUpdateRange( start, count );
  44534. }
  44535. /**
  44536. * Clears all update ranges.
  44537. */
  44538. clearUpdateRanges() {
  44539. this.nodeUniform.clearUpdateRanges();
  44540. }
  44541. /**
  44542. * The buffer's byte length.
  44543. *
  44544. * @type {number}
  44545. * @readonly
  44546. */
  44547. get byteLength() {
  44548. return getFloatLength( this.buffer.byteLength );
  44549. }
  44550. /**
  44551. * The uniform buffer.
  44552. *
  44553. * @type {Float32Array}
  44554. */
  44555. get buffer() {
  44556. return this.nodeUniform.value;
  44557. }
  44558. }
  44559. /**
  44560. * This class represents a uniform buffer binding but with
  44561. * an API that allows to maintain individual uniform objects.
  44562. *
  44563. * @private
  44564. * @augments UniformBuffer
  44565. */
  44566. class UniformsGroup extends UniformBuffer {
  44567. /**
  44568. * Constructs a new uniforms group.
  44569. *
  44570. * @param {string} name - The group's name.
  44571. */
  44572. constructor( name ) {
  44573. super( name );
  44574. /**
  44575. * This flag can be used for type testing.
  44576. *
  44577. * @type {boolean}
  44578. * @readonly
  44579. * @default true
  44580. */
  44581. this.isUniformsGroup = true;
  44582. /**
  44583. * An array with the raw uniform values.
  44584. *
  44585. * @private
  44586. * @type {?Array<number>}
  44587. * @default null
  44588. */
  44589. this._values = null;
  44590. /**
  44591. * An array of uniform objects.
  44592. *
  44593. * The order of uniforms in this array must match the order of uniforms in the shader.
  44594. *
  44595. * @type {Array<Uniform>}
  44596. */
  44597. this.uniforms = [];
  44598. /**
  44599. * A cache for the uniform update ranges.
  44600. *
  44601. * @private
  44602. * @type {Map<number, {start: number, count: number}>}
  44603. */
  44604. this._updateRangeCache = new Map();
  44605. /**
  44606. * Uniform indices whose range has already been pushed into `updateRanges`
  44607. * during the current update cycle. Reset on `clearUpdateRanges()`.
  44608. *
  44609. * @private
  44610. * @type {Set<number>}
  44611. */
  44612. this._addedIndices = new Set();
  44613. }
  44614. /**
  44615. * Adds a uniform's update range to this buffer.
  44616. *
  44617. * @param {Uniform} uniform - The uniform.
  44618. */
  44619. addUniformUpdateRange( uniform ) {
  44620. const index = uniform.index;
  44621. if ( this._addedIndices.has( index ) ) return;
  44622. let range = this._updateRangeCache.get( index );
  44623. if ( range === undefined ) {
  44624. range = { start: 0, count: 0 };
  44625. this._updateRangeCache.set( index, range );
  44626. }
  44627. range.start = uniform.offset;
  44628. range.count = uniform.itemSize;
  44629. this._addedIndices.add( index );
  44630. this.updateRanges.push( range );
  44631. }
  44632. /**
  44633. * Clears all update ranges of this buffer.
  44634. */
  44635. clearUpdateRanges() {
  44636. this._addedIndices.clear();
  44637. super.clearUpdateRanges();
  44638. }
  44639. /**
  44640. * Adds a uniform to this group.
  44641. *
  44642. * @param {Uniform} uniform - The uniform to add.
  44643. * @return {UniformsGroup} A reference to this group.
  44644. */
  44645. addUniform( uniform ) {
  44646. this.uniforms.push( uniform );
  44647. return this;
  44648. }
  44649. /**
  44650. * Removes a uniform from this group.
  44651. *
  44652. * @param {Uniform} uniform - The uniform to remove.
  44653. * @return {UniformsGroup} A reference to this group.
  44654. */
  44655. removeUniform( uniform ) {
  44656. const index = this.uniforms.indexOf( uniform );
  44657. if ( index !== -1 ) {
  44658. this.uniforms.splice( index, 1 );
  44659. }
  44660. return this;
  44661. }
  44662. /**
  44663. * An array with the raw uniform values.
  44664. *
  44665. * @type {Array<number>}
  44666. */
  44667. get values() {
  44668. if ( this._values === null ) {
  44669. this._values = Array.from( this.buffer );
  44670. }
  44671. return this._values;
  44672. }
  44673. /**
  44674. * A Float32 array buffer with the uniform values.
  44675. *
  44676. * @type {Float32Array}
  44677. */
  44678. get buffer() {
  44679. let buffer = this._buffer;
  44680. if ( buffer === null ) {
  44681. const byteLength = this.byteLength;
  44682. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  44683. this._buffer = buffer;
  44684. }
  44685. return buffer;
  44686. }
  44687. /**
  44688. * The byte length of the buffer with correct buffer alignment.
  44689. *
  44690. * @type {number}
  44691. */
  44692. get byteLength() {
  44693. const bytesPerElement = this.bytesPerElement;
  44694. let offset = 0; // global buffer offset in bytes
  44695. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  44696. const uniform = this.uniforms[ i ];
  44697. const boundary = uniform.boundary;
  44698. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  44699. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  44700. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  44701. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  44702. offset += chunkPadding;
  44703. // Check for chunk overflow
  44704. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  44705. // Add padding to the end of the chunk
  44706. offset += ( GPU_CHUNK_BYTES - chunkStart );
  44707. }
  44708. uniform.offset = offset / bytesPerElement;
  44709. uniform.index = i;
  44710. offset += itemSize;
  44711. }
  44712. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  44713. }
  44714. /**
  44715. * Updates this group by updating each uniform object of
  44716. * the internal uniform list. The uniform objects check if their
  44717. * values has actually changed so this method only returns
  44718. * `true` if there is a real value change.
  44719. *
  44720. * @return {boolean} Whether the uniforms have been updated and
  44721. * must be uploaded to the GPU.
  44722. */
  44723. update() {
  44724. let updated = false;
  44725. for ( const uniform of this.uniforms ) {
  44726. if ( this.updateByType( uniform ) === true ) {
  44727. updated = true;
  44728. }
  44729. }
  44730. return updated;
  44731. }
  44732. /**
  44733. * Releases the buffer.
  44734. */
  44735. release() {
  44736. super.release();
  44737. this._values = null;
  44738. }
  44739. /**
  44740. * Updates a given uniform by calling an update method matching
  44741. * the uniforms type.
  44742. *
  44743. * @param {Uniform} uniform - The uniform to update.
  44744. * @return {boolean} Whether the uniform has been updated or not.
  44745. */
  44746. updateByType( uniform ) {
  44747. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  44748. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  44749. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  44750. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  44751. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  44752. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  44753. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  44754. error( 'WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  44755. }
  44756. /**
  44757. * Updates a given Number uniform.
  44758. *
  44759. * @param {NumberUniform} uniform - The Number uniform.
  44760. * @return {boolean} Whether the uniform has been updated or not.
  44761. */
  44762. updateNumber( uniform ) {
  44763. let updated = false;
  44764. const a = this.values;
  44765. const v = uniform.getValue();
  44766. const offset = uniform.offset;
  44767. const type = uniform.getType();
  44768. if ( a[ offset ] !== v ) {
  44769. const b = this._getBufferForType( type );
  44770. b[ offset ] = a[ offset ] = v;
  44771. updated = true;
  44772. this.addUniformUpdateRange( uniform );
  44773. }
  44774. return updated;
  44775. }
  44776. /**
  44777. * Updates a given Vector2 uniform.
  44778. *
  44779. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  44780. * @return {boolean} Whether the uniform has been updated or not.
  44781. */
  44782. updateVector2( uniform ) {
  44783. let updated = false;
  44784. const a = this.values;
  44785. const v = uniform.getValue();
  44786. const offset = uniform.offset;
  44787. const type = uniform.getType();
  44788. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  44789. const b = this._getBufferForType( type );
  44790. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  44791. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  44792. updated = true;
  44793. this.addUniformUpdateRange( uniform );
  44794. }
  44795. return updated;
  44796. }
  44797. /**
  44798. * Updates a given Vector3 uniform.
  44799. *
  44800. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  44801. * @return {boolean} Whether the uniform has been updated or not.
  44802. */
  44803. updateVector3( uniform ) {
  44804. let updated = false;
  44805. const a = this.values;
  44806. const v = uniform.getValue();
  44807. const offset = uniform.offset;
  44808. const type = uniform.getType();
  44809. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  44810. const b = this._getBufferForType( type );
  44811. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  44812. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  44813. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  44814. updated = true;
  44815. this.addUniformUpdateRange( uniform );
  44816. }
  44817. return updated;
  44818. }
  44819. /**
  44820. * Updates a given Vector4 uniform.
  44821. *
  44822. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  44823. * @return {boolean} Whether the uniform has been updated or not.
  44824. */
  44825. updateVector4( uniform ) {
  44826. let updated = false;
  44827. const a = this.values;
  44828. const v = uniform.getValue();
  44829. const offset = uniform.offset;
  44830. const type = uniform.getType();
  44831. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 3 ] !== v.w ) {
  44832. const b = this._getBufferForType( type );
  44833. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  44834. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  44835. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  44836. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  44837. updated = true;
  44838. this.addUniformUpdateRange( uniform );
  44839. }
  44840. return updated;
  44841. }
  44842. /**
  44843. * Updates a given Color uniform.
  44844. *
  44845. * @param {ColorUniform} uniform - The Color uniform.
  44846. * @return {boolean} Whether the uniform has been updated or not.
  44847. */
  44848. updateColor( uniform ) {
  44849. let updated = false;
  44850. const a = this.values;
  44851. const c = uniform.getValue();
  44852. const offset = uniform.offset;
  44853. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  44854. const b = this.buffer;
  44855. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  44856. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  44857. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  44858. updated = true;
  44859. this.addUniformUpdateRange( uniform );
  44860. }
  44861. return updated;
  44862. }
  44863. /**
  44864. * Updates a given Matrix3 uniform.
  44865. *
  44866. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  44867. * @return {boolean} Whether the uniform has been updated or not.
  44868. */
  44869. updateMatrix3( uniform ) {
  44870. let updated = false;
  44871. const a = this.values;
  44872. const e = uniform.getValue().elements;
  44873. const offset = uniform.offset;
  44874. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  44875. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  44876. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  44877. const b = this.buffer;
  44878. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  44879. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  44880. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  44881. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  44882. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  44883. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  44884. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  44885. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  44886. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  44887. updated = true;
  44888. this.addUniformUpdateRange( uniform );
  44889. }
  44890. return updated;
  44891. }
  44892. /**
  44893. * Updates a given Matrix4 uniform.
  44894. *
  44895. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  44896. * @return {boolean} Whether the uniform has been updated or not.
  44897. */
  44898. updateMatrix4( uniform ) {
  44899. let updated = false;
  44900. const a = this.values;
  44901. const e = uniform.getValue().elements;
  44902. const offset = uniform.offset;
  44903. if ( arraysEqual( a, e, offset ) === false ) {
  44904. const b = this.buffer;
  44905. b.set( e, offset );
  44906. setArray( a, e, offset );
  44907. updated = true;
  44908. this.addUniformUpdateRange( uniform );
  44909. }
  44910. return updated;
  44911. }
  44912. /**
  44913. * Returns a typed array that matches the given data type.
  44914. *
  44915. * @private
  44916. * @param {string} type - The data type.
  44917. * @return {TypedArray} The typed array.
  44918. */
  44919. _getBufferForType( type ) {
  44920. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  44921. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  44922. return this.buffer;
  44923. }
  44924. }
  44925. /**
  44926. * Sets the values of the second array to the first array.
  44927. *
  44928. * @private
  44929. * @param {TypedArray} a - The first array.
  44930. * @param {TypedArray} b - The second array.
  44931. * @param {number} offset - An index offset for the first array.
  44932. */
  44933. function setArray( a, b, offset ) {
  44934. for ( let i = 0, l = b.length; i < l; i ++ ) {
  44935. a[ offset + i ] = b[ i ];
  44936. }
  44937. }
  44938. /**
  44939. * Returns `true` if the given arrays are equal.
  44940. *
  44941. * @private
  44942. * @param {TypedArray} a - The first array.
  44943. * @param {TypedArray} b - The second array.
  44944. * @param {number} offset - An index offset for the first array.
  44945. * @return {boolean} Whether the given arrays are equal or not.
  44946. */
  44947. function arraysEqual( a, b, offset ) {
  44948. for ( let i = 0, l = b.length; i < l; i ++ ) {
  44949. if ( a[ offset + i ] !== b[ i ] ) return false;
  44950. }
  44951. return true;
  44952. }
  44953. let _id$3 = 0;
  44954. /**
  44955. * A special form of uniforms group that represents
  44956. * the individual uniforms as node-based uniforms.
  44957. *
  44958. * @private
  44959. * @augments UniformsGroup
  44960. */
  44961. class NodeUniformsGroup extends UniformsGroup {
  44962. /**
  44963. * Constructs a new node-based uniforms group.
  44964. *
  44965. * @param {string} name - The group's name.
  44966. * @param {UniformGroupNode} groupNode - The uniform group node.
  44967. */
  44968. constructor( name, groupNode ) {
  44969. super( name );
  44970. /**
  44971. * The group's ID.
  44972. *
  44973. * @type {number}
  44974. */
  44975. this.id = _id$3 ++;
  44976. /**
  44977. * The uniform group node.
  44978. *
  44979. * @type {UniformGroupNode}
  44980. */
  44981. this.groupNode = groupNode;
  44982. /**
  44983. * This flag can be used for type testing.
  44984. *
  44985. * @type {boolean}
  44986. * @readonly
  44987. * @default true
  44988. */
  44989. this.isNodeUniformsGroup = true;
  44990. }
  44991. }
  44992. /**
  44993. * Represents a sampler binding type.
  44994. *
  44995. * @private
  44996. * @augments Binding
  44997. */
  44998. class Sampler extends Binding {
  44999. /**
  45000. * Constructs a new sampler.
  45001. *
  45002. * @param {string} name - The samplers's name.
  45003. * @param {?Texture} texture - The texture this binding is referring to.
  45004. */
  45005. constructor( name, texture ) {
  45006. super( name );
  45007. /**
  45008. * The texture the sampler is referring to.
  45009. *
  45010. * @private
  45011. * @type {?Texture}
  45012. */
  45013. this._texture = texture;
  45014. /**
  45015. * The binding's version.
  45016. *
  45017. * @type {number}
  45018. */
  45019. this.version = -1;
  45020. /**
  45021. * The binding's generation which is an additional version
  45022. * qualifier.
  45023. *
  45024. * @type {?number}
  45025. * @default null
  45026. */
  45027. this.generation = null;
  45028. /**
  45029. * The binding's sampler key.
  45030. *
  45031. * @type {string}
  45032. * @default ''
  45033. */
  45034. this.samplerKey = '';
  45035. /**
  45036. * This flag can be used for type testing.
  45037. *
  45038. * @type {boolean}
  45039. * @readonly
  45040. * @default true
  45041. */
  45042. this.isSampler = true;
  45043. }
  45044. /**
  45045. * Sets the texture of this sampler.
  45046. *
  45047. * @param {Texture} value - The texture to set.
  45048. */
  45049. set texture( value ) {
  45050. if ( this._texture === value ) return;
  45051. this._texture = value;
  45052. this.reset();
  45053. }
  45054. /**
  45055. * Gets the texture of this sampler.
  45056. * @return {?Texture} The texture.
  45057. */
  45058. get texture() {
  45059. return this._texture;
  45060. }
  45061. /**
  45062. * Updates the binding.
  45063. *
  45064. * @return {boolean} Whether the texture has been updated and must be
  45065. * uploaded to the GPU.
  45066. */
  45067. update() {
  45068. const { texture, version } = this;
  45069. if ( version !== texture.version ) {
  45070. this.version = texture.version;
  45071. return true;
  45072. }
  45073. return false;
  45074. }
  45075. /**
  45076. * Resets the version and generation. This is used when the texture
  45077. * the binding is pointing to is disposed or exchanged.
  45078. */
  45079. reset() {
  45080. this.generation = null;
  45081. this.version = -1;
  45082. }
  45083. }
  45084. let _id$2 = 0;
  45085. /**
  45086. * Represents a sampled texture binding type.
  45087. *
  45088. * @private
  45089. * @augments Sampler
  45090. */
  45091. class SampledTexture extends Sampler {
  45092. /**
  45093. * Constructs a new sampled texture.
  45094. *
  45095. * @param {string} name - The sampled texture's name.
  45096. * @param {?Texture} texture - The texture this binding is referring to.
  45097. */
  45098. constructor( name, texture ) {
  45099. super( name, texture );
  45100. /**
  45101. * This identifier.
  45102. *
  45103. * @type {number}
  45104. */
  45105. this.id = _id$2 ++;
  45106. /**
  45107. * Whether the texture is a storage texture or not.
  45108. *
  45109. * @type {boolean}
  45110. * @default false
  45111. */
  45112. this.store = false;
  45113. /**
  45114. * The mip level to bind for storage textures.
  45115. *
  45116. * @type {number}
  45117. * @default 0
  45118. */
  45119. this.mipLevel = 0;
  45120. /**
  45121. * This flag can be used for type testing.
  45122. *
  45123. * @type {boolean}
  45124. * @readonly
  45125. * @default true
  45126. */
  45127. this.isSampledTexture = true;
  45128. }
  45129. }
  45130. /**
  45131. * A special form of sampled texture binding type.
  45132. * It's texture value is managed by a node object.
  45133. *
  45134. * @private
  45135. * @augments SampledTexture
  45136. */
  45137. class NodeSampledTexture extends SampledTexture {
  45138. /**
  45139. * Constructs a new node-based sampled texture.
  45140. *
  45141. * @param {string} name - The textures's name.
  45142. * @param {TextureNode} textureNode - The texture node.
  45143. * @param {UniformGroupNode} groupNode - The uniform group node.
  45144. * @param {?string} [access=null] - The access type.
  45145. */
  45146. constructor( name, textureNode, groupNode, access = null ) {
  45147. super( name, textureNode ? textureNode.value : null );
  45148. /**
  45149. * The texture node.
  45150. *
  45151. * @type {TextureNode}
  45152. */
  45153. this.textureNode = textureNode;
  45154. /**
  45155. * The uniform group node.
  45156. *
  45157. * @type {UniformGroupNode}
  45158. */
  45159. this.groupNode = groupNode;
  45160. /**
  45161. * The access type.
  45162. *
  45163. * @type {?string}
  45164. * @default null
  45165. */
  45166. this.access = access;
  45167. }
  45168. /**
  45169. * Updates the binding.
  45170. *
  45171. * @return {boolean} Whether the texture has been updated and must be
  45172. * uploaded to the GPU.
  45173. */
  45174. update() {
  45175. const { textureNode } = this;
  45176. if ( this.texture !== textureNode.value ) {
  45177. this.texture = textureNode.value;
  45178. return true;
  45179. }
  45180. return super.update();
  45181. }
  45182. }
  45183. /**
  45184. * A special form of sampled cube texture binding type.
  45185. * It's texture value is managed by a node object.
  45186. *
  45187. * @private
  45188. * @augments NodeSampledTexture
  45189. */
  45190. class NodeSampledCubeTexture extends NodeSampledTexture {
  45191. /**
  45192. * Constructs a new node-based sampled cube texture.
  45193. *
  45194. * @param {string} name - The textures's name.
  45195. * @param {TextureNode} textureNode - The texture node.
  45196. * @param {UniformGroupNode} groupNode - The uniform group node.
  45197. * @param {?string} [access=null] - The access type.
  45198. */
  45199. constructor( name, textureNode, groupNode, access = null ) {
  45200. super( name, textureNode, groupNode, access );
  45201. /**
  45202. * This flag can be used for type testing.
  45203. *
  45204. * @type {boolean}
  45205. * @readonly
  45206. * @default true
  45207. */
  45208. this.isSampledCubeTexture = true;
  45209. }
  45210. }
  45211. /**
  45212. * A special form of sampled 3D texture binding type.
  45213. * It's texture value is managed by a node object.
  45214. *
  45215. * @private
  45216. * @augments NodeSampledTexture
  45217. */
  45218. class NodeSampledTexture3D extends NodeSampledTexture {
  45219. /**
  45220. * Constructs a new node-based sampled 3D texture.
  45221. *
  45222. * @param {string} name - The textures's name.
  45223. * @param {TextureNode} textureNode - The texture node.
  45224. * @param {UniformGroupNode} groupNode - The uniform group node.
  45225. * @param {?string} [access=null] - The access type.
  45226. */
  45227. constructor( name, textureNode, groupNode, access = null ) {
  45228. super( name, textureNode, groupNode, access );
  45229. /**
  45230. * This flag can be used for type testing.
  45231. *
  45232. * @type {boolean}
  45233. * @readonly
  45234. * @default true
  45235. */
  45236. this.isSampledTexture3D = true;
  45237. }
  45238. }
  45239. const glslPolyfills = {
  45240. bitcast_int_uint: new CodeNode( /* glsl */'uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }' ),
  45241. bitcast_uint_int: new CodeNode( /* glsl */'uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }' ),
  45242. textureGather: new CodeNode( /* glsl */`
  45243. vec4 tsl_textureGather( const int comp, sampler2D map, vec2 coord, ivec2 offset, bool flipY ) {
  45244. if ( flipY ) offset.y = - offset.y;
  45245. vec2 size = vec2( textureSize( map, 0 ) );
  45246. vec2 st = floor( coord * size + vec2( offset ) - 0.5 );
  45247. vec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;
  45248. vec4 ret = vec4(
  45249. textureLod( map, ij.xw, 0.0 )[ comp ],
  45250. textureLod( map, ij.zw, 0.0 )[ comp ],
  45251. textureLod( map, ij.zy, 0.0 )[ comp ],
  45252. textureLod( map, ij.xy, 0.0 )[ comp ]
  45253. );
  45254. return flipY ? ret.wzyx : ret;
  45255. }
  45256. ` ),
  45257. textureGatherArray: new CodeNode( /* glsl */`
  45258. vec4 tsl_textureGather_array( const int comp, sampler2DArray map, vec3 coord, ivec2 offset, bool flipY ) {
  45259. if ( flipY ) offset.y = - offset.y;
  45260. vec2 size = vec2( textureSize( map, 0 ).xy );
  45261. vec2 st = floor( coord.xy * size + vec2( offset ) - 0.5 );
  45262. vec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;
  45263. vec4 ret = vec4(
  45264. textureLod( map, vec3( ij.xw, coord.z ), 0.0 )[ comp ],
  45265. textureLod( map, vec3( ij.zw, coord.z ), 0.0 )[ comp ],
  45266. textureLod( map, vec3( ij.zy, coord.z ), 0.0 )[ comp ],
  45267. textureLod( map, vec3( ij.xy, coord.z ), 0.0 )[ comp ]
  45268. );
  45269. return flipY ? ret.wzyx : ret;
  45270. }
  45271. ` ),
  45272. textureGatherCompare: new CodeNode( /* glsl */`
  45273. vec4 tsl_textureGatherCompare( sampler2DShadow map, vec2 coord, ivec2 offset, float ref, bool flipY ) {
  45274. if ( flipY ) offset.y = - offset.y;
  45275. vec2 size = vec2( textureSize( map, 0 ) );
  45276. vec2 st = floor( coord * size + vec2( offset ) - 0.5 );
  45277. vec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;
  45278. vec4 ret = vec4(
  45279. textureLod( map, vec3( ij.xw, ref ), 0.0 ),
  45280. textureLod( map, vec3( ij.zw, ref ), 0.0 ),
  45281. textureLod( map, vec3( ij.zy, ref ), 0.0 ),
  45282. textureLod( map, vec3( ij.xy, ref ), 0.0 )
  45283. );
  45284. return flipY ? ret.wzyx : ret;
  45285. }
  45286. ` ),
  45287. textureGatherCompareArray: new CodeNode( /* glsl */`
  45288. vec4 tsl_textureGatherCompare_array( sampler2DArrayShadow map, vec3 coord, ivec2 offset, float ref, bool flipY ) {
  45289. if ( flipY ) offset.y = - offset.y;
  45290. vec2 size = vec2( textureSize( map, 0 ).xy );
  45291. vec2 st = floor( coord.xy * size + vec2( offset ) - 0.5 );
  45292. vec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;
  45293. vec4 ret = vec4(
  45294. texture( map, vec4( ij.xw, coord.z, ref ) ),
  45295. texture( map, vec4( ij.zw, coord.z, ref ) ),
  45296. texture( map, vec4( ij.zy, coord.z, ref ) ),
  45297. texture( map, vec4( ij.xy, coord.z, ref ) )
  45298. );
  45299. return flipY ? ret.wzyx : ret;
  45300. }
  45301. ` )
  45302. };
  45303. const glslMethods = {
  45304. textureDimensions: 'textureSize',
  45305. equals: 'equal',
  45306. bitcast_float_int: 'floatBitsToInt',
  45307. bitcast_int_float: 'intBitsToFloat',
  45308. bitcast_uint_float: 'uintBitsToFloat',
  45309. bitcast_float_uint: 'floatBitsToUint',
  45310. bitcast_uint_int: 'tsl_bitcast_uint_to_int',
  45311. bitcast_int_uint: 'tsl_bitcast_int_to_uint',
  45312. floatpack_snorm_2x16: 'packSnorm2x16',
  45313. floatpack_unorm_2x16: 'packUnorm2x16',
  45314. floatpack_float16_2x16: 'packHalf2x16',
  45315. floatunpack_snorm_2x16: 'unpackSnorm2x16',
  45316. floatunpack_unorm_2x16: 'unpackUnorm2x16',
  45317. floatunpack_float16_2x16: 'unpackHalf2x16'
  45318. };
  45319. const precisionLib = {
  45320. low: 'lowp',
  45321. medium: 'mediump',
  45322. high: 'highp'
  45323. };
  45324. const supports$1 = {
  45325. swizzleAssign: true,
  45326. storageBuffer: false
  45327. };
  45328. const interpolationTypeMap = {
  45329. perspective: 'smooth',
  45330. linear: 'noperspective'
  45331. };
  45332. const interpolationModeMap = {
  45333. 'centroid': 'centroid'
  45334. };
  45335. const defaultPrecisions = `
  45336. precision highp float;
  45337. precision highp int;
  45338. precision highp sampler2D;
  45339. precision highp sampler3D;
  45340. precision highp samplerCube;
  45341. precision highp sampler2DArray;
  45342. precision highp usampler2D;
  45343. precision highp usampler3D;
  45344. precision highp usamplerCube;
  45345. precision highp usampler2DArray;
  45346. precision highp isampler2D;
  45347. precision highp isampler3D;
  45348. precision highp isamplerCube;
  45349. precision highp isampler2DArray;
  45350. precision highp sampler2DShadow;
  45351. precision highp sampler2DArrayShadow;
  45352. precision highp samplerCubeShadow;
  45353. `;
  45354. /**
  45355. * A node builder targeting GLSL.
  45356. *
  45357. * This module generates GLSL shader code from node materials and also
  45358. * generates the respective bindings and vertex buffer definitions. These
  45359. * data are later used by the renderer to create render and compute pipelines
  45360. * for render objects.
  45361. *
  45362. * @augments NodeBuilder
  45363. */
  45364. class GLSLNodeBuilder extends NodeBuilder {
  45365. /**
  45366. * Constructs a new GLSL node builder renderer.
  45367. *
  45368. * @param {Object3D} object - The 3D object.
  45369. * @param {Renderer} renderer - The renderer.
  45370. */
  45371. constructor( object, renderer ) {
  45372. super( object, renderer, new GLSLNodeParser() );
  45373. /**
  45374. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  45375. * another dictionary which manages UBOs per group ('render','frame','object').
  45376. *
  45377. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  45378. */
  45379. this.uniformGroups = {};
  45380. /**
  45381. * An array that holds objects defining the varying and attribute data in
  45382. * context of Transform Feedback.
  45383. *
  45384. * @type {Array<Object<string,AttributeNode|string>>}
  45385. */
  45386. this.transforms = [];
  45387. /**
  45388. * A dictionary that holds for each shader stage a Map of used extensions.
  45389. *
  45390. * @type {Object<string,Map<string,Object>>}
  45391. */
  45392. this.extensions = {};
  45393. /**
  45394. * A dictionary that holds for each shader stage an Array of used builtins.
  45395. *
  45396. * @type {Object<string,Array<string>>}
  45397. */
  45398. this.builtins = { vertex: [], fragment: [], compute: [] };
  45399. }
  45400. /**
  45401. * Checks if the given texture requires a manual conversion to the working color space.
  45402. *
  45403. * @param {Texture} texture - The texture to check.
  45404. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  45405. */
  45406. needsToWorkingColorSpace( texture ) {
  45407. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  45408. }
  45409. /**
  45410. * Includes the given method name into the current
  45411. * function node.
  45412. *
  45413. * @private
  45414. * @param {string} name - The method name to include.
  45415. * @return {CodeNode} The respective code node.
  45416. */
  45417. _include( name ) {
  45418. const codeNode = glslPolyfills[ name ];
  45419. codeNode.build( this );
  45420. this.addInclude( codeNode );
  45421. return codeNode;
  45422. }
  45423. /**
  45424. * Returns the native shader method name for a given generic name.
  45425. *
  45426. * @param {string} method - The method name to resolve.
  45427. * @return {string} The resolved GLSL method name.
  45428. */
  45429. getMethod( method ) {
  45430. if ( glslPolyfills[ method ] !== undefined ) {
  45431. this._include( method );
  45432. }
  45433. return glslMethods[ method ] || method;
  45434. }
  45435. /**
  45436. * Returns the bitcast method name for a given input and outputType.
  45437. *
  45438. * @param {string} type - The output type to bitcast to.
  45439. * @param {string} inputType - The input type of the.
  45440. * @return {string} The resolved GLSL bitcast invocation.
  45441. */
  45442. getBitcastMethod( type, inputType ) {
  45443. return this.getMethod( `bitcast_${ inputType }_${ type }` );
  45444. }
  45445. /**
  45446. * Returns the float packing method name for a given numeric encoding.
  45447. *
  45448. * @param {string} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  45449. * @returns {string} The resolved GLSL float packing method name.
  45450. */
  45451. getFloatPackingMethod( encoding ) {
  45452. return this.getMethod( `floatpack_${ encoding }_2x16` );
  45453. }
  45454. /**
  45455. * Returns the float unpacking method name for a given numeric encoding.
  45456. *
  45457. * @param {string} encoding - The numeric encoding that describes how the integer values are mapped to the float range.
  45458. * @returns {string} The resolved GLSL float unpacking method name.
  45459. */
  45460. getFloatUnpackingMethod( encoding ) {
  45461. return this.getMethod( `floatunpack_${ encoding }_2x16` );
  45462. }
  45463. /**
  45464. * Returns the native snippet for a ternary operation.
  45465. *
  45466. * @param {string} condSnippet - The condition determining which expression gets resolved.
  45467. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  45468. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  45469. * @return {string} The resolved method name.
  45470. */
  45471. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  45472. return `${condSnippet} ? ${ifSnippet} : ${elseSnippet}`;
  45473. }
  45474. /**
  45475. * Returns the output struct name. Not relevant for GLSL.
  45476. *
  45477. * @return {string}
  45478. */
  45479. getOutputStructName() {
  45480. return '';
  45481. }
  45482. /**
  45483. * Builds the given shader node.
  45484. *
  45485. * @param {ShaderNodeInternal} shaderNode - The shader node.
  45486. * @return {string} The GLSL function code.
  45487. */
  45488. buildFunctionCode( shaderNode ) {
  45489. const layout = shaderNode.layout;
  45490. const flowData = this.flowShaderNode( shaderNode );
  45491. const parameters = [];
  45492. for ( const input of layout.inputs ) {
  45493. parameters.push( this.getType( input.type ) + ' ' + input.name );
  45494. }
  45495. //
  45496. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  45497. ${ flowData.vars }
  45498. ${ flowData.code }
  45499. return ${ flowData.result };
  45500. }`;
  45501. //
  45502. return code;
  45503. }
  45504. /**
  45505. * Setups the Pixel Buffer Object (PBO) for the given storage
  45506. * buffer node.
  45507. *
  45508. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  45509. */
  45510. setupPBO( storageBufferNode ) {
  45511. const attribute = storageBufferNode.value;
  45512. if ( attribute.pbo === undefined ) {
  45513. const originalArray = attribute.array;
  45514. const numElements = attribute.count * attribute.itemSize;
  45515. const { itemSize } = attribute;
  45516. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  45517. let format = isInteger ? RedIntegerFormat : RedFormat;
  45518. if ( itemSize === 2 ) {
  45519. format = isInteger ? RGIntegerFormat : RGFormat;
  45520. } else if ( itemSize === 3 ) {
  45521. format = isInteger ? RGBIntegerFormat : RGBFormat;
  45522. } else if ( itemSize === 4 ) {
  45523. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  45524. }
  45525. const typeMap = {
  45526. Float32Array: FloatType,
  45527. Uint8Array: UnsignedByteType,
  45528. Uint16Array: UnsignedShortType,
  45529. Uint32Array: UnsignedIntType,
  45530. Int8Array: ByteType,
  45531. Int16Array: ShortType,
  45532. Int32Array: IntType,
  45533. Uint8ClampedArray: UnsignedByteType,
  45534. };
  45535. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  45536. let height = Math.ceil( ( numElements / itemSize ) / width );
  45537. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  45538. const newSize = width * height * itemSize;
  45539. const newArray = new originalArray.constructor( newSize );
  45540. newArray.set( originalArray, 0 );
  45541. attribute.array = newArray;
  45542. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  45543. pboTexture.needsUpdate = true;
  45544. pboTexture.isPBOTexture = true;
  45545. const pbo = new TextureNode( pboTexture, null, null );
  45546. pbo.setPrecision( 'high' );
  45547. attribute.pboNode = pbo;
  45548. attribute.pbo = pbo.value;
  45549. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  45550. }
  45551. }
  45552. /**
  45553. * Returns a GLSL snippet that represents the property name of the given node.
  45554. *
  45555. * @param {Node} node - The node.
  45556. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45557. * @return {string} The property name.
  45558. */
  45559. getPropertyName( node, shaderStage = this.shaderStage ) {
  45560. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  45561. return node.name;
  45562. }
  45563. return super.getPropertyName( node, shaderStage );
  45564. }
  45565. /**
  45566. * Setups the Pixel Buffer Object (PBO) for the given storage
  45567. * buffer node.
  45568. *
  45569. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  45570. * @return {string} The property name.
  45571. */
  45572. generatePBO( storageArrayElementNode ) {
  45573. const { node, indexNode } = storageArrayElementNode;
  45574. const attribute = node.value;
  45575. if ( this.renderer.backend.has( attribute ) ) {
  45576. const attributeData = this.renderer.backend.get( attribute );
  45577. attributeData.pbo = attribute.pbo;
  45578. }
  45579. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  45580. const textureName = this.getPropertyName( nodeUniform );
  45581. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  45582. const indexSnippet = indexNode.build( this, 'uint' );
  45583. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  45584. let propertyName = elementNodeData.propertyName;
  45585. if ( propertyName === undefined ) {
  45586. // property element
  45587. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  45588. propertyName = this.getPropertyName( nodeVar );
  45589. // property size
  45590. const bufferNodeData = this.getDataFromNode( node );
  45591. let propertySizeName = bufferNodeData.propertySizeName;
  45592. if ( propertySizeName === undefined ) {
  45593. propertySizeName = propertyName + 'Size';
  45594. this.getVarFromNode( node, propertySizeName, 'uint' );
  45595. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  45596. bufferNodeData.propertySizeName = propertySizeName;
  45597. }
  45598. //
  45599. const { itemSize } = attribute;
  45600. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  45601. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  45602. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, '0', null, null );
  45603. //
  45604. let prefix = 'vec4';
  45605. if ( attribute.pbo.type === UnsignedIntType ) {
  45606. prefix = 'uvec4';
  45607. } else if ( attribute.pbo.type === IntType ) {
  45608. prefix = 'ivec4';
  45609. }
  45610. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  45611. elementNodeData.propertyName = propertyName;
  45612. }
  45613. return propertyName;
  45614. }
  45615. /**
  45616. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  45617. *
  45618. * @param {?Texture} texture - The texture.
  45619. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45620. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  45621. * @param {?string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45622. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  45623. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  45624. * @return {string} The GLSL snippet.
  45625. */
  45626. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  45627. if ( levelSnippet === null ) levelSnippet = '0';
  45628. let snippet;
  45629. if ( depthSnippet ) {
  45630. if ( offsetSnippet ) {
  45631. snippet = `texelFetchOffset( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), int( ${ levelSnippet } ), ${ offsetSnippet } )`;
  45632. } else {
  45633. snippet = `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), int( ${ levelSnippet } ) )`;
  45634. }
  45635. } else {
  45636. if ( offsetSnippet ) {
  45637. snippet = `texelFetchOffset( ${ textureProperty }, ${ uvIndexSnippet }, int( ${ levelSnippet } ), ${ offsetSnippet } )`;
  45638. } else {
  45639. snippet = `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, int( ${ levelSnippet } ) )`;
  45640. }
  45641. }
  45642. if ( texture !== null && texture.isDepthTexture ) {
  45643. snippet += '.x';
  45644. }
  45645. return snippet;
  45646. }
  45647. /**
  45648. * Generates the GLSL snippet for sampling/loading the given texture.
  45649. *
  45650. * @param {Texture} texture - The texture.
  45651. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45652. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  45653. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  45654. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  45655. * @return {string} The GLSL snippet.
  45656. */
  45657. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet ) {
  45658. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  45659. if ( texture.isDepthTexture ) {
  45660. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } ).x`;
  45661. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  45662. }
  45663. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } )`;
  45664. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  45665. }
  45666. /**
  45667. * Generates the GLSL snippet when sampling textures with explicit mip level.
  45668. *
  45669. * @param {Texture} texture - The texture.
  45670. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45671. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  45672. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45673. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  45674. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  45675. * @return {string} The GLSL snippet.
  45676. */
  45677. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  45678. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  45679. if ( offsetSnippet ) {
  45680. return `textureLodOffset( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  45681. }
  45682. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  45683. }
  45684. /**
  45685. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  45686. *
  45687. * @param {Texture} texture - The texture.
  45688. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45689. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  45690. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  45691. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  45692. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  45693. * @return {string} The GLSL snippet.
  45694. */
  45695. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet ) {
  45696. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  45697. if ( offsetSnippet ) {
  45698. return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ biasSnippet } )`;
  45699. }
  45700. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  45701. }
  45702. /**
  45703. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  45704. *
  45705. * @param {Texture} texture - The texture.
  45706. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45707. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  45708. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  45709. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  45710. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  45711. * @return {string} The GLSL snippet.
  45712. */
  45713. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet ) {
  45714. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  45715. if ( offsetSnippet ) {
  45716. return `textureGradOffset( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  45717. }
  45718. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  45719. }
  45720. /**
  45721. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  45722. * against a reference value.
  45723. *
  45724. * @param {Texture} texture - The texture.
  45725. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45726. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  45727. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  45728. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  45729. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  45730. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45731. * @return {string} The GLSL snippet.
  45732. */
  45733. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  45734. if ( shaderStage === 'fragment' ) {
  45735. // Cube shadow maps use vec4(direction, compareValue)
  45736. if ( texture.isCubeTexture ) {
  45737. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ compareSnippet } ) )`;
  45738. }
  45739. if ( depthSnippet ) {
  45740. if ( offsetSnippet ) {
  45741. return `textureOffset( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  45742. }
  45743. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  45744. }
  45745. if ( offsetSnippet ) {
  45746. return `textureOffset( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  45747. }
  45748. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  45749. } else {
  45750. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  45751. }
  45752. }
  45753. /**
  45754. * Generates the GLSL snippet for gathering four texels from the given texture.
  45755. *
  45756. * @param {Texture} texture - The texture.
  45757. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45758. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  45759. * @param {string} gatherSnippet - A GLSL snippet that represents the index of the channel to read.
  45760. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  45761. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  45762. * @param {?string} flipYSnippet - A GLSL snippet that represents the y-flip. Only used for WebGL.
  45763. * @return {string} The GLSL snippet.
  45764. */
  45765. generateTextureGather( texture, textureProperty, uvSnippet, gatherSnippet, depthSnippet, offsetSnippet, flipYSnippet ) {
  45766. if ( texture.isDepthTexture ) gatherSnippet = '0';
  45767. if ( offsetSnippet === null ) offsetSnippet = 'ivec2( 0 )';
  45768. if ( flipYSnippet === null ) flipYSnippet = 'false';
  45769. if ( depthSnippet ) {
  45770. this._include( 'textureGatherArray' );
  45771. return `tsl_textureGather_array( ${gatherSnippet}, ${ textureProperty }, vec3( ${ uvSnippet }, ${ depthSnippet } ), ${ offsetSnippet }, ${ flipYSnippet } )`;
  45772. }
  45773. this._include( 'textureGather' );
  45774. return `tsl_textureGather( ${gatherSnippet}, ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ flipYSnippet } )`;
  45775. }
  45776. /**
  45777. * Generates the GLSL snippet for performing a depth comparison on four texels in the given depth texture.
  45778. *
  45779. * @param {Texture} texture - The texture.
  45780. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45781. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  45782. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  45783. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  45784. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  45785. * @param {?string} flipYSnippet - A GLSL snippet that represents the y-flip. Only used for WebGL.
  45786. * @return {string} The GLSL snippet.
  45787. */
  45788. generateTextureGatherCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, flipYSnippet ) {
  45789. if ( offsetSnippet === null ) offsetSnippet = 'ivec2( 0 )';
  45790. if ( flipYSnippet === null ) flipYSnippet = 'false';
  45791. if ( depthSnippet ) {
  45792. this._include( 'textureGatherCompareArray' );
  45793. return `tsl_textureGatherCompare_array( ${ textureProperty }, vec3( ${ uvSnippet }, ${depthSnippet} ), ${ offsetSnippet }, ${ compareSnippet }, ${ flipYSnippet } )`;
  45794. }
  45795. this._include( 'textureGatherCompare' );
  45796. return `tsl_textureGatherCompare( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ compareSnippet }, ${ flipYSnippet } )`;
  45797. }
  45798. /**
  45799. * Returns the uniforms of the given shader stage as a GLSL string.
  45800. *
  45801. * @param {string} shaderStage - The shader stage.
  45802. * @return {string} The GLSL snippet that defines the uniforms.
  45803. */
  45804. getUniforms( shaderStage ) {
  45805. const uniforms = this.uniforms[ shaderStage ];
  45806. const bindingSnippets = [];
  45807. const uniformGroups = {};
  45808. for ( const uniform of uniforms ) {
  45809. let snippet = null;
  45810. let group = false;
  45811. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  45812. const textureNode = uniform.node;
  45813. const texture = textureNode.value;
  45814. let typePrefix = '';
  45815. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  45816. if ( texture.type === UnsignedIntType ) {
  45817. typePrefix = 'u';
  45818. } else if ( texture.type === IntType ) {
  45819. typePrefix = 'i';
  45820. }
  45821. }
  45822. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  45823. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  45824. } else if ( texture.compareFunction && textureNode.compareNode !== null ) {
  45825. if ( texture.isArrayTexture === true ) {
  45826. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  45827. } else {
  45828. snippet = `sampler2DShadow ${ uniform.name };`;
  45829. }
  45830. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  45831. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  45832. } else {
  45833. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  45834. }
  45835. } else if ( uniform.type === 'cubeTexture' ) {
  45836. snippet = `samplerCube ${ uniform.name };`;
  45837. } else if ( uniform.type === 'cubeDepthTexture' ) {
  45838. const texture = uniform.node.value;
  45839. if ( texture.compareFunction ) {
  45840. snippet = `samplerCubeShadow ${ uniform.name };`;
  45841. } else {
  45842. snippet = `samplerCube ${ uniform.name };`;
  45843. }
  45844. } else if ( uniform.type === 'buffer' ) {
  45845. const bufferNode = uniform.node;
  45846. const bufferType = this.getType( bufferNode.bufferType );
  45847. const bufferCount = bufferNode.bufferCount;
  45848. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  45849. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  45850. } else {
  45851. const groupName = uniform.groupNode.name;
  45852. // Check if this group has already been processed
  45853. if ( uniformGroups[ groupName ] === undefined ) {
  45854. // Get the shared uniform group that contains uniforms from all stages
  45855. const sharedUniformGroup = this.uniformGroups[ groupName ];
  45856. if ( sharedUniformGroup !== undefined ) {
  45857. // Generate snippets for ALL uniforms in this shared group
  45858. const snippets = [];
  45859. for ( const sharedUniform of sharedUniformGroup.uniforms ) {
  45860. const type = sharedUniform.getType();
  45861. const vectorType = this.getVectorType( type );
  45862. const precision = sharedUniform.nodeUniform.node.precision;
  45863. let uniformSnippet = `${ vectorType } ${ sharedUniform.name };`;
  45864. if ( precision !== null ) {
  45865. uniformSnippet = precisionLib[ precision ] + ' ' + uniformSnippet;
  45866. }
  45867. snippets.push( '\t' + uniformSnippet );
  45868. }
  45869. uniformGroups[ groupName ] = snippets;
  45870. }
  45871. }
  45872. group = true;
  45873. }
  45874. if ( ! group ) {
  45875. const precision = uniform.node.precision;
  45876. if ( precision !== null ) {
  45877. snippet = precisionLib[ precision ] + ' ' + snippet;
  45878. }
  45879. snippet = 'uniform ' + snippet;
  45880. bindingSnippets.push( snippet );
  45881. }
  45882. }
  45883. let output = '';
  45884. for ( const name in uniformGroups ) {
  45885. const groupSnippets = uniformGroups[ name ];
  45886. output += this._getGLSLUniformStruct( name, groupSnippets.join( '\n' ) ) + '\n';
  45887. }
  45888. output += bindingSnippets.join( '\n' );
  45889. return output;
  45890. }
  45891. /**
  45892. * Returns the type for a given buffer attribute.
  45893. *
  45894. * @param {BufferAttribute} attribute - The buffer attribute.
  45895. * @return {string} The type.
  45896. */
  45897. getTypeFromAttribute( attribute ) {
  45898. let nodeType = super.getTypeFromAttribute( attribute );
  45899. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  45900. let dataAttribute = attribute;
  45901. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  45902. const array = dataAttribute.array;
  45903. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  45904. nodeType = nodeType.slice( 1 );
  45905. }
  45906. }
  45907. return nodeType;
  45908. }
  45909. /**
  45910. * Returns the shader attributes of the given shader stage as a GLSL string.
  45911. *
  45912. * @param {string} shaderStage - The shader stage.
  45913. * @return {string} The GLSL snippet that defines the shader attributes.
  45914. */
  45915. getAttributes( shaderStage ) {
  45916. let snippet = '';
  45917. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  45918. const attributes = this.getAttributesArray();
  45919. let location = 0;
  45920. for ( const attribute of attributes ) {
  45921. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  45922. }
  45923. }
  45924. return snippet;
  45925. }
  45926. /**
  45927. * Returns the members of the given struct type node as a GLSL string.
  45928. *
  45929. * @param {StructTypeNode} struct - The struct type node.
  45930. * @return {string} The GLSL snippet that defines the struct members.
  45931. */
  45932. getStructMembers( struct ) {
  45933. const snippets = [];
  45934. for ( const member of struct.members ) {
  45935. snippets.push( `\t${ member.type } ${ member.name };` );
  45936. }
  45937. return snippets.join( '\n' );
  45938. }
  45939. /**
  45940. * Returns the structs of the given shader stage as a GLSL string.
  45941. *
  45942. * @param {string} shaderStage - The shader stage.
  45943. * @return {string} The GLSL snippet that defines the structs.
  45944. */
  45945. getStructs( shaderStage ) {
  45946. const snippets = [];
  45947. const structs = this.structs[ shaderStage ];
  45948. const outputSnippet = [];
  45949. for ( const struct of structs ) {
  45950. if ( struct.output ) {
  45951. for ( const member of struct.members ) {
  45952. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  45953. }
  45954. } else {
  45955. let snippet = 'struct ' + struct.name + ' {\n';
  45956. snippet += this.getStructMembers( struct );
  45957. snippet += '\n};\n';
  45958. snippets.push( snippet );
  45959. }
  45960. }
  45961. if ( shaderStage === 'fragment' && outputSnippet.length === 0 ) {
  45962. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  45963. }
  45964. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  45965. }
  45966. /**
  45967. * Returns the varyings of the given shader stage as a GLSL string.
  45968. *
  45969. * @param {string} shaderStage - The shader stage.
  45970. * @return {string} The GLSL snippet that defines the varyings.
  45971. */
  45972. getVaryings( shaderStage ) {
  45973. let snippet = '';
  45974. const varyings = this.varyings;
  45975. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  45976. for ( const varying of varyings ) {
  45977. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  45978. const type = this.getType( varying.type );
  45979. if ( varying.needsInterpolation ) {
  45980. if ( varying.interpolationType ) {
  45981. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  45982. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  45983. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  45984. } else {
  45985. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  45986. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  45987. }
  45988. } else {
  45989. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  45990. }
  45991. }
  45992. } else if ( shaderStage === 'fragment' ) {
  45993. for ( const varying of varyings ) {
  45994. if ( varying.needsInterpolation ) {
  45995. const type = this.getType( varying.type );
  45996. if ( varying.interpolationType ) {
  45997. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  45998. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  45999. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  46000. } else {
  46001. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  46002. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  46003. }
  46004. }
  46005. }
  46006. }
  46007. for ( const builtin of this.builtins[ shaderStage ] ) {
  46008. snippet += `${builtin};\n`;
  46009. }
  46010. return snippet;
  46011. }
  46012. /**
  46013. * Returns the vertex index builtin.
  46014. *
  46015. * @return {string} The vertex index.
  46016. */
  46017. getVertexIndex() {
  46018. return 'uint( gl_VertexID )';
  46019. }
  46020. /**
  46021. * Contextually returns either the vertex stage instance index builtin
  46022. * or the linearized index of an compute invocation within a grid of workgroups.
  46023. *
  46024. * @return {string} The instance index.
  46025. */
  46026. getInstanceIndex() {
  46027. return 'uint( gl_InstanceID )';
  46028. }
  46029. /**
  46030. * Returns a builtin representing the index of an invocation within its workgroup.
  46031. *
  46032. * @return {string} The invocation local index.
  46033. */
  46034. getInvocationLocalIndex() {
  46035. const workgroupSize = this.object.workgroupSize;
  46036. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  46037. return `uint( gl_InstanceID ) % ${size}u`;
  46038. }
  46039. /**
  46040. * Returns a builtin representing the size of a subgroup within the current shader.
  46041. */
  46042. getSubgroupSize() {
  46043. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node' );
  46044. }
  46045. /**
  46046. * Returns a builtin representing the index of an invocation within its subgroup.
  46047. */
  46048. getInvocationSubgroupIndex() {
  46049. error( 'GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node' );
  46050. }
  46051. /**
  46052. * Returns a builtin representing the index of the current invocation's subgroup within its workgroup.
  46053. */
  46054. getSubgroupIndex() {
  46055. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node' );
  46056. }
  46057. /**
  46058. * Returns the draw index builtin.
  46059. *
  46060. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  46061. */
  46062. getDrawIndex() {
  46063. const extensions = this.renderer.backend.extensions;
  46064. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  46065. return 'uint( gl_DrawID )';
  46066. } else {
  46067. return 'nodeUniformDrawId'; // fallback to uniform
  46068. }
  46069. }
  46070. /**
  46071. * Returns the front facing builtin.
  46072. *
  46073. * @return {string} The front facing builtin.
  46074. */
  46075. getFrontFacing() {
  46076. return 'gl_FrontFacing';
  46077. }
  46078. /**
  46079. * Returns the frag coord builtin.
  46080. *
  46081. * @return {string} The frag coord builtin.
  46082. */
  46083. getFragCoord() {
  46084. return 'gl_FragCoord.xy';
  46085. }
  46086. /**
  46087. * Returns the frag depth builtin.
  46088. *
  46089. * @return {string} The frag depth builtin.
  46090. */
  46091. getFragDepth() {
  46092. return 'gl_FragDepth';
  46093. }
  46094. /**
  46095. * Enables the given extension.
  46096. *
  46097. * @param {string} name - The extension name.
  46098. * @param {string} behavior - The extension behavior.
  46099. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  46100. */
  46101. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  46102. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  46103. if ( map.has( name ) === false ) {
  46104. map.set( name, {
  46105. name,
  46106. behavior
  46107. } );
  46108. }
  46109. }
  46110. /**
  46111. * Returns the enabled extensions of the given shader stage as a GLSL string.
  46112. *
  46113. * @param {string} shaderStage - The shader stage.
  46114. * @return {string} The GLSL snippet that defines the enabled extensions.
  46115. */
  46116. getExtensions( shaderStage ) {
  46117. const snippets = [];
  46118. if ( shaderStage === 'vertex' ) {
  46119. const ext = this.renderer.backend.extensions;
  46120. const isBatchedMesh = this.object.isBatchedMesh;
  46121. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  46122. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  46123. }
  46124. }
  46125. const extensions = this.extensions[ shaderStage ];
  46126. if ( extensions !== undefined ) {
  46127. for ( const { name, behavior } of extensions.values() ) {
  46128. snippets.push( `#extension ${name} : ${behavior}` );
  46129. }
  46130. }
  46131. return snippets.join( '\n' );
  46132. }
  46133. /**
  46134. * Returns the clip distances builtin.
  46135. *
  46136. * @return {string} The clip distances builtin.
  46137. */
  46138. getClipDistance() {
  46139. return 'gl_ClipDistance';
  46140. }
  46141. /**
  46142. * Whether the requested feature is available or not.
  46143. *
  46144. * @param {string} name - The requested feature.
  46145. * @return {boolean} Whether the requested feature is supported or not.
  46146. */
  46147. isAvailable( name ) {
  46148. let result = supports$1[ name ];
  46149. if ( result === undefined ) {
  46150. let extensionName;
  46151. result = false;
  46152. switch ( name ) {
  46153. case 'float32Filterable':
  46154. extensionName = 'OES_texture_float_linear';
  46155. break;
  46156. case 'clipDistance':
  46157. extensionName = 'WEBGL_clip_cull_distance';
  46158. break;
  46159. }
  46160. if ( extensionName !== undefined ) {
  46161. const extensions = this.renderer.backend.extensions;
  46162. if ( extensions.has( extensionName ) ) {
  46163. extensions.get( extensionName );
  46164. result = true;
  46165. }
  46166. }
  46167. supports$1[ name ] = result;
  46168. }
  46169. return result;
  46170. }
  46171. /**
  46172. * Whether to flip texture data along its vertical axis or not.
  46173. *
  46174. * @return {boolean} Returns always `true` in context of GLSL.
  46175. */
  46176. isFlipY() {
  46177. return true;
  46178. }
  46179. /**
  46180. * Enables hardware clipping.
  46181. *
  46182. * @param {string} planeCount - The clipping plane count.
  46183. */
  46184. enableHardwareClipping( planeCount ) {
  46185. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  46186. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  46187. }
  46188. /**
  46189. * Enables multiview.
  46190. */
  46191. enableMultiview() {
  46192. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  46193. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  46194. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  46195. }
  46196. /**
  46197. * Registers a transform in context of Transform Feedback.
  46198. *
  46199. * @param {string} varyingName - The varying name.
  46200. * @param {AttributeNode} attributeNode - The attribute node.
  46201. */
  46202. registerTransform( varyingName, attributeNode ) {
  46203. this.transforms.push( { varyingName, attributeNode } );
  46204. }
  46205. /**
  46206. * Returns the transforms of the given shader stage as a GLSL string.
  46207. *
  46208. * @param {string} shaderStage - The shader stage.
  46209. * @return {string} The GLSL snippet that defines the transforms.
  46210. */
  46211. getTransforms( /* shaderStage */ ) {
  46212. const transforms = this.transforms;
  46213. let snippet = '';
  46214. for ( let i = 0; i < transforms.length; i ++ ) {
  46215. const transform = transforms[ i ];
  46216. const attributeName = this.getPropertyName( transform.attributeNode );
  46217. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  46218. }
  46219. return snippet;
  46220. }
  46221. /**
  46222. * Returns a GLSL struct based on the given name and variables.
  46223. *
  46224. * @private
  46225. * @param {string} name - The struct name.
  46226. * @param {string} vars - The struct variables.
  46227. * @return {string} The GLSL snippet representing a struct.
  46228. */
  46229. _getGLSLUniformStruct( name, vars ) {
  46230. return `
  46231. layout( std140 ) uniform ${name} {
  46232. ${vars}
  46233. };`;
  46234. }
  46235. /**
  46236. * Returns a GLSL vertex shader based on the given shader data.
  46237. *
  46238. * @private
  46239. * @param {Object} shaderData - The shader data.
  46240. * @return {string} The vertex shader.
  46241. */
  46242. _getGLSLVertexCode( shaderData ) {
  46243. return `#version 300 es
  46244. ${ this.getSignature() }
  46245. // extensions
  46246. ${shaderData.extensions}
  46247. // precision
  46248. ${ defaultPrecisions }
  46249. // structs
  46250. ${shaderData.structs}
  46251. // uniforms
  46252. ${shaderData.uniforms}
  46253. // varyings
  46254. ${shaderData.varyings}
  46255. // attributes
  46256. ${shaderData.attributes}
  46257. // vars
  46258. ${shaderData.vars}
  46259. // codes
  46260. ${shaderData.codes}
  46261. void main() {
  46262. // transforms
  46263. ${shaderData.transforms}
  46264. // flow
  46265. ${shaderData.flow}
  46266. gl_PointSize = 1.0;
  46267. }
  46268. `;
  46269. }
  46270. /**
  46271. * Returns a GLSL fragment shader based on the given shader data.
  46272. *
  46273. * @private
  46274. * @param {Object} shaderData - The shader data.
  46275. * @return {string} The vertex shader.
  46276. */
  46277. _getGLSLFragmentCode( shaderData ) {
  46278. return `#version 300 es
  46279. ${ this.getSignature() }
  46280. // extensions
  46281. ${shaderData.extensions}
  46282. // precision
  46283. ${ defaultPrecisions }
  46284. // structs
  46285. ${shaderData.structs}
  46286. // uniforms
  46287. ${shaderData.uniforms}
  46288. // varyings
  46289. ${shaderData.varyings}
  46290. // vars
  46291. ${shaderData.vars}
  46292. // codes
  46293. ${shaderData.codes}
  46294. void main() {
  46295. // flow
  46296. ${shaderData.flow}
  46297. }
  46298. `;
  46299. }
  46300. /**
  46301. * Controls the code build of the shader stages.
  46302. */
  46303. buildCode() {
  46304. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  46305. this.sortBindingGroups();
  46306. for ( const shaderStage in shadersData ) {
  46307. let flow = '// code\n\n';
  46308. flow += this.flowCode[ shaderStage ];
  46309. const flowNodes = this.flowNodes[ shaderStage ];
  46310. const mainNode = flowNodes[ flowNodes.length - 1 ];
  46311. for ( const node of flowNodes ) {
  46312. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  46313. const slotName = node.name;
  46314. if ( slotName ) {
  46315. if ( flow.length > 0 ) flow += '\n';
  46316. flow += `\t// flow -> ${ slotName }\n\t`;
  46317. }
  46318. flow += `${ flowSlotData.code }\n\t`;
  46319. if ( node === mainNode && shaderStage !== 'compute' ) {
  46320. flow += '// result\n\t';
  46321. if ( shaderStage === 'vertex' ) {
  46322. flow += 'gl_Position = ';
  46323. flow += `${ flowSlotData.result };`;
  46324. } else if ( shaderStage === 'fragment' ) {
  46325. if ( ! node.outputNode.isOutputStructNode ) {
  46326. flow += 'fragColor = ';
  46327. flow += `${ flowSlotData.result };`;
  46328. }
  46329. }
  46330. }
  46331. }
  46332. const stageData = shadersData[ shaderStage ];
  46333. stageData.extensions = this.getExtensions( shaderStage );
  46334. stageData.uniforms = this.getUniforms( shaderStage );
  46335. stageData.attributes = this.getAttributes( shaderStage );
  46336. stageData.varyings = this.getVaryings( shaderStage );
  46337. stageData.vars = this.getVars( shaderStage, true );
  46338. stageData.structs = this.getStructs( shaderStage );
  46339. stageData.codes = this.getCodes( shaderStage );
  46340. stageData.transforms = this.getTransforms( shaderStage );
  46341. stageData.flow = flow;
  46342. // fallbacks
  46343. if ( shaderStage === 'vertex' ) {
  46344. const ext = this.renderer.backend.extensions;
  46345. if ( this.object.isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) === false ) {
  46346. stageData.uniforms += '\nuniform uint nodeUniformDrawId;\n';
  46347. }
  46348. }
  46349. }
  46350. if ( this.material !== null ) {
  46351. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  46352. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  46353. } else {
  46354. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  46355. }
  46356. }
  46357. /**
  46358. * This method is one of the more important ones since it's responsible
  46359. * for generating a matching binding instance for the given uniform node.
  46360. *
  46361. * These bindings are later used in the renderer to create bind groups
  46362. * and layouts.
  46363. *
  46364. * @param {UniformNode} node - The uniform node.
  46365. * @param {string} type - The node data type.
  46366. * @param {string} shaderStage - The shader stage.
  46367. * @param {?string} [name=null] - An optional uniform name.
  46368. * @return {NodeUniform} The node uniform object.
  46369. */
  46370. getUniformFromNode( node, type, shaderStage, name = null ) {
  46371. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  46372. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  46373. let uniformGPU = nodeData.uniformGPU;
  46374. if ( uniformGPU === undefined ) {
  46375. const group = node.groupNode;
  46376. const groupName = group.name;
  46377. const bindings = this.getBindGroupArray( groupName, shaderStage );
  46378. if ( type === 'texture' ) {
  46379. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  46380. bindings.push( uniformGPU );
  46381. } else if ( type === 'cubeTexture' || type === 'cubeDepthTexture' ) {
  46382. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  46383. bindings.push( uniformGPU );
  46384. } else if ( type === 'texture3D' ) {
  46385. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  46386. bindings.push( uniformGPU );
  46387. } else if ( type === 'buffer' ) {
  46388. uniformNode.name = `buffer${ node.id }`;
  46389. const sharedData = this.getSharedDataFromNode( node );
  46390. let buffer = sharedData.buffer;
  46391. if ( buffer === undefined ) {
  46392. node.name = `NodeBuffer_${ node.id }`;
  46393. buffer = new NodeUniformBuffer( node, group );
  46394. buffer.name = node.name;
  46395. sharedData.buffer = buffer;
  46396. }
  46397. bindings.push( buffer );
  46398. uniformGPU = buffer;
  46399. } else {
  46400. let uniformsGroup = this.uniformGroups[ groupName ];
  46401. if ( uniformsGroup === undefined ) {
  46402. uniformsGroup = new NodeUniformsGroup( groupName, group );
  46403. this.uniformGroups[ groupName ] = uniformsGroup;
  46404. bindings.push( uniformsGroup );
  46405. } else {
  46406. // Add to bindings for this stage if not already present
  46407. if ( bindings.indexOf( uniformsGroup ) === -1 ) {
  46408. bindings.push( uniformsGroup );
  46409. }
  46410. }
  46411. uniformGPU = this.getNodeUniform( uniformNode, type );
  46412. // Only add uniform if not already present in the group (check by name to avoid duplicates across stages)
  46413. const uniformName = uniformGPU.name;
  46414. const alreadyExists = uniformsGroup.uniforms.some( u => u.name === uniformName );
  46415. if ( ! alreadyExists ) {
  46416. uniformsGroup.addUniform( uniformGPU );
  46417. }
  46418. }
  46419. nodeData.uniformGPU = uniformGPU;
  46420. }
  46421. return uniformNode;
  46422. }
  46423. }
  46424. let _vector2 = null;
  46425. let _color4 = null;
  46426. /**
  46427. * Most of the rendering related logic is implemented in the
  46428. * {@link Renderer} module and related management components.
  46429. * Sometimes it is required though to execute commands which are
  46430. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  46431. * This abstract base class defines an interface that encapsulates
  46432. * all backend-related logic. Derived classes for each backend must
  46433. * implement the interface.
  46434. *
  46435. * @abstract
  46436. * @private
  46437. */
  46438. class Backend {
  46439. /**
  46440. * Constructs a new backend.
  46441. *
  46442. * @param {Object} parameters - An object holding parameters for the backend.
  46443. */
  46444. constructor( parameters = {} ) {
  46445. /**
  46446. * The parameters of the backend.
  46447. *
  46448. * @type {Object}
  46449. */
  46450. this.parameters = Object.assign( {}, parameters );
  46451. /**
  46452. * This weak map holds backend-specific data of objects
  46453. * like textures, attributes or render targets.
  46454. *
  46455. * @type {WeakMap<Object, Object>}
  46456. */
  46457. this.data = new WeakMap();
  46458. /**
  46459. * A reference to the renderer.
  46460. *
  46461. * @type {?Renderer}
  46462. * @default null
  46463. */
  46464. this.renderer = null;
  46465. /**
  46466. * A reference to the canvas element the renderer is drawing to.
  46467. *
  46468. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  46469. * @default null
  46470. */
  46471. this.domElement = null;
  46472. /**
  46473. * A reference to the timestamp query pool.
  46474. *
  46475. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  46476. */
  46477. this.timestampQueryPool = {
  46478. [ TimestampQuery.RENDER ]: null,
  46479. [ TimestampQuery.COMPUTE ]: null
  46480. };
  46481. /**
  46482. * Whether to track timestamps with a Timestamp Query API or not.
  46483. *
  46484. * @type {boolean}
  46485. * @default false
  46486. */
  46487. this.trackTimestamp = ( parameters.trackTimestamp === true );
  46488. }
  46489. /**
  46490. * Initializes the backend so it is ready for usage. Concrete backends
  46491. * are supposed to implement their rendering context creation and related
  46492. * operations in this method.
  46493. *
  46494. * @async
  46495. * @param {Renderer} renderer - The renderer.
  46496. * @return {Promise} A Promise that resolves when the backend has been initialized.
  46497. */
  46498. async init( renderer ) {
  46499. this.renderer = renderer;
  46500. }
  46501. /**
  46502. * The coordinate system of the backend.
  46503. *
  46504. * @abstract
  46505. * @type {number}
  46506. * @readonly
  46507. */
  46508. get coordinateSystem() {}
  46509. // render context
  46510. /**
  46511. * This method is executed at the beginning of a render call and
  46512. * can be used by the backend to prepare the state for upcoming
  46513. * draw calls.
  46514. *
  46515. * @abstract
  46516. * @param {RenderContext} renderContext - The render context.
  46517. */
  46518. beginRender( /*renderContext*/ ) {}
  46519. /**
  46520. * This method is executed at the end of a render call and
  46521. * can be used by the backend to finalize work after draw
  46522. * calls.
  46523. *
  46524. * @abstract
  46525. * @param {RenderContext} renderContext - The render context.
  46526. */
  46527. finishRender( /*renderContext*/ ) {}
  46528. /**
  46529. * This method is executed at the beginning of a compute call and
  46530. * can be used by the backend to prepare the state for upcoming
  46531. * compute tasks.
  46532. *
  46533. * @abstract
  46534. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  46535. */
  46536. beginCompute( /*computeGroup*/ ) {}
  46537. /**
  46538. * This method is executed at the end of a compute call and
  46539. * can be used by the backend to finalize work after compute
  46540. * tasks.
  46541. *
  46542. * @abstract
  46543. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  46544. */
  46545. finishCompute( /*computeGroup*/ ) {}
  46546. // render object
  46547. /**
  46548. * Executes a draw command for the given render object.
  46549. *
  46550. * @abstract
  46551. * @param {RenderObject} renderObject - The render object to draw.
  46552. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  46553. */
  46554. draw( /*renderObject, info*/ ) { }
  46555. // compute node
  46556. /**
  46557. * Executes a compute command for the given compute node.
  46558. *
  46559. * @abstract
  46560. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  46561. * @param {Node} computeNode - The compute node.
  46562. * @param {Array<BindGroup>} bindings - The bindings.
  46563. * @param {ComputePipeline} computePipeline - The compute pipeline.
  46564. */
  46565. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  46566. // program
  46567. /**
  46568. * Creates a shader program from the given programmable stage.
  46569. *
  46570. * @abstract
  46571. * @param {ProgrammableStage} program - The programmable stage.
  46572. */
  46573. createProgram( /*program*/ ) { }
  46574. /**
  46575. * Destroys the shader program of the given programmable stage.
  46576. *
  46577. * @abstract
  46578. * @param {ProgrammableStage} program - The programmable stage.
  46579. */
  46580. destroyProgram( /*program*/ ) { }
  46581. // bindings
  46582. /**
  46583. * Creates bindings from the given bind group definition.
  46584. *
  46585. * @abstract
  46586. * @param {BindGroup} bindGroup - The bind group.
  46587. * @param {Array<BindGroup>} bindings - Array of bind groups.
  46588. * @param {number} cacheIndex - The cache index.
  46589. * @param {number} version - The version.
  46590. */
  46591. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  46592. /**
  46593. * Updates the given bind group definition.
  46594. *
  46595. * @abstract
  46596. * @param {BindGroup} bindGroup - The bind group.
  46597. * @param {Array<BindGroup>} bindings - Array of bind groups.
  46598. * @param {number} cacheIndex - The cache index.
  46599. * @param {number} version - The version.
  46600. */
  46601. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  46602. /**
  46603. * Updates a buffer binding.
  46604. *
  46605. * @abstract
  46606. * @param {Buffer} binding - The buffer binding to update.
  46607. */
  46608. updateBinding( /*binding*/ ) { }
  46609. // pipeline
  46610. /**
  46611. * Creates a render pipeline for the given render object.
  46612. *
  46613. * @abstract
  46614. * @param {RenderObject} renderObject - The render object.
  46615. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  46616. */
  46617. createRenderPipeline( /*renderObject, promises*/ ) { }
  46618. /**
  46619. * Creates a compute pipeline for the given compute node.
  46620. *
  46621. * @abstract
  46622. * @param {ComputePipeline} computePipeline - The compute pipeline.
  46623. * @param {Array<BindGroup>} bindings - The bindings.
  46624. */
  46625. createComputePipeline( /*computePipeline, bindings*/ ) { }
  46626. // cache key
  46627. /**
  46628. * Returns `true` if the render pipeline requires an update.
  46629. *
  46630. * @abstract
  46631. * @param {RenderObject} renderObject - The render object.
  46632. * @return {boolean} Whether the render pipeline requires an update or not.
  46633. */
  46634. needsRenderUpdate( /*renderObject*/ ) { }
  46635. /**
  46636. * Returns a cache key that is used to identify render pipelines.
  46637. *
  46638. * @abstract
  46639. * @param {RenderObject} renderObject - The render object.
  46640. * @return {string} The cache key.
  46641. */
  46642. getRenderCacheKey( /*renderObject*/ ) { }
  46643. // node builder
  46644. /**
  46645. * Returns a node builder for the given render object.
  46646. *
  46647. * @abstract
  46648. * @param {RenderObject} renderObject - The render object.
  46649. * @param {Renderer} renderer - The renderer.
  46650. * @return {NodeBuilder} The node builder.
  46651. */
  46652. createNodeBuilder( /*renderObject, renderer*/ ) { }
  46653. // textures
  46654. /**
  46655. * Updates a GPU sampler for the given texture.
  46656. *
  46657. * @abstract
  46658. * @param {Texture} texture - The texture to update the sampler for.
  46659. * @param {TextureNode} textureNode - The texture node to update the sampler with.
  46660. * @return {string} The current sampler key.
  46661. */
  46662. updateSampler( /*texture, textureNode*/ ) { }
  46663. /**
  46664. * Creates a default texture for the given texture that can be used
  46665. * as a placeholder until the actual texture is ready for usage.
  46666. *
  46667. * @abstract
  46668. * @param {Texture} texture - The texture to create a default texture for.
  46669. */
  46670. createDefaultTexture( /*texture*/ ) { }
  46671. /**
  46672. * Defines a texture on the GPU for the given texture object.
  46673. *
  46674. * @abstract
  46675. * @param {Texture} texture - The texture.
  46676. * @param {Object} [options={}] - Optional configuration parameter.
  46677. */
  46678. createTexture( /*texture, options={}*/ ) { }
  46679. /**
  46680. * Uploads the updated texture data to the GPU.
  46681. *
  46682. * @abstract
  46683. * @param {Texture} texture - The texture.
  46684. * @param {Object} [options={}] - Optional configuration parameter.
  46685. */
  46686. updateTexture( /*texture, options = {}*/ ) { }
  46687. /**
  46688. * Generates mipmaps for the given texture.
  46689. *
  46690. * @abstract
  46691. * @param {Texture} texture - The texture.
  46692. */
  46693. generateMipmaps( /*texture*/ ) { }
  46694. /**
  46695. * Destroys the GPU data for the given texture object.
  46696. *
  46697. * @abstract
  46698. * @param {Texture} texture - The texture.
  46699. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  46700. */
  46701. destroyTexture( /*texture, isDefaultTexture*/ ) { }
  46702. /**
  46703. * Returns texture data as a typed array.
  46704. *
  46705. * @abstract
  46706. * @async
  46707. * @param {Texture} texture - The texture to copy.
  46708. * @param {number} x - The x coordinate of the copy origin.
  46709. * @param {number} y - The y coordinate of the copy origin.
  46710. * @param {number} width - The width of the copy.
  46711. * @param {number} height - The height of the copy.
  46712. * @param {number} faceIndex - The face index.
  46713. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  46714. */
  46715. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  46716. /**
  46717. * Copies data of the given source texture to the given destination texture.
  46718. *
  46719. * @abstract
  46720. * @param {Texture} srcTexture - The source texture.
  46721. * @param {Texture} dstTexture - The destination texture.
  46722. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  46723. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  46724. * @param {number} [srcLevel=0] - The source mip level to copy from.
  46725. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  46726. */
  46727. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  46728. /**
  46729. * Copies the current bound framebuffer to the given texture.
  46730. *
  46731. * @abstract
  46732. * @param {Texture} texture - The destination texture.
  46733. * @param {RenderContext} renderContext - The render context.
  46734. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  46735. */
  46736. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  46737. // attributes
  46738. /**
  46739. * Creates the GPU buffer of a shader attribute.
  46740. *
  46741. * @abstract
  46742. * @param {BufferAttribute} attribute - The buffer attribute.
  46743. */
  46744. createAttribute( /*attribute*/ ) { }
  46745. /**
  46746. * Creates the GPU buffer of an indexed shader attribute.
  46747. *
  46748. * @abstract
  46749. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  46750. */
  46751. createIndexAttribute( /*attribute*/ ) { }
  46752. /**
  46753. * Creates the GPU buffer of a storage attribute.
  46754. *
  46755. * @abstract
  46756. * @param {BufferAttribute} attribute - The buffer attribute.
  46757. */
  46758. createStorageAttribute( /*attribute*/ ) { }
  46759. /**
  46760. * Creates a uniform buffer.
  46761. *
  46762. * @abstract
  46763. * @param {Buffer} uniformBuffer - The uniform buffer.
  46764. */
  46765. createUniformBuffer( /*uniformBuffer*/ ) { }
  46766. /**
  46767. * Destroys a uniform buffer.
  46768. *
  46769. * @abstract
  46770. * @param {Buffer} uniformBuffer - The uniform buffer.
  46771. */
  46772. destroyUniformBuffer( /*uniformBuffer*/ ) { }
  46773. /**
  46774. * Updates the GPU buffer of a shader attribute.
  46775. *
  46776. * @abstract
  46777. * @param {BufferAttribute} attribute - The buffer attribute to update.
  46778. */
  46779. updateAttribute( /*attribute*/ ) { }
  46780. /**
  46781. * Destroys the GPU buffer of a shader attribute.
  46782. *
  46783. * @abstract
  46784. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  46785. */
  46786. destroyAttribute( /*attribute*/ ) { }
  46787. // canvas
  46788. /**
  46789. * Returns the backend's rendering context.
  46790. *
  46791. * @abstract
  46792. * @return {Object} The rendering context.
  46793. */
  46794. getContext() { }
  46795. /**
  46796. * Backends can use this method if they have to run
  46797. * logic when the renderer gets resized.
  46798. *
  46799. * @abstract
  46800. */
  46801. updateSize() { }
  46802. /**
  46803. * Updates the viewport with the values from the given render context.
  46804. *
  46805. * @abstract
  46806. * @param {RenderContext} renderContext - The render context.
  46807. */
  46808. updateViewport( /*renderContext*/ ) {}
  46809. // utils
  46810. /**
  46811. * Updates a unique identifier for the given render context that can be used
  46812. * to allocate resources like occlusion queries or timestamp queries.
  46813. *
  46814. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  46815. */
  46816. updateTimeStampUID( abstractRenderContext ) {
  46817. const contextData = this.get( abstractRenderContext );
  46818. const frame = this.renderer.info.frame;
  46819. let prefix;
  46820. if ( abstractRenderContext.isComputeNode === true ) {
  46821. prefix = 'c:' + this.renderer.info.compute.frameCalls;
  46822. } else {
  46823. prefix = 'r:' + this.renderer.info.render.frameCalls;
  46824. }
  46825. contextData.timestampUID = prefix + ':' + abstractRenderContext.id + ':f' + frame;
  46826. }
  46827. /**
  46828. * Returns a unique identifier for the given render context that can be used
  46829. * to allocate resources like occlusion queries or timestamp queries.
  46830. *
  46831. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  46832. * @return {string} The unique identifier.
  46833. */
  46834. getTimestampUID( abstractRenderContext ) {
  46835. return this.get( abstractRenderContext ).timestampUID;
  46836. }
  46837. /**
  46838. * Returns all timestamp frames for the given type.
  46839. *
  46840. * @param {string} type - The type of the time stamp.
  46841. * @return {Array<number>} The timestamp frames.
  46842. */
  46843. getTimestampFrames( type ) {
  46844. const queryPool = this.timestampQueryPool[ type ];
  46845. return queryPool ? queryPool.getTimestampFrames() : [];
  46846. }
  46847. /**
  46848. * Returns the query pool for the given uid.
  46849. *
  46850. * @param {string} uid - The unique identifier.
  46851. * @return {TimestampQueryPool} The query pool.
  46852. */
  46853. _getQueryPool( uid ) {
  46854. const type = uid.startsWith( 'c:' ) ? TimestampQuery.COMPUTE : TimestampQuery.RENDER;
  46855. const queryPool = this.timestampQueryPool[ type ];
  46856. return queryPool;
  46857. }
  46858. /**
  46859. * Returns the timestamp for the given uid.
  46860. *
  46861. * @param {string} uid - The unique identifier.
  46862. * @return {number} The timestamp.
  46863. */
  46864. getTimestamp( uid ) {
  46865. const queryPool = this._getQueryPool( uid );
  46866. return queryPool.getTimestamp( uid );
  46867. }
  46868. /**
  46869. * Returns `true` if a timestamp for the given uid is available.
  46870. *
  46871. * @param {string} uid - The unique identifier.
  46872. * @return {boolean} Whether the timestamp is available or not.
  46873. */
  46874. hasTimestamp( uid ) {
  46875. const queryPool = this._getQueryPool( uid );
  46876. return queryPool.hasTimestamp( uid );
  46877. }
  46878. /**
  46879. * Returns `true` if the given 3D object is fully occluded by other
  46880. * 3D objects in the scene. Backends must implement this method by using
  46881. * a Occlusion Query API.
  46882. *
  46883. * @abstract
  46884. * @param {RenderContext} renderContext - The render context.
  46885. * @param {Object3D} object - The 3D object to test.
  46886. * @return {boolean} Whether the 3D object is fully occluded or not.
  46887. */
  46888. isOccluded( /*renderContext, object*/ ) {}
  46889. /**
  46890. * Resolves the time stamp for the given render context and type.
  46891. *
  46892. * @async
  46893. * @abstract
  46894. * @param {string} [type='render'] - The type of the time stamp.
  46895. * @return {Promise<number>} A Promise that resolves with the time stamp.
  46896. */
  46897. async resolveTimestampsAsync( type = 'render' ) {
  46898. if ( ! this.trackTimestamp ) {
  46899. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  46900. return;
  46901. }
  46902. const queryPool = this.timestampQueryPool[ type ];
  46903. if ( ! queryPool ) {
  46904. return;
  46905. }
  46906. const duration = await queryPool.resolveQueriesAsync();
  46907. this.renderer.info[ type ].timestamp = duration;
  46908. return duration;
  46909. }
  46910. /**
  46911. * This method performs a readback operation by moving buffer data from
  46912. * a storage buffer attribute from the GPU to the CPU.
  46913. *
  46914. * @async
  46915. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  46916. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  46917. */
  46918. async getArrayBufferAsync( /* attribute */ ) {}
  46919. /**
  46920. * Checks if the given feature is supported by the backend.
  46921. *
  46922. * @async
  46923. * @abstract
  46924. * @param {string} name - The feature's name.
  46925. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  46926. */
  46927. async hasFeatureAsync( /*name*/ ) { }
  46928. /**
  46929. * Checks if the given feature is supported by the backend.
  46930. *
  46931. * @abstract
  46932. * @param {string} name - The feature's name.
  46933. * @return {boolean} Whether the feature is supported or not.
  46934. */
  46935. hasFeature( /*name*/ ) {}
  46936. /**
  46937. * Returns the drawing buffer size.
  46938. *
  46939. * @return {Vector2} The drawing buffer size.
  46940. */
  46941. getDrawingBufferSize() {
  46942. _vector2 = _vector2 || new Vector2();
  46943. return this.renderer.getDrawingBufferSize( _vector2 );
  46944. }
  46945. /**
  46946. * Defines the scissor test.
  46947. *
  46948. * @abstract
  46949. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  46950. */
  46951. setScissorTest( /*boolean*/ ) { }
  46952. /**
  46953. * Returns the clear color and alpha into a single
  46954. * color object.
  46955. *
  46956. * @return {Color4} The clear color.
  46957. */
  46958. getClearColor() {
  46959. const renderer = this.renderer;
  46960. _color4 = _color4 || new Color4();
  46961. renderer.getClearColor( _color4 );
  46962. _color4.getRGB( _color4 );
  46963. return _color4;
  46964. }
  46965. /**
  46966. * Returns the DOM element. If no DOM element exists, the backend
  46967. * creates a new one.
  46968. *
  46969. * @return {HTMLCanvasElement} The DOM element.
  46970. */
  46971. getDomElement() {
  46972. let domElement = this.domElement;
  46973. if ( domElement === null ) {
  46974. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  46975. // OffscreenCanvas does not have setAttribute, see #22811
  46976. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  46977. this.domElement = domElement;
  46978. }
  46979. return domElement;
  46980. }
  46981. /**
  46982. * Checks if the backend has the given compatibility.
  46983. *
  46984. * @abstract
  46985. * @param {string} name - The compatibility.
  46986. * @return {boolean} Whether the backend has the given compatibility or not.
  46987. */
  46988. hasCompatibility( /*name*/ ) {
  46989. return false;
  46990. }
  46991. /**
  46992. * Initializes the render target defined in the given render context.
  46993. *
  46994. * @abstract
  46995. * @param {RenderContext} renderContext - The render context.
  46996. */
  46997. initRenderTarget( /*renderContext*/ ) {}
  46998. /**
  46999. * Sets a dictionary for the given object into the
  47000. * internal data structure.
  47001. *
  47002. * @param {Object} object - The object.
  47003. * @param {Object} value - The dictionary to set.
  47004. */
  47005. set( object, value ) {
  47006. this.data.set( object, value );
  47007. }
  47008. /**
  47009. * Returns the dictionary for the given object.
  47010. *
  47011. * @param {Object} object - The object.
  47012. * @return {Object} The object's dictionary.
  47013. */
  47014. get( object ) {
  47015. let map = this.data.get( object );
  47016. if ( map === undefined ) {
  47017. map = {};
  47018. this.data.set( object, map );
  47019. }
  47020. return map;
  47021. }
  47022. /**
  47023. * Checks if the given object has a dictionary
  47024. * with data defined.
  47025. *
  47026. * @param {Object} object - The object.
  47027. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  47028. */
  47029. has( object ) {
  47030. return this.data.has( object );
  47031. }
  47032. /**
  47033. * Deletes an object from the internal data structure.
  47034. *
  47035. * @param {Object} object - The object to delete.
  47036. */
  47037. delete( object ) {
  47038. this.data.delete( object );
  47039. }
  47040. /**
  47041. * Delete GPU data associated with a bind group.
  47042. *
  47043. * @abstract
  47044. * @param {BindGroup} bindGroup - The bind group.
  47045. */
  47046. deleteBindGroupData( /*bindGroup*/ ) { }
  47047. /**
  47048. * Frees internal resources.
  47049. *
  47050. * @abstract
  47051. */
  47052. dispose() { }
  47053. }
  47054. let _id$1 = 0;
  47055. /**
  47056. * This module is internally used in context of compute shaders.
  47057. * This type of shader is not natively supported in WebGL 2 and
  47058. * thus implemented via Transform Feedback. `DualAttributeData`
  47059. * manages the related data.
  47060. *
  47061. * @private
  47062. */
  47063. class DualAttributeData {
  47064. constructor( attributeData, dualBuffer ) {
  47065. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  47066. this.type = attributeData.type;
  47067. this.bufferType = attributeData.bufferType;
  47068. this.pbo = attributeData.pbo;
  47069. this.byteLength = attributeData.byteLength;
  47070. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  47071. this.version = attributeData.version;
  47072. this.isInteger = attributeData.isInteger;
  47073. this.activeBufferIndex = 0;
  47074. this.baseId = attributeData.id;
  47075. }
  47076. get id() {
  47077. return `${ this.baseId }|${ this.activeBufferIndex }`;
  47078. }
  47079. get bufferGPU() {
  47080. return this.buffers[ this.activeBufferIndex ];
  47081. }
  47082. get transformBuffer() {
  47083. return this.buffers[ this.activeBufferIndex ^ 1 ];
  47084. }
  47085. switchBuffers() {
  47086. this.activeBufferIndex ^= 1;
  47087. }
  47088. }
  47089. /**
  47090. * A WebGL 2 backend utility module for managing shader attributes.
  47091. *
  47092. * @private
  47093. */
  47094. class WebGLAttributeUtils {
  47095. /**
  47096. * Constructs a new utility object.
  47097. *
  47098. * @param {WebGLBackend} backend - The WebGL 2 backend.
  47099. */
  47100. constructor( backend ) {
  47101. /**
  47102. * A reference to the WebGL 2 backend.
  47103. *
  47104. * @type {WebGLBackend}
  47105. */
  47106. this.backend = backend;
  47107. }
  47108. /**
  47109. * Creates the GPU buffer for the given buffer attribute.
  47110. *
  47111. * @param {BufferAttribute} attribute - The buffer attribute.
  47112. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  47113. */
  47114. createAttribute( attribute, bufferType ) {
  47115. const backend = this.backend;
  47116. const { gl } = backend;
  47117. const array = attribute.array;
  47118. const usage = attribute.usage || gl.STATIC_DRAW;
  47119. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  47120. const bufferData = backend.get( bufferAttribute );
  47121. let bufferGPU = bufferData.bufferGPU;
  47122. if ( bufferGPU === undefined ) {
  47123. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  47124. bufferData.bufferGPU = bufferGPU;
  47125. bufferData.bufferType = bufferType;
  47126. bufferData.version = bufferAttribute.version;
  47127. }
  47128. //attribute.onUploadCallback();
  47129. let type;
  47130. if ( array instanceof Float32Array ) {
  47131. type = gl.FLOAT;
  47132. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  47133. type = gl.HALF_FLOAT;
  47134. } else if ( array instanceof Uint16Array ) {
  47135. if ( attribute.isFloat16BufferAttribute ) {
  47136. type = gl.HALF_FLOAT;
  47137. } else {
  47138. type = gl.UNSIGNED_SHORT;
  47139. }
  47140. } else if ( array instanceof Int16Array ) {
  47141. type = gl.SHORT;
  47142. } else if ( array instanceof Uint32Array ) {
  47143. type = gl.UNSIGNED_INT;
  47144. } else if ( array instanceof Int32Array ) {
  47145. type = gl.INT;
  47146. } else if ( array instanceof Int8Array ) {
  47147. type = gl.BYTE;
  47148. } else if ( array instanceof Uint8Array ) {
  47149. type = gl.UNSIGNED_BYTE;
  47150. } else if ( array instanceof Uint8ClampedArray ) {
  47151. type = gl.UNSIGNED_BYTE;
  47152. } else {
  47153. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  47154. }
  47155. let attributeData = {
  47156. bufferGPU,
  47157. bufferType,
  47158. type,
  47159. byteLength: array.byteLength,
  47160. bytesPerElement: array.BYTES_PER_ELEMENT,
  47161. version: attribute.version,
  47162. pbo: attribute.pbo,
  47163. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  47164. id: _id$1 ++
  47165. };
  47166. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  47167. // create buffer for transform feedback use
  47168. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  47169. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  47170. }
  47171. backend.set( attribute, attributeData );
  47172. }
  47173. /**
  47174. * Updates the GPU buffer of the given buffer attribute.
  47175. *
  47176. * @param {BufferAttribute} attribute - The buffer attribute.
  47177. */
  47178. updateAttribute( attribute ) {
  47179. const backend = this.backend;
  47180. const { gl } = backend;
  47181. const array = attribute.array;
  47182. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  47183. const bufferData = backend.get( bufferAttribute );
  47184. const bufferType = bufferData.bufferType;
  47185. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  47186. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  47187. if ( updateRanges.length === 0 ) {
  47188. // Not using update ranges
  47189. gl.bufferSubData( bufferType, 0, array );
  47190. } else {
  47191. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  47192. const range = updateRanges[ i ];
  47193. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  47194. array, range.start, range.count );
  47195. }
  47196. bufferAttribute.clearUpdateRanges();
  47197. }
  47198. gl.bindBuffer( bufferType, null );
  47199. bufferData.version = bufferAttribute.version;
  47200. }
  47201. /**
  47202. * Destroys the GPU buffer of the given buffer attribute.
  47203. *
  47204. * @param {BufferAttribute} attribute - The buffer attribute.
  47205. */
  47206. destroyAttribute( attribute ) {
  47207. const backend = this.backend;
  47208. const { gl } = backend;
  47209. if ( attribute.isInterleavedBufferAttribute ) {
  47210. backend.delete( attribute.data );
  47211. }
  47212. const attributeData = backend.get( attribute );
  47213. gl.deleteBuffer( attributeData.bufferGPU );
  47214. backend.delete( attribute );
  47215. }
  47216. /**
  47217. * This method performs a readback operation by moving buffer data from
  47218. * a storage buffer attribute from the GPU to the CPU. ReadbackBuffer can
  47219. * be used to retain and reuse handles to the intermediate buffers and prevent
  47220. * new allocation.
  47221. *
  47222. * @async
  47223. * @param {BufferAttribute} attribute - The storage buffer attribute to read frm.
  47224. * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute.
  47225. * @param {number} offset - The storage buffer attribute.
  47226. * @param {number} count - The offset from which to start reading the
  47227. * @return {Promise<ArrayBuffer|ReadbackBuffer>} A promise that resolves with the buffer data when the data are ready.
  47228. */
  47229. async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) {
  47230. const backend = this.backend;
  47231. const { gl } = backend;
  47232. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  47233. const attributeInfo = backend.get( bufferAttribute );
  47234. const { bufferGPU } = attributeInfo;
  47235. const byteLength = count === -1 ? attributeInfo.byteLength - offset : count;
  47236. // read the data back
  47237. let dstBuffer;
  47238. if ( target === null ) {
  47239. dstBuffer = new Uint8Array( new ArrayBuffer( byteLength ) );
  47240. } else if ( target.isReadbackBuffer ) {
  47241. if ( target._mapped === true ) {
  47242. throw new Error( 'WebGPURenderer: ReadbackBuffer must be released before being used again.' );
  47243. }
  47244. const releaseCallback = () => {
  47245. target.buffer = null;
  47246. target._mapped = false;
  47247. target.removeEventListener( 'release', releaseCallback );
  47248. target.removeEventListener( 'dispose', releaseCallback );
  47249. };
  47250. target.addEventListener( 'release', releaseCallback );
  47251. target.addEventListener( 'dispose', releaseCallback );
  47252. // WebGL has no concept of a "mapped" data buffer so we create a new buffer, instead.
  47253. dstBuffer = new Uint8Array( new ArrayBuffer( byteLength ) );
  47254. target.buffer = dstBuffer.buffer;
  47255. } else {
  47256. dstBuffer = new Uint8Array( target );
  47257. }
  47258. // Ensure the buffer is bound before reading
  47259. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  47260. gl.getBufferSubData( gl.COPY_READ_BUFFER, offset, dstBuffer );
  47261. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  47262. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  47263. // return the appropriate type
  47264. if ( target && target.isReadbackBuffer ) {
  47265. return target;
  47266. } else {
  47267. return dstBuffer.buffer;
  47268. }
  47269. }
  47270. /**
  47271. * Creates a WebGL buffer with the given data.
  47272. *
  47273. * @private
  47274. * @param {WebGL2RenderingContext} gl - The rendering context.
  47275. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  47276. * @param {TypedArray} array - The array of the buffer attribute.
  47277. * @param {GLenum} usage - The usage.
  47278. * @return {WebGLBuffer} The WebGL buffer.
  47279. */
  47280. _createBuffer( gl, bufferType, array, usage ) {
  47281. const bufferGPU = gl.createBuffer();
  47282. gl.bindBuffer( bufferType, bufferGPU );
  47283. gl.bufferData( bufferType, array, usage );
  47284. gl.bindBuffer( bufferType, null );
  47285. return bufferGPU;
  47286. }
  47287. }
  47288. let equationToGL, factorToGL;
  47289. /**
  47290. * A WebGL 2 backend utility module for managing the WebGL state.
  47291. *
  47292. * The major goal of this module is to reduce the number of state changes
  47293. * by caching the WEbGL state with a series of variables. In this way, the
  47294. * renderer only executes state change commands when necessary which
  47295. * improves the overall performance.
  47296. *
  47297. * @private
  47298. */
  47299. class WebGLState {
  47300. /**
  47301. * Constructs a new utility object.
  47302. *
  47303. * @param {WebGLBackend} backend - The WebGL 2 backend.
  47304. */
  47305. constructor( backend ) {
  47306. /**
  47307. * A reference to the WebGL 2 backend.
  47308. *
  47309. * @type {WebGLBackend}
  47310. */
  47311. this.backend = backend;
  47312. /**
  47313. * A reference to the rendering context.
  47314. *
  47315. * @type {WebGL2RenderingContext}
  47316. */
  47317. this.gl = this.backend.gl;
  47318. // Below properties are intended to cache
  47319. // the WebGL state and are not explicitly
  47320. // documented for convenience reasons.
  47321. this.enabled = {};
  47322. this.parameters = {};
  47323. this.currentFlipSided = null;
  47324. this.currentCullFace = null;
  47325. this.currentProgram = null;
  47326. this.currentBlendingEnabled = false;
  47327. this.currentBlending = null;
  47328. this.currentBlendSrc = null;
  47329. this.currentBlendDst = null;
  47330. this.currentBlendSrcAlpha = null;
  47331. this.currentBlendDstAlpha = null;
  47332. this.currentPremultipledAlpha = null;
  47333. this.currentPolygonOffsetFactor = null;
  47334. this.currentPolygonOffsetUnits = null;
  47335. this.currentColorMask = null;
  47336. this.currentDepthReversed = false;
  47337. this.currentDepthFunc = null;
  47338. this.currentDepthMask = null;
  47339. this.currentStencilFunc = null;
  47340. this.currentStencilRef = null;
  47341. this.currentStencilFuncMask = null;
  47342. this.currentStencilFail = null;
  47343. this.currentStencilZFail = null;
  47344. this.currentStencilZPass = null;
  47345. this.currentStencilMask = null;
  47346. this.currentLineWidth = null;
  47347. this.currentClippingPlanes = 0;
  47348. this.currentVAO = null;
  47349. this.currentIndex = null;
  47350. this.currentBoundFramebuffers = {};
  47351. this.currentDrawbuffers = new WeakMap();
  47352. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  47353. this.currentTextureSlot = null;
  47354. this.currentBoundTextures = {};
  47355. this.currentBoundBufferBases = {};
  47356. this._init();
  47357. }
  47358. /**
  47359. * Inits the state of the utility.
  47360. *
  47361. * @private
  47362. */
  47363. _init() {
  47364. const gl = this.gl;
  47365. // Store only WebGL constants here.
  47366. equationToGL = {
  47367. [ AddEquation ]: gl.FUNC_ADD,
  47368. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  47369. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  47370. };
  47371. factorToGL = {
  47372. [ ZeroFactor ]: gl.ZERO,
  47373. [ OneFactor ]: gl.ONE,
  47374. [ SrcColorFactor ]: gl.SRC_COLOR,
  47375. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  47376. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  47377. [ DstColorFactor ]: gl.DST_COLOR,
  47378. [ DstAlphaFactor ]: gl.DST_ALPHA,
  47379. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  47380. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  47381. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  47382. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  47383. };
  47384. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  47385. const viewportParam = gl.getParameter( gl.VIEWPORT );
  47386. this.currentScissor = new Vector4().fromArray( scissorParam );
  47387. this.currentViewport = new Vector4().fromArray( viewportParam );
  47388. this._tempVec4 = new Vector4();
  47389. }
  47390. /**
  47391. * Enables the given WebGL capability.
  47392. *
  47393. * This method caches the capability state so
  47394. * `gl.enable()` is only called when necessary.
  47395. *
  47396. * @param {GLenum} id - The capability to enable.
  47397. */
  47398. enable( id ) {
  47399. const { enabled } = this;
  47400. if ( enabled[ id ] !== true ) {
  47401. this.gl.enable( id );
  47402. enabled[ id ] = true;
  47403. }
  47404. }
  47405. /**
  47406. * Disables the given WebGL capability.
  47407. *
  47408. * This method caches the capability state so
  47409. * `gl.disable()` is only called when necessary.
  47410. *
  47411. * @param {GLenum} id - The capability to enable.
  47412. */
  47413. disable( id ) {
  47414. const { enabled } = this;
  47415. if ( enabled[ id ] !== false ) {
  47416. this.gl.disable( id );
  47417. enabled[ id ] = false;
  47418. }
  47419. }
  47420. /**
  47421. * Specifies whether polygons are front- or back-facing
  47422. * by setting the winding orientation.
  47423. *
  47424. * This method caches the state so `gl.frontFace()` is only
  47425. * called when necessary.
  47426. *
  47427. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  47428. */
  47429. setFlipSided( flipSided ) {
  47430. if ( this.currentFlipSided !== flipSided ) {
  47431. const { gl } = this;
  47432. if ( flipSided ) {
  47433. gl.frontFace( gl.CW );
  47434. } else {
  47435. gl.frontFace( gl.CCW );
  47436. }
  47437. this.currentFlipSided = flipSided;
  47438. }
  47439. }
  47440. /**
  47441. * Specifies whether or not front- and/or back-facing
  47442. * polygons can be culled.
  47443. *
  47444. * This method caches the state so `gl.cullFace()` is only
  47445. * called when necessary.
  47446. *
  47447. * @param {number} cullFace - Defines which polygons are candidates for culling.
  47448. */
  47449. setCullFace( cullFace ) {
  47450. const { gl } = this;
  47451. if ( cullFace !== CullFaceNone ) {
  47452. this.enable( gl.CULL_FACE );
  47453. if ( cullFace !== this.currentCullFace ) {
  47454. if ( cullFace === CullFaceBack ) {
  47455. gl.cullFace( gl.BACK );
  47456. } else if ( cullFace === CullFaceFront ) {
  47457. gl.cullFace( gl.FRONT );
  47458. } else {
  47459. gl.cullFace( gl.FRONT_AND_BACK );
  47460. }
  47461. }
  47462. } else {
  47463. this.disable( gl.CULL_FACE );
  47464. }
  47465. this.currentCullFace = cullFace;
  47466. }
  47467. /**
  47468. * Specifies the width of line primitives.
  47469. *
  47470. * This method caches the state so `gl.lineWidth()` is only
  47471. * called when necessary.
  47472. *
  47473. * @param {number} width - The line width.
  47474. */
  47475. setLineWidth( width ) {
  47476. const { currentLineWidth, gl } = this;
  47477. if ( width !== currentLineWidth ) {
  47478. gl.lineWidth( width );
  47479. this.currentLineWidth = width;
  47480. }
  47481. }
  47482. setMRTBlending( textures, mrt, material ) {
  47483. const gl = this.gl;
  47484. const drawBuffersIndexedExt = this.backend.drawBuffersIndexedExt;
  47485. if ( ! drawBuffersIndexedExt ) {
  47486. 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.' );
  47487. return;
  47488. }
  47489. for ( let i = 0; i < textures.length; i ++ ) {
  47490. const texture = textures[ i ];
  47491. let blending = null;
  47492. if ( mrt !== null ) {
  47493. const blendMode = mrt.getBlendMode( texture.name );
  47494. if ( blendMode.blending === MaterialBlending ) {
  47495. // use material blending
  47496. blending = material;
  47497. } else if ( blendMode.blending !== NoBlending ) {
  47498. blending = blendMode;
  47499. }
  47500. } else {
  47501. // use material blending
  47502. blending = material;
  47503. }
  47504. if ( blending !== null ) {
  47505. this._setMRTBlendingIndex( i, blending );
  47506. } else {
  47507. // use opaque blending (no blending)
  47508. drawBuffersIndexedExt.blendFuncSeparateiOES( i, gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  47509. }
  47510. }
  47511. }
  47512. /**
  47513. * Applies blending configuration for a specific draw buffer index.
  47514. *
  47515. * @private
  47516. * @param {number} index - The draw buffer index.
  47517. * @param {Object} blending - The blending configuration (material or BlendMode).
  47518. */
  47519. _setMRTBlendingIndex( index, blending ) {
  47520. const { gl } = this;
  47521. const drawBuffersIndexedExt = this.backend.drawBuffersIndexedExt;
  47522. const blendingType = blending.blending;
  47523. const blendSrc = blending.blendSrc;
  47524. const blendDst = blending.blendDst;
  47525. const blendEquation = blending.blendEquation;
  47526. const premultipliedAlpha = blending.premultipliedAlpha;
  47527. if ( blendingType === CustomBlending ) {
  47528. const blendSrcAlpha = blending.blendSrcAlpha !== null ? blending.blendSrcAlpha : blendSrc;
  47529. const blendDstAlpha = blending.blendDstAlpha !== null ? blending.blendDstAlpha : blendDst;
  47530. const blendEquationAlpha = blending.blendEquationAlpha !== null ? blending.blendEquationAlpha : blendEquation;
  47531. drawBuffersIndexedExt.blendEquationSeparateiOES( index, equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  47532. drawBuffersIndexedExt.blendFuncSeparateiOES( index, factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  47533. } else {
  47534. drawBuffersIndexedExt.blendEquationSeparateiOES( index, gl.FUNC_ADD, gl.FUNC_ADD );
  47535. if ( premultipliedAlpha ) {
  47536. switch ( blendingType ) {
  47537. case NormalBlending:
  47538. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  47539. break;
  47540. case AdditiveBlending:
  47541. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  47542. break;
  47543. case SubtractiveBlending:
  47544. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  47545. break;
  47546. case MultiplyBlending:
  47547. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  47548. break;
  47549. default:
  47550. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  47551. break;
  47552. }
  47553. } else {
  47554. switch ( blendingType ) {
  47555. case NormalBlending:
  47556. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  47557. break;
  47558. case AdditiveBlending:
  47559. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  47560. break;
  47561. case SubtractiveBlending:
  47562. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  47563. break;
  47564. case MultiplyBlending:
  47565. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  47566. break;
  47567. default:
  47568. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  47569. break;
  47570. }
  47571. }
  47572. }
  47573. }
  47574. /**
  47575. * Defines the blending.
  47576. *
  47577. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  47578. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  47579. *
  47580. * @param {number} blending - The blending type.
  47581. * @param {number} blendEquation - The blending equation.
  47582. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  47583. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  47584. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  47585. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  47586. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  47587. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  47588. */
  47589. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  47590. const { gl } = this;
  47591. if ( blending === NoBlending ) {
  47592. if ( this.currentBlendingEnabled === true ) {
  47593. this.disable( gl.BLEND );
  47594. this.currentBlendingEnabled = false;
  47595. }
  47596. return;
  47597. }
  47598. if ( this.currentBlendingEnabled === false ) {
  47599. this.enable( gl.BLEND );
  47600. this.currentBlendingEnabled = true;
  47601. }
  47602. if ( blending !== CustomBlending ) {
  47603. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  47604. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  47605. gl.blendEquation( gl.FUNC_ADD );
  47606. this.currentBlendEquation = AddEquation;
  47607. this.currentBlendEquationAlpha = AddEquation;
  47608. }
  47609. if ( premultipliedAlpha ) {
  47610. switch ( blending ) {
  47611. case NormalBlending:
  47612. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  47613. break;
  47614. case AdditiveBlending:
  47615. gl.blendFunc( gl.ONE, gl.ONE );
  47616. break;
  47617. case SubtractiveBlending:
  47618. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  47619. break;
  47620. case MultiplyBlending:
  47621. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  47622. break;
  47623. default:
  47624. error( 'WebGLState: Invalid blending: ', blending );
  47625. break;
  47626. }
  47627. } else {
  47628. switch ( blending ) {
  47629. case NormalBlending:
  47630. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  47631. break;
  47632. case AdditiveBlending:
  47633. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  47634. break;
  47635. case SubtractiveBlending:
  47636. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  47637. break;
  47638. case MultiplyBlending:
  47639. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  47640. break;
  47641. default:
  47642. error( 'WebGLState: Invalid blending: ', blending );
  47643. break;
  47644. }
  47645. }
  47646. this.currentBlendSrc = null;
  47647. this.currentBlendDst = null;
  47648. this.currentBlendSrcAlpha = null;
  47649. this.currentBlendDstAlpha = null;
  47650. this.currentBlending = blending;
  47651. this.currentPremultipledAlpha = premultipliedAlpha;
  47652. }
  47653. return;
  47654. }
  47655. // custom blending
  47656. blendEquationAlpha = blendEquationAlpha || blendEquation;
  47657. blendSrcAlpha = blendSrcAlpha || blendSrc;
  47658. blendDstAlpha = blendDstAlpha || blendDst;
  47659. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  47660. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  47661. this.currentBlendEquation = blendEquation;
  47662. this.currentBlendEquationAlpha = blendEquationAlpha;
  47663. }
  47664. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  47665. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  47666. this.currentBlendSrc = blendSrc;
  47667. this.currentBlendDst = blendDst;
  47668. this.currentBlendSrcAlpha = blendSrcAlpha;
  47669. this.currentBlendDstAlpha = blendDstAlpha;
  47670. }
  47671. this.currentBlending = blending;
  47672. this.currentPremultipledAlpha = false;
  47673. }
  47674. /**
  47675. * Specifies whether colors can be written when rendering
  47676. * into a framebuffer or not.
  47677. *
  47678. * This method caches the state so `gl.colorMask()` is only
  47679. * called when necessary.
  47680. *
  47681. * @param {boolean} colorMask - The color mask.
  47682. */
  47683. setColorMask( colorMask ) {
  47684. if ( this.currentColorMask !== colorMask ) {
  47685. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  47686. this.currentColorMask = colorMask;
  47687. }
  47688. }
  47689. /**
  47690. * Specifies whether the depth test is enabled or not.
  47691. *
  47692. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  47693. */
  47694. setDepthTest( depthTest ) {
  47695. const { gl } = this;
  47696. if ( depthTest ) {
  47697. this.enable( gl.DEPTH_TEST );
  47698. } else {
  47699. this.disable( gl.DEPTH_TEST );
  47700. }
  47701. }
  47702. /**
  47703. * Configures the WebGL state to use a reversed depth buffer.
  47704. *
  47705. * @param {boolean} reversed - Whether the depth buffer is reversed or not.
  47706. */
  47707. setReversedDepth( reversed ) {
  47708. if ( this.currentDepthReversed !== reversed ) {
  47709. const ext = this.backend.extensions.get( 'EXT_clip_control' );
  47710. if ( reversed ) {
  47711. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT );
  47712. } else {
  47713. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT );
  47714. }
  47715. this.currentDepthReversed = reversed;
  47716. }
  47717. }
  47718. /**
  47719. * Specifies whether depth values can be written when rendering
  47720. * into a framebuffer or not.
  47721. *
  47722. * This method caches the state so `gl.depthMask()` is only
  47723. * called when necessary.
  47724. *
  47725. * @param {boolean} depthMask - The depth mask.
  47726. */
  47727. setDepthMask( depthMask ) {
  47728. if ( this.currentDepthMask !== depthMask ) {
  47729. this.gl.depthMask( depthMask );
  47730. this.currentDepthMask = depthMask;
  47731. }
  47732. }
  47733. /**
  47734. * Specifies the depth compare function.
  47735. *
  47736. * This method caches the state so `gl.depthFunc()` is only
  47737. * called when necessary.
  47738. *
  47739. * @param {number} depthFunc - The depth compare function.
  47740. */
  47741. setDepthFunc( depthFunc ) {
  47742. if ( this.currentDepthReversed ) depthFunc = ReversedDepthFuncs[ depthFunc ];
  47743. if ( this.currentDepthFunc !== depthFunc ) {
  47744. const { gl } = this;
  47745. switch ( depthFunc ) {
  47746. case NeverDepth:
  47747. gl.depthFunc( gl.NEVER );
  47748. break;
  47749. case AlwaysDepth:
  47750. gl.depthFunc( gl.ALWAYS );
  47751. break;
  47752. case LessDepth:
  47753. gl.depthFunc( gl.LESS );
  47754. break;
  47755. case LessEqualDepth:
  47756. gl.depthFunc( gl.LEQUAL );
  47757. break;
  47758. case EqualDepth:
  47759. gl.depthFunc( gl.EQUAL );
  47760. break;
  47761. case GreaterEqualDepth:
  47762. gl.depthFunc( gl.GEQUAL );
  47763. break;
  47764. case GreaterDepth:
  47765. gl.depthFunc( gl.GREATER );
  47766. break;
  47767. case NotEqualDepth:
  47768. gl.depthFunc( gl.NOTEQUAL );
  47769. break;
  47770. default:
  47771. gl.depthFunc( gl.LEQUAL );
  47772. }
  47773. this.currentDepthFunc = depthFunc;
  47774. }
  47775. }
  47776. /**
  47777. * Specifies the scissor box.
  47778. *
  47779. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  47780. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  47781. * @param {number} width - The width of the viewport.
  47782. * @param {number} height - The height of the viewport.
  47783. *
  47784. */
  47785. scissor( x, y, width, height ) {
  47786. const scissor = this._tempVec4.set( x, y, width, height );
  47787. if ( this.currentScissor.equals( scissor ) === false ) {
  47788. const { gl } = this;
  47789. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  47790. this.currentScissor.copy( scissor );
  47791. }
  47792. }
  47793. /**
  47794. * Specifies the viewport.
  47795. *
  47796. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  47797. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  47798. * @param {number} width - The width of the viewport.
  47799. * @param {number} height - The height of the viewport.
  47800. *
  47801. */
  47802. viewport( x, y, width, height ) {
  47803. const viewport = this._tempVec4.set( x, y, width, height );
  47804. if ( this.currentViewport.equals( viewport ) === false ) {
  47805. const { gl } = this;
  47806. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  47807. this.currentViewport.copy( viewport );
  47808. }
  47809. }
  47810. /**
  47811. * Defines the scissor test.
  47812. *
  47813. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  47814. */
  47815. setScissorTest( boolean ) {
  47816. const gl = this.gl;
  47817. if ( boolean ) {
  47818. this.enable( gl.SCISSOR_TEST );
  47819. } else {
  47820. this.disable( gl.SCISSOR_TEST );
  47821. }
  47822. }
  47823. /**
  47824. * Specifies whether the stencil test is enabled or not.
  47825. *
  47826. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  47827. */
  47828. setStencilTest( stencilTest ) {
  47829. const { gl } = this;
  47830. if ( stencilTest ) {
  47831. this.enable( gl.STENCIL_TEST );
  47832. } else {
  47833. this.disable( gl.STENCIL_TEST );
  47834. }
  47835. }
  47836. /**
  47837. * Specifies whether stencil values can be written when rendering
  47838. * into a framebuffer or not.
  47839. *
  47840. * This method caches the state so `gl.stencilMask()` is only
  47841. * called when necessary.
  47842. *
  47843. * @param {boolean} stencilMask - The stencil mask.
  47844. */
  47845. setStencilMask( stencilMask ) {
  47846. if ( this.currentStencilMask !== stencilMask ) {
  47847. this.gl.stencilMask( stencilMask );
  47848. this.currentStencilMask = stencilMask;
  47849. }
  47850. }
  47851. /**
  47852. * Specifies whether the stencil test functions.
  47853. *
  47854. * This method caches the state so `gl.stencilFunc()` is only
  47855. * called when necessary.
  47856. *
  47857. * @param {number} stencilFunc - The stencil compare function.
  47858. * @param {number} stencilRef - The reference value for the stencil test.
  47859. * @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.
  47860. */
  47861. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  47862. if ( this.currentStencilFunc !== stencilFunc ||
  47863. this.currentStencilRef !== stencilRef ||
  47864. this.currentStencilFuncMask !== stencilMask ) {
  47865. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  47866. this.currentStencilFunc = stencilFunc;
  47867. this.currentStencilRef = stencilRef;
  47868. this.currentStencilFuncMask = stencilMask;
  47869. }
  47870. }
  47871. /**
  47872. * Specifies whether the stencil test operation.
  47873. *
  47874. * This method caches the state so `gl.stencilOp()` is only
  47875. * called when necessary.
  47876. *
  47877. * @param {number} stencilFail - The function to use when the stencil test fails.
  47878. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  47879. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  47880. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  47881. */
  47882. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  47883. if ( this.currentStencilFail !== stencilFail ||
  47884. this.currentStencilZFail !== stencilZFail ||
  47885. this.currentStencilZPass !== stencilZPass ) {
  47886. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  47887. this.currentStencilFail = stencilFail;
  47888. this.currentStencilZFail = stencilZFail;
  47889. this.currentStencilZPass = stencilZPass;
  47890. }
  47891. }
  47892. /**
  47893. * Configures the WebGL state for the given material.
  47894. *
  47895. * @param {Material} material - The material to configure the state for.
  47896. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  47897. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  47898. */
  47899. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  47900. const { gl } = this;
  47901. material.side === DoubleSide
  47902. ? this.disable( gl.CULL_FACE )
  47903. : this.enable( gl.CULL_FACE );
  47904. let flipSided = ( material.side === BackSide );
  47905. if ( frontFaceCW ) flipSided = ! flipSided;
  47906. this.setFlipSided( flipSided );
  47907. ( material.blending === NormalBlending && material.transparent === false )
  47908. ? this.setBlending( NoBlending )
  47909. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  47910. this.setDepthFunc( material.depthFunc );
  47911. this.setDepthTest( material.depthTest );
  47912. this.setDepthMask( material.depthWrite );
  47913. this.setColorMask( material.colorWrite );
  47914. const stencilWrite = material.stencilWrite;
  47915. this.setStencilTest( stencilWrite );
  47916. if ( stencilWrite ) {
  47917. this.setStencilMask( material.stencilWriteMask );
  47918. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  47919. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  47920. }
  47921. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  47922. material.alphaToCoverage === true && this.backend.renderer.currentSamples > 0
  47923. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  47924. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  47925. if ( hardwareClippingPlanes > 0 ) {
  47926. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  47927. const CLIP_DISTANCE0_WEBGL = 0x3000;
  47928. for ( let i = 0; i < 8; i ++ ) {
  47929. if ( i < hardwareClippingPlanes ) {
  47930. this.enable( CLIP_DISTANCE0_WEBGL + i );
  47931. } else {
  47932. this.disable( CLIP_DISTANCE0_WEBGL + i );
  47933. }
  47934. }
  47935. }
  47936. }
  47937. }
  47938. /**
  47939. * Specifies the polygon offset.
  47940. *
  47941. * This method caches the state so `gl.polygonOffset()` is only
  47942. * called when necessary.
  47943. *
  47944. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  47945. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  47946. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  47947. */
  47948. setPolygonOffset( polygonOffset, factor, units ) {
  47949. const { gl } = this;
  47950. if ( polygonOffset ) {
  47951. this.enable( gl.POLYGON_OFFSET_FILL );
  47952. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  47953. gl.polygonOffset( factor, units );
  47954. this.currentPolygonOffsetFactor = factor;
  47955. this.currentPolygonOffsetUnits = units;
  47956. }
  47957. } else {
  47958. this.disable( gl.POLYGON_OFFSET_FILL );
  47959. }
  47960. }
  47961. /**
  47962. * Defines the usage of the given WebGL program.
  47963. *
  47964. * This method caches the state so `gl.useProgram()` is only
  47965. * called when necessary.
  47966. *
  47967. * @param {WebGLProgram} program - The WebGL program to use.
  47968. * @return {boolean} Whether a program change has been executed or not.
  47969. */
  47970. useProgram( program ) {
  47971. if ( this.currentProgram !== program ) {
  47972. this.gl.useProgram( program );
  47973. this.currentProgram = program;
  47974. return true;
  47975. }
  47976. return false;
  47977. }
  47978. /**
  47979. * Sets the vertex state by binding the given VAO and element buffer.
  47980. *
  47981. * @param {WebGLVertexArrayObject} vao - The VAO.
  47982. * @param {?WebGLBuffer} indexBuffer - The index buffer.
  47983. * @return {boolean} Whether a vertex state has been changed or not.
  47984. */
  47985. setVertexState( vao, indexBuffer = null ) {
  47986. const gl = this.gl;
  47987. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  47988. gl.bindVertexArray( vao );
  47989. if ( indexBuffer !== null ) {
  47990. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  47991. }
  47992. this.currentVAO = vao;
  47993. this.currentIndex = indexBuffer;
  47994. return true;
  47995. }
  47996. return false;
  47997. }
  47998. /**
  47999. * Resets the vertex array state by resetting the VAO and element buffer.
  48000. */
  48001. resetVertexState() {
  48002. const gl = this.gl;
  48003. gl.bindVertexArray( null );
  48004. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  48005. this.currentVAO = null;
  48006. this.currentIndex = null;
  48007. }
  48008. // framebuffer
  48009. /**
  48010. * Binds the given framebuffer.
  48011. *
  48012. * This method caches the state so `gl.bindFramebuffer()` is only
  48013. * called when necessary.
  48014. *
  48015. * @param {number} target - The binding point (target).
  48016. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  48017. * @return {boolean} Whether a bind has been executed or not.
  48018. */
  48019. bindFramebuffer( target, framebuffer ) {
  48020. const { gl, currentBoundFramebuffers } = this;
  48021. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  48022. gl.bindFramebuffer( target, framebuffer );
  48023. currentBoundFramebuffers[ target ] = framebuffer;
  48024. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  48025. if ( target === gl.DRAW_FRAMEBUFFER ) {
  48026. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  48027. }
  48028. if ( target === gl.FRAMEBUFFER ) {
  48029. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  48030. }
  48031. return true;
  48032. }
  48033. return false;
  48034. }
  48035. /**
  48036. * Defines draw buffers to which fragment colors are written into.
  48037. * Configures the MRT setup of custom framebuffers.
  48038. *
  48039. * This method caches the state so `gl.drawBuffers()` is only
  48040. * called when necessary.
  48041. *
  48042. * @param {RenderContext} renderContext - The render context.
  48043. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  48044. */
  48045. drawBuffers( renderContext, framebuffer ) {
  48046. const { gl } = this;
  48047. let drawBuffers = [];
  48048. let needsUpdate = false;
  48049. if ( renderContext.textures !== null ) {
  48050. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  48051. if ( drawBuffers === undefined ) {
  48052. drawBuffers = [];
  48053. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  48054. }
  48055. const textures = renderContext.textures;
  48056. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  48057. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  48058. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  48059. }
  48060. drawBuffers.length = textures.length;
  48061. needsUpdate = true;
  48062. }
  48063. } else {
  48064. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  48065. drawBuffers[ 0 ] = gl.BACK;
  48066. needsUpdate = true;
  48067. }
  48068. }
  48069. if ( needsUpdate ) {
  48070. gl.drawBuffers( drawBuffers );
  48071. }
  48072. }
  48073. // texture
  48074. /**
  48075. * Makes the given texture unit active.
  48076. *
  48077. * This method caches the state so `gl.activeTexture()` is only
  48078. * called when necessary.
  48079. *
  48080. * @param {number} webglSlot - The texture unit to make active.
  48081. */
  48082. activeTexture( webglSlot ) {
  48083. const { gl, currentTextureSlot, maxTextures } = this;
  48084. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  48085. if ( currentTextureSlot !== webglSlot ) {
  48086. gl.activeTexture( webglSlot );
  48087. this.currentTextureSlot = webglSlot;
  48088. }
  48089. }
  48090. /**
  48091. * Binds the given WebGL texture to a target.
  48092. *
  48093. * This method caches the state so `gl.bindTexture()` is only
  48094. * called when necessary.
  48095. *
  48096. * @param {number} webglType - The binding point (target).
  48097. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  48098. * @param {number} webglSlot - The texture.
  48099. */
  48100. bindTexture( webglType, webglTexture, webglSlot ) {
  48101. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  48102. if ( webglSlot === undefined ) {
  48103. if ( currentTextureSlot === null ) {
  48104. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  48105. } else {
  48106. webglSlot = currentTextureSlot;
  48107. }
  48108. }
  48109. let boundTexture = currentBoundTextures[ webglSlot ];
  48110. if ( boundTexture === undefined ) {
  48111. boundTexture = { type: undefined, texture: undefined };
  48112. currentBoundTextures[ webglSlot ] = boundTexture;
  48113. }
  48114. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  48115. if ( currentTextureSlot !== webglSlot ) {
  48116. gl.activeTexture( webglSlot );
  48117. this.currentTextureSlot = webglSlot;
  48118. }
  48119. gl.bindTexture( webglType, webglTexture );
  48120. boundTexture.type = webglType;
  48121. boundTexture.texture = webglTexture;
  48122. }
  48123. }
  48124. /**
  48125. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  48126. *
  48127. * This method caches the state so `gl.bindBufferBase()` is only
  48128. * called when necessary.
  48129. *
  48130. * @param {number} target - The target for the bind operation.
  48131. * @param {number} index - The index of the target.
  48132. * @param {WebGLBuffer} buffer - The WebGL buffer.
  48133. * @return {boolean} Whether a bind has been executed or not.
  48134. */
  48135. bindBufferBase( target, index, buffer ) {
  48136. const { gl } = this;
  48137. const key = `${target}-${index}`;
  48138. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  48139. gl.bindBufferBase( target, index, buffer );
  48140. this.currentBoundBufferBases[ key ] = buffer;
  48141. return true;
  48142. }
  48143. return false;
  48144. }
  48145. /**
  48146. * Unbinds the current bound texture.
  48147. *
  48148. * This method caches the state so `gl.bindTexture()` is only
  48149. * called when necessary.
  48150. */
  48151. unbindTexture() {
  48152. const { gl, currentTextureSlot, currentBoundTextures } = this;
  48153. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  48154. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  48155. gl.bindTexture( boundTexture.type, null );
  48156. boundTexture.type = undefined;
  48157. boundTexture.texture = undefined;
  48158. }
  48159. }
  48160. /**
  48161. * Returns the value for the given parameter.
  48162. *
  48163. * @param {number} name - The paramter to get the value for.
  48164. * @return {any} The value for the given parameter.
  48165. */
  48166. getParameter( name ) {
  48167. const { gl, parameters } = this;
  48168. if ( parameters[ name ] !== undefined ) {
  48169. return parameters[ name ];
  48170. } else {
  48171. return gl.getParameter( name );
  48172. }
  48173. }
  48174. /**
  48175. * Specifies a pixel storage mode.
  48176. *
  48177. * @param {number} name - The parameter to set.
  48178. * @param {any} value - A value to set the parameter to.
  48179. */
  48180. pixelStorei( name, value ) {
  48181. const { gl, parameters } = this;
  48182. if ( parameters[ name ] !== value ) {
  48183. gl.pixelStorei( name, value );
  48184. parameters[ name ] = value;
  48185. }
  48186. }
  48187. }
  48188. /**
  48189. * A WebGL 2 backend utility module with common helpers.
  48190. *
  48191. * @private
  48192. */
  48193. class WebGLUtils {
  48194. /**
  48195. * Constructs a new utility object.
  48196. *
  48197. * @param {WebGLBackend} backend - The WebGL 2 backend.
  48198. */
  48199. constructor( backend ) {
  48200. /**
  48201. * A reference to the WebGL 2 backend.
  48202. *
  48203. * @type {WebGLBackend}
  48204. */
  48205. this.backend = backend;
  48206. /**
  48207. * A reference to the rendering context.
  48208. *
  48209. * @type {WebGL2RenderingContext}
  48210. */
  48211. this.gl = this.backend.gl;
  48212. /**
  48213. * A reference to a backend module holding extension-related
  48214. * utility functions.
  48215. *
  48216. * @type {WebGLExtensions}
  48217. */
  48218. this.extensions = backend.extensions;
  48219. }
  48220. /**
  48221. * Converts the given three.js constant into a WebGL constant.
  48222. * The method currently supports the conversion of texture formats
  48223. * and types.
  48224. *
  48225. * @param {number} p - The three.js constant.
  48226. * @param {string} [colorSpace=NoColorSpace] - The color space.
  48227. * @return {?number} The corresponding WebGL constant.
  48228. */
  48229. convert( p, colorSpace = NoColorSpace ) {
  48230. const { gl, extensions } = this;
  48231. let extension;
  48232. const transfer = ColorManagement.getTransfer( colorSpace );
  48233. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  48234. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  48235. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  48236. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  48237. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  48238. if ( p === ByteType ) return gl.BYTE;
  48239. if ( p === ShortType ) return gl.SHORT;
  48240. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  48241. if ( p === IntType ) return gl.INT;
  48242. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  48243. if ( p === FloatType ) return gl.FLOAT;
  48244. if ( p === HalfFloatType ) {
  48245. return gl.HALF_FLOAT;
  48246. }
  48247. if ( p === AlphaFormat ) return gl.ALPHA;
  48248. if ( p === RGBFormat ) return gl.RGB;
  48249. if ( p === RGBAFormat ) return gl.RGBA;
  48250. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  48251. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  48252. // WebGL2 formats.
  48253. if ( p === RedFormat ) return gl.RED;
  48254. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  48255. if ( p === RGFormat ) return gl.RG;
  48256. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  48257. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  48258. // S3TC
  48259. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  48260. if ( transfer === SRGBTransfer ) {
  48261. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  48262. if ( extension !== null ) {
  48263. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  48264. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  48265. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  48266. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  48267. } else {
  48268. return null;
  48269. }
  48270. } else {
  48271. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  48272. if ( extension !== null ) {
  48273. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  48274. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  48275. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  48276. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  48277. } else {
  48278. return null;
  48279. }
  48280. }
  48281. }
  48282. // PVRTC
  48283. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  48284. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  48285. if ( extension !== null ) {
  48286. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  48287. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  48288. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  48289. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  48290. } else {
  48291. return null;
  48292. }
  48293. }
  48294. // ETC
  48295. 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 ) {
  48296. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  48297. if ( extension !== null ) {
  48298. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  48299. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  48300. if ( p === R11_EAC_Format ) return extension.COMPRESSED_R11_EAC;
  48301. if ( p === SIGNED_R11_EAC_Format ) return extension.COMPRESSED_SIGNED_R11_EAC;
  48302. if ( p === RG11_EAC_Format ) return extension.COMPRESSED_RG11_EAC;
  48303. if ( p === SIGNED_RG11_EAC_Format ) return extension.COMPRESSED_SIGNED_RG11_EAC;
  48304. } else {
  48305. return null;
  48306. }
  48307. }
  48308. // ASTC
  48309. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  48310. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  48311. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  48312. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  48313. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  48314. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  48315. if ( extension !== null ) {
  48316. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  48317. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  48318. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  48319. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  48320. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  48321. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  48322. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  48323. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  48324. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  48325. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  48326. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  48327. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  48328. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  48329. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  48330. } else {
  48331. return null;
  48332. }
  48333. }
  48334. // BPTC
  48335. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  48336. extension = extensions.get( 'EXT_texture_compression_bptc' );
  48337. if ( extension !== null ) {
  48338. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  48339. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  48340. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  48341. } else {
  48342. return null;
  48343. }
  48344. }
  48345. // RGTC
  48346. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  48347. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  48348. if ( extension !== null ) {
  48349. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  48350. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  48351. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  48352. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  48353. } else {
  48354. return null;
  48355. }
  48356. }
  48357. //
  48358. if ( p === UnsignedInt248Type ) {
  48359. return gl.UNSIGNED_INT_24_8;
  48360. }
  48361. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  48362. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  48363. }
  48364. /**
  48365. * This method can be used to synchronize the CPU with the GPU by waiting until
  48366. * ongoing GPU commands have been completed.
  48367. *
  48368. * @private
  48369. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  48370. */
  48371. _clientWaitAsync() {
  48372. const { gl } = this;
  48373. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  48374. gl.flush();
  48375. return new Promise( ( resolve, reject ) => {
  48376. function test() {
  48377. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  48378. if ( res === gl.WAIT_FAILED ) {
  48379. gl.deleteSync( sync );
  48380. reject();
  48381. return;
  48382. }
  48383. if ( res === gl.TIMEOUT_EXPIRED ) {
  48384. requestAnimationFrame( test );
  48385. return;
  48386. }
  48387. gl.deleteSync( sync );
  48388. resolve();
  48389. }
  48390. test();
  48391. } );
  48392. }
  48393. }
  48394. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  48395. /**
  48396. * A WebGL 2 backend utility module for managing textures.
  48397. *
  48398. * @private
  48399. */
  48400. class WebGLTextureUtils {
  48401. /**
  48402. * Constructs a new utility object.
  48403. *
  48404. * @param {WebGLBackend} backend - The WebGL 2 backend.
  48405. */
  48406. constructor( backend ) {
  48407. /**
  48408. * A reference to the WebGL 2 backend.
  48409. *
  48410. * @type {WebGLBackend}
  48411. */
  48412. this.backend = backend;
  48413. /**
  48414. * A reference to the rendering context.
  48415. *
  48416. * @type {WebGL2RenderingContext}
  48417. */
  48418. this.gl = backend.gl;
  48419. /**
  48420. * A reference to a backend module holding extension-related
  48421. * utility functions.
  48422. *
  48423. * @type {WebGLExtensions}
  48424. */
  48425. this.extensions = backend.extensions;
  48426. /**
  48427. * A dictionary for managing default textures. The key
  48428. * is the binding point (target), the value the WEbGL texture object.
  48429. *
  48430. * @type {Object<GLenum,WebGLTexture>}
  48431. */
  48432. this.defaultTextures = {};
  48433. /**
  48434. * A scratch framebuffer used for attaching the source texture in
  48435. * {@link copyTextureToTexture}.
  48436. *
  48437. * @private
  48438. * @type {?WebGLFramebuffer}
  48439. */
  48440. this._srcFramebuffer = null;
  48441. /**
  48442. * A scratch framebuffer used for attaching the destination texture in
  48443. * {@link copyTextureToTexture}.
  48444. *
  48445. * @private
  48446. * @type {?WebGLFramebuffer}
  48447. */
  48448. this._dstFramebuffer = null;
  48449. if ( initialized === false ) {
  48450. this._init();
  48451. initialized = true;
  48452. }
  48453. }
  48454. /**
  48455. * Inits the state of the utility.
  48456. *
  48457. * @private
  48458. */
  48459. _init() {
  48460. const gl = this.gl;
  48461. // Store only WebGL constants here.
  48462. wrappingToGL = {
  48463. [ RepeatWrapping ]: gl.REPEAT,
  48464. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  48465. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  48466. };
  48467. filterToGL = {
  48468. [ NearestFilter ]: gl.NEAREST,
  48469. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  48470. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  48471. [ LinearFilter ]: gl.LINEAR,
  48472. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  48473. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  48474. };
  48475. compareToGL = {
  48476. [ NeverCompare ]: gl.NEVER,
  48477. [ AlwaysCompare ]: gl.ALWAYS,
  48478. [ LessCompare ]: gl.LESS,
  48479. [ LessEqualCompare ]: gl.LEQUAL,
  48480. [ EqualCompare ]: gl.EQUAL,
  48481. [ GreaterEqualCompare ]: gl.GEQUAL,
  48482. [ GreaterCompare ]: gl.GREATER,
  48483. [ NotEqualCompare ]: gl.NOTEQUAL
  48484. };
  48485. }
  48486. /**
  48487. * Returns the native texture type for the given texture.
  48488. *
  48489. * @param {Texture} texture - The texture.
  48490. * @return {GLenum} The native texture type.
  48491. */
  48492. getGLTextureType( texture ) {
  48493. const { gl } = this;
  48494. let glTextureType;
  48495. if ( texture.isCubeTexture === true ) {
  48496. glTextureType = gl.TEXTURE_CUBE_MAP;
  48497. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  48498. glTextureType = gl.TEXTURE_2D_ARRAY;
  48499. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  48500. glTextureType = gl.TEXTURE_3D;
  48501. } else {
  48502. glTextureType = gl.TEXTURE_2D;
  48503. }
  48504. return glTextureType;
  48505. }
  48506. /**
  48507. * Returns the native texture type for the given texture.
  48508. *
  48509. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  48510. * @param {GLenum} glFormat - The WebGL format.
  48511. * @param {GLenum} glType - The WebGL type.
  48512. * @param {string} colorSpace - The texture's color space.
  48513. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  48514. * @return {GLenum} The internal format.
  48515. */
  48516. getInternalFormat( internalFormatName, glFormat, glType, normalized, colorSpace, forceLinearTransfer = false ) {
  48517. const { gl, extensions } = this;
  48518. if ( internalFormatName !== null ) {
  48519. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  48520. warn( 'WebGLBackend: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  48521. }
  48522. let extTextureNorm16 = null;
  48523. if ( normalized ) {
  48524. extTextureNorm16 = extensions.get( 'EXT_texture_norm16' );
  48525. if ( ! extTextureNorm16 ) {
  48526. warn( 'WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension' );
  48527. }
  48528. }
  48529. let internalFormat = glFormat;
  48530. if ( glFormat === gl.RED ) {
  48531. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  48532. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  48533. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  48534. if ( glType === gl.BYTE ) internalFormat = gl.R8_SNORM;
  48535. if ( glType === gl.UNSIGNED_SHORT && extTextureNorm16 ) internalFormat = extTextureNorm16.R16_EXT;
  48536. if ( glType === gl.SHORT && extTextureNorm16 ) internalFormat = extTextureNorm16.R16_SNORM_EXT;
  48537. }
  48538. if ( glFormat === gl.RED_INTEGER ) {
  48539. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  48540. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  48541. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  48542. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  48543. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  48544. if ( glType === gl.INT ) internalFormat = gl.R32I;
  48545. }
  48546. if ( glFormat === gl.RG ) {
  48547. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  48548. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  48549. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  48550. if ( glType === gl.BYTE ) internalFormat = gl.RG8_SNORM;
  48551. if ( glType === gl.UNSIGNED_SHORT && extTextureNorm16 ) internalFormat = extTextureNorm16.RG16_EXT;
  48552. if ( glType === gl.SHORT && extTextureNorm16 ) internalFormat = extTextureNorm16.RG16_SNORM_EXT;
  48553. }
  48554. if ( glFormat === gl.RG_INTEGER ) {
  48555. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  48556. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  48557. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  48558. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  48559. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  48560. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  48561. }
  48562. if ( glFormat === gl.RGB ) {
  48563. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  48564. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  48565. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  48566. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  48567. if ( glType === gl.BYTE ) internalFormat = gl.RGB8_SNORM;
  48568. if ( glType === gl.UNSIGNED_SHORT && extTextureNorm16 ) internalFormat = extTextureNorm16.RGB16_EXT;
  48569. if ( glType === gl.SHORT && extTextureNorm16 ) internalFormat = extTextureNorm16.RGB16_SNORM_EXT;
  48570. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  48571. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  48572. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  48573. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  48574. if ( glType === gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = gl.R11F_G11F_B10F;
  48575. }
  48576. if ( glFormat === gl.RGB_INTEGER ) {
  48577. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  48578. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  48579. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  48580. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  48581. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  48582. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  48583. }
  48584. if ( glFormat === gl.RGBA ) {
  48585. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  48586. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  48587. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  48588. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  48589. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8_SNORM;
  48590. if ( glType === gl.UNSIGNED_SHORT && extTextureNorm16 ) internalFormat = extTextureNorm16.RGBA16_EXT;
  48591. if ( glType === gl.SHORT && extTextureNorm16 ) internalFormat = extTextureNorm16.RGBA16_SNORM_EXT;
  48592. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  48593. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  48594. }
  48595. if ( glFormat === gl.RGBA_INTEGER ) {
  48596. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  48597. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  48598. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  48599. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  48600. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  48601. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  48602. }
  48603. if ( glFormat === gl.DEPTH_COMPONENT ) {
  48604. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  48605. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  48606. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  48607. }
  48608. if ( glFormat === gl.DEPTH_STENCIL ) {
  48609. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  48610. }
  48611. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  48612. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  48613. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  48614. extensions.get( 'EXT_color_buffer_float' );
  48615. }
  48616. return internalFormat;
  48617. }
  48618. /**
  48619. * Sets the texture parameters for the given texture.
  48620. *
  48621. * @param {GLenum} textureType - The texture type.
  48622. * @param {Texture} texture - The texture.
  48623. */
  48624. setTextureParameters( textureType, texture ) {
  48625. const { gl, extensions, backend } = this;
  48626. const { state } = this.backend;
  48627. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  48628. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  48629. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  48630. state.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  48631. state.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  48632. state.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  48633. state.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  48634. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  48635. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  48636. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  48637. // WebGL 2 does not support wrapping for depth 2D array textures
  48638. if ( ! texture.isArrayTexture ) {
  48639. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  48640. }
  48641. }
  48642. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  48643. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  48644. // follow WebGPU backend mapping for texture filtering
  48645. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  48646. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  48647. if ( texture.compareFunction ) {
  48648. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  48649. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  48650. }
  48651. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  48652. if ( texture.magFilter === NearestFilter ) return;
  48653. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  48654. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  48655. if ( texture.anisotropy > 1 ) {
  48656. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  48657. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.capabilities.getMaxAnisotropy() ) );
  48658. }
  48659. }
  48660. }
  48661. /**
  48662. * Creates a default texture for the given texture that can be used
  48663. * as a placeholder until the actual texture is ready for usage.
  48664. *
  48665. * @param {Texture} texture - The texture to create a default texture for.
  48666. */
  48667. createDefaultTexture( texture ) {
  48668. const { gl, backend, defaultTextures } = this;
  48669. const glTextureType = this.getGLTextureType( texture );
  48670. let textureGPU = defaultTextures[ glTextureType ];
  48671. if ( textureGPU === undefined ) {
  48672. textureGPU = gl.createTexture();
  48673. backend.state.bindTexture( glTextureType, textureGPU );
  48674. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  48675. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  48676. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  48677. defaultTextures[ glTextureType ] = textureGPU;
  48678. }
  48679. backend.set( texture, {
  48680. textureGPU,
  48681. glTextureType
  48682. } );
  48683. }
  48684. /**
  48685. * Defines a texture on the GPU for the given texture object.
  48686. *
  48687. * @param {Texture} texture - The texture.
  48688. * @param {Object} [options={}] - Optional configuration parameter.
  48689. * @return {undefined}
  48690. */
  48691. createTexture( texture, options ) {
  48692. const { gl, backend } = this;
  48693. const { levels, width, height, depth } = options;
  48694. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  48695. const glType = backend.utils.convert( texture.type );
  48696. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.normalized, texture.colorSpace, texture.isVideoTexture );
  48697. const textureGPU = gl.createTexture();
  48698. const glTextureType = this.getGLTextureType( texture );
  48699. backend.state.bindTexture( glTextureType, textureGPU );
  48700. this.setTextureParameters( glTextureType, texture );
  48701. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  48702. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  48703. } else if ( texture.isData3DTexture ) {
  48704. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  48705. } else if ( ! texture.isVideoTexture ) {
  48706. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  48707. }
  48708. backend.set( texture, {
  48709. textureGPU,
  48710. glTextureType,
  48711. glFormat,
  48712. glType,
  48713. glInternalFormat
  48714. } );
  48715. }
  48716. /**
  48717. * Uploads texture buffer data to the GPU memory.
  48718. *
  48719. * @param {WebGLBuffer} buffer - The buffer data.
  48720. * @param {Texture} texture - The texture,
  48721. */
  48722. copyBufferToTexture( buffer, texture ) {
  48723. const { gl, backend } = this;
  48724. const { state } = backend;
  48725. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  48726. const { width, height } = texture.source.data;
  48727. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  48728. backend.state.bindTexture( glTextureType, textureGPU );
  48729. state.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  48730. state.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  48731. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  48732. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  48733. backend.state.unbindTexture();
  48734. // debug
  48735. // const framebuffer = gl.createFramebuffer();
  48736. // backend.state.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  48737. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  48738. // const readout = new Float32Array( width * height * 4 );
  48739. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  48740. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  48741. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  48742. // backend.state.bindFramebuffer( gl.FRAMEBUFFER, null );
  48743. // log( readout );
  48744. }
  48745. /**
  48746. * Uploads the updated texture data to the GPU.
  48747. *
  48748. * @param {Texture} texture - The texture.
  48749. * @param {Object} [options={}] - Optional configuration parameter.
  48750. */
  48751. updateTexture( texture, options ) {
  48752. const { gl } = this;
  48753. const { width, height } = options;
  48754. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  48755. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  48756. return;
  48757. this.backend.state.bindTexture( glTextureType, textureGPU );
  48758. this.setTextureParameters( glTextureType, texture );
  48759. if ( texture.isCompressedTexture ) {
  48760. const mipmaps = texture.mipmaps;
  48761. const image = options.image;
  48762. for ( let i = 0; i < mipmaps.length; i ++ ) {
  48763. const mipmap = mipmaps[ i ];
  48764. if ( texture.isCompressedArrayTexture ) {
  48765. if ( texture.format !== gl.RGBA ) {
  48766. if ( glFormat !== null ) {
  48767. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  48768. } else {
  48769. warn( 'WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  48770. }
  48771. } else {
  48772. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  48773. }
  48774. } else {
  48775. if ( glFormat !== null ) {
  48776. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  48777. } else {
  48778. warn( 'WebGLBackend: Unsupported compressed texture format' );
  48779. }
  48780. }
  48781. }
  48782. } else if ( texture.isCubeTexture ) {
  48783. const images = options.images;
  48784. const mipmaps = texture.mipmaps;
  48785. for ( let i = 0; i < 6; i ++ ) {
  48786. const image = getImage( images[ i ] );
  48787. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  48788. for ( let j = 0; j < mipmaps.length; j ++ ) {
  48789. const mipmap = mipmaps[ j ];
  48790. const image = getImage( mipmap.images[ i ] );
  48791. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, image.width, image.height, glFormat, glType, image );
  48792. }
  48793. }
  48794. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  48795. const image = options.image;
  48796. if ( texture.layerUpdates.size > 0 ) {
  48797. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  48798. for ( const layerIndex of texture.layerUpdates ) {
  48799. const layerData = image.data.subarray(
  48800. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  48801. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  48802. );
  48803. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  48804. }
  48805. texture.clearLayerUpdates();
  48806. } else {
  48807. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  48808. }
  48809. } else if ( texture.isData3DTexture ) {
  48810. const image = options.image;
  48811. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  48812. } else if ( texture.isVideoTexture ) {
  48813. texture.update();
  48814. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  48815. } else if ( texture.isHTMLTexture ) {
  48816. if ( typeof gl.texElementImage2D === 'function' ) {
  48817. gl.texElementImage2D( gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, options.image );
  48818. }
  48819. } else {
  48820. const mipmaps = texture.mipmaps;
  48821. if ( mipmaps.length > 0 ) {
  48822. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  48823. const mipmap = mipmaps[ i ];
  48824. const image = getImage( mipmap );
  48825. gl.texSubImage2D( glTextureType, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, image );
  48826. }
  48827. } else {
  48828. const image = getImage( options.image );
  48829. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  48830. }
  48831. }
  48832. }
  48833. /**
  48834. * Generates mipmaps for the given texture.
  48835. *
  48836. * @param {Texture} texture - The texture.
  48837. */
  48838. generateMipmaps( texture ) {
  48839. const { gl, backend } = this;
  48840. const { textureGPU, glTextureType } = backend.get( texture );
  48841. backend.state.bindTexture( glTextureType, textureGPU );
  48842. gl.generateMipmap( glTextureType );
  48843. }
  48844. /**
  48845. * Deallocates the render buffers of the given render target.
  48846. *
  48847. * @param {RenderTarget} renderTarget - The render target.
  48848. */
  48849. deallocateRenderBuffers( renderTarget ) {
  48850. const { gl, backend } = this;
  48851. // remove framebuffer reference
  48852. if ( renderTarget ) {
  48853. const renderContextData = backend.get( renderTarget );
  48854. renderContextData.renderBufferStorageSetup = undefined;
  48855. if ( renderContextData.framebuffers ) {
  48856. for ( const cacheKey in renderContextData.framebuffers ) {
  48857. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  48858. }
  48859. delete renderContextData.framebuffers;
  48860. }
  48861. if ( renderContextData.depthRenderbuffer ) {
  48862. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  48863. delete renderContextData.depthRenderbuffer;
  48864. }
  48865. if ( renderContextData.stencilRenderbuffer ) {
  48866. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  48867. delete renderContextData.stencilRenderbuffer;
  48868. }
  48869. if ( renderContextData.msaaFrameBuffer ) {
  48870. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  48871. delete renderContextData.msaaFrameBuffer;
  48872. }
  48873. if ( renderContextData.msaaRenderbuffers ) {
  48874. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  48875. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  48876. }
  48877. delete renderContextData.msaaRenderbuffers;
  48878. }
  48879. }
  48880. }
  48881. /**
  48882. * Destroys the GPU data for the given texture object.
  48883. *
  48884. * @param {Texture} texture - The texture.
  48885. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  48886. */
  48887. destroyTexture( texture, isDefaultTexture = false ) {
  48888. const { gl, backend } = this;
  48889. const { textureGPU, renderTarget } = backend.get( texture );
  48890. this.deallocateRenderBuffers( renderTarget );
  48891. if ( isDefaultTexture === false ) {
  48892. gl.deleteTexture( textureGPU );
  48893. }
  48894. backend.delete( texture );
  48895. }
  48896. /**
  48897. * Copies data of the given source texture to the given destination texture.
  48898. *
  48899. * @param {Texture} srcTexture - The source texture.
  48900. * @param {Texture} dstTexture - The destination texture.
  48901. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  48902. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  48903. * @param {number} [srcLevel=0] - The source mip level to copy from.
  48904. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  48905. */
  48906. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  48907. const { gl, backend } = this;
  48908. const { state } = this.backend;
  48909. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  48910. state.bindTexture( glTextureType, dstTextureGPU );
  48911. // gather the necessary dimensions to copy
  48912. let width, height, depth, minX, minY, minZ;
  48913. let dstX, dstY, dstZ;
  48914. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  48915. if ( srcRegion !== null ) {
  48916. width = srcRegion.max.x - srcRegion.min.x;
  48917. height = srcRegion.max.y - srcRegion.min.y;
  48918. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  48919. minX = srcRegion.min.x;
  48920. minY = srcRegion.min.y;
  48921. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  48922. } else {
  48923. const levelScale = Math.pow( 2, - srcLevel );
  48924. width = Math.floor( image.width * levelScale );
  48925. height = Math.floor( image.height * levelScale );
  48926. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  48927. depth = image.depth;
  48928. } else if ( srcTexture.isData3DTexture ) {
  48929. depth = Math.floor( image.depth * levelScale );
  48930. } else {
  48931. depth = 1;
  48932. }
  48933. minX = 0;
  48934. minY = 0;
  48935. minZ = 0;
  48936. }
  48937. if ( dstPosition !== null ) {
  48938. dstX = dstPosition.x;
  48939. dstY = dstPosition.y;
  48940. dstZ = dstPosition.z;
  48941. } else {
  48942. dstX = 0;
  48943. dstY = 0;
  48944. dstZ = 0;
  48945. }
  48946. state.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  48947. state.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  48948. state.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  48949. // used for copying data from cpu
  48950. const currentUnpackRowLen = state.getParameter( gl.UNPACK_ROW_LENGTH );
  48951. const currentUnpackImageHeight = state.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  48952. const currentUnpackSkipPixels = state.getParameter( gl.UNPACK_SKIP_PIXELS );
  48953. const currentUnpackSkipRows = state.getParameter( gl.UNPACK_SKIP_ROWS );
  48954. const currentUnpackSkipImages = state.getParameter( gl.UNPACK_SKIP_IMAGES );
  48955. state.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  48956. state.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  48957. state.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  48958. state.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  48959. state.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  48960. // set up the src texture
  48961. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture || dstTexture.isArrayTexture;
  48962. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  48963. if ( srcTexture.isDepthTexture ) {
  48964. const srcTextureData = backend.get( srcTexture );
  48965. const dstTextureData = backend.get( dstTexture );
  48966. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  48967. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  48968. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  48969. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  48970. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  48971. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  48972. for ( let i = 0; i < depth; i ++ ) {
  48973. // if the source or destination are a 3d target then a layer needs to be bound
  48974. if ( isSrc3D ) {
  48975. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  48976. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  48977. }
  48978. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.DEPTH_BUFFER_BIT, gl.NEAREST );
  48979. }
  48980. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  48981. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  48982. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || backend.has( srcTexture ) ) {
  48983. // get the appropriate frame buffers
  48984. const srcTextureData = backend.get( srcTexture );
  48985. if ( this._srcFramebuffer === null ) this._srcFramebuffer = gl.createFramebuffer();
  48986. if ( this._dstFramebuffer === null ) this._dstFramebuffer = gl.createFramebuffer();
  48987. // bind the frame buffer targets
  48988. state.bindFramebuffer( gl.READ_FRAMEBUFFER, this._srcFramebuffer );
  48989. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, this._dstFramebuffer );
  48990. for ( let i = 0; i < depth; i ++ ) {
  48991. // assign the correct layers and mip maps to the frame buffers
  48992. if ( isSrc3D ) {
  48993. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  48994. } else {
  48995. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, srcTextureData.textureGPU, srcLevel );
  48996. }
  48997. if ( isDst3D ) {
  48998. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  48999. } else {
  49000. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dstTextureGPU, dstLevel );
  49001. }
  49002. // copy the data using the fastest function that can achieve the copy
  49003. if ( srcLevel !== 0 ) {
  49004. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST );
  49005. } else if ( isDst3D ) {
  49006. gl.copyTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  49007. } else {
  49008. gl.copyTexSubImage2D( glTextureType, dstLevel, dstX, dstY, minX, minY, width, height );
  49009. }
  49010. }
  49011. // unbind read, draw buffers
  49012. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  49013. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  49014. } else {
  49015. if ( isDst3D ) {
  49016. // copy data into the 3d texture
  49017. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  49018. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  49019. } else if ( dstTexture.isCompressedArrayTexture ) {
  49020. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  49021. } else {
  49022. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  49023. }
  49024. } else {
  49025. // copy data into the 2d texture
  49026. if ( srcTexture.isDataTexture ) {
  49027. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  49028. } else if ( srcTexture.isCompressedTexture ) {
  49029. gl.compressedTexSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  49030. } else {
  49031. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  49032. }
  49033. }
  49034. }
  49035. // reset values
  49036. state.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  49037. state.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  49038. state.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  49039. state.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  49040. state.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  49041. // Generate mipmaps only when copying level 0
  49042. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  49043. gl.generateMipmap( glTextureType );
  49044. }
  49045. state.unbindTexture();
  49046. }
  49047. /**
  49048. * Copies the current bound framebuffer to the given texture.
  49049. *
  49050. * @param {Texture} texture - The destination texture.
  49051. * @param {RenderContext} renderContext - The render context.
  49052. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  49053. */
  49054. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  49055. const { gl } = this;
  49056. const { state } = this.backend;
  49057. const { textureGPU } = this.backend.get( texture );
  49058. const { x, y, z: width, w: height } = rectangle;
  49059. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  49060. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  49061. if ( requireDrawFrameBuffer ) {
  49062. const partial = ( x !== 0 || y !== 0 );
  49063. let mask;
  49064. let attachment;
  49065. if ( texture.isDepthTexture === true ) {
  49066. mask = gl.DEPTH_BUFFER_BIT;
  49067. attachment = gl.DEPTH_ATTACHMENT;
  49068. if ( renderContext.stencil ) {
  49069. mask |= gl.STENCIL_BUFFER_BIT;
  49070. }
  49071. } else {
  49072. mask = gl.COLOR_BUFFER_BIT;
  49073. attachment = gl.COLOR_ATTACHMENT0;
  49074. }
  49075. if ( partial ) {
  49076. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  49077. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  49078. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  49079. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  49080. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  49081. const flippedY = srcHeight - y - height;
  49082. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  49083. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  49084. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  49085. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  49086. state.unbindTexture();
  49087. } else {
  49088. const fb = gl.createFramebuffer();
  49089. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  49090. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  49091. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  49092. gl.deleteFramebuffer( fb );
  49093. }
  49094. } else {
  49095. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  49096. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  49097. state.unbindTexture();
  49098. }
  49099. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  49100. this.backend._setFramebuffer( renderContext );
  49101. }
  49102. /**
  49103. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  49104. *
  49105. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  49106. * @param {RenderContext} renderContext - The render context.
  49107. * @param {number} samples - The MSAA sample count.
  49108. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  49109. */
  49110. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  49111. const { gl } = this;
  49112. const renderTarget = renderContext.renderTarget;
  49113. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  49114. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  49115. if ( depthBuffer && ! stencilBuffer ) {
  49116. let glInternalFormat = gl.DEPTH_COMPONENT24;
  49117. if ( useMultisampledRTT === true ) {
  49118. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  49119. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  49120. } else if ( samples > 0 ) {
  49121. if ( depthTexture && depthTexture.isDepthTexture ) {
  49122. if ( depthTexture.type === gl.FLOAT ) {
  49123. glInternalFormat = gl.DEPTH_COMPONENT32F;
  49124. }
  49125. }
  49126. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  49127. } else {
  49128. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  49129. }
  49130. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  49131. } else if ( depthBuffer && stencilBuffer ) {
  49132. if ( samples > 0 ) {
  49133. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  49134. } else {
  49135. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  49136. }
  49137. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  49138. }
  49139. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  49140. }
  49141. /**
  49142. * Returns texture data as a typed array.
  49143. *
  49144. * @async
  49145. * @param {Texture} texture - The texture to copy.
  49146. * @param {number} x - The x coordinate of the copy origin.
  49147. * @param {number} y - The y coordinate of the copy origin.
  49148. * @param {number} width - The width of the copy.
  49149. * @param {number} height - The height of the copy.
  49150. * @param {number} faceIndex - The face index.
  49151. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  49152. */
  49153. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  49154. const { backend, gl } = this;
  49155. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  49156. const fb = gl.createFramebuffer();
  49157. backend.state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  49158. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  49159. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  49160. const typedArrayType = this._getTypedArrayType( glType );
  49161. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  49162. const elementCount = width * height;
  49163. const byteLength = elementCount * bytesPerTexel;
  49164. const buffer = gl.createBuffer();
  49165. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  49166. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  49167. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  49168. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  49169. await backend.utils._clientWaitAsync();
  49170. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  49171. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  49172. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  49173. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  49174. backend.state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  49175. gl.deleteFramebuffer( fb );
  49176. return dstBuffer;
  49177. }
  49178. /**
  49179. * Returns the corresponding typed array type for the given WebGL data type.
  49180. *
  49181. * @private
  49182. * @param {GLenum} glType - The WebGL data type.
  49183. * @return {TypedArray.constructor} The typed array type.
  49184. */
  49185. _getTypedArrayType( glType ) {
  49186. const { gl } = this;
  49187. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  49188. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  49189. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  49190. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  49191. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  49192. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  49193. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  49194. if ( glType === gl.FLOAT ) return Float32Array;
  49195. throw new Error( `Unsupported WebGL type: ${glType}` );
  49196. }
  49197. /**
  49198. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  49199. *
  49200. * @private
  49201. * @param {GLenum} glType - The WebGL data type.
  49202. * @param {GLenum} glFormat - The WebGL texture format.
  49203. * @return {number} The bytes-per-texel.
  49204. */
  49205. _getBytesPerTexel( glType, glFormat ) {
  49206. const { gl } = this;
  49207. let bytesPerComponent = 0;
  49208. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  49209. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  49210. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  49211. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  49212. glType === gl.UNSIGNED_SHORT ||
  49213. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  49214. if ( glType === gl.UNSIGNED_INT ||
  49215. glType === gl.FLOAT ) bytesPerComponent = 4;
  49216. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  49217. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  49218. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  49219. }
  49220. /**
  49221. * Frees the internal resources.
  49222. */
  49223. dispose() {
  49224. const { gl } = this;
  49225. if ( this._srcFramebuffer !== null ) gl.deleteFramebuffer( this._srcFramebuffer );
  49226. if ( this._dstFramebuffer !== null ) gl.deleteFramebuffer( this._dstFramebuffer );
  49227. }
  49228. }
  49229. function getImage( source ) {
  49230. if ( source.isDataTexture ) {
  49231. return source.image.data;
  49232. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  49233. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  49234. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  49235. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  49236. return source;
  49237. }
  49238. return source.data;
  49239. }
  49240. /**
  49241. * A WebGL 2 backend utility module for managing extensions.
  49242. *
  49243. * @private
  49244. */
  49245. class WebGLExtensions {
  49246. /**
  49247. * Constructs a new utility object.
  49248. *
  49249. * @param {WebGLBackend} backend - The WebGL 2 backend.
  49250. */
  49251. constructor( backend ) {
  49252. /**
  49253. * A reference to the WebGL 2 backend.
  49254. *
  49255. * @type {WebGLBackend}
  49256. */
  49257. this.backend = backend;
  49258. /**
  49259. * A reference to the rendering context.
  49260. *
  49261. * @type {WebGL2RenderingContext}
  49262. */
  49263. this.gl = this.backend.gl;
  49264. /**
  49265. * A list with all the supported WebGL extensions.
  49266. *
  49267. * @type {Array<string>}
  49268. */
  49269. this.availableExtensions = this.gl.getSupportedExtensions();
  49270. /**
  49271. * A dictionary with requested WebGL extensions.
  49272. * The key is the name of the extension, the value
  49273. * the requested extension object.
  49274. *
  49275. * @type {Object<string,Object>}
  49276. */
  49277. this.extensions = {};
  49278. }
  49279. /**
  49280. * Returns the extension object for the given extension name.
  49281. *
  49282. * @param {string} name - The extension name.
  49283. * @return {Object} The extension object.
  49284. */
  49285. get( name ) {
  49286. let extension = this.extensions[ name ];
  49287. if ( extension === undefined ) {
  49288. extension = this.gl.getExtension( name );
  49289. this.extensions[ name ] = extension;
  49290. }
  49291. return extension;
  49292. }
  49293. /**
  49294. * Returns `true` if the requested extension is available.
  49295. *
  49296. * @param {string} name - The extension name.
  49297. * @return {boolean} Whether the given extension is available or not.
  49298. */
  49299. has( name ) {
  49300. return this.availableExtensions.includes( name );
  49301. }
  49302. }
  49303. /**
  49304. * A WebGL 2 backend utility module for managing the device's capabilities.
  49305. *
  49306. * @private
  49307. */
  49308. class WebGLCapabilities {
  49309. /**
  49310. * Constructs a new utility object.
  49311. *
  49312. * @param {WebGLBackend} backend - The WebGL 2 backend.
  49313. */
  49314. constructor( backend ) {
  49315. /**
  49316. * A reference to the WebGL 2 backend.
  49317. *
  49318. * @type {WebGLBackend}
  49319. */
  49320. this.backend = backend;
  49321. /**
  49322. * This value holds the cached max anisotropy value.
  49323. *
  49324. * @type {?number}
  49325. * @default null
  49326. */
  49327. this.maxAnisotropy = null;
  49328. /**
  49329. * This value holds the cached max uniform block size value.
  49330. *
  49331. * @type {?number}
  49332. * @default null
  49333. */
  49334. this.maxUniformBlockSize = null;
  49335. }
  49336. /**
  49337. * Returns the maximum anisotropy texture filtering value. This value
  49338. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  49339. * WebGL extension.
  49340. *
  49341. * @return {number} The maximum anisotropy texture filtering value.
  49342. */
  49343. getMaxAnisotropy() {
  49344. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  49345. const gl = this.backend.gl;
  49346. const extensions = this.backend.extensions;
  49347. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  49348. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  49349. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  49350. } else {
  49351. this.maxAnisotropy = 0;
  49352. }
  49353. return this.maxAnisotropy;
  49354. }
  49355. /**
  49356. * Returns the maximum number of bytes available for uniform buffers.
  49357. *
  49358. * @return {number} The maximum number of bytes available for uniform buffers.
  49359. */
  49360. getUniformBufferLimit() {
  49361. if ( this.maxUniformBlockSize !== null ) return this.maxUniformBlockSize;
  49362. const gl = this.backend.gl;
  49363. this.maxUniformBlockSize = gl.getParameter( gl.MAX_UNIFORM_BLOCK_SIZE );
  49364. return this.maxUniformBlockSize;
  49365. }
  49366. }
  49367. const GLFeatureName = {
  49368. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  49369. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  49370. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  49371. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  49372. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  49373. 'WEBGL_compressed_texture_s3tc': 'texture-compression-s3tc',
  49374. 'EXT_texture_compression_bptc': 'texture-compression-bc',
  49375. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  49376. 'OVR_multiview2': 'OVR_multiview2'
  49377. };
  49378. class WebGLBufferRenderer {
  49379. constructor( backend ) {
  49380. this.gl = backend.gl;
  49381. this.extensions = backend.extensions;
  49382. this.info = backend.renderer.info;
  49383. this.mode = null;
  49384. this.index = 0;
  49385. this.type = null;
  49386. this.object = null;
  49387. }
  49388. render( start, count ) {
  49389. const { gl, mode, object, type, info, index } = this;
  49390. if ( index !== 0 ) {
  49391. gl.drawElements( mode, count, type, start );
  49392. } else {
  49393. gl.drawArrays( mode, start, count );
  49394. }
  49395. info.update( object, count, 1 );
  49396. }
  49397. renderInstances( start, count, primcount ) {
  49398. const { gl, mode, type, index, object, info } = this;
  49399. if ( primcount === 0 ) return;
  49400. if ( index !== 0 ) {
  49401. gl.drawElementsInstanced( mode, count, type, start, primcount );
  49402. } else {
  49403. gl.drawArraysInstanced( mode, start, count, primcount );
  49404. }
  49405. info.update( object, count, primcount );
  49406. }
  49407. renderMultiDraw( starts, counts, drawCount ) {
  49408. const { extensions, mode, object, info } = this;
  49409. if ( drawCount === 0 ) return;
  49410. const extension = extensions.get( 'WEBGL_multi_draw' );
  49411. if ( extension === null ) {
  49412. for ( let i = 0; i < drawCount; i ++ ) {
  49413. this.render( starts[ i ], counts[ i ] );
  49414. }
  49415. } else {
  49416. if ( this.index !== 0 ) {
  49417. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  49418. } else {
  49419. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  49420. }
  49421. let elementCount = 0;
  49422. for ( let i = 0; i < drawCount; i ++ ) {
  49423. elementCount += counts[ i ];
  49424. }
  49425. info.update( object, elementCount, 1 );
  49426. }
  49427. }
  49428. //
  49429. }
  49430. /**
  49431. * Abstract base class of a timestamp query pool.
  49432. *
  49433. * @abstract
  49434. */
  49435. class TimestampQueryPool {
  49436. /**
  49437. * Creates a new timestamp query pool.
  49438. *
  49439. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  49440. */
  49441. constructor( maxQueries = 256 ) {
  49442. /**
  49443. * Whether to track timestamps or not.
  49444. *
  49445. * @type {boolean}
  49446. * @default true
  49447. */
  49448. this.trackTimestamp = true;
  49449. /**
  49450. * Maximum number of queries this pool can hold.
  49451. *
  49452. * @type {number}
  49453. * @default 256
  49454. */
  49455. this.maxQueries = maxQueries;
  49456. /**
  49457. * How many queries allocated so far.
  49458. *
  49459. * @type {number}
  49460. * @default 0
  49461. */
  49462. this.currentQueryIndex = 0;
  49463. /**
  49464. * Tracks offsets for different contexts.
  49465. *
  49466. * @type {Map<string, number>}
  49467. */
  49468. this.queryOffsets = new Map();
  49469. /**
  49470. * Whether the pool has been disposed or not.
  49471. *
  49472. * @type {boolean}
  49473. * @default false
  49474. */
  49475. this.isDisposed = false;
  49476. /**
  49477. * The total frame duration until the next update.
  49478. *
  49479. * @type {number}
  49480. * @default 0
  49481. */
  49482. this.lastValue = 0;
  49483. /**
  49484. * Stores all timestamp frames.
  49485. *
  49486. * @type {Array<number>}
  49487. */
  49488. this.frames = [];
  49489. /**
  49490. * This property is used to avoid multiple concurrent resolve operations.
  49491. * The WebGL backend uses it as a boolean flag. In context of WebGPU, it holds
  49492. * the promise of the current resolve operation.
  49493. *
  49494. * @type {boolean|Promise<number>}
  49495. * @default false
  49496. */
  49497. this.pendingResolve = false;
  49498. /**
  49499. * Stores the latest timestamp for each render context.
  49500. *
  49501. * @type {Map<string, number>}
  49502. */
  49503. this.timestamps = new Map();
  49504. }
  49505. /**
  49506. * Returns all timestamp frames.
  49507. *
  49508. * @return {Array<number>} The timestamp frames.
  49509. */
  49510. getTimestampFrames() {
  49511. return this.frames;
  49512. }
  49513. /**
  49514. * Returns the timestamp for a given render context.
  49515. *
  49516. * @param {string} uid - A unique identifier for the render context.
  49517. * @return {?number} The timestamp, or undefined if not available.
  49518. */
  49519. getTimestamp( uid ) {
  49520. let timestamp = this.timestamps.get( uid );
  49521. if ( timestamp === undefined ) {
  49522. warn( `TimestampQueryPool: No timestamp available for uid ${ uid }.` );
  49523. timestamp = 0;
  49524. }
  49525. return timestamp;
  49526. }
  49527. /**
  49528. * Returns whether a timestamp is available for a given render context.
  49529. *
  49530. * @param {string} uid - A unique identifier for the render context.
  49531. * @return {boolean} True if a timestamp is available, false otherwise.
  49532. */
  49533. hasTimestamp( uid ) {
  49534. return this.timestamps.has( uid );
  49535. }
  49536. /**
  49537. * Allocate queries for a specific uid.
  49538. *
  49539. * @abstract
  49540. * @param {string} uid - A unique identifier for the render context.
  49541. * @param {number} frameId - The current frame identifier.
  49542. * @returns {?number}
  49543. */
  49544. allocateQueriesForContext( /* uid, frameId */ ) {}
  49545. /**
  49546. * Resolve all timestamps and return data (or process them).
  49547. *
  49548. * @abstract
  49549. * @async
  49550. * @returns {Promise<number>|number} The resolved timestamp value.
  49551. */
  49552. async resolveQueriesAsync() {}
  49553. /**
  49554. * Dispose of the query pool.
  49555. *
  49556. * @abstract
  49557. */
  49558. dispose() {}
  49559. }
  49560. /**
  49561. * Manages a pool of WebGL timestamp queries for performance measurement.
  49562. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  49563. *
  49564. * @augments TimestampQueryPool
  49565. */
  49566. class WebGLTimestampQueryPool extends TimestampQueryPool {
  49567. /**
  49568. * Creates a new WebGL timestamp query pool.
  49569. *
  49570. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  49571. * @param {string} type - The type identifier for this query pool.
  49572. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  49573. */
  49574. constructor( gl, type, maxQueries = 2048 ) {
  49575. super( maxQueries );
  49576. this.gl = gl;
  49577. this.type = type;
  49578. // Check for timer query extensions
  49579. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  49580. gl.getExtension( 'EXT_disjoint_timer_query' );
  49581. if ( ! this.ext ) {
  49582. warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  49583. this.trackTimestamp = false;
  49584. return;
  49585. }
  49586. // Create query objects
  49587. this.queries = [];
  49588. for ( let i = 0; i < this.maxQueries; i ++ ) {
  49589. this.queries.push( gl.createQuery() );
  49590. }
  49591. this.activeQuery = null;
  49592. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  49593. }
  49594. /**
  49595. * Allocates a pair of queries for a given render context.
  49596. *
  49597. * @param {string} uid - A unique identifier for the render context.
  49598. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  49599. */
  49600. allocateQueriesForContext( uid ) {
  49601. if ( ! this.trackTimestamp ) return null;
  49602. // Check if we have enough space for a new query pair
  49603. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  49604. 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() } ).` );
  49605. return null;
  49606. }
  49607. const baseOffset = this.currentQueryIndex;
  49608. this.currentQueryIndex += 2;
  49609. // Initialize query states
  49610. this.queryStates.set( baseOffset, 'inactive' );
  49611. this.queryOffsets.set( uid, baseOffset );
  49612. return baseOffset;
  49613. }
  49614. /**
  49615. * Begins a timestamp query for the specified render context.
  49616. *
  49617. * @param {string} uid - A unique identifier for the render context.
  49618. */
  49619. beginQuery( uid ) {
  49620. if ( ! this.trackTimestamp || this.isDisposed ) {
  49621. return;
  49622. }
  49623. const baseOffset = this.queryOffsets.get( uid );
  49624. if ( baseOffset == null ) {
  49625. return;
  49626. }
  49627. // Don't start a new query if there's an active one
  49628. if ( this.activeQuery !== null ) {
  49629. return;
  49630. }
  49631. const query = this.queries[ baseOffset ];
  49632. if ( ! query ) {
  49633. return;
  49634. }
  49635. try {
  49636. // Only begin if query is inactive
  49637. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  49638. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  49639. this.activeQuery = baseOffset;
  49640. this.queryStates.set( baseOffset, 'started' );
  49641. }
  49642. } catch ( e ) {
  49643. error( 'Error in beginQuery:', e );
  49644. this.activeQuery = null;
  49645. this.queryStates.set( baseOffset, 'inactive' );
  49646. }
  49647. }
  49648. /**
  49649. * Ends the active timestamp query for the specified render context.
  49650. *
  49651. * @param {string} uid - A unique identifier for the render context.
  49652. */
  49653. endQuery( uid ) {
  49654. if ( ! this.trackTimestamp || this.isDisposed ) {
  49655. return;
  49656. }
  49657. const baseOffset = this.queryOffsets.get( uid );
  49658. if ( baseOffset == null ) {
  49659. return;
  49660. }
  49661. // Only end if this is the active query
  49662. if ( this.activeQuery !== baseOffset ) {
  49663. return;
  49664. }
  49665. try {
  49666. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  49667. this.queryStates.set( baseOffset, 'ended' );
  49668. this.activeQuery = null;
  49669. } catch ( e ) {
  49670. error( 'Error in endQuery:', e );
  49671. // Reset state on error
  49672. this.queryStates.set( baseOffset, 'inactive' );
  49673. this.activeQuery = null;
  49674. }
  49675. }
  49676. /**
  49677. * Asynchronously resolves all completed queries and returns the total duration.
  49678. *
  49679. * @async
  49680. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  49681. */
  49682. async resolveQueriesAsync() {
  49683. if ( ! this.trackTimestamp || this.pendingResolve ) {
  49684. return this.lastValue;
  49685. }
  49686. this.pendingResolve = true;
  49687. try {
  49688. // Wait for all ended queries to complete
  49689. const resolvePromises = new Map();
  49690. for ( const [ uid, baseOffset ] of this.queryOffsets ) {
  49691. const state = this.queryStates.get( baseOffset );
  49692. if ( state === 'ended' ) {
  49693. const query = this.queries[ baseOffset ];
  49694. resolvePromises.set( uid, this.resolveQuery( query ) );
  49695. }
  49696. }
  49697. if ( resolvePromises.size === 0 ) {
  49698. return this.lastValue;
  49699. }
  49700. //
  49701. const framesDuration = {};
  49702. const frames = [];
  49703. for ( const [ uid, promise ] of resolvePromises ) {
  49704. const match = uid.match( /^(.*):f(\d+)$/ );
  49705. const frame = parseInt( match[ 2 ] );
  49706. if ( frames.includes( frame ) === false ) {
  49707. frames.push( frame );
  49708. }
  49709. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  49710. const duration = await promise;
  49711. this.timestamps.set( uid, duration );
  49712. framesDuration[ frame ] += duration;
  49713. }
  49714. // Return the total duration of the last frame
  49715. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  49716. // Store the last valid result
  49717. this.lastValue = totalDuration;
  49718. this.frames = frames;
  49719. // Reset states
  49720. this.currentQueryIndex = 0;
  49721. this.queryOffsets.clear();
  49722. this.queryStates.clear();
  49723. this.activeQuery = null;
  49724. return totalDuration;
  49725. } catch ( e ) {
  49726. error( 'Error resolving queries:', e );
  49727. return this.lastValue;
  49728. } finally {
  49729. this.pendingResolve = false;
  49730. }
  49731. }
  49732. /**
  49733. * Resolves a single query, checking for completion and disjoint operation.
  49734. *
  49735. * @async
  49736. * @param {WebGLQuery} query - The query object to resolve.
  49737. * @returns {Promise<number>} The elapsed time in milliseconds.
  49738. */
  49739. async resolveQuery( query ) {
  49740. return new Promise( ( resolve ) => {
  49741. if ( this.isDisposed ) {
  49742. resolve( this.lastValue );
  49743. return;
  49744. }
  49745. let timeoutId;
  49746. let isResolved = false;
  49747. const cleanup = () => {
  49748. if ( timeoutId ) {
  49749. clearTimeout( timeoutId );
  49750. timeoutId = null;
  49751. }
  49752. };
  49753. const finalizeResolution = ( value ) => {
  49754. if ( ! isResolved ) {
  49755. isResolved = true;
  49756. cleanup();
  49757. resolve( value );
  49758. }
  49759. };
  49760. const checkQuery = () => {
  49761. if ( this.isDisposed ) {
  49762. finalizeResolution( this.lastValue );
  49763. return;
  49764. }
  49765. try {
  49766. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  49767. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  49768. if ( disjoint ) {
  49769. finalizeResolution( this.lastValue );
  49770. return;
  49771. }
  49772. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  49773. if ( ! available ) {
  49774. timeoutId = setTimeout( checkQuery, 1 );
  49775. return;
  49776. }
  49777. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  49778. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  49779. } catch ( e ) {
  49780. error( 'Error checking query:', e );
  49781. resolve( this.lastValue );
  49782. }
  49783. };
  49784. checkQuery();
  49785. } );
  49786. }
  49787. /**
  49788. * Releases all resources held by this query pool.
  49789. * This includes deleting all query objects and clearing internal state.
  49790. */
  49791. dispose() {
  49792. if ( this.isDisposed ) {
  49793. return;
  49794. }
  49795. this.isDisposed = true;
  49796. if ( ! this.trackTimestamp ) return;
  49797. for ( const query of this.queries ) {
  49798. this.gl.deleteQuery( query );
  49799. }
  49800. this.queries = [];
  49801. this.queryStates.clear();
  49802. this.queryOffsets.clear();
  49803. this.lastValue = 0;
  49804. this.activeQuery = null;
  49805. }
  49806. }
  49807. /**
  49808. * A backend implementation targeting WebGL 2.
  49809. *
  49810. * @private
  49811. * @augments Backend
  49812. */
  49813. class WebGLBackend extends Backend {
  49814. /**
  49815. * WebGLBackend options.
  49816. *
  49817. * @typedef {Object} WebGLBackend~Options
  49818. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  49819. * @property {boolean} [reversedDepthBuffer=false] - Whether reversed depth buffer is enabled or not.
  49820. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  49821. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  49822. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  49823. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  49824. * @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.
  49825. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  49826. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  49827. */
  49828. /**
  49829. * Constructs a new WebGPU backend.
  49830. *
  49831. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  49832. */
  49833. constructor( parameters = {} ) {
  49834. super( parameters );
  49835. /**
  49836. * This flag can be used for type testing.
  49837. *
  49838. * @type {boolean}
  49839. * @readonly
  49840. * @default true
  49841. */
  49842. this.isWebGLBackend = true;
  49843. /**
  49844. * A reference to a backend module holding shader attribute-related
  49845. * utility functions.
  49846. *
  49847. * @type {?WebGLAttributeUtils}
  49848. * @default null
  49849. */
  49850. this.attributeUtils = null;
  49851. /**
  49852. * A reference to a backend module holding extension-related
  49853. * utility functions.
  49854. *
  49855. * @type {?WebGLExtensions}
  49856. * @default null
  49857. */
  49858. this.extensions = null;
  49859. /**
  49860. * A reference to a backend module holding capability-related
  49861. * utility functions.
  49862. *
  49863. * @type {?WebGLCapabilities}
  49864. * @default null
  49865. */
  49866. this.capabilities = null;
  49867. /**
  49868. * A reference to a backend module holding texture-related
  49869. * utility functions.
  49870. *
  49871. * @type {?WebGLTextureUtils}
  49872. * @default null
  49873. */
  49874. this.textureUtils = null;
  49875. /**
  49876. * A reference to a backend module holding renderer-related
  49877. * utility functions.
  49878. *
  49879. * @type {?WebGLBufferRenderer}
  49880. * @default null
  49881. */
  49882. this.bufferRenderer = null;
  49883. /**
  49884. * A reference to the rendering context.
  49885. *
  49886. * @type {?WebGL2RenderingContext}
  49887. * @default null
  49888. */
  49889. this.gl = null;
  49890. /**
  49891. * A reference to a backend module holding state-related
  49892. * utility functions.
  49893. *
  49894. * @type {?WebGLState}
  49895. * @default null
  49896. */
  49897. this.state = null;
  49898. /**
  49899. * A reference to a backend module holding common
  49900. * utility functions.
  49901. *
  49902. * @type {?WebGLUtils}
  49903. * @default null
  49904. */
  49905. this.utils = null;
  49906. /**
  49907. * Dictionary for caching VAOs.
  49908. *
  49909. * @type {Object<string,WebGLVertexArrayObject>}
  49910. */
  49911. this.vaoCache = {};
  49912. /**
  49913. * Dictionary for caching transform feedback objects.
  49914. *
  49915. * @type {Object<string,WebGLTransformFeedback>}
  49916. */
  49917. this.transformFeedbackCache = {};
  49918. /**
  49919. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  49920. * Only relevant when using compute shaders.
  49921. *
  49922. * @type {boolean}
  49923. * @default false
  49924. */
  49925. this.discard = false;
  49926. /**
  49927. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  49928. * device does not support the extension.
  49929. *
  49930. * @type {?EXTDisjointTimerQueryWebGL2}
  49931. * @default null
  49932. */
  49933. this.disjoint = null;
  49934. /**
  49935. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  49936. * device does not support the extension.
  49937. *
  49938. * @type {?KHRParallelShaderCompile}
  49939. * @default null
  49940. */
  49941. this.parallel = null;
  49942. /**
  49943. * A reference to the current render context.
  49944. *
  49945. * @private
  49946. * @type {RenderContext}
  49947. * @default null
  49948. */
  49949. this._currentContext = null;
  49950. /**
  49951. * A unique collection of bindings.
  49952. *
  49953. * @private
  49954. * @type {WeakSet<Array<BindGroup>>}
  49955. */
  49956. this._knownBindings = new WeakSet();
  49957. /**
  49958. * Whether the device supports framebuffers invalidation or not.
  49959. *
  49960. * @private
  49961. * @type {boolean}
  49962. */
  49963. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  49964. /**
  49965. * The target framebuffer when rendering with
  49966. * the WebXR device API.
  49967. *
  49968. * @private
  49969. * @type {?WebGLFramebuffer}
  49970. * @default null
  49971. */
  49972. this._xrFramebuffer = null;
  49973. }
  49974. /**
  49975. * Initializes the backend so it is ready for usage.
  49976. *
  49977. * @param {Renderer} renderer - The renderer.
  49978. */
  49979. init( renderer ) {
  49980. super.init( renderer );
  49981. //
  49982. const parameters = this.parameters;
  49983. const contextAttributes = {
  49984. antialias: renderer.currentSamples > 0,
  49985. alpha: true, // always true for performance reasons
  49986. depth: renderer.depth,
  49987. stencil: renderer.stencil
  49988. };
  49989. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  49990. function onContextLost( event ) {
  49991. event.preventDefault();
  49992. const contextLossInfo = {
  49993. api: 'WebGL',
  49994. message: event.statusMessage || 'Unknown reason',
  49995. reason: null,
  49996. originalEvent: event
  49997. };
  49998. renderer.onDeviceLost( contextLossInfo );
  49999. }
  50000. this._onContextLost = onContextLost;
  50001. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  50002. this.gl = glContext;
  50003. this.extensions = new WebGLExtensions( this );
  50004. this.capabilities = new WebGLCapabilities( this );
  50005. this.attributeUtils = new WebGLAttributeUtils( this );
  50006. this.textureUtils = new WebGLTextureUtils( this );
  50007. this.bufferRenderer = new WebGLBufferRenderer( this );
  50008. this.state = new WebGLState( this );
  50009. this.utils = new WebGLUtils( this );
  50010. this.extensions.get( 'EXT_color_buffer_float' );
  50011. this.extensions.get( 'WEBGL_clip_cull_distance' );
  50012. this.extensions.get( 'OES_texture_float_linear' );
  50013. this.extensions.get( 'EXT_color_buffer_half_float' );
  50014. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  50015. this.extensions.get( 'WEBGL_render_shared_exponent' );
  50016. this.extensions.get( 'WEBGL_multi_draw' );
  50017. this.extensions.get( 'OVR_multiview2' );
  50018. this.extensions.get( 'EXT_clip_control' );
  50019. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  50020. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  50021. this.drawBuffersIndexedExt = this.extensions.get( 'OES_draw_buffers_indexed' );
  50022. if ( parameters.reversedDepthBuffer ) {
  50023. if ( this.extensions.has( 'EXT_clip_control' ) ) {
  50024. renderer.reversedDepthBuffer = true;
  50025. } else {
  50026. warn( 'WebGPURenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.' );
  50027. renderer.reversedDepthBuffer = false;
  50028. }
  50029. }
  50030. if ( renderer.reversedDepthBuffer ) {
  50031. this.state.setReversedDepth( true );
  50032. }
  50033. }
  50034. /**
  50035. * The coordinate system of the backend.
  50036. *
  50037. * @type {number}
  50038. * @readonly
  50039. */
  50040. get coordinateSystem() {
  50041. return WebGLCoordinateSystem;
  50042. }
  50043. /**
  50044. * This method performs a readback operation by moving buffer data from
  50045. * a storage buffer attribute from the GPU to the CPU. ReadbackBuffer can
  50046. * be used to retain and reuse handles to the intermediate buffers and prevent
  50047. * new allocation.
  50048. *
  50049. * @async
  50050. * @param {BufferAttribute} attribute - The storage buffer attribute to read frm.
  50051. * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute.
  50052. * @param {number} offset - The storage buffer attribute.
  50053. * @param {number} count - The offset from which to start reading the
  50054. * @return {Promise<ArrayBuffer|ReadbackBuffer>} A promise that resolves with the buffer data when the data are ready.
  50055. */
  50056. async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) {
  50057. return await this.attributeUtils.getArrayBufferAsync( attribute, target, offset, count );
  50058. }
  50059. /**
  50060. * Ensures the backend is XR compatible.
  50061. *
  50062. * @async
  50063. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  50064. */
  50065. async makeXRCompatible() {
  50066. const attributes = this.gl.getContextAttributes();
  50067. if ( attributes.xrCompatible !== true ) {
  50068. await this.gl.makeXRCompatible();
  50069. }
  50070. }
  50071. /**
  50072. * Sets the XR rendering destination.
  50073. *
  50074. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  50075. */
  50076. setXRTarget( xrFramebuffer ) {
  50077. this._xrFramebuffer = xrFramebuffer;
  50078. }
  50079. /**
  50080. * Configures the given XR render target with external textures.
  50081. *
  50082. * This method is only relevant when using the WebXR Layers API.
  50083. *
  50084. * @param {XRRenderTarget} renderTarget - The XR render target.
  50085. * @param {WebGLTexture} colorTexture - A native color texture.
  50086. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  50087. */
  50088. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  50089. const gl = this.gl;
  50090. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  50091. if ( depthTexture !== null ) {
  50092. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  50093. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  50094. // The multisample_render_to_texture extension doesn't work properly if there
  50095. // are midframe flushes and an external depth texture.
  50096. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  50097. warn( 'WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  50098. }
  50099. renderTarget._autoAllocateDepthBuffer = false;
  50100. }
  50101. }
  50102. /**
  50103. * Inits a time stamp query for the given render context.
  50104. *
  50105. * @param {string} type - The type of the timestamp query.
  50106. * @param {string} uid - A unique identifier for the timestamp query.
  50107. */
  50108. initTimestampQuery( type, uid ) {
  50109. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  50110. if ( ! this.timestampQueryPool[ type ] ) {
  50111. // TODO: Variable maxQueries?
  50112. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  50113. }
  50114. const timestampQueryPool = this.timestampQueryPool[ type ];
  50115. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  50116. if ( baseOffset !== null ) {
  50117. timestampQueryPool.beginQuery( uid );
  50118. }
  50119. }
  50120. // timestamp utils
  50121. /**
  50122. * Prepares the timestamp buffer.
  50123. *
  50124. * @param {string} type - The type of the timestamp query.
  50125. * @param {string} uid - A unique identifier for the timestamp query.
  50126. */
  50127. prepareTimestampBuffer( type, uid ) {
  50128. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  50129. const timestampQueryPool = this.timestampQueryPool[ type ];
  50130. timestampQueryPool.endQuery( uid );
  50131. }
  50132. /**
  50133. * Returns the backend's rendering context.
  50134. *
  50135. * @return {WebGL2RenderingContext} The rendering context.
  50136. */
  50137. getContext() {
  50138. return this.gl;
  50139. }
  50140. /**
  50141. * This method is executed at the beginning of a render call and prepares
  50142. * the WebGL state for upcoming render calls
  50143. *
  50144. * @param {RenderContext} renderContext - The render context.
  50145. */
  50146. beginRender( renderContext ) {
  50147. const { state } = this;
  50148. const renderContextData = this.get( renderContext );
  50149. //
  50150. if ( renderContext.viewport ) {
  50151. this.updateViewport( renderContext );
  50152. } else {
  50153. const { width, height } = this.getDrawingBufferSize();
  50154. state.viewport( 0, 0, width, height );
  50155. }
  50156. if ( renderContext.scissor ) {
  50157. this.updateScissor( renderContext );
  50158. } else {
  50159. const { width, height } = this.getDrawingBufferSize();
  50160. state.scissor( 0, 0, width, height );
  50161. }
  50162. //
  50163. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  50164. renderContextData.previousContext = this._currentContext;
  50165. this._currentContext = renderContext;
  50166. this._setFramebuffer( renderContext );
  50167. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  50168. const occlusionQueryCount = renderContext.occlusionQueryCount;
  50169. if ( occlusionQueryCount > 0 ) {
  50170. // Get a reference to the array of objects with queries. The renderContextData property
  50171. // can be changed by another render pass before the async reading of all previous queries complete
  50172. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  50173. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  50174. renderContextData.lastOcclusionObject = null;
  50175. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  50176. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  50177. renderContextData.occlusionQueryIndex = 0;
  50178. }
  50179. }
  50180. /**
  50181. * This method is executed at the end of a render call and finalizes work
  50182. * after draw calls.
  50183. *
  50184. * @param {RenderContext} renderContext - The render context.
  50185. */
  50186. finishRender( renderContext ) {
  50187. const { gl, state } = this;
  50188. const renderContextData = this.get( renderContext );
  50189. const previousContext = renderContextData.previousContext;
  50190. state.resetVertexState();
  50191. const occlusionQueryCount = renderContext.occlusionQueryCount;
  50192. if ( occlusionQueryCount > 0 ) {
  50193. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  50194. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  50195. }
  50196. this.resolveOccludedAsync( renderContext );
  50197. }
  50198. const textures = renderContext.textures;
  50199. if ( textures !== null ) {
  50200. for ( let i = 0; i < textures.length; i ++ ) {
  50201. const texture = textures[ i ];
  50202. if ( texture.generateMipmaps ) {
  50203. this.generateMipmaps( texture );
  50204. }
  50205. }
  50206. }
  50207. this._currentContext = previousContext;
  50208. this._resolveRenderTarget( renderContext );
  50209. if ( previousContext !== null ) {
  50210. this._setFramebuffer( previousContext );
  50211. if ( previousContext.viewport ) {
  50212. this.updateViewport( previousContext );
  50213. } else {
  50214. const { width, height } = this.getDrawingBufferSize();
  50215. state.viewport( 0, 0, width, height );
  50216. }
  50217. if ( previousContext.scissor ) {
  50218. this.updateScissor( previousContext );
  50219. } else {
  50220. const { width, height } = this.getDrawingBufferSize();
  50221. state.scissor( 0, 0, width, height );
  50222. }
  50223. }
  50224. this.prepareTimestampBuffer( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  50225. }
  50226. /**
  50227. * This method processes the result of occlusion queries and writes it
  50228. * into render context data.
  50229. *
  50230. * @async
  50231. * @param {RenderContext} renderContext - The render context.
  50232. */
  50233. resolveOccludedAsync( renderContext ) {
  50234. const renderContextData = this.get( renderContext );
  50235. // handle occlusion query results
  50236. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  50237. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  50238. const occluded = new WeakSet();
  50239. const { gl } = this;
  50240. renderContextData.currentOcclusionQueryObjects = null;
  50241. renderContextData.currentOcclusionQueries = null;
  50242. const check = () => {
  50243. let completed = 0;
  50244. // check all queries and requeue as appropriate
  50245. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  50246. const query = currentOcclusionQueries[ i ];
  50247. if ( query === null ) continue;
  50248. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  50249. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  50250. currentOcclusionQueries[ i ] = null;
  50251. gl.deleteQuery( query );
  50252. completed ++;
  50253. }
  50254. }
  50255. if ( completed < currentOcclusionQueries.length ) {
  50256. requestAnimationFrame( check );
  50257. } else {
  50258. renderContextData.occluded = occluded;
  50259. }
  50260. };
  50261. check();
  50262. }
  50263. }
  50264. /**
  50265. * Returns `true` if the given 3D object is fully occluded by other
  50266. * 3D objects in the scene.
  50267. *
  50268. * @param {RenderContext} renderContext - The render context.
  50269. * @param {Object3D} object - The 3D object to test.
  50270. * @return {boolean} Whether the 3D object is fully occluded or not.
  50271. */
  50272. isOccluded( renderContext, object ) {
  50273. const renderContextData = this.get( renderContext );
  50274. return renderContextData.occluded && renderContextData.occluded.has( object );
  50275. }
  50276. /**
  50277. * Updates the viewport with the values from the given render context.
  50278. *
  50279. * @param {RenderContext} renderContext - The render context.
  50280. */
  50281. updateViewport( renderContext ) {
  50282. const { state } = this;
  50283. const { x, y, width, height } = renderContext.viewportValue;
  50284. state.viewport( x, renderContext.height - height - y, width, height );
  50285. }
  50286. /**
  50287. * Updates the scissor with the values from the given render context.
  50288. *
  50289. * @param {RenderContext} renderContext - The render context.
  50290. */
  50291. updateScissor( renderContext ) {
  50292. const { state } = this;
  50293. const { x, y, width, height } = renderContext.scissorValue;
  50294. state.scissor( x, renderContext.height - height - y, width, height );
  50295. }
  50296. /**
  50297. * Defines the scissor test.
  50298. *
  50299. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  50300. */
  50301. setScissorTest( boolean ) {
  50302. const state = this.state;
  50303. state.setScissorTest( boolean );
  50304. }
  50305. /**
  50306. * Returns the clear color and alpha into a single
  50307. * color object.
  50308. *
  50309. * @return {Color4} The clear color.
  50310. */
  50311. getClearColor() {
  50312. const clearColor = super.getClearColor();
  50313. // Since the canvas is always created with alpha: true,
  50314. // WebGL must always premultiply the clear color.
  50315. clearColor.r *= clearColor.a;
  50316. clearColor.g *= clearColor.a;
  50317. clearColor.b *= clearColor.a;
  50318. return clearColor;
  50319. }
  50320. /**
  50321. * Performs a clear operation.
  50322. *
  50323. * @param {boolean} color - Whether the color buffer should be cleared or not.
  50324. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  50325. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  50326. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  50327. * @param {boolean} [setFrameBuffer=true] - Controls whether the intermediate framebuffer should be set or not.
  50328. * @param {boolean} [resolveRenderTarget=true] - Controls whether an active render target should be resolved
  50329. * or not. Only relevant for explicit clears.
  50330. */
  50331. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true, resolveRenderTarget = true ) {
  50332. const { gl, renderer } = this;
  50333. if ( descriptor === null ) {
  50334. const clearColor = this.getClearColor();
  50335. descriptor = {
  50336. textures: null,
  50337. clearColorValue: clearColor
  50338. };
  50339. }
  50340. //
  50341. let clear = 0;
  50342. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  50343. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  50344. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  50345. if ( clear !== 0 ) {
  50346. let clearColor;
  50347. if ( descriptor.clearColorValue ) {
  50348. clearColor = descriptor.clearColorValue;
  50349. } else {
  50350. clearColor = this.getClearColor();
  50351. }
  50352. const clearDepth = renderer.getClearDepth();
  50353. const clearStencil = renderer.getClearStencil();
  50354. if ( depth ) this.state.setDepthMask( true );
  50355. if ( descriptor.textures === null ) {
  50356. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  50357. gl.clear( clear );
  50358. } else {
  50359. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  50360. if ( color ) {
  50361. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  50362. if ( i === 0 ) {
  50363. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  50364. } else {
  50365. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  50366. }
  50367. }
  50368. }
  50369. if ( depth && stencil ) {
  50370. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  50371. } else if ( depth ) {
  50372. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  50373. } else if ( stencil ) {
  50374. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  50375. }
  50376. if ( setFrameBuffer && resolveRenderTarget ) this._resolveRenderTarget( descriptor );
  50377. // Restore the framebuffer of the active render pass when clearing an unrelated
  50378. // render target, so subsequent draws in the pass don't bind to the cleared target.
  50379. if ( setFrameBuffer && this._currentContext !== null && this._currentContext !== descriptor ) {
  50380. this._setFramebuffer( this._currentContext );
  50381. }
  50382. }
  50383. }
  50384. }
  50385. /**
  50386. * This method is executed at the beginning of a compute call and
  50387. * prepares the state for upcoming compute tasks.
  50388. *
  50389. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  50390. */
  50391. beginCompute( computeGroup ) {
  50392. const { state, gl } = this;
  50393. //
  50394. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  50395. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  50396. }
  50397. /**
  50398. * Executes a compute command for the given compute node.
  50399. *
  50400. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  50401. * @param {Node} computeNode - The compute node.
  50402. * @param {Array<BindGroup>} bindings - The bindings.
  50403. * @param {ComputePipeline} pipeline - The compute pipeline.
  50404. * @param {?number} [count=null] - The count of compute invocations. If `null`, the count is determined by the compute node.
  50405. */
  50406. compute( computeGroup, computeNode, bindings, pipeline, count = null ) {
  50407. const { state, gl } = this;
  50408. if ( this.discard === false ) {
  50409. // required here to handle async behaviour of render.compute()
  50410. state.enable( gl.RASTERIZER_DISCARD );
  50411. this.discard = true;
  50412. }
  50413. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  50414. const vaoKey = this._getVaoKey( attributes );
  50415. const vaoGPU = this.vaoCache[ vaoKey ];
  50416. if ( vaoGPU === undefined ) {
  50417. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  50418. } else {
  50419. state.setVertexState( vaoGPU );
  50420. }
  50421. state.useProgram( programGPU );
  50422. this._bindUniforms( bindings );
  50423. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  50424. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  50425. gl.beginTransformFeedback( gl.POINTS );
  50426. count = ( count !== null ) ? count : computeNode.count;
  50427. if ( Array.isArray( count ) ) {
  50428. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not an array.' );
  50429. count = count[ 0 ];
  50430. } else if ( count && typeof count === 'object' && count.isIndirectStorageBufferAttribute ) {
  50431. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute' );
  50432. count = computeNode.count;
  50433. }
  50434. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  50435. gl.drawArraysInstanced( gl.POINTS, 0, 1, count );
  50436. } else {
  50437. gl.drawArrays( gl.POINTS, 0, count );
  50438. }
  50439. gl.endTransformFeedback();
  50440. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  50441. // switch active buffers
  50442. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  50443. const dualAttributeData = transformBuffers[ i ];
  50444. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  50445. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  50446. }
  50447. dualAttributeData.switchBuffers();
  50448. }
  50449. }
  50450. /**
  50451. * This method is executed at the end of a compute call and
  50452. * finalizes work after compute tasks.
  50453. *
  50454. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  50455. */
  50456. finishCompute( computeGroup ) {
  50457. const { state, gl } = this;
  50458. this.discard = false;
  50459. state.disable( gl.RASTERIZER_DISCARD );
  50460. this.prepareTimestampBuffer( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  50461. if ( this._currentContext ) {
  50462. this._setFramebuffer( this._currentContext );
  50463. }
  50464. }
  50465. /**
  50466. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  50467. *
  50468. * @param {RenderContext} renderContext - The render context.
  50469. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  50470. *
  50471. * @private
  50472. */
  50473. _isRenderCameraDepthArray( renderContext ) {
  50474. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  50475. }
  50476. /**
  50477. * Internal draw function.
  50478. *
  50479. * @private
  50480. * @param {Object3D} object - The object to render.
  50481. * @param {WebGLBufferRenderer} renderer - The internal renderer.
  50482. * @param {number} firstVertex - The first vertex to render.
  50483. * @param {number} vertexCount - The vertex count.
  50484. * @param {number} instanceCount - The intance count.
  50485. * @param {WebGLProgram} programGPU - The raw WebGL shader program.
  50486. */
  50487. _draw( object, renderer, firstVertex, vertexCount, instanceCount, programGPU ) {
  50488. if ( object.isBatchedMesh ) {
  50489. if ( this.hasFeature( 'WEBGL_multi_draw' ) === false ) {
  50490. const { gl } = this;
  50491. const drawIdLocation = gl.getUniformLocation( programGPU, 'nodeUniformDrawId' );
  50492. const starts = object._multiDrawStarts;
  50493. const counts = object._multiDrawCounts;
  50494. const drawCount = object._multiDrawCount;
  50495. for ( let i = 0; i < drawCount; i ++ ) {
  50496. gl.uniform1ui( drawIdLocation, i );
  50497. renderer.render( starts[ i ], counts[ i ] );
  50498. }
  50499. } else {
  50500. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  50501. }
  50502. } else if ( instanceCount > 1 ) {
  50503. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  50504. } else {
  50505. renderer.render( firstVertex, vertexCount );
  50506. }
  50507. }
  50508. /**
  50509. * Executes a draw command for the given render object.
  50510. *
  50511. * @param {RenderObject} renderObject - The render object to draw.
  50512. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  50513. */
  50514. draw( renderObject/*, info*/ ) {
  50515. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  50516. const { programGPU } = this.get( pipeline );
  50517. const { gl, state } = this;
  50518. const contextData = this.get( context );
  50519. const drawParams = renderObject.getDrawParameters();
  50520. if ( drawParams === null ) return;
  50521. //
  50522. this._bindUniforms( renderObject.getBindings() );
  50523. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  50524. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  50525. if ( context.mrt !== null && context.textures !== null ) {
  50526. state.setMRTBlending( context.textures, context.mrt, material );
  50527. }
  50528. state.useProgram( programGPU );
  50529. // vertex state
  50530. const attributes = renderObject.getAttributes();
  50531. const attributesData = this.get( attributes );
  50532. let vaoGPU = attributesData.vaoGPU;
  50533. if ( vaoGPU === undefined ) {
  50534. const vaoKey = this._getVaoKey( attributes );
  50535. vaoGPU = this.vaoCache[ vaoKey ];
  50536. if ( vaoGPU === undefined ) {
  50537. vaoGPU = this._createVao( attributes );
  50538. this.vaoCache[ vaoKey ] = vaoGPU;
  50539. attributesData.vaoGPU = vaoGPU;
  50540. }
  50541. }
  50542. const index = renderObject.getIndex();
  50543. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  50544. state.setVertexState( vaoGPU, indexGPU );
  50545. //
  50546. const lastObject = contextData.lastOcclusionObject;
  50547. if ( lastObject !== object && lastObject !== undefined ) {
  50548. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  50549. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  50550. contextData.occlusionQueryIndex ++;
  50551. }
  50552. if ( object.occlusionTest === true ) {
  50553. const query = gl.createQuery();
  50554. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  50555. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  50556. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  50557. }
  50558. contextData.lastOcclusionObject = object;
  50559. }
  50560. //
  50561. const renderer = this.bufferRenderer;
  50562. if ( object.isPoints ) renderer.mode = gl.POINTS;
  50563. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  50564. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  50565. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  50566. else {
  50567. if ( material.wireframe === true ) {
  50568. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  50569. renderer.mode = gl.LINES;
  50570. } else {
  50571. renderer.mode = gl.TRIANGLES;
  50572. }
  50573. }
  50574. //
  50575. const { vertexCount, instanceCount } = drawParams;
  50576. let { firstVertex } = drawParams;
  50577. renderer.object = object;
  50578. if ( index !== null ) {
  50579. firstVertex *= index.array.BYTES_PER_ELEMENT;
  50580. const indexData = this.get( index );
  50581. renderer.index = index.count;
  50582. renderer.type = indexData.type;
  50583. } else {
  50584. renderer.index = 0;
  50585. }
  50586. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  50587. const cameraData = this.get( renderObject.camera );
  50588. const cameras = renderObject.camera.cameras;
  50589. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  50590. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  50591. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  50592. const indexesGPU = [];
  50593. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  50594. const bufferGPU = gl.createBuffer();
  50595. data[ 0 ] = i;
  50596. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  50597. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  50598. indexesGPU.push( bufferGPU );
  50599. }
  50600. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  50601. }
  50602. let cameraIndexBufferIndex = 0;
  50603. bindingsSearch: for ( const bindGroup of renderObject.getBindings() ) {
  50604. for ( const binding of bindGroup.bindings ) {
  50605. if ( binding === cameraIndex ) break bindingsSearch;
  50606. if ( binding.isUniformsGroup || binding.isUniformBuffer ) cameraIndexBufferIndex ++;
  50607. }
  50608. }
  50609. const pixelRatio = this.renderer.getPixelRatio();
  50610. const renderTarget = this._currentContext.renderTarget;
  50611. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  50612. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  50613. if ( isRenderCameraDepthArray ) {
  50614. // Clear the depth texture
  50615. const textureData = this.get( renderTarget.depthTexture );
  50616. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  50617. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  50618. const { stencilBuffer } = renderTarget;
  50619. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  50620. this.renderer._activeCubeFace = i;
  50621. this._currentContext.activeCubeFace = i;
  50622. this._setFramebuffer( this._currentContext );
  50623. this.clear( false, true, stencilBuffer, this._currentContext, false, false );
  50624. }
  50625. this.renderer._activeCubeFace = prevActiveCubeFace;
  50626. this._currentContext.activeCubeFace = prevActiveCubeFace;
  50627. }
  50628. }
  50629. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  50630. const subCamera = cameras[ i ];
  50631. if ( object.layers.test( subCamera.layers ) ) {
  50632. if ( isRenderCameraDepthArray ) {
  50633. // Update the active layer
  50634. this.renderer._activeCubeFace = i;
  50635. this._currentContext.activeCubeFace = i;
  50636. this._setFramebuffer( this._currentContext );
  50637. }
  50638. const vp = subCamera.viewport;
  50639. if ( vp !== undefined ) {
  50640. const x = vp.x * pixelRatio;
  50641. const y = vp.y * pixelRatio;
  50642. const width = vp.width * pixelRatio;
  50643. const height = vp.height * pixelRatio;
  50644. state.viewport(
  50645. Math.floor( x ),
  50646. Math.floor( renderObject.context.height - height - y ),
  50647. Math.floor( width ),
  50648. Math.floor( height )
  50649. );
  50650. }
  50651. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexBufferIndex, cameraData.indexesGPU[ i ] );
  50652. this._draw( object, renderer, firstVertex, vertexCount, instanceCount, programGPU );
  50653. }
  50654. this._currentContext.activeCubeFace = prevActiveCubeFace;
  50655. this.renderer._activeCubeFace = prevActiveCubeFace;
  50656. }
  50657. } else {
  50658. this._draw( object, renderer, firstVertex, vertexCount, instanceCount, programGPU );
  50659. }
  50660. }
  50661. /**
  50662. * Explain why always null is returned.
  50663. *
  50664. * @param {RenderObject} renderObject - The render object.
  50665. * @return {boolean} Whether the render pipeline requires an update or not.
  50666. */
  50667. needsRenderUpdate( /*renderObject*/ ) {
  50668. return false;
  50669. }
  50670. /**
  50671. * Explain why no cache key is computed.
  50672. *
  50673. * @param {RenderObject} renderObject - The render object.
  50674. * @return {string} The cache key.
  50675. */
  50676. getRenderCacheKey( /*renderObject*/ ) {
  50677. return '';
  50678. }
  50679. // textures
  50680. /**
  50681. * Creates a default texture for the given texture that can be used
  50682. * as a placeholder until the actual texture is ready for usage.
  50683. *
  50684. * @param {Texture} texture - The texture to create a default texture for.
  50685. */
  50686. createDefaultTexture( texture ) {
  50687. this.textureUtils.createDefaultTexture( texture );
  50688. }
  50689. /**
  50690. * Defines a texture on the GPU for the given texture object.
  50691. *
  50692. * @param {Texture} texture - The texture.
  50693. * @param {Object} [options={}] - Optional configuration parameter.
  50694. */
  50695. createTexture( texture, options ) {
  50696. this.textureUtils.createTexture( texture, options );
  50697. }
  50698. /**
  50699. * Uploads the updated texture data to the GPU.
  50700. *
  50701. * @param {Texture} texture - The texture.
  50702. * @param {Object} [options={}] - Optional configuration parameter.
  50703. */
  50704. updateTexture( texture, options ) {
  50705. this.textureUtils.updateTexture( texture, options );
  50706. }
  50707. /**
  50708. * Generates mipmaps for the given texture.
  50709. *
  50710. * @param {Texture} texture - The texture.
  50711. */
  50712. generateMipmaps( texture ) {
  50713. this.textureUtils.generateMipmaps( texture );
  50714. }
  50715. /**
  50716. * Destroys the GPU data for the given texture object.
  50717. *
  50718. * @param {Texture} texture - The texture.
  50719. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  50720. */
  50721. destroyTexture( texture, isDefaultTexture = false ) {
  50722. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  50723. }
  50724. /**
  50725. * Returns texture data as a typed array.
  50726. *
  50727. * @async
  50728. * @param {Texture} texture - The texture to copy.
  50729. * @param {number} x - The x coordinate of the copy origin.
  50730. * @param {number} y - The y coordinate of the copy origin.
  50731. * @param {number} width - The width of the copy.
  50732. * @param {number} height - The height of the copy.
  50733. * @param {number} faceIndex - The face index.
  50734. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  50735. */
  50736. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  50737. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  50738. }
  50739. /**
  50740. * This method does nothing since WebGL 2 has no concept of samplers.
  50741. *
  50742. * @param {Texture} texture - The texture to update the sampler for.
  50743. * @param {TextureNode} textureNode - The texture node to update the sampler with.
  50744. * @return {string} The current sampler key.
  50745. */
  50746. updateSampler( /*texture, textureNode*/ ) {
  50747. return '';
  50748. }
  50749. // node builder
  50750. /**
  50751. * Returns a node builder for the given render object.
  50752. *
  50753. * @param {RenderObject} object - The render object.
  50754. * @param {Renderer} renderer - The renderer.
  50755. * @return {GLSLNodeBuilder} The node builder.
  50756. */
  50757. createNodeBuilder( object, renderer ) {
  50758. return new GLSLNodeBuilder( object, renderer );
  50759. }
  50760. // program
  50761. /**
  50762. * Creates a shader program from the given programmable stage.
  50763. *
  50764. * @param {ProgrammableStage} program - The programmable stage.
  50765. */
  50766. createProgram( program ) {
  50767. const gl = this.gl;
  50768. const { stage, code } = program;
  50769. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  50770. gl.shaderSource( shader, code );
  50771. gl.compileShader( shader );
  50772. this.set( program, {
  50773. shaderGPU: shader
  50774. } );
  50775. }
  50776. /**
  50777. * Destroys the shader program of the given programmable stage.
  50778. *
  50779. * @param {ProgrammableStage} program - The programmable stage.
  50780. */
  50781. destroyProgram( program ) {
  50782. this.delete( program );
  50783. }
  50784. /**
  50785. * Creates a render pipeline for the given render object.
  50786. *
  50787. * @param {RenderObject} renderObject - The render object.
  50788. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  50789. */
  50790. createRenderPipeline( renderObject, promises ) {
  50791. const gl = this.gl;
  50792. const pipeline = renderObject.pipeline;
  50793. // Program
  50794. const { fragmentProgram, vertexProgram } = pipeline;
  50795. const programGPU = gl.createProgram();
  50796. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  50797. const vertexShader = this.get( vertexProgram ).shaderGPU;
  50798. gl.attachShader( programGPU, fragmentShader );
  50799. gl.attachShader( programGPU, vertexShader );
  50800. gl.linkProgram( programGPU );
  50801. this.set( pipeline, {
  50802. programGPU,
  50803. fragmentShader,
  50804. vertexShader
  50805. } );
  50806. if ( promises !== null && this.parallel ) {
  50807. const p = new Promise( ( resolve /*, reject*/ ) => {
  50808. const parallel = this.parallel;
  50809. const checkStatus = () => {
  50810. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  50811. this._completeCompile( renderObject, pipeline );
  50812. resolve();
  50813. } else {
  50814. requestAnimationFrame( checkStatus );
  50815. }
  50816. };
  50817. checkStatus();
  50818. } );
  50819. promises.push( p );
  50820. return;
  50821. }
  50822. this._completeCompile( renderObject, pipeline );
  50823. }
  50824. /**
  50825. * Formats the source code of error messages.
  50826. *
  50827. * @private
  50828. * @param {string} string - The code.
  50829. * @param {number} errorLine - The error line.
  50830. * @return {string} The formatted code.
  50831. */
  50832. _handleSource( string, errorLine ) {
  50833. const lines = string.split( '\n' );
  50834. const lines2 = [];
  50835. const from = Math.max( errorLine - 6, 0 );
  50836. const to = Math.min( errorLine + 6, lines.length );
  50837. for ( let i = from; i < to; i ++ ) {
  50838. const line = i + 1;
  50839. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  50840. }
  50841. return lines2.join( '\n' );
  50842. }
  50843. /**
  50844. * Gets the shader compilation errors from the info log.
  50845. *
  50846. * @private
  50847. * @param {WebGL2RenderingContext} gl - The rendering context.
  50848. * @param {WebGLShader} shader - The WebGL shader object.
  50849. * @param {string} type - The shader type.
  50850. * @return {string} The shader errors.
  50851. */
  50852. _getShaderErrors( gl, shader, type ) {
  50853. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  50854. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  50855. const errors = shaderInfoLog.trim();
  50856. if ( status && errors === '' ) return '';
  50857. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  50858. if ( errorMatches ) {
  50859. const errorLine = parseInt( errorMatches[ 1 ] );
  50860. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  50861. } else {
  50862. return errors;
  50863. }
  50864. }
  50865. /**
  50866. * Logs shader compilation errors.
  50867. *
  50868. * @private
  50869. * @param {WebGLProgram} programGPU - The WebGL program.
  50870. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  50871. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  50872. */
  50873. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  50874. if ( this.renderer.debug.checkShaderErrors ) {
  50875. const gl = this.gl;
  50876. const programInfoLog = gl.getProgramInfoLog( programGPU ) || '';
  50877. const programLog = programInfoLog.trim();
  50878. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  50879. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  50880. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  50881. } else {
  50882. // default error reporting
  50883. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  50884. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  50885. error(
  50886. 'WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  50887. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  50888. 'Program Info Log: ' + programLog + '\n' +
  50889. vertexErrors + '\n' +
  50890. fragmentErrors
  50891. );
  50892. }
  50893. } else if ( programLog !== '' ) {
  50894. warn( 'WebGLProgram: Program Info Log:', programLog );
  50895. }
  50896. }
  50897. }
  50898. /**
  50899. * Completes the shader program setup for the given render object.
  50900. *
  50901. * @private
  50902. * @param {RenderObject} renderObject - The render object.
  50903. * @param {RenderPipeline} pipeline - The render pipeline.
  50904. */
  50905. _completeCompile( renderObject, pipeline ) {
  50906. const { state, gl } = this;
  50907. const pipelineData = this.get( pipeline );
  50908. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  50909. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  50910. this._logProgramError( programGPU, fragmentShader, vertexShader );
  50911. }
  50912. state.useProgram( programGPU );
  50913. // Bindings
  50914. const bindings = renderObject.getBindings();
  50915. this._setupBindings( bindings, programGPU );
  50916. //
  50917. this.set( pipeline, {
  50918. programGPU,
  50919. pipeline: programGPU
  50920. } );
  50921. }
  50922. /**
  50923. * Creates a compute pipeline for the given compute node.
  50924. *
  50925. * @param {ComputePipeline} computePipeline - The compute pipeline.
  50926. * @param {Array<BindGroup>} bindings - The bindings.
  50927. */
  50928. createComputePipeline( computePipeline, bindings ) {
  50929. const { state, gl } = this;
  50930. // Program
  50931. const fragmentProgram = {
  50932. stage: 'fragment',
  50933. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  50934. };
  50935. this.createProgram( fragmentProgram );
  50936. const { computeProgram } = computePipeline;
  50937. const programGPU = gl.createProgram();
  50938. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  50939. const vertexShader = this.get( computeProgram ).shaderGPU;
  50940. const transforms = computeProgram.transforms;
  50941. const transformVaryingNames = [];
  50942. const transformAttributeNodes = [];
  50943. for ( let i = 0; i < transforms.length; i ++ ) {
  50944. const transform = transforms[ i ];
  50945. transformVaryingNames.push( transform.varyingName );
  50946. transformAttributeNodes.push( transform.attributeNode );
  50947. }
  50948. gl.attachShader( programGPU, fragmentShader );
  50949. gl.attachShader( programGPU, vertexShader );
  50950. gl.transformFeedbackVaryings(
  50951. programGPU,
  50952. transformVaryingNames,
  50953. gl.SEPARATE_ATTRIBS
  50954. );
  50955. gl.linkProgram( programGPU );
  50956. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  50957. this._logProgramError( programGPU, fragmentShader, vertexShader );
  50958. }
  50959. state.useProgram( programGPU );
  50960. // Bindings
  50961. this._setupBindings( bindings, programGPU );
  50962. const attributeNodes = computeProgram.attributes;
  50963. const attributes = [];
  50964. const transformBuffers = [];
  50965. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  50966. const attribute = attributeNodes[ i ].node.attribute;
  50967. attributes.push( attribute );
  50968. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  50969. }
  50970. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  50971. const attribute = transformAttributeNodes[ i ].attribute;
  50972. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  50973. const attributeData = this.get( attribute );
  50974. transformBuffers.push( attributeData );
  50975. }
  50976. //
  50977. this.set( computePipeline, {
  50978. programGPU,
  50979. transformBuffers,
  50980. attributes
  50981. } );
  50982. }
  50983. /**
  50984. * Creates bindings from the given bind group definition.
  50985. *
  50986. * @param {BindGroup} bindGroup - The bind group.
  50987. * @param {Array<BindGroup>} bindings - Array of bind groups.
  50988. * @param {number} cacheIndex - The cache index.
  50989. * @param {number} version - The version.
  50990. */
  50991. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  50992. if ( this._knownBindings.has( bindings ) === false ) {
  50993. this._knownBindings.add( bindings );
  50994. let uniformBuffers = 0;
  50995. let textures = 0;
  50996. for ( const bindGroup of bindings ) {
  50997. this.set( bindGroup, {
  50998. textures: textures,
  50999. uniformBuffers: uniformBuffers
  51000. } );
  51001. for ( const binding of bindGroup.bindings ) {
  51002. if ( binding.isUniformBuffer ) uniformBuffers ++;
  51003. if ( binding.isSampledTexture ) textures ++;
  51004. }
  51005. }
  51006. }
  51007. this.updateBindings( bindGroup, bindings );
  51008. }
  51009. /**
  51010. * Updates the given bind group definition.
  51011. *
  51012. * @param {BindGroup} bindGroup - The bind group.
  51013. * @param {Array<BindGroup>} bindings - Array of bind groups.
  51014. * @param {number} cacheIndex - The cache index.
  51015. * @param {number} version - The version.
  51016. */
  51017. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  51018. const { gl } = this;
  51019. for ( const binding of bindGroup.bindings ) {
  51020. const map = this.get( binding );
  51021. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  51022. const array = binding.buffer;
  51023. const bufferGPU = map.bufferGPU;
  51024. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  51025. // update
  51026. const updateRanges = binding.updateRanges;
  51027. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  51028. if ( updateRanges.length === 0 ) {
  51029. gl.bufferData( gl.UNIFORM_BUFFER, array, gl.DYNAMIC_DRAW );
  51030. } else {
  51031. const isTyped = isTypedArray( array );
  51032. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  51033. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  51034. const range = updateRanges[ i ];
  51035. const dataOffset = range.start * byteOffsetFactor;
  51036. const size = range.count * byteOffsetFactor;
  51037. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  51038. gl.bufferSubData( gl.UNIFORM_BUFFER, bufferOffset, array, dataOffset, size );
  51039. }
  51040. }
  51041. this.set( binding, map );
  51042. } else if ( binding.isSampledTexture ) {
  51043. const { textureGPU, glTextureType } = this.get( binding.texture );
  51044. map.textureGPU = textureGPU;
  51045. map.glTextureType = glTextureType;
  51046. this.set( binding, map );
  51047. }
  51048. }
  51049. }
  51050. /**
  51051. * Updates a buffer binding.
  51052. *
  51053. * @param {Buffer} binding - The buffer binding to update.
  51054. */
  51055. updateBinding( binding ) {
  51056. const gl = this.gl;
  51057. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  51058. const bindingData = this.get( binding );
  51059. const bufferGPU = bindingData.bufferGPU;
  51060. const array = binding.buffer;
  51061. const updateRanges = binding.updateRanges;
  51062. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  51063. if ( updateRanges.length === 0 ) {
  51064. gl.bufferData( gl.UNIFORM_BUFFER, array, gl.DYNAMIC_DRAW );
  51065. } else {
  51066. const isTyped = isTypedArray( array );
  51067. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  51068. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  51069. const range = updateRanges[ i ];
  51070. const dataOffset = range.start * byteOffsetFactor;
  51071. const size = range.count * byteOffsetFactor;
  51072. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  51073. gl.bufferSubData( gl.UNIFORM_BUFFER, bufferOffset, array, dataOffset, size );
  51074. }
  51075. }
  51076. }
  51077. }
  51078. // attributes
  51079. /**
  51080. * Creates a uniform buffer.
  51081. *
  51082. * @param {Buffer} uniformBuffer - The uniform buffer.
  51083. */
  51084. createUniformBuffer( uniformBuffer ) {
  51085. const uniformBufferData = this.get( uniformBuffer );
  51086. if ( uniformBufferData.bufferGPU === undefined ) {
  51087. const gl = this.gl;
  51088. const array = uniformBuffer.buffer;
  51089. uniformBufferData.bufferGPU = gl.createBuffer();
  51090. gl.bindBuffer( gl.UNIFORM_BUFFER, uniformBufferData.bufferGPU );
  51091. gl.bufferData( gl.UNIFORM_BUFFER, array.byteLength, gl.DYNAMIC_DRAW );
  51092. }
  51093. }
  51094. /**
  51095. * Destroys the GPU data for the given uniform buffer.
  51096. *
  51097. * @param {Buffer} uniformBuffer - The uniform buffer.
  51098. */
  51099. destroyUniformBuffer( uniformBuffer ) {
  51100. const uniformBufferData = this.get( uniformBuffer );
  51101. this.gl.deleteBuffer( uniformBufferData.bufferGPU );
  51102. this.delete( uniformBuffer );
  51103. }
  51104. /**
  51105. * Creates the GPU buffer of an indexed shader attribute.
  51106. *
  51107. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  51108. */
  51109. createIndexAttribute( attribute ) {
  51110. const gl = this.gl;
  51111. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  51112. }
  51113. /**
  51114. * Creates the GPU buffer of a shader attribute.
  51115. *
  51116. * @param {BufferAttribute} attribute - The buffer attribute.
  51117. */
  51118. createAttribute( attribute ) {
  51119. if ( this.has( attribute ) ) return;
  51120. const gl = this.gl;
  51121. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  51122. }
  51123. /**
  51124. * Creates the GPU buffer of a storage attribute.
  51125. *
  51126. * @param {BufferAttribute} attribute - The buffer attribute.
  51127. */
  51128. createStorageAttribute( attribute ) {
  51129. if ( this.has( attribute ) ) return;
  51130. const gl = this.gl;
  51131. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  51132. }
  51133. /**
  51134. * Updates the GPU buffer of a shader attribute.
  51135. *
  51136. * @param {BufferAttribute} attribute - The buffer attribute to update.
  51137. */
  51138. updateAttribute( attribute ) {
  51139. this.attributeUtils.updateAttribute( attribute );
  51140. }
  51141. /**
  51142. * Destroys the GPU buffer of a shader attribute.
  51143. *
  51144. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  51145. */
  51146. destroyAttribute( attribute ) {
  51147. this.attributeUtils.destroyAttribute( attribute );
  51148. }
  51149. /**
  51150. * Checks if the given feature is supported by the backend.
  51151. *
  51152. * @param {string} name - The feature's name.
  51153. * @return {boolean} Whether the feature is supported or not.
  51154. */
  51155. hasFeature( name ) {
  51156. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  51157. const extensions = this.extensions;
  51158. for ( let i = 0; i < keysMatching.length; i ++ ) {
  51159. if ( extensions.has( keysMatching[ i ] ) ) return true;
  51160. }
  51161. return false;
  51162. }
  51163. /**
  51164. * Copies data of the given source texture to the given destination texture.
  51165. *
  51166. * @param {Texture} srcTexture - The source texture.
  51167. * @param {Texture} dstTexture - The destination texture.
  51168. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  51169. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  51170. * @param {number} [srcLevel=0] - The source mip level to copy from.
  51171. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  51172. */
  51173. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  51174. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  51175. }
  51176. /**
  51177. * Copies the current bound framebuffer to the given texture.
  51178. *
  51179. * @param {Texture} texture - The destination texture.
  51180. * @param {RenderContext} renderContext - The render context.
  51181. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  51182. */
  51183. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  51184. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  51185. }
  51186. /**
  51187. * Checks if the given compatibility is supported by the backend.
  51188. *
  51189. * @param {string} name - The compatibility name.
  51190. * @return {boolean} Whether the compatibility is supported or not.
  51191. */
  51192. hasCompatibility( name ) {
  51193. if ( name === Compatibility.TEXTURE_COMPARE ) return true;
  51194. return super.hasCompatibility( name );
  51195. }
  51196. /**
  51197. * Initializes the render target defined in the given render context.
  51198. *
  51199. * @param {RenderContext} renderContext - The render context.
  51200. */
  51201. initRenderTarget( renderContext ) {
  51202. const { gl, state } = this;
  51203. this._setFramebuffer( renderContext );
  51204. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  51205. }
  51206. /**
  51207. * Configures the active framebuffer from the given render context.
  51208. *
  51209. * @private
  51210. * @param {RenderContext} descriptor - The render context.
  51211. */
  51212. _setFramebuffer( descriptor ) {
  51213. const { gl, state } = this;
  51214. let currentFrameBuffer = null;
  51215. if ( descriptor.textures !== null ) {
  51216. const renderTarget = descriptor.renderTarget;
  51217. const renderTargetContextData = this.get( renderTarget );
  51218. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  51219. const isCube = renderTarget.isCubeRenderTarget === true;
  51220. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  51221. const isRenderTargetArray = renderTarget.depth > 1;
  51222. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  51223. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  51224. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  51225. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  51226. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  51227. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  51228. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  51229. const cacheKey = getCacheKey( descriptor );
  51230. let fb;
  51231. if ( isCube ) {
  51232. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  51233. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  51234. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  51235. fb = this._xrFramebuffer;
  51236. } else {
  51237. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  51238. fb = renderTargetContextData.framebuffers[ cacheKey ];
  51239. }
  51240. if ( fb === undefined ) {
  51241. fb = gl.createFramebuffer();
  51242. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  51243. const textures = descriptor.textures;
  51244. const depthInvalidationArray = [];
  51245. if ( isCube ) {
  51246. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  51247. const { textureGPU } = this.get( textures[ 0 ] );
  51248. const cubeFace = this.renderer._activeCubeFace;
  51249. const mipLevel = this.renderer._activeMipmapLevel;
  51250. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, mipLevel );
  51251. } else {
  51252. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  51253. for ( let i = 0; i < textures.length; i ++ ) {
  51254. const texture = textures[ i ];
  51255. const textureData = this.get( texture );
  51256. textureData.renderTarget = descriptor.renderTarget;
  51257. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  51258. const attachment = gl.COLOR_ATTACHMENT0 + i;
  51259. if ( renderTarget.multiview ) {
  51260. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  51261. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  51262. const layer = this.renderer._activeCubeFace;
  51263. const mipLevel = this.renderer._activeMipmapLevel;
  51264. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, mipLevel, layer );
  51265. } else {
  51266. if ( useMultisampledRTT ) {
  51267. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  51268. } else {
  51269. const mipLevel = this.renderer._activeMipmapLevel;
  51270. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, mipLevel );
  51271. }
  51272. }
  51273. }
  51274. }
  51275. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  51276. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  51277. const renderbuffer = gl.createRenderbuffer();
  51278. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  51279. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  51280. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  51281. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  51282. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  51283. } else {
  51284. if ( descriptor.depthTexture !== null ) {
  51285. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  51286. const textureData = this.get( descriptor.depthTexture );
  51287. textureData.renderTarget = descriptor.renderTarget;
  51288. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  51289. if ( renderTarget.multiview ) {
  51290. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  51291. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  51292. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  51293. } else {
  51294. if ( descriptor.depthTexture.isArrayTexture ) {
  51295. const layer = this.renderer._activeCubeFace;
  51296. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  51297. } else if ( descriptor.depthTexture.isCubeTexture ) {
  51298. const cubeFace = this.renderer._activeCubeFace;
  51299. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureData.textureGPU, 0 );
  51300. } else {
  51301. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  51302. }
  51303. }
  51304. }
  51305. }
  51306. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  51307. } else {
  51308. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  51309. if ( isRenderCameraDepthArray ) {
  51310. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  51311. const layer = this.renderer._activeCubeFace;
  51312. const depthData = this.get( descriptor.depthTexture );
  51313. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  51314. gl.framebufferTextureLayer(
  51315. gl.FRAMEBUFFER,
  51316. depthStyle,
  51317. depthData.textureGPU,
  51318. 0,
  51319. layer
  51320. );
  51321. }
  51322. // rebind external XR textures
  51323. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  51324. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  51325. // rebind color
  51326. const textureData = this.get( descriptor.textures[ 0 ] );
  51327. if ( renderTarget.multiview ) {
  51328. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  51329. } else if ( useMultisampledRTT ) {
  51330. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  51331. } else {
  51332. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  51333. }
  51334. // rebind depth
  51335. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  51336. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  51337. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  51338. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  51339. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  51340. } else {
  51341. const textureData = this.get( descriptor.depthTexture );
  51342. if ( renderTarget.multiview ) {
  51343. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  51344. } else if ( useMultisampledRTT ) {
  51345. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  51346. } else {
  51347. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  51348. }
  51349. }
  51350. }
  51351. }
  51352. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  51353. if ( msaaFb === undefined ) {
  51354. const invalidationArray = [];
  51355. msaaFb = gl.createFramebuffer();
  51356. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  51357. const msaaRenderbuffers = [];
  51358. const textures = descriptor.textures;
  51359. for ( let i = 0; i < textures.length; i ++ ) {
  51360. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  51361. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  51362. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  51363. const texture = descriptor.textures[ i ];
  51364. const textureData = this.get( texture );
  51365. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  51366. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  51367. }
  51368. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  51369. renderTargetContextData.msaaFrameBuffer = msaaFb;
  51370. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  51371. if ( depthBuffer && depthRenderbuffer === undefined ) {
  51372. depthRenderbuffer = gl.createRenderbuffer();
  51373. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  51374. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  51375. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  51376. invalidationArray.push( depthStyle );
  51377. }
  51378. renderTargetContextData.invalidationArray = invalidationArray;
  51379. }
  51380. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  51381. } else {
  51382. currentFrameBuffer = fb;
  51383. }
  51384. state.drawBuffers( descriptor, fb );
  51385. }
  51386. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  51387. }
  51388. /**
  51389. * Computes the VAO key for the given index and attributes.
  51390. *
  51391. * @private
  51392. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  51393. * @return {string} The VAO key.
  51394. */
  51395. _getVaoKey( attributes ) {
  51396. let key = '';
  51397. for ( let i = 0; i < attributes.length; i ++ ) {
  51398. const attributeData = this.get( attributes[ i ] );
  51399. key += ':' + attributeData.id;
  51400. }
  51401. return key;
  51402. }
  51403. /**
  51404. * Creates a VAO from the index and attributes.
  51405. *
  51406. * @private
  51407. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  51408. * @return {Object} The VAO data.
  51409. */
  51410. _createVao( attributes ) {
  51411. const { gl } = this;
  51412. const vaoGPU = gl.createVertexArray();
  51413. gl.bindVertexArray( vaoGPU );
  51414. for ( let i = 0; i < attributes.length; i ++ ) {
  51415. const attribute = attributes[ i ];
  51416. const attributeData = this.get( attribute );
  51417. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  51418. gl.enableVertexAttribArray( i );
  51419. let stride, offset;
  51420. if ( attribute.isInterleavedBufferAttribute === true ) {
  51421. stride = attribute.data.stride * attributeData.bytesPerElement;
  51422. offset = attribute.offset * attributeData.bytesPerElement;
  51423. } else {
  51424. stride = 0;
  51425. offset = 0;
  51426. }
  51427. if ( attributeData.isInteger ) {
  51428. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  51429. } else {
  51430. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  51431. }
  51432. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  51433. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  51434. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  51435. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  51436. }
  51437. }
  51438. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  51439. return vaoGPU;
  51440. }
  51441. /**
  51442. * Creates a transform feedback from the given transform buffers.
  51443. *
  51444. * @private
  51445. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  51446. * @return {WebGLTransformFeedback} The transform feedback.
  51447. */
  51448. _getTransformFeedback( transformBuffers ) {
  51449. let key = '';
  51450. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  51451. key += ':' + transformBuffers[ i ].id;
  51452. }
  51453. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  51454. if ( transformFeedbackGPU !== undefined ) {
  51455. return transformFeedbackGPU;
  51456. }
  51457. const { gl } = this;
  51458. transformFeedbackGPU = gl.createTransformFeedback();
  51459. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  51460. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  51461. const attributeData = transformBuffers[ i ];
  51462. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  51463. }
  51464. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  51465. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  51466. return transformFeedbackGPU;
  51467. }
  51468. /**
  51469. * Setups the given bindings.
  51470. *
  51471. * @private
  51472. * @param {Array<BindGroup>} bindings - The bindings.
  51473. * @param {WebGLProgram} programGPU - The WebGL program.
  51474. */
  51475. _setupBindings( bindings, programGPU ) {
  51476. const gl = this.gl;
  51477. let uniformBuffers = 0;
  51478. let textures = 0;
  51479. for ( const bindGroup of bindings ) {
  51480. for ( const binding of bindGroup.bindings ) {
  51481. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  51482. const index = uniformBuffers ++;
  51483. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  51484. gl.uniformBlockBinding( programGPU, location, index );
  51485. } else if ( binding.isSampledTexture ) {
  51486. const index = textures ++;
  51487. const location = gl.getUniformLocation( programGPU, binding.name );
  51488. gl.uniform1i( location, index );
  51489. }
  51490. }
  51491. }
  51492. }
  51493. /**
  51494. * Binds the given uniforms.
  51495. *
  51496. * @private
  51497. * @param {Array<BindGroup>} bindings - The bindings.
  51498. */
  51499. _bindUniforms( bindings ) {
  51500. const { gl, state } = this;
  51501. let uniformBuffers = 0;
  51502. let textures = 0;
  51503. for ( const bindGroup of bindings ) {
  51504. for ( const binding of bindGroup.bindings ) {
  51505. const bindingData = this.get( binding );
  51506. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  51507. const index = uniformBuffers ++;
  51508. // TODO USE bindBufferRange to group multiple uniform buffers
  51509. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  51510. } else if ( binding.isSampledTexture ) {
  51511. const index = textures ++;
  51512. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  51513. }
  51514. }
  51515. }
  51516. }
  51517. /**
  51518. * The method ensures multisampled render targets are resolved.
  51519. *
  51520. * @private
  51521. * @param {RenderContext} renderContext - The render context.
  51522. */
  51523. _resolveRenderTarget( renderContext ) {
  51524. const { gl, state } = this;
  51525. const renderTarget = renderContext.renderTarget;
  51526. if ( renderContext.textures !== null && renderTarget ) {
  51527. const renderTargetContextData = this.get( renderTarget );
  51528. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  51529. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  51530. let mask = gl.COLOR_BUFFER_BIT;
  51531. if ( renderTarget.resolveDepthBuffer ) {
  51532. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  51533. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  51534. }
  51535. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  51536. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  51537. const textures = renderContext.textures;
  51538. const isMRT = textures.length > 1;
  51539. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  51540. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  51541. if ( isMRT ) {
  51542. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  51543. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  51544. for ( let i = 0; i < textures.length; i ++ ) {
  51545. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  51546. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  51547. }
  51548. }
  51549. for ( let i = 0; i < textures.length; i ++ ) {
  51550. if ( isMRT ) {
  51551. // configure attachment for resolve
  51552. const { textureGPU } = this.get( textures[ i ] );
  51553. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  51554. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  51555. }
  51556. if ( renderContext.scissor ) {
  51557. const { x, y, width, height } = renderContext.scissorValue;
  51558. const viewY = renderContext.height - height - y;
  51559. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  51560. } else {
  51561. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  51562. }
  51563. }
  51564. if ( isMRT ) {
  51565. // restore attachments
  51566. for ( let i = 0; i < textures.length; i ++ ) {
  51567. const { textureGPU } = this.get( textures[ i ] );
  51568. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  51569. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  51570. }
  51571. }
  51572. if ( this._supportsInvalidateFramebuffer === true ) {
  51573. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  51574. }
  51575. } else if ( renderTarget.resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  51576. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  51577. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  51578. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  51579. }
  51580. }
  51581. }
  51582. /**
  51583. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  51584. * should be used when MSAA is enabled.
  51585. *
  51586. * @private
  51587. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  51588. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  51589. */
  51590. _useMultisampledExtension( renderTarget ) {
  51591. if ( renderTarget.multiview === true ) {
  51592. return true;
  51593. }
  51594. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  51595. }
  51596. /**
  51597. * Frees internal resources.
  51598. */
  51599. dispose() {
  51600. if ( this.textureUtils !== null ) this.textureUtils.dispose();
  51601. const extension = this.extensions.get( 'WEBGL_lose_context' );
  51602. if ( extension ) extension.loseContext();
  51603. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  51604. }
  51605. }
  51606. const GPUPrimitiveTopology = {
  51607. PointList: 'point-list',
  51608. LineList: 'line-list',
  51609. LineStrip: 'line-strip',
  51610. TriangleList: 'triangle-list'};
  51611. const GPUShaderStage = ( typeof self !== 'undefined' && self.GPUShaderStage ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  51612. const GPUCompareFunction = {
  51613. Never: 'never',
  51614. Less: 'less',
  51615. Equal: 'equal',
  51616. LessEqual: 'less-equal',
  51617. Greater: 'greater',
  51618. NotEqual: 'not-equal',
  51619. GreaterEqual: 'greater-equal',
  51620. Always: 'always'
  51621. };
  51622. const GPUStoreOp = {
  51623. Store: 'store'};
  51624. const GPULoadOp = {
  51625. Load: 'load',
  51626. Clear: 'clear'
  51627. };
  51628. const GPUFrontFace = {
  51629. CCW: 'ccw',
  51630. CW: 'cw'
  51631. };
  51632. const GPUCullMode = {
  51633. None: 'none',
  51634. Back: 'back'
  51635. };
  51636. const GPUIndexFormat = {
  51637. Uint16: 'uint16',
  51638. Uint32: 'uint32'
  51639. };
  51640. const GPUTextureFormat = {
  51641. // 8-bit formats
  51642. R8Unorm: 'r8unorm',
  51643. R8Snorm: 'r8snorm',
  51644. R8Uint: 'r8uint',
  51645. R8Sint: 'r8sint',
  51646. // 16-bit formats
  51647. R16Uint: 'r16uint',
  51648. R16Sint: 'r16sint',
  51649. R16Float: 'r16float',
  51650. RG8Unorm: 'rg8unorm',
  51651. RG8Snorm: 'rg8snorm',
  51652. RG8Uint: 'rg8uint',
  51653. RG8Sint: 'rg8sint',
  51654. R16Unorm: 'r16unorm',
  51655. R16Snorm: 'r16snorm',
  51656. // 32-bit formats
  51657. R32Uint: 'r32uint',
  51658. R32Sint: 'r32sint',
  51659. R32Float: 'r32float',
  51660. RG16Uint: 'rg16uint',
  51661. RG16Sint: 'rg16sint',
  51662. RG16Float: 'rg16float',
  51663. RGBA8Unorm: 'rgba8unorm',
  51664. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  51665. RGBA8Snorm: 'rgba8snorm',
  51666. RGBA8Uint: 'rgba8uint',
  51667. RGBA8Sint: 'rgba8sint',
  51668. BGRA8Unorm: 'bgra8unorm',
  51669. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  51670. RG16Unorm: 'rg16unorm',
  51671. RG16Snorm: 'rg16snorm',
  51672. // Packed 32-bit formats
  51673. RGB9E5UFloat: 'rgb9e5ufloat',
  51674. RGB10A2Unorm: 'rgb10a2unorm',
  51675. RG11B10UFloat: 'rg11b10ufloat',
  51676. // 64-bit formats
  51677. RG32Uint: 'rg32uint',
  51678. RG32Sint: 'rg32sint',
  51679. RG32Float: 'rg32float',
  51680. RGBA16Uint: 'rgba16uint',
  51681. RGBA16Sint: 'rgba16sint',
  51682. RGBA16Float: 'rgba16float',
  51683. RGBA16Unorm: 'rgba16unorm',
  51684. RGBA16Snorm: 'rgba16snorm',
  51685. // 128-bit formats
  51686. RGBA32Uint: 'rgba32uint',
  51687. RGBA32Sint: 'rgba32sint',
  51688. RGBA32Float: 'rgba32float',
  51689. Depth16Unorm: 'depth16unorm',
  51690. Depth24Plus: 'depth24plus',
  51691. Depth24PlusStencil8: 'depth24plus-stencil8',
  51692. Depth32Float: 'depth32float',
  51693. // 'depth32float-stencil8' extension
  51694. Depth32FloatStencil8: 'depth32float-stencil8',
  51695. // BC compressed formats usable if 'texture-compression-bc' is both
  51696. // supported by the device/user agent and enabled in requestDevice.
  51697. BC1RGBAUnorm: 'bc1-rgba-unorm',
  51698. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  51699. BC2RGBAUnorm: 'bc2-rgba-unorm',
  51700. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  51701. BC3RGBAUnorm: 'bc3-rgba-unorm',
  51702. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  51703. BC4RUnorm: 'bc4-r-unorm',
  51704. BC4RSnorm: 'bc4-r-snorm',
  51705. BC5RGUnorm: 'bc5-rg-unorm',
  51706. BC5RGSnorm: 'bc5-rg-snorm',
  51707. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  51708. BC6HRGBFloat: 'bc6h-rgb-float',
  51709. BC7RGBAUnorm: 'bc7-rgba-unorm',
  51710. BC7RGBAUnormSRGB: 'bc7-rgba-unorm-srgb',
  51711. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  51712. // supported by the device/user agent and enabled in requestDevice.
  51713. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  51714. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  51715. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  51716. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  51717. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  51718. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  51719. EACR11Unorm: 'eac-r11unorm',
  51720. EACR11Snorm: 'eac-r11snorm',
  51721. EACRG11Unorm: 'eac-rg11unorm',
  51722. EACRG11Snorm: 'eac-rg11snorm',
  51723. // ASTC compressed formats usable if 'texture-compression-astc' is both
  51724. // supported by the device/user agent and enabled in requestDevice.
  51725. ASTC4x4Unorm: 'astc-4x4-unorm',
  51726. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  51727. ASTC5x4Unorm: 'astc-5x4-unorm',
  51728. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  51729. ASTC5x5Unorm: 'astc-5x5-unorm',
  51730. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  51731. ASTC6x5Unorm: 'astc-6x5-unorm',
  51732. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  51733. ASTC6x6Unorm: 'astc-6x6-unorm',
  51734. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  51735. ASTC8x5Unorm: 'astc-8x5-unorm',
  51736. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  51737. ASTC8x6Unorm: 'astc-8x6-unorm',
  51738. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  51739. ASTC8x8Unorm: 'astc-8x8-unorm',
  51740. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  51741. ASTC10x5Unorm: 'astc-10x5-unorm',
  51742. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  51743. ASTC10x6Unorm: 'astc-10x6-unorm',
  51744. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  51745. ASTC10x8Unorm: 'astc-10x8-unorm',
  51746. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  51747. ASTC10x10Unorm: 'astc-10x10-unorm',
  51748. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  51749. ASTC12x10Unorm: 'astc-12x10-unorm',
  51750. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  51751. ASTC12x12Unorm: 'astc-12x12-unorm',
  51752. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  51753. };
  51754. const GPUAddressMode = {
  51755. ClampToEdge: 'clamp-to-edge',
  51756. Repeat: 'repeat',
  51757. MirrorRepeat: 'mirror-repeat'
  51758. };
  51759. const GPUFilterMode = {
  51760. Linear: 'linear',
  51761. Nearest: 'nearest'
  51762. };
  51763. const GPUBlendFactor = {
  51764. Zero: 'zero',
  51765. One: 'one',
  51766. Src: 'src',
  51767. OneMinusSrc: 'one-minus-src',
  51768. SrcAlpha: 'src-alpha',
  51769. OneMinusSrcAlpha: 'one-minus-src-alpha',
  51770. Dst: 'dst',
  51771. OneMinusDst: 'one-minus-dst',
  51772. DstAlpha: 'dst-alpha',
  51773. OneMinusDstAlpha: 'one-minus-dst-alpha',
  51774. SrcAlphaSaturated: 'src-alpha-saturated',
  51775. Constant: 'constant',
  51776. OneMinusConstant: 'one-minus-constant'
  51777. };
  51778. const GPUBlendOperation = {
  51779. Add: 'add',
  51780. Subtract: 'subtract',
  51781. ReverseSubtract: 'reverse-subtract',
  51782. Min: 'min',
  51783. Max: 'max'
  51784. };
  51785. const GPUColorWriteFlags = {
  51786. None: 0,
  51787. All: 0xF
  51788. };
  51789. const GPUStencilOperation = {
  51790. Keep: 'keep',
  51791. Zero: 'zero',
  51792. Replace: 'replace',
  51793. Invert: 'invert',
  51794. IncrementClamp: 'increment-clamp',
  51795. DecrementClamp: 'decrement-clamp',
  51796. IncrementWrap: 'increment-wrap',
  51797. DecrementWrap: 'decrement-wrap'
  51798. };
  51799. const GPUBufferBindingType = {
  51800. Storage: 'storage',
  51801. ReadOnlyStorage: 'read-only-storage'
  51802. };
  51803. const GPUStorageTextureAccess = {
  51804. WriteOnly: 'write-only',
  51805. ReadOnly: 'read-only',
  51806. ReadWrite: 'read-write',
  51807. };
  51808. const GPUSamplerBindingType = {
  51809. NonFiltering: 'non-filtering',
  51810. Comparison: 'comparison'
  51811. };
  51812. const GPUTextureSampleType = {
  51813. Float: 'float',
  51814. UnfilterableFloat: 'unfilterable-float',
  51815. Depth: 'depth',
  51816. SInt: 'sint',
  51817. UInt: 'uint'
  51818. };
  51819. const GPUTextureDimension = {
  51820. TwoD: '2d',
  51821. ThreeD: '3d'
  51822. };
  51823. const GPUTextureViewDimension = {
  51824. TwoD: '2d',
  51825. TwoDArray: '2d-array',
  51826. Cube: 'cube',
  51827. ThreeD: '3d'
  51828. };
  51829. const GPUTextureAspect = {
  51830. All: 'all'};
  51831. const GPUInputStepMode = {
  51832. Vertex: 'vertex',
  51833. Instance: 'instance'
  51834. };
  51835. const GPUFeatureName = {
  51836. CoreFeaturesAndLimits: 'core-features-and-limits',
  51837. DepthClipControl: 'depth-clip-control',
  51838. Depth32FloatStencil8: 'depth32float-stencil8',
  51839. TextureCompressionBC: 'texture-compression-bc',
  51840. TextureCompressionBCSliced3D: 'texture-compression-bc-sliced-3d',
  51841. TextureCompressionETC2: 'texture-compression-etc2',
  51842. TextureCompressionASTC: 'texture-compression-astc',
  51843. TextureCompressionASTCSliced3D: 'texture-compression-astc-sliced-3d',
  51844. TimestampQuery: 'timestamp-query',
  51845. IndirectFirstInstance: 'indirect-first-instance',
  51846. ShaderF16: 'shader-f16',
  51847. RG11B10UFloat: 'rg11b10ufloat-renderable',
  51848. BGRA8UNormStorage: 'bgra8unorm-storage',
  51849. Float32Filterable: 'float32-filterable',
  51850. Float32Blendable: 'float32-blendable',
  51851. ClipDistances: 'clip-distances',
  51852. DualSourceBlending: 'dual-source-blending',
  51853. Subgroups: 'subgroups',
  51854. TextureFormatsTier1: 'texture-formats-tier1',
  51855. TextureFormatsTier2: 'texture-formats-tier2'
  51856. };
  51857. const GPUFeatureMap = {
  51858. 'texture-compression-s3tc': 'texture-compression-bc',
  51859. 'texture-compression-etc1': 'texture-compression-etc2'
  51860. };
  51861. /**
  51862. * A special form of sampler binding type.
  51863. * It's texture value is managed by a node object.
  51864. *
  51865. * @private
  51866. * @augments Sampler
  51867. */
  51868. class NodeSampler extends Sampler {
  51869. /**
  51870. * Constructs a new node-based sampler.
  51871. *
  51872. * @param {string} name - The samplers's name.
  51873. * @param {TextureNode} textureNode - The texture node.
  51874. * @param {UniformGroupNode} groupNode - The uniform group node.
  51875. */
  51876. constructor( name, textureNode, groupNode ) {
  51877. super( name, textureNode ? textureNode.value : null );
  51878. /**
  51879. * The texture node.
  51880. *
  51881. * @type {TextureNode}
  51882. */
  51883. this.textureNode = textureNode;
  51884. /**
  51885. * The uniform group node.
  51886. *
  51887. * @type {UniformGroupNode}
  51888. */
  51889. this.groupNode = groupNode;
  51890. }
  51891. /**
  51892. * Updates the texture value of this sampler.
  51893. *
  51894. * @return {boolean} Whether the sampler needs an update or not.
  51895. */
  51896. update() {
  51897. const { textureNode } = this;
  51898. if ( this.texture !== textureNode.value ) {
  51899. this.texture = textureNode.value;
  51900. return true;
  51901. }
  51902. return super.update();
  51903. }
  51904. }
  51905. /**
  51906. * Represents a storage buffer binding type.
  51907. *
  51908. * @private
  51909. * @augments Buffer
  51910. */
  51911. class StorageBuffer extends Buffer {
  51912. /**
  51913. * Constructs a new uniform buffer.
  51914. *
  51915. * @param {string} name - The buffer's name.
  51916. * @param {BufferAttribute} attribute - The buffer attribute.
  51917. */
  51918. constructor( name, attribute ) {
  51919. super( name, attribute ? attribute.array : null );
  51920. /**
  51921. * This flag can be used for type testing.
  51922. *
  51923. * @private
  51924. * @type {BufferAttribute}
  51925. */
  51926. this._attribute = attribute;
  51927. /**
  51928. * This flag can be used for type testing.
  51929. *
  51930. * @type {boolean}
  51931. * @readonly
  51932. * @default true
  51933. */
  51934. this.isStorageBuffer = true;
  51935. }
  51936. /**
  51937. * The storage buffer attribute.
  51938. *
  51939. * @type {BufferAttribute}
  51940. */
  51941. get attribute() {
  51942. return this._attribute;
  51943. }
  51944. }
  51945. let _id = 0;
  51946. /**
  51947. * A special form of storage buffer binding type.
  51948. * It's buffer value is managed by a node object.
  51949. *
  51950. * @private
  51951. * @augments StorageBuffer
  51952. */
  51953. class NodeStorageBuffer extends StorageBuffer {
  51954. /**
  51955. * Constructs a new node-based storage buffer.
  51956. *
  51957. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  51958. * @param {UniformGroupNode} groupNode - The uniform group node.
  51959. */
  51960. constructor( nodeUniform, groupNode ) {
  51961. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  51962. /**
  51963. * The node uniform.
  51964. *
  51965. * @type {StorageBufferNode}
  51966. */
  51967. this.nodeUniform = nodeUniform;
  51968. /**
  51969. * The access type.
  51970. *
  51971. * @type {string}
  51972. */
  51973. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  51974. /**
  51975. * The uniform group node.
  51976. *
  51977. * @type {UniformGroupNode}
  51978. */
  51979. this.groupNode = groupNode;
  51980. }
  51981. /**
  51982. * The storage buffer attribute node.
  51983. *
  51984. * @type {StorageBufferAttribute}
  51985. */
  51986. get attribute() {
  51987. return this.nodeUniform.value;
  51988. }
  51989. /**
  51990. * The storage buffer.
  51991. *
  51992. * @type {Float32Array}
  51993. */
  51994. get buffer() {
  51995. return this.nodeUniform.value.array;
  51996. }
  51997. }
  51998. const _commandList = [ null ];
  51999. /**
  52000. * A WebGPU backend utility module with common helpers.
  52001. *
  52002. * @private
  52003. */
  52004. class WebGPUUtils {
  52005. /**
  52006. * Constructs a new utility object.
  52007. *
  52008. * @param {WebGPUBackend} backend - The WebGPU backend.
  52009. */
  52010. constructor( backend ) {
  52011. /**
  52012. * A reference to the WebGPU backend.
  52013. *
  52014. * @type {WebGPUBackend}
  52015. */
  52016. this.backend = backend;
  52017. }
  52018. /**
  52019. * Returns the depth/stencil GPU format for the given render context.
  52020. *
  52021. * @param {RenderContext} renderContext - The render context.
  52022. * @return {string} The depth/stencil GPU texture format.
  52023. */
  52024. getCurrentDepthStencilFormat( renderContext ) {
  52025. let format;
  52026. if ( renderContext.depth ) {
  52027. if ( renderContext.depthTexture !== null ) {
  52028. format = this.getTextureFormatGPU( renderContext.depthTexture );
  52029. } else if ( renderContext.stencil ) {
  52030. if ( this.backend.renderer.reversedDepthBuffer === true ) {
  52031. format = GPUTextureFormat.Depth32FloatStencil8;
  52032. } else {
  52033. format = GPUTextureFormat.Depth24PlusStencil8;
  52034. }
  52035. } else {
  52036. if ( this.backend.renderer.reversedDepthBuffer === true ) {
  52037. format = GPUTextureFormat.Depth32Float;
  52038. } else {
  52039. format = GPUTextureFormat.Depth24Plus;
  52040. }
  52041. }
  52042. }
  52043. return format;
  52044. }
  52045. /**
  52046. * Returns the GPU format for the given texture.
  52047. *
  52048. * @param {Texture} texture - The texture.
  52049. * @return {string} The GPU texture format.
  52050. */
  52051. getTextureFormatGPU( texture ) {
  52052. return this.backend.get( texture ).format;
  52053. }
  52054. /**
  52055. * Returns an object that defines the multi-sampling state of the given texture.
  52056. *
  52057. * @param {Texture} texture - The texture.
  52058. * @return {Object} The multi-sampling state.
  52059. */
  52060. getTextureSampleData( texture ) {
  52061. let samples;
  52062. if ( texture.isFramebufferTexture ) {
  52063. samples = 1;
  52064. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  52065. const renderer = this.backend.renderer;
  52066. const renderTarget = renderer.getRenderTarget();
  52067. samples = renderTarget ? renderTarget.samples : renderer.currentSamples;
  52068. } else if ( texture.renderTarget ) {
  52069. samples = texture.renderTarget.samples;
  52070. }
  52071. samples = samples || 1;
  52072. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  52073. const primarySamples = isMSAA ? 1 : samples;
  52074. return { samples, primarySamples, isMSAA };
  52075. }
  52076. /**
  52077. * Returns the default color attachment's GPU format of the current render context.
  52078. *
  52079. * @param {RenderContext} renderContext - The render context.
  52080. * @return {string} The GPU texture format of the default color attachment.
  52081. */
  52082. getCurrentColorFormat( renderContext ) {
  52083. let format;
  52084. if ( renderContext.textures !== null ) {
  52085. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  52086. } else {
  52087. format = this.getPreferredCanvasFormat(); // default context format
  52088. }
  52089. return format;
  52090. }
  52091. /**
  52092. * Returns the GPU formats of all color attachments of the current render context.
  52093. *
  52094. * @param {RenderContext} renderContext - The render context.
  52095. * @return {Array<string>} The GPU texture formats of all color attachments.
  52096. */
  52097. getCurrentColorFormats( renderContext ) {
  52098. if ( renderContext.textures !== null ) {
  52099. return renderContext.textures.map( t => this.getTextureFormatGPU( t ) );
  52100. } else {
  52101. return [ this.getPreferredCanvasFormat() ]; // default context format
  52102. }
  52103. }
  52104. /**
  52105. * Returns the output color space of the current render context.
  52106. *
  52107. * @param {RenderContext} renderContext - The render context.
  52108. * @return {string} The output color space.
  52109. */
  52110. getCurrentColorSpace( renderContext ) {
  52111. if ( renderContext.textures !== null ) {
  52112. return renderContext.textures[ 0 ].colorSpace;
  52113. }
  52114. return this.backend.renderer.outputColorSpace;
  52115. }
  52116. /**
  52117. * Returns GPU primitive topology for the given object and material.
  52118. *
  52119. * @param {Object3D} object - The 3D object.
  52120. * @param {Material} material - The material.
  52121. * @return {string} The GPU primitive topology.
  52122. */
  52123. getPrimitiveTopology( object, material ) {
  52124. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  52125. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  52126. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  52127. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  52128. }
  52129. /**
  52130. * Returns a modified sample count from the given sample count value.
  52131. *
  52132. * That is required since WebGPU only supports either 1 or 4.
  52133. *
  52134. * @param {number} sampleCount - The input sample count.
  52135. * @return {number} The (potentially updated) output sample count.
  52136. */
  52137. getSampleCount( sampleCount ) {
  52138. return sampleCount >= 4 ? 4 : 1;
  52139. }
  52140. /**
  52141. * Returns the sample count of the given render context.
  52142. *
  52143. * @param {RenderContext} renderContext - The render context.
  52144. * @return {number} The sample count.
  52145. */
  52146. getSampleCountRenderContext( renderContext ) {
  52147. if ( renderContext.textures !== null ) {
  52148. return this.getSampleCount( renderContext.sampleCount );
  52149. }
  52150. return this.getSampleCount( this.backend.renderer.currentSamples );
  52151. }
  52152. /**
  52153. * Returns the preferred canvas format.
  52154. *
  52155. * There is a separate method for this so it's possible to
  52156. * honor edge cases for specific devices.
  52157. *
  52158. * @return {string} The GPU texture format of the canvas.
  52159. */
  52160. getPreferredCanvasFormat() {
  52161. const parameters = this.backend.parameters;
  52162. const bufferType = parameters.outputType;
  52163. if ( bufferType === undefined ) {
  52164. return navigator.gpu.getPreferredCanvasFormat();
  52165. } else if ( bufferType === UnsignedByteType ) {
  52166. return GPUTextureFormat.BGRA8Unorm;
  52167. } else if ( bufferType === HalfFloatType ) {
  52168. return GPUTextureFormat.RGBA16Float;
  52169. } else {
  52170. throw new Error( 'Unsupported output buffer type.' );
  52171. }
  52172. }
  52173. }
  52174. /**
  52175. * Submits a single GPU command to the device queue using a shared, module-scoped
  52176. * array to avoid per-call array allocations.
  52177. *
  52178. * @private
  52179. * @param {GPUDevice} device - The GPU device.
  52180. * @param {GPUCommandBuffer} command - The command buffer to submit.
  52181. */
  52182. function submit( device, command ) {
  52183. _commandList[ 0 ] = command;
  52184. device.queue.submit( _commandList );
  52185. _commandList[ 0 ] = null;
  52186. }
  52187. /**
  52188. * Reusable descriptor for `GPUDevice.createBindGroup()`.
  52189. *
  52190. * @private
  52191. */
  52192. class GPUBindGroupDescriptor {
  52193. constructor() {
  52194. /**
  52195. * The label of the bind group.
  52196. *
  52197. * @type {string}
  52198. */
  52199. this.label = '';
  52200. /**
  52201. * The bind group layout the bind group conforms to.
  52202. *
  52203. * @type {?GPUBindGroupLayout}
  52204. * @default null
  52205. */
  52206. this.layout = null;
  52207. /**
  52208. * The bind group entries.
  52209. *
  52210. * @type {Array<Object>}
  52211. */
  52212. this.entries = [];
  52213. }
  52214. /**
  52215. * Resets the descriptor to its default state. The internal `entries` array
  52216. * is emptied without releasing its backing storage.
  52217. */
  52218. reset() {
  52219. this.label = '';
  52220. this.layout = null;
  52221. this.entries.length = 0;
  52222. }
  52223. }
  52224. /**
  52225. * Reusable descriptor for `GPUDevice.createBuffer()`.
  52226. *
  52227. * @private
  52228. */
  52229. class GPUBufferDescriptor {
  52230. constructor() {
  52231. /**
  52232. * The label of the buffer.
  52233. *
  52234. * @type {string}
  52235. */
  52236. this.label = '';
  52237. /**
  52238. * The size of the buffer in bytes.
  52239. *
  52240. * @type {number}
  52241. * @default 0
  52242. */
  52243. this.size = 0;
  52244. /**
  52245. * The allowed usages for the buffer.
  52246. *
  52247. * @type {number}
  52248. * @default 0
  52249. */
  52250. this.usage = 0;
  52251. /**
  52252. * Whether the buffer is in the mapped state at creation.
  52253. *
  52254. * @type {boolean}
  52255. * @default false
  52256. */
  52257. this.mappedAtCreation = false;
  52258. }
  52259. /**
  52260. * Resets the descriptor to its default state.
  52261. */
  52262. reset() {
  52263. this.label = '';
  52264. this.size = 0;
  52265. this.usage = 0;
  52266. this.mappedAtCreation = false;
  52267. }
  52268. }
  52269. /**
  52270. * Reusable descriptor for `GPUDevice.createCommandEncoder()`.
  52271. *
  52272. * @private
  52273. */
  52274. class GPUCommandEncoderDescriptor {
  52275. constructor() {
  52276. /**
  52277. * The label of the command encoder.
  52278. *
  52279. * @type {string}
  52280. */
  52281. this.label = '';
  52282. }
  52283. /**
  52284. * Resets the descriptor to its default state.
  52285. */
  52286. reset() {
  52287. this.label = '';
  52288. }
  52289. }
  52290. /**
  52291. * Reusable descriptor for `GPUDevice.createRenderBundleEncoder()`.
  52292. *
  52293. * @private
  52294. */
  52295. class GPURenderBundleEncoderDescriptor {
  52296. constructor() {
  52297. /**
  52298. * The label of the render bundle encoder.
  52299. *
  52300. * @type {string}
  52301. */
  52302. this.label = '';
  52303. /**
  52304. * The formats of the color attachments the bundle is compatible with.
  52305. *
  52306. * @type {?Array<?string>}
  52307. * @default null
  52308. */
  52309. this.colorFormats = null;
  52310. /**
  52311. * The format of the depth/stencil attachment the bundle is compatible with.
  52312. *
  52313. * @type {string|undefined}
  52314. */
  52315. this.depthStencilFormat = undefined;
  52316. /**
  52317. * The number of samples per pixel the bundle is compatible with.
  52318. *
  52319. * @type {number}
  52320. * @default 1
  52321. */
  52322. this.sampleCount = 1;
  52323. /**
  52324. * Whether the depth attachment is read-only.
  52325. *
  52326. * @type {boolean}
  52327. * @default false
  52328. */
  52329. this.depthReadOnly = false;
  52330. /**
  52331. * Whether the stencil attachment is read-only.
  52332. *
  52333. * @type {boolean}
  52334. * @default false
  52335. */
  52336. this.stencilReadOnly = false;
  52337. }
  52338. /**
  52339. * Resets the descriptor to its default state.
  52340. */
  52341. reset() {
  52342. this.label = '';
  52343. this.colorFormats = null;
  52344. this.depthStencilFormat = undefined;
  52345. this.sampleCount = 1;
  52346. this.depthReadOnly = false;
  52347. this.stencilReadOnly = false;
  52348. }
  52349. }
  52350. /**
  52351. * Reusable descriptor for `GPURenderPassColorAttachment`, the type of each
  52352. * entry in `GPURenderPassDescriptor.colorAttachments`.
  52353. *
  52354. * @private
  52355. */
  52356. class GPURenderPassColorAttachment {
  52357. constructor() {
  52358. /**
  52359. * The texture view the pass renders into.
  52360. *
  52361. * @type {?GPUTextureView}
  52362. * @default null
  52363. */
  52364. this.view = null;
  52365. /**
  52366. * The depth slice the pass renders into.
  52367. *
  52368. * @type {number|undefined}
  52369. */
  52370. this.depthSlice = undefined;
  52371. /**
  52372. * The texture view that receives the resolved output of multisampled rendering.
  52373. *
  52374. * @type {?GPUTextureView|undefined}
  52375. */
  52376. this.resolveTarget = undefined;
  52377. /**
  52378. * The clear value used when `loadOp` is `'clear'`.
  52379. *
  52380. * @type {Object|undefined}
  52381. */
  52382. this.clearValue = undefined;
  52383. /**
  52384. * The load operation performed at the start of the pass.
  52385. *
  52386. * @type {string|undefined}
  52387. */
  52388. this.loadOp = undefined;
  52389. /**
  52390. * The store operation performed at the end of the pass.
  52391. *
  52392. * @type {string|undefined}
  52393. */
  52394. this.storeOp = undefined;
  52395. }
  52396. /**
  52397. * Resets the descriptor to its default state.
  52398. */
  52399. reset() {
  52400. this.view = null;
  52401. this.depthSlice = undefined;
  52402. this.resolveTarget = undefined;
  52403. this.clearValue = undefined;
  52404. this.loadOp = undefined;
  52405. this.storeOp = undefined;
  52406. }
  52407. }
  52408. /**
  52409. * Reusable descriptor for `GPUCommandEncoder.beginRenderPass()`.
  52410. *
  52411. * @private
  52412. */
  52413. class GPURenderPassDescriptor {
  52414. constructor() {
  52415. /**
  52416. * The label of the render pass.
  52417. *
  52418. * @type {string}
  52419. */
  52420. this.label = '';
  52421. /**
  52422. * The color attachments of the render pass.
  52423. *
  52424. * @type {Array<?Object>}
  52425. */
  52426. this.colorAttachments = [];
  52427. /**
  52428. * The depth-stencil attachment of the render pass.
  52429. *
  52430. * @type {Object|undefined}
  52431. */
  52432. this.depthStencilAttachment = undefined;
  52433. /**
  52434. * The query set used for occlusion queries during the pass.
  52435. *
  52436. * @type {?GPUQuerySet|undefined}
  52437. */
  52438. this.occlusionQuerySet = undefined;
  52439. /**
  52440. * Defines which timestamp values are written and where.
  52441. *
  52442. * @type {Object|undefined}
  52443. */
  52444. this.timestampWrites = undefined;
  52445. /**
  52446. * The maximum number of draw calls that can be issued during the pass.
  52447. *
  52448. * @type {number}
  52449. * @default 50000000
  52450. */
  52451. this.maxDrawCount = 50000000;
  52452. }
  52453. /**
  52454. * Resets the descriptor to its default state. The internal `colorAttachments`
  52455. * array is emptied without releasing its backing storage.
  52456. */
  52457. reset() {
  52458. this.label = '';
  52459. this.colorAttachments.length = 0;
  52460. this.depthStencilAttachment = undefined;
  52461. this.occlusionQuerySet = undefined;
  52462. this.timestampWrites = undefined;
  52463. this.maxDrawCount = 50000000;
  52464. }
  52465. }
  52466. /**
  52467. * Reusable descriptor for `GPUDevice.createRenderPipeline()` and
  52468. * `createRenderPipelineAsync()`.
  52469. *
  52470. * @private
  52471. */
  52472. class GPURenderPipelineDescriptor {
  52473. constructor() {
  52474. /**
  52475. * The label of the render pipeline.
  52476. *
  52477. * @type {string}
  52478. */
  52479. this.label = '';
  52480. /**
  52481. * The pipeline layout the pipeline conforms to, or `'auto'`.
  52482. *
  52483. * @type {?GPUPipelineLayout|string}
  52484. * @default null
  52485. */
  52486. this.layout = null;
  52487. /**
  52488. * The programmable vertex stage.
  52489. *
  52490. * @type {?Object}
  52491. * @default null
  52492. */
  52493. this.vertex = null;
  52494. /**
  52495. * The primitive-assembly state.
  52496. *
  52497. * @type {Object}
  52498. */
  52499. this.primitive = {};
  52500. /**
  52501. * The depth/stencil state, omitted when the pipeline has no depth or stencil aspect.
  52502. *
  52503. * @type {Object|undefined}
  52504. */
  52505. this.depthStencil = undefined;
  52506. /**
  52507. * The multisample state.
  52508. *
  52509. * @type {GPUMultisampleState}
  52510. */
  52511. this.multisample = new GPUMultisampleState();
  52512. /**
  52513. * The programmable fragment stage. Omitted for vertex-only pipelines.
  52514. *
  52515. * @type {?Object}
  52516. * @default null
  52517. */
  52518. this.fragment = null;
  52519. }
  52520. /**
  52521. * Resets the descriptor to its default state.
  52522. */
  52523. reset() {
  52524. this.label = '';
  52525. this.layout = null;
  52526. this.vertex = null;
  52527. this.primitive = {};
  52528. this.depthStencil = undefined;
  52529. this.multisample.reset();
  52530. this.fragment = null;
  52531. }
  52532. }
  52533. /**
  52534. * Reusable nested state for `GPURenderPipelineDescriptor.multisample`.
  52535. *
  52536. * @private
  52537. */
  52538. class GPUMultisampleState {
  52539. constructor() {
  52540. /**
  52541. * The number of samples per pixel.
  52542. *
  52543. * @type {number}
  52544. * @default 1
  52545. */
  52546. this.count = 1;
  52547. /**
  52548. * A bitmask determining which samples are written to.
  52549. *
  52550. * @type {number}
  52551. * @default 0xFFFFFFFF
  52552. */
  52553. this.mask = 0xFFFFFFFF;
  52554. /**
  52555. * Whether a fragment's alpha channel is used to generate a sample coverage mask.
  52556. *
  52557. * @type {boolean}
  52558. * @default false
  52559. */
  52560. this.alphaToCoverageEnabled = false;
  52561. }
  52562. /**
  52563. * Resets the state to its default values.
  52564. */
  52565. reset() {
  52566. this.count = 1;
  52567. this.mask = 0xFFFFFFFF;
  52568. this.alphaToCoverageEnabled = false;
  52569. }
  52570. }
  52571. /**
  52572. * Reusable descriptor for `GPUDevice.createShaderModule()`.
  52573. *
  52574. * @private
  52575. */
  52576. class GPUShaderModuleDescriptor {
  52577. constructor() {
  52578. /**
  52579. * The label of the shader module.
  52580. *
  52581. * @type {string}
  52582. */
  52583. this.label = '';
  52584. /**
  52585. * The WGSL source code of the shader module.
  52586. *
  52587. * @type {string}
  52588. */
  52589. this.code = '';
  52590. /**
  52591. * Compilation hints that may help the implementation produce optimized code.
  52592. *
  52593. * @type {Array<Object>}
  52594. */
  52595. this.compilationHints = [];
  52596. }
  52597. /**
  52598. * Resets the descriptor to its default state.
  52599. */
  52600. reset() {
  52601. this.label = '';
  52602. this.code = '';
  52603. this.compilationHints.length = 0;
  52604. }
  52605. }
  52606. /**
  52607. * Reusable descriptor for `GPUDevice.createTexture()`.
  52608. *
  52609. * @private
  52610. */
  52611. class GPUTextureDescriptor {
  52612. constructor() {
  52613. /**
  52614. * The label of the texture.
  52615. *
  52616. * @type {string}
  52617. */
  52618. this.label = '';
  52619. /**
  52620. * The size of the texture.
  52621. *
  52622. * @type {{width: number, height: number, depthOrArrayLayers: number}}
  52623. */
  52624. this.size = { width: 0, height: 1, depthOrArrayLayers: 1 };
  52625. /**
  52626. * The number of mip levels the texture will contain.
  52627. *
  52628. * @type {number}
  52629. * @default 1
  52630. */
  52631. this.mipLevelCount = 1;
  52632. /**
  52633. * The sample count of the texture.
  52634. *
  52635. * @type {number}
  52636. * @default 1
  52637. */
  52638. this.sampleCount = 1;
  52639. /**
  52640. * The dimension of the set of texel coordinates.
  52641. *
  52642. * @type {string}
  52643. * @default '2d'
  52644. */
  52645. this.dimension = '2d';
  52646. /**
  52647. * The format of the texture.
  52648. *
  52649. * @type {string|undefined}
  52650. */
  52651. this.format = undefined;
  52652. /**
  52653. * The allowed usages for the texture.
  52654. *
  52655. * @type {number|undefined}
  52656. */
  52657. this.usage = undefined;
  52658. /**
  52659. * The formats that views of this texture may use.
  52660. *
  52661. * @type {Array<string>}
  52662. */
  52663. this.viewFormats = [];
  52664. /**
  52665. * The view dimension to use when binding the texture (compatibility mode).
  52666. *
  52667. * @type {string|undefined}
  52668. */
  52669. this.textureBindingViewDimension = undefined;
  52670. }
  52671. /**
  52672. * Resets the descriptor to its default state.
  52673. */
  52674. reset() {
  52675. this.label = '';
  52676. this.size.width = 0;
  52677. this.size.height = 1;
  52678. this.size.depthOrArrayLayers = 1;
  52679. this.mipLevelCount = 1;
  52680. this.sampleCount = 1;
  52681. this.dimension = '2d';
  52682. this.format = undefined;
  52683. this.usage = undefined;
  52684. this.viewFormats.length = 0;
  52685. this.textureBindingViewDimension = undefined;
  52686. }
  52687. }
  52688. /**
  52689. * Reusable descriptor for `GPUTexture.createView()`.
  52690. *
  52691. * @private
  52692. */
  52693. class GPUTextureViewDescriptor {
  52694. constructor() {
  52695. /**
  52696. * The label of the texture view.
  52697. *
  52698. * @type {string}
  52699. */
  52700. this.label = '';
  52701. /**
  52702. * The format of the texture view.
  52703. *
  52704. * @type {string|undefined}
  52705. */
  52706. this.format = undefined;
  52707. /**
  52708. * The dimension of the texture view.
  52709. *
  52710. * @type {string|undefined}
  52711. */
  52712. this.dimension = undefined;
  52713. /**
  52714. * The allowed usages for the texture view.
  52715. *
  52716. * @type {number}
  52717. * @default 0
  52718. */
  52719. this.usage = 0;
  52720. /**
  52721. * Which aspect of the texture is referenced.
  52722. *
  52723. * @type {string}
  52724. * @default 'all'
  52725. */
  52726. this.aspect = 'all';
  52727. /**
  52728. * The first mip level accessible to the texture view.
  52729. *
  52730. * @type {number}
  52731. * @default 0
  52732. */
  52733. this.baseMipLevel = 0;
  52734. /**
  52735. * The number of mip levels accessible to the texture view.
  52736. *
  52737. * @type {number|undefined}
  52738. */
  52739. this.mipLevelCount = undefined;
  52740. /**
  52741. * The first array layer accessible to the texture view.
  52742. *
  52743. * @type {number}
  52744. * @default 0
  52745. */
  52746. this.baseArrayLayer = 0;
  52747. /**
  52748. * The number of array layers accessible to the texture view.
  52749. *
  52750. * @type {number|undefined}
  52751. */
  52752. this.arrayLayerCount = undefined;
  52753. /**
  52754. * The component swizzle to apply when sampling the texture view.
  52755. * Requires the `'texture-component-swizzle'` feature; ignored otherwise.
  52756. *
  52757. * @type {string}
  52758. * @default 'rgba'
  52759. */
  52760. this.swizzle = 'rgba';
  52761. }
  52762. /**
  52763. * Resets the descriptor to its default state.
  52764. */
  52765. reset() {
  52766. this.label = '';
  52767. this.format = undefined;
  52768. this.dimension = undefined;
  52769. this.usage = 0;
  52770. this.aspect = 'all';
  52771. this.baseMipLevel = 0;
  52772. this.mipLevelCount = undefined;
  52773. this.baseArrayLayer = 0;
  52774. this.arrayLayerCount = undefined;
  52775. this.swizzle = 'rgba';
  52776. }
  52777. }
  52778. const _bindGroupDescriptor$1 = new GPUBindGroupDescriptor();
  52779. const _bufferDescriptor$5 = new GPUBufferDescriptor();
  52780. const _commandEncoderDescriptor$4 = new GPUCommandEncoderDescriptor();
  52781. const _renderBundleEncoderDescriptor$1 = new GPURenderBundleEncoderDescriptor();
  52782. const _renderPassDescriptor = new GPURenderPassDescriptor();
  52783. const _renderPipelineDescriptor$1 = new GPURenderPipelineDescriptor();
  52784. const _colorAttachment = new GPURenderPassColorAttachment();
  52785. const _shaderModuleDescriptor$1 = new GPUShaderModuleDescriptor();
  52786. const _textureDescriptor$1 = new GPUTextureDescriptor();
  52787. const _viewDescriptor$2 = new GPUTextureViewDescriptor();
  52788. /**
  52789. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  52790. *
  52791. * @private
  52792. */
  52793. class WebGPUTexturePassUtils extends DataMap {
  52794. /**
  52795. * Constructs a new utility object.
  52796. *
  52797. * @param {GPUDevice} device - The WebGPU device.
  52798. */
  52799. constructor( device ) {
  52800. super();
  52801. /**
  52802. * The WebGPU device.
  52803. *
  52804. * @type {GPUDevice}
  52805. */
  52806. this.device = device;
  52807. const mipmapSource = `
  52808. struct VarysStruct {
  52809. @builtin( position ) Position: vec4f,
  52810. @location( 0 ) vTex : vec2f,
  52811. @location( 1 ) @interpolate(flat, either) vBaseArrayLayer: u32,
  52812. };
  52813. @group( 0 ) @binding ( 2 )
  52814. var<uniform> flipY: u32;
  52815. @vertex
  52816. fn mainVS(
  52817. @builtin( vertex_index ) vertexIndex : u32,
  52818. @builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct {
  52819. var Varys : VarysStruct;
  52820. var pos = array(
  52821. vec2f( -1, -1 ),
  52822. vec2f( -1, 3 ),
  52823. vec2f( 3, -1 ),
  52824. );
  52825. let p = pos[ vertexIndex ];
  52826. let mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 );
  52827. Varys.vTex = p * mult + vec2f( 0.5 );
  52828. Varys.Position = vec4f( p, 0, 1 );
  52829. Varys.vBaseArrayLayer = instanceIndex;
  52830. return Varys;
  52831. }
  52832. @group( 0 ) @binding( 0 )
  52833. var imgSampler : sampler;
  52834. @group( 0 ) @binding( 1 )
  52835. var img2d : texture_2d<f32>;
  52836. @fragment
  52837. fn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
  52838. return textureSample( img2d, imgSampler, Varys.vTex );
  52839. }
  52840. @group( 0 ) @binding( 1 )
  52841. var img2dArray : texture_2d_array<f32>;
  52842. @fragment
  52843. fn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
  52844. return textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer );
  52845. }
  52846. const faceMat = array(
  52847. mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x
  52848. mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x
  52849. mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y
  52850. mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y
  52851. mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z
  52852. mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z
  52853. );
  52854. @group( 0 ) @binding( 1 )
  52855. var imgCube : texture_cube<f32>;
  52856. @fragment
  52857. fn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
  52858. return textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) );
  52859. }
  52860. `;
  52861. /**
  52862. * The mipmap GPU sampler.
  52863. *
  52864. * @type {GPUSampler}
  52865. */
  52866. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  52867. /**
  52868. * The flipY GPU sampler.
  52869. *
  52870. * @type {GPUSampler}
  52871. */
  52872. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  52873. /**
  52874. * flip uniform buffer
  52875. * @type {GPUBuffer}
  52876. */
  52877. _bufferDescriptor$5.size = 4;
  52878. _bufferDescriptor$5.usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  52879. this.flipUniformBuffer = device.createBuffer( _bufferDescriptor$5 );
  52880. _bufferDescriptor$5.reset();
  52881. device.queue.writeBuffer( this.flipUniformBuffer, 0, new Uint32Array( [ 1 ] ) );
  52882. /**
  52883. * no flip uniform buffer
  52884. * @type {GPUBuffer}
  52885. */
  52886. _bufferDescriptor$5.size = 4;
  52887. _bufferDescriptor$5.usage = GPUBufferUsage.UNIFORM;
  52888. this.noFlipUniformBuffer = device.createBuffer( _bufferDescriptor$5 );
  52889. _bufferDescriptor$5.reset();
  52890. /**
  52891. * A cache for GPU render pipelines used for copy/transfer passes.
  52892. * Every texture format and textureBindingViewDimension combo requires a unique pipeline.
  52893. *
  52894. * @type {Object<string,GPURenderPipeline>}
  52895. */
  52896. this.transferPipelines = {};
  52897. /**
  52898. * The mipmap shader module.
  52899. *
  52900. * @type {GPUShaderModule}
  52901. */
  52902. _shaderModuleDescriptor$1.label = 'mipmap';
  52903. _shaderModuleDescriptor$1.code = mipmapSource;
  52904. this.mipmapShaderModule = device.createShaderModule( _shaderModuleDescriptor$1 );
  52905. _shaderModuleDescriptor$1.reset();
  52906. }
  52907. /**
  52908. * Returns a render pipeline for the internal copy render pass. The pass
  52909. * requires a unique render pipeline for each texture format.
  52910. *
  52911. * @param {string} format - The GPU texture format
  52912. * @param {string?} textureBindingViewDimension - The GPU texture binding view dimension
  52913. * @return {GPURenderPipeline} The GPU render pipeline.
  52914. */
  52915. getTransferPipeline( format, textureBindingViewDimension ) {
  52916. textureBindingViewDimension = textureBindingViewDimension || '2d-array';
  52917. const key = `${ format }-${ textureBindingViewDimension }`;
  52918. let pipeline = this.transferPipelines[ key ];
  52919. if ( pipeline === undefined ) {
  52920. _renderPipelineDescriptor$1.label = `mipmap-${ format }-${ textureBindingViewDimension }`;
  52921. _renderPipelineDescriptor$1.vertex = { module: this.mipmapShaderModule };
  52922. _renderPipelineDescriptor$1.fragment = {
  52923. module: this.mipmapShaderModule,
  52924. entryPoint: `main_${ textureBindingViewDimension.replace( '-', '_' ) }`,
  52925. targets: [ { format } ]
  52926. };
  52927. _renderPipelineDescriptor$1.layout = 'auto';
  52928. pipeline = this.device.createRenderPipeline( _renderPipelineDescriptor$1 );
  52929. _renderPipelineDescriptor$1.reset();
  52930. this.transferPipelines[ key ] = pipeline;
  52931. }
  52932. return pipeline;
  52933. }
  52934. /**
  52935. * Flip the contents of the given GPU texture along its vertical axis.
  52936. *
  52937. * @param {GPUTexture} textureGPU - The GPU texture object.
  52938. * @param {Object} textureGPUDescriptor - The texture descriptor.
  52939. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  52940. */
  52941. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  52942. const format = textureGPUDescriptor.format;
  52943. const { width, height } = textureGPUDescriptor.size;
  52944. _textureDescriptor$1.size.width = width;
  52945. _textureDescriptor$1.size.height = height;
  52946. _textureDescriptor$1.format = format;
  52947. _textureDescriptor$1.usage = GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING;
  52948. const tempTexture = this.device.createTexture( _textureDescriptor$1 );
  52949. _textureDescriptor$1.reset();
  52950. const copyTransferPipeline = this.getTransferPipeline( format, textureGPU.textureBindingViewDimension );
  52951. const flipTransferPipeline = this.getTransferPipeline( format, tempTexture.textureBindingViewDimension );
  52952. const commandEncoder = this.device.createCommandEncoder( _commandEncoderDescriptor$4 );
  52953. const pass = ( pipeline, sourceTexture, sourceArrayLayer, destinationTexture, destinationArrayLayer, flipY ) => {
  52954. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  52955. _viewDescriptor$2.dimension = sourceTexture.textureBindingViewDimension || '2d-array';
  52956. _viewDescriptor$2.mipLevelCount = 1;
  52957. const sourceView = sourceTexture.createView( _viewDescriptor$2 );
  52958. _viewDescriptor$2.reset();
  52959. _bindGroupDescriptor$1.layout = bindGroupLayout;
  52960. _bindGroupDescriptor$1.entries.push( {
  52961. binding: 0,
  52962. resource: this.flipYSampler
  52963. }, {
  52964. binding: 1,
  52965. resource: sourceView,
  52966. }, {
  52967. binding: 2,
  52968. resource: { buffer: flipY ? this.flipUniformBuffer : this.noFlipUniformBuffer }
  52969. } );
  52970. const bindGroup = this.device.createBindGroup( _bindGroupDescriptor$1 );
  52971. _bindGroupDescriptor$1.reset();
  52972. _viewDescriptor$2.dimension = '2d';
  52973. _viewDescriptor$2.mipLevelCount = 1;
  52974. _viewDescriptor$2.baseArrayLayer = destinationArrayLayer;
  52975. _viewDescriptor$2.arrayLayerCount = 1;
  52976. const destinationView = destinationTexture.createView( _viewDescriptor$2 );
  52977. _viewDescriptor$2.reset();
  52978. _colorAttachment.view = destinationView;
  52979. _colorAttachment.loadOp = GPULoadOp.Clear;
  52980. _colorAttachment.storeOp = GPUStoreOp.Store;
  52981. _renderPassDescriptor.colorAttachments.push( _colorAttachment );
  52982. const passEncoder = commandEncoder.beginRenderPass( _renderPassDescriptor );
  52983. _renderPassDescriptor.reset();
  52984. _colorAttachment.reset();
  52985. passEncoder.setPipeline( pipeline );
  52986. passEncoder.setBindGroup( 0, bindGroup );
  52987. passEncoder.draw( 3, 1, 0, sourceArrayLayer );
  52988. passEncoder.end();
  52989. };
  52990. pass( copyTransferPipeline, textureGPU, baseArrayLayer, tempTexture, 0, false );
  52991. pass( flipTransferPipeline, tempTexture, 0, textureGPU, baseArrayLayer, true );
  52992. submit( this.device, commandEncoder.finish() );
  52993. tempTexture.destroy();
  52994. }
  52995. /**
  52996. * Generates mipmaps for the given GPU texture.
  52997. *
  52998. * @param {GPUTexture} textureGPU - The GPU texture object.
  52999. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  53000. */
  53001. generateMipmaps( textureGPU, encoder = null ) {
  53002. const textureData = this.get( textureGPU );
  53003. const passes = textureData.layers || this._mipmapCreateBundles( textureGPU );
  53004. let commandEncoder = encoder;
  53005. if ( commandEncoder === null ) {
  53006. _commandEncoderDescriptor$4.label = 'mipmapEncoder';
  53007. commandEncoder = this.device.createCommandEncoder( _commandEncoderDescriptor$4 );
  53008. _commandEncoderDescriptor$4.reset();
  53009. }
  53010. this._mipmapRunBundles( commandEncoder, passes );
  53011. if ( encoder === null ) submit( this.device, commandEncoder.finish() );
  53012. textureData.layers = passes;
  53013. }
  53014. /**
  53015. * Since multiple copy render passes are required to generate mipmaps, the passes
  53016. * are managed as render bundles to improve performance.
  53017. *
  53018. * @param {GPUTexture} textureGPU - The GPU texture object.
  53019. * @return {Array<Object>} An array of render bundles.
  53020. */
  53021. _mipmapCreateBundles( textureGPU ) {
  53022. const textureBindingViewDimension = textureGPU.textureBindingViewDimension || '2d-array';
  53023. const pipeline = this.getTransferPipeline( textureGPU.format, textureBindingViewDimension );
  53024. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  53025. const passes = [];
  53026. for ( let baseMipLevel = 1; baseMipLevel < textureGPU.mipLevelCount; baseMipLevel ++ ) {
  53027. for ( let baseArrayLayer = 0; baseArrayLayer < textureGPU.depthOrArrayLayers; baseArrayLayer ++ ) {
  53028. _viewDescriptor$2.dimension = textureBindingViewDimension;
  53029. _viewDescriptor$2.baseMipLevel = baseMipLevel - 1;
  53030. _viewDescriptor$2.mipLevelCount = 1;
  53031. const sourceView = textureGPU.createView( _viewDescriptor$2 );
  53032. _viewDescriptor$2.reset();
  53033. _bindGroupDescriptor$1.layout = bindGroupLayout;
  53034. _bindGroupDescriptor$1.entries.push( {
  53035. binding: 0,
  53036. resource: this.mipmapSampler
  53037. }, {
  53038. binding: 1,
  53039. resource: sourceView,
  53040. }, {
  53041. binding: 2,
  53042. resource: { buffer: this.noFlipUniformBuffer }
  53043. } );
  53044. const bindGroup = this.device.createBindGroup( _bindGroupDescriptor$1 );
  53045. _bindGroupDescriptor$1.reset();
  53046. _viewDescriptor$2.dimension = '2d';
  53047. _viewDescriptor$2.baseMipLevel = baseMipLevel;
  53048. _viewDescriptor$2.mipLevelCount = 1;
  53049. _viewDescriptor$2.baseArrayLayer = baseArrayLayer;
  53050. _viewDescriptor$2.arrayLayerCount = 1;
  53051. const destinationView = textureGPU.createView( _viewDescriptor$2 );
  53052. _viewDescriptor$2.reset();
  53053. const passColorAttachment = new GPURenderPassColorAttachment();
  53054. passColorAttachment.view = destinationView;
  53055. passColorAttachment.loadOp = GPULoadOp.Clear;
  53056. passColorAttachment.storeOp = GPUStoreOp.Store;
  53057. const passDescriptor = new GPURenderPassDescriptor();
  53058. passDescriptor.colorAttachments.push( passColorAttachment );
  53059. _renderBundleEncoderDescriptor$1.colorFormats = [ textureGPU.format ];
  53060. const passEncoder = this.device.createRenderBundleEncoder( _renderBundleEncoderDescriptor$1 );
  53061. _renderBundleEncoderDescriptor$1.reset();
  53062. passEncoder.setPipeline( pipeline );
  53063. passEncoder.setBindGroup( 0, bindGroup );
  53064. passEncoder.draw( 3, 1, 0, baseArrayLayer );
  53065. passes.push( {
  53066. renderBundles: [ passEncoder.finish() ],
  53067. passDescriptor
  53068. } );
  53069. }
  53070. }
  53071. return passes;
  53072. }
  53073. /**
  53074. * Executes the render bundles.
  53075. *
  53076. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  53077. * @param {Array<Object>} passes - An array of render bundles.
  53078. */
  53079. _mipmapRunBundles( commandEncoder, passes ) {
  53080. const levels = passes.length;
  53081. for ( let i = 0; i < levels; i ++ ) {
  53082. const pass = passes[ i ];
  53083. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  53084. passEncoder.executeBundles( pass.renderBundles );
  53085. passEncoder.end();
  53086. }
  53087. }
  53088. }
  53089. /**
  53090. * Reusable descriptor for `GPUDevice.createSampler()`.
  53091. *
  53092. * @private
  53093. */
  53094. class GPUSamplerDescriptor {
  53095. constructor() {
  53096. /**
  53097. * The label of the sampler.
  53098. *
  53099. * @type {string}
  53100. */
  53101. this.label = '';
  53102. /**
  53103. * The address mode for the sampler's U coordinate.
  53104. *
  53105. * @type {string}
  53106. * @default 'clamp-to-edge'
  53107. */
  53108. this.addressModeU = 'clamp-to-edge';
  53109. /**
  53110. * The address mode for the sampler's V coordinate.
  53111. *
  53112. * @type {string}
  53113. * @default 'clamp-to-edge'
  53114. */
  53115. this.addressModeV = 'clamp-to-edge';
  53116. /**
  53117. * The address mode for the sampler's W coordinate.
  53118. *
  53119. * @type {string}
  53120. * @default 'clamp-to-edge'
  53121. */
  53122. this.addressModeW = 'clamp-to-edge';
  53123. /**
  53124. * The magnification filter mode.
  53125. *
  53126. * @type {string}
  53127. * @default 'nearest'
  53128. */
  53129. this.magFilter = 'nearest';
  53130. /**
  53131. * The minification filter mode.
  53132. *
  53133. * @type {string}
  53134. * @default 'nearest'
  53135. */
  53136. this.minFilter = 'nearest';
  53137. /**
  53138. * The mipmap filter mode.
  53139. *
  53140. * @type {string}
  53141. * @default 'nearest'
  53142. */
  53143. this.mipmapFilter = 'nearest';
  53144. /**
  53145. * The minimum level of detail used to sample.
  53146. *
  53147. * @type {number}
  53148. * @default 0
  53149. */
  53150. this.lodMinClamp = 0;
  53151. /**
  53152. * The maximum level of detail used to sample.
  53153. *
  53154. * @type {number}
  53155. * @default 32
  53156. */
  53157. this.lodMaxClamp = 32;
  53158. /**
  53159. * The compare function used by the sampler.
  53160. *
  53161. * @type {string|undefined}
  53162. */
  53163. this.compare = undefined;
  53164. /**
  53165. * The maximum allowed anisotropic filtering.
  53166. *
  53167. * @type {number}
  53168. * @default 1
  53169. */
  53170. this.maxAnisotropy = 1;
  53171. }
  53172. /**
  53173. * Resets the descriptor to its default state.
  53174. */
  53175. reset() {
  53176. this.label = '';
  53177. this.addressModeU = 'clamp-to-edge';
  53178. this.addressModeV = 'clamp-to-edge';
  53179. this.addressModeW = 'clamp-to-edge';
  53180. this.magFilter = 'nearest';
  53181. this.minFilter = 'nearest';
  53182. this.mipmapFilter = 'nearest';
  53183. this.lodMinClamp = 0;
  53184. this.lodMaxClamp = 32;
  53185. this.compare = undefined;
  53186. this.maxAnisotropy = 1;
  53187. }
  53188. }
  53189. /**
  53190. * Reusable descriptor for `GPUTexelCopyTextureInfo`, the texture side of
  53191. * `GPUCommandEncoder.copyTextureToTexture()`, `copyTextureToBuffer()` and
  53192. * `GPUQueue.writeTexture()`.
  53193. *
  53194. * @private
  53195. */
  53196. class GPUTexelCopyTextureInfo {
  53197. constructor() {
  53198. /**
  53199. * The target texture.
  53200. *
  53201. * @type {?GPUTexture}
  53202. * @default null
  53203. */
  53204. this.texture = null;
  53205. /**
  53206. * The mipmap level of the texture.
  53207. *
  53208. * @type {number}
  53209. * @default 0
  53210. */
  53211. this.mipLevel = 0;
  53212. /**
  53213. * The origin offset within the texture.
  53214. *
  53215. * @type {{x: number, y: number, z: number}}
  53216. */
  53217. this.origin = { x: 0, y: 0, z: 0 };
  53218. /**
  53219. * Which aspect of the texture is referenced.
  53220. *
  53221. * @type {string}
  53222. * @default 'all'
  53223. */
  53224. this.aspect = 'all';
  53225. }
  53226. /**
  53227. * Resets the descriptor to its default state.
  53228. */
  53229. reset() {
  53230. this.texture = null;
  53231. this.mipLevel = 0;
  53232. this.origin.x = 0;
  53233. this.origin.y = 0;
  53234. this.origin.z = 0;
  53235. this.aspect = 'all';
  53236. }
  53237. }
  53238. /**
  53239. * Reusable descriptor for `GPUTexelCopyBufferInfo`, the buffer side of
  53240. * `GPUCommandEncoder.copyTextureToBuffer()` and `copyBufferToTexture()`.
  53241. *
  53242. * @private
  53243. */
  53244. class GPUTexelCopyBufferInfo {
  53245. constructor() {
  53246. /**
  53247. * The target buffer.
  53248. *
  53249. * @type {?GPUBuffer}
  53250. * @default null
  53251. */
  53252. this.buffer = null;
  53253. /**
  53254. * The byte offset within the buffer where the texel data begins.
  53255. *
  53256. * @type {number}
  53257. * @default 0
  53258. */
  53259. this.offset = 0;
  53260. /**
  53261. * The stride, in bytes, between rows of texel blocks.
  53262. *
  53263. * @type {number|undefined}
  53264. */
  53265. this.bytesPerRow = undefined;
  53266. /**
  53267. * The number of texel block rows per single image of the texture.
  53268. *
  53269. * @type {number|undefined}
  53270. */
  53271. this.rowsPerImage = undefined;
  53272. }
  53273. /**
  53274. * Resets the descriptor to its default state.
  53275. */
  53276. reset() {
  53277. this.buffer = null;
  53278. this.offset = 0;
  53279. this.bytesPerRow = undefined;
  53280. this.rowsPerImage = undefined;
  53281. }
  53282. }
  53283. /**
  53284. * Reusable descriptor for `GPUTexelCopyBufferLayout`, the data-layout argument
  53285. * to `GPUQueue.writeTexture()`.
  53286. *
  53287. * @private
  53288. */
  53289. class GPUTexelCopyBufferLayout {
  53290. constructor() {
  53291. /**
  53292. * The byte offset within the source data where the texel data begins.
  53293. *
  53294. * @type {number}
  53295. * @default 0
  53296. */
  53297. this.offset = 0;
  53298. /**
  53299. * The stride, in bytes, between rows of texel blocks.
  53300. *
  53301. * @type {number|undefined}
  53302. */
  53303. this.bytesPerRow = undefined;
  53304. /**
  53305. * The number of texel block rows per single image of the texture.
  53306. *
  53307. * @type {number|undefined}
  53308. */
  53309. this.rowsPerImage = undefined;
  53310. }
  53311. /**
  53312. * Resets the descriptor to its default state.
  53313. */
  53314. reset() {
  53315. this.offset = 0;
  53316. this.bytesPerRow = undefined;
  53317. this.rowsPerImage = undefined;
  53318. }
  53319. }
  53320. /**
  53321. * Reusable descriptor for `GPUCopyExternalImageSourceInfo`, the source argument
  53322. * to `GPUQueue.copyExternalImageToTexture()`.
  53323. *
  53324. * @private
  53325. */
  53326. class GPUCopyExternalImageSourceInfo {
  53327. constructor() {
  53328. /**
  53329. * The image-like source.
  53330. *
  53331. * @type {?(ImageBitmap|ImageData|HTMLImageElement|HTMLVideoElement|VideoFrame|HTMLCanvasElement|OffscreenCanvas)}
  53332. * @default null
  53333. */
  53334. this.source = null;
  53335. /**
  53336. * The origin offset within the source.
  53337. *
  53338. * @type {{x: number, y: number}}
  53339. */
  53340. this.origin = { x: 0, y: 0 };
  53341. /**
  53342. * Whether the source is flipped vertically before copying.
  53343. *
  53344. * @type {boolean}
  53345. * @default false
  53346. */
  53347. this.flipY = false;
  53348. }
  53349. /**
  53350. * Resets the descriptor to its default state.
  53351. */
  53352. reset() {
  53353. this.source = null;
  53354. this.origin.x = 0;
  53355. this.origin.y = 0;
  53356. this.flipY = false;
  53357. }
  53358. }
  53359. /**
  53360. * Reusable descriptor for `GPUCopyExternalImageDestInfo`, the destination
  53361. * argument to `GPUQueue.copyExternalImageToTexture()`.
  53362. *
  53363. * @private
  53364. * @augments GPUTexelCopyTextureInfo
  53365. */
  53366. class GPUCopyExternalImageDestInfo extends GPUTexelCopyTextureInfo {
  53367. constructor() {
  53368. super();
  53369. /**
  53370. * The predefined color space the destination texture is interpreted in.
  53371. *
  53372. * @type {string}
  53373. * @default 'srgb'
  53374. */
  53375. this.colorSpace = 'srgb';
  53376. /**
  53377. * Whether the destination texture has premultiplied alpha.
  53378. *
  53379. * @type {boolean}
  53380. * @default false
  53381. */
  53382. this.premultipliedAlpha = false;
  53383. }
  53384. /**
  53385. * Resets the descriptor to its default state.
  53386. */
  53387. reset() {
  53388. super.reset();
  53389. this.colorSpace = 'srgb';
  53390. this.premultipliedAlpha = false;
  53391. }
  53392. }
  53393. /**
  53394. * Reusable descriptor for `GPUExtent3D` in its dictionary form, used by
  53395. * `GPUQueue.writeTexture()`, `GPUQueue.copyExternalImageToTexture()` and
  53396. * the various `GPUCommandEncoder` copy methods.
  53397. *
  53398. * @private
  53399. */
  53400. class GPUExtent3D {
  53401. constructor() {
  53402. /**
  53403. * The width of the extent.
  53404. *
  53405. * @type {number}
  53406. * @default 0
  53407. */
  53408. this.width = 0;
  53409. /**
  53410. * The height of the extent.
  53411. *
  53412. * @type {number}
  53413. * @default 1
  53414. */
  53415. this.height = 1;
  53416. /**
  53417. * The depth (for 3D textures) or number of array layers.
  53418. *
  53419. * @type {number}
  53420. * @default 1
  53421. */
  53422. this.depthOrArrayLayers = 1;
  53423. }
  53424. /**
  53425. * Resets the descriptor to its default state.
  53426. */
  53427. reset() {
  53428. this.width = 0;
  53429. this.height = 1;
  53430. this.depthOrArrayLayers = 1;
  53431. }
  53432. }
  53433. const _bufferDescriptor$4 = new GPUBufferDescriptor();
  53434. const _commandEncoderDescriptor$3 = new GPUCommandEncoderDescriptor();
  53435. const _samplerDescriptor = new GPUSamplerDescriptor();
  53436. const _texelCopyTextureInfo = new GPUTexelCopyTextureInfo();
  53437. const _texelCopyBufferInfo = new GPUTexelCopyBufferInfo();
  53438. const _texelCopyBufferLayout = new GPUTexelCopyBufferLayout();
  53439. const _copyExternalImageSourceInfo = new GPUCopyExternalImageSourceInfo();
  53440. const _copyExternalImageDestInfo = new GPUCopyExternalImageDestInfo();
  53441. const _textureDescriptor = new GPUTextureDescriptor();
  53442. const _extent3D$1 = new GPUExtent3D();
  53443. const _compareToWebGPU = {
  53444. [ NeverCompare ]: 'never',
  53445. [ LessCompare ]: 'less',
  53446. [ EqualCompare ]: 'equal',
  53447. [ LessEqualCompare ]: 'less-equal',
  53448. [ GreaterCompare ]: 'greater',
  53449. [ GreaterEqualCompare ]: 'greater-equal',
  53450. [ AlwaysCompare ]: 'always',
  53451. [ NotEqualCompare ]: 'not-equal'
  53452. };
  53453. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  53454. function writeTextureLayer( device, textureGPU, mipLevel, layerIndex, mipmap, bytesPerImage, bytesPerRow, rowsPerImage, textureWidth, textureHeight ) {
  53455. _texelCopyTextureInfo.texture = textureGPU;
  53456. _texelCopyTextureInfo.mipLevel = mipLevel;
  53457. _texelCopyTextureInfo.origin.z = layerIndex;
  53458. _texelCopyBufferLayout.offset = layerIndex * bytesPerImage;
  53459. _texelCopyBufferLayout.bytesPerRow = bytesPerRow;
  53460. _texelCopyBufferLayout.rowsPerImage = rowsPerImage;
  53461. _extent3D$1.width = textureWidth;
  53462. _extent3D$1.height = textureHeight;
  53463. device.queue.writeTexture(
  53464. _texelCopyTextureInfo,
  53465. mipmap.data,
  53466. _texelCopyBufferLayout,
  53467. _extent3D$1
  53468. );
  53469. _texelCopyTextureInfo.reset();
  53470. _texelCopyBufferLayout.reset();
  53471. _extent3D$1.reset();
  53472. }
  53473. /**
  53474. * A WebGPU backend utility module for managing textures.
  53475. *
  53476. * @private
  53477. */
  53478. class WebGPUTextureUtils {
  53479. /**
  53480. * Constructs a new utility object.
  53481. *
  53482. * @param {WebGPUBackend} backend - The WebGPU backend.
  53483. */
  53484. constructor( backend ) {
  53485. /**
  53486. * A reference to the WebGPU backend.
  53487. *
  53488. * @type {WebGPUBackend}
  53489. */
  53490. this.backend = backend;
  53491. /**
  53492. * A reference to the pass utils.
  53493. *
  53494. * @type {?WebGPUTexturePassUtils}
  53495. * @default null
  53496. */
  53497. this._passUtils = null;
  53498. /**
  53499. * A dictionary for managing default textures. The key
  53500. * is the texture format, the value the texture object.
  53501. *
  53502. * @type {Object<string,Texture>}
  53503. */
  53504. this.defaultTexture = {};
  53505. /**
  53506. * A dictionary for managing default cube textures. The key
  53507. * is the texture format, the value the texture object.
  53508. *
  53509. * @type {Object<string,CubeTexture>}
  53510. */
  53511. this.defaultCubeTexture = {};
  53512. /**
  53513. * A default video frame.
  53514. *
  53515. * @type {?VideoFrame}
  53516. * @default null
  53517. */
  53518. this.defaultVideoFrame = null;
  53519. /**
  53520. * A cache of shared texture samplers.
  53521. *
  53522. * @type {Map<string, Object>}
  53523. */
  53524. this._samplerCache = new Map();
  53525. }
  53526. /**
  53527. * Creates a GPU sampler for the given texture.
  53528. *
  53529. * @param {Texture} texture - The texture to create the sampler for.
  53530. * @param {TextureNode} textureNode - The texture node to update the sampler with.
  53531. * @return {string} The current sampler key.
  53532. */
  53533. updateSampler( texture, textureNode ) {
  53534. const backend = this.backend;
  53535. const samplerKey = texture.minFilter + '-' + texture.magFilter + '-' +
  53536. texture.wrapS + '-' + texture.wrapT + '-' + ( texture.wrapR || '0' ) + '-' +
  53537. texture.anisotropy + '-' + ( texture.isDepthTexture === true ? 1 : 0 ) + '-' +
  53538. ( texture.compareFunction !== null && textureNode.compareNode !== null ? texture.compareFunction : 0 );
  53539. let samplerData = this._samplerCache.get( samplerKey );
  53540. if ( samplerData === undefined ) {
  53541. _samplerDescriptor.addressModeU = this._convertAddressMode( texture.wrapS );
  53542. _samplerDescriptor.addressModeV = this._convertAddressMode( texture.wrapT );
  53543. _samplerDescriptor.addressModeW = this._convertAddressMode( texture.wrapR );
  53544. _samplerDescriptor.magFilter = this._convertFilterMode( texture.magFilter );
  53545. _samplerDescriptor.minFilter = this._convertFilterMode( texture.minFilter );
  53546. _samplerDescriptor.mipmapFilter = this._convertMipmapFilterMode( texture.minFilter );
  53547. // Depth textures without compare function must use non-filtering (nearest) sampling
  53548. if ( texture.isDepthTexture && ( texture.compareFunction === null || textureNode.compareNode === null ) ) {
  53549. _samplerDescriptor.magFilter = GPUFilterMode.Nearest;
  53550. _samplerDescriptor.minFilter = GPUFilterMode.Nearest;
  53551. _samplerDescriptor.mipmapFilter = GPUFilterMode.Nearest;
  53552. }
  53553. // anisotropy can only be used when all filter modes are set to linear.
  53554. if ( _samplerDescriptor.magFilter === GPUFilterMode.Linear && _samplerDescriptor.minFilter === GPUFilterMode.Linear && _samplerDescriptor.mipmapFilter === GPUFilterMode.Linear ) {
  53555. _samplerDescriptor.maxAnisotropy = texture.anisotropy;
  53556. }
  53557. if ( texture.isDepthTexture && texture.compareFunction !== null && textureNode.compareNode !== null && backend.hasCompatibility( Compatibility.TEXTURE_COMPARE ) ) {
  53558. _samplerDescriptor.compare = _compareToWebGPU[ texture.compareFunction ];
  53559. }
  53560. const sampler = backend.device.createSampler( _samplerDescriptor );
  53561. _samplerDescriptor.reset();
  53562. samplerData = { sampler, usedTimes: 0 };
  53563. this._samplerCache.set( samplerKey, samplerData );
  53564. }
  53565. const textureData = backend.get( texture );
  53566. if ( textureData.sampler !== samplerData.sampler ) {
  53567. // check if previous sampler is unused so it can be deleted
  53568. if ( textureData.sampler !== undefined ) {
  53569. const oldSamplerData = this._samplerCache.get( textureData.samplerKey );
  53570. oldSamplerData.usedTimes --;
  53571. if ( oldSamplerData.usedTimes === 0 ) {
  53572. this._samplerCache.delete( textureData.samplerKey );
  53573. }
  53574. }
  53575. // update to new sampler data
  53576. textureData.samplerKey = samplerKey;
  53577. textureData.sampler = samplerData.sampler;
  53578. samplerData.usedTimes ++;
  53579. }
  53580. return samplerKey;
  53581. }
  53582. /**
  53583. * Creates a default texture for the given texture that can be used
  53584. * as a placeholder until the actual texture is ready for usage.
  53585. *
  53586. * @param {Texture} texture - The texture to create a default texture for.
  53587. */
  53588. createDefaultTexture( texture ) {
  53589. let textureGPU;
  53590. const format = getFormat( texture, this.backend.device );
  53591. if ( texture.isCubeTexture ) {
  53592. textureGPU = this._getDefaultCubeTextureGPU( format );
  53593. } else {
  53594. textureGPU = this._getDefaultTextureGPU( format );
  53595. }
  53596. this.backend.get( texture ).texture = textureGPU;
  53597. }
  53598. /**
  53599. * Defines a texture on the GPU for the given texture object.
  53600. *
  53601. * @param {Texture} texture - The texture.
  53602. * @param {Object} [options={}] - Optional configuration parameter.
  53603. */
  53604. createTexture( texture, options = {} ) {
  53605. const backend = this.backend;
  53606. const textureData = backend.get( texture );
  53607. if ( textureData.initialized ) {
  53608. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  53609. }
  53610. if ( texture.isExternalTexture ) {
  53611. textureData.texture = texture.sourceTexture;
  53612. textureData.initialized = true;
  53613. return;
  53614. }
  53615. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  53616. if ( options.levels === undefined ) options.levels = 1;
  53617. if ( options.depth === undefined ) options.depth = 1;
  53618. const { width, height, depth, levels } = options;
  53619. if ( texture.isFramebufferTexture ) {
  53620. if ( options.renderTarget ) {
  53621. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  53622. } else {
  53623. options.format = this.backend.utils.getPreferredCanvasFormat();
  53624. }
  53625. }
  53626. const dimension = this._getDimension( texture );
  53627. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  53628. textureData.format = format;
  53629. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  53630. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  53631. if ( texture.isStorageTexture === true ) {
  53632. usage |= GPUTextureUsage.STORAGE_BINDING;
  53633. }
  53634. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true && format !== GPUTextureFormat.RGB9E5UFloat ) {
  53635. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  53636. }
  53637. const textureDescriptorGPU = new GPUTextureDescriptor();
  53638. textureDescriptorGPU.label = texture.name;
  53639. textureDescriptorGPU.size.width = width;
  53640. textureDescriptorGPU.size.height = height;
  53641. textureDescriptorGPU.size.depthOrArrayLayers = depth;
  53642. textureDescriptorGPU.mipLevelCount = levels;
  53643. textureDescriptorGPU.sampleCount = primarySamples;
  53644. textureDescriptorGPU.dimension = dimension;
  53645. textureDescriptorGPU.format = format;
  53646. textureDescriptorGPU.usage = usage;
  53647. // texture creation
  53648. if ( format === undefined ) {
  53649. warn( 'WebGPURenderer: Texture format not supported.' );
  53650. this.createDefaultTexture( texture );
  53651. return;
  53652. }
  53653. if ( texture.isCubeTexture ) {
  53654. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  53655. }
  53656. try {
  53657. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  53658. } catch ( e ) {
  53659. warn( 'WebGPURenderer: Failed to create texture with descriptor:', textureDescriptorGPU );
  53660. this.createDefaultTexture( texture );
  53661. return;
  53662. }
  53663. if ( isMSAA ) {
  53664. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  53665. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  53666. msaaTextureDescriptorGPU.sampleCount = samples;
  53667. msaaTextureDescriptorGPU.mipLevelCount = 1; // See https://www.w3.org/TR/webgpu/#texture-creation
  53668. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  53669. }
  53670. textureData.initialized = true;
  53671. textureData.textureDescriptorGPU = textureDescriptorGPU;
  53672. }
  53673. /**
  53674. * Destroys the GPU data for the given texture object.
  53675. *
  53676. * @param {Texture} texture - The texture.
  53677. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  53678. */
  53679. destroyTexture( texture, isDefaultTexture = false ) {
  53680. const backend = this.backend;
  53681. const textureData = backend.get( texture );
  53682. if ( textureData.texture !== undefined && isDefaultTexture === false ) textureData.texture.destroy();
  53683. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  53684. backend.delete( texture );
  53685. }
  53686. /**
  53687. * Generates mipmaps for the given texture.
  53688. *
  53689. * @param {Texture} texture - The texture.
  53690. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  53691. */
  53692. generateMipmaps( texture, encoder = null ) {
  53693. const textureData = this.backend.get( texture );
  53694. this._generateMipmaps( textureData.texture, encoder );
  53695. }
  53696. /**
  53697. * Returns the color buffer representing the color
  53698. * attachment of the default framebuffer.
  53699. *
  53700. * @return {GPUTexture} The color buffer.
  53701. */
  53702. getColorBuffer() {
  53703. const backend = this.backend;
  53704. const canvasTarget = backend.renderer.getCanvasTarget();
  53705. const { width, height } = backend.getDrawingBufferSize();
  53706. const samples = backend.renderer.currentSamples;
  53707. const colorTexture = canvasTarget.colorTexture;
  53708. const colorTextureData = backend.get( colorTexture );
  53709. if ( colorTexture.width === width && colorTexture.height === height && colorTexture.samples === samples ) {
  53710. return colorTextureData.texture;
  53711. }
  53712. // recreate
  53713. let colorBuffer = colorTextureData.texture;
  53714. if ( colorBuffer ) colorBuffer.destroy();
  53715. _textureDescriptor.label = 'colorBuffer';
  53716. _textureDescriptor.size.width = width;
  53717. _textureDescriptor.size.height = height;
  53718. _textureDescriptor.sampleCount = backend.utils.getSampleCount( backend.renderer.currentSamples );
  53719. _textureDescriptor.format = backend.utils.getPreferredCanvasFormat();
  53720. _textureDescriptor.usage = GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC;
  53721. colorBuffer = backend.device.createTexture( _textureDescriptor );
  53722. _textureDescriptor.reset();
  53723. //
  53724. colorTexture.source.width = width;
  53725. colorTexture.source.height = height;
  53726. colorTexture.samples = samples;
  53727. colorTextureData.texture = colorBuffer;
  53728. return colorBuffer;
  53729. }
  53730. /**
  53731. * Returns the depth buffer representing the depth
  53732. * attachment of the default framebuffer.
  53733. *
  53734. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  53735. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  53736. * @return {GPUTexture} The depth buffer.
  53737. */
  53738. getDepthBuffer( depth = true, stencil = false ) {
  53739. const backend = this.backend;
  53740. const canvasTarget = backend.renderer.getCanvasTarget();
  53741. const { width, height } = backend.getDrawingBufferSize();
  53742. const samples = backend.renderer.currentSamples;
  53743. const depthTexture = canvasTarget.depthTexture;
  53744. if ( depthTexture.width === width &&
  53745. depthTexture.height === height &&
  53746. depthTexture.samples === samples &&
  53747. depthTexture.depth === depth &&
  53748. depthTexture.stencil === stencil ) {
  53749. return backend.get( depthTexture ).texture;
  53750. }
  53751. //
  53752. const depthTextureGPU = backend.get( depthTexture ).texture;
  53753. let format, type;
  53754. if ( stencil ) {
  53755. format = DepthStencilFormat;
  53756. type = backend.renderer.reversedDepthBuffer === true ? FloatType : UnsignedInt248Type;
  53757. } else if ( depth ) {
  53758. format = DepthFormat;
  53759. type = backend.renderer.reversedDepthBuffer === true ? FloatType : UnsignedIntType;
  53760. }
  53761. if ( depthTextureGPU !== undefined ) {
  53762. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type && depthTexture.samples === samples ) {
  53763. return depthTextureGPU;
  53764. }
  53765. this.destroyTexture( depthTexture );
  53766. }
  53767. // recreate
  53768. depthTexture.name = 'depthBuffer';
  53769. depthTexture.format = format;
  53770. depthTexture.type = type;
  53771. depthTexture.image.width = width;
  53772. depthTexture.image.height = height;
  53773. depthTexture.samples = samples;
  53774. this.createTexture( depthTexture, { width, height } );
  53775. return backend.get( depthTexture ).texture;
  53776. }
  53777. /**
  53778. * Uploads the updated texture data to the GPU.
  53779. *
  53780. * @param {Texture} texture - The texture.
  53781. * @param {Object} [options={}] - Optional configuration parameter.
  53782. */
  53783. updateTexture( texture, options ) {
  53784. const textureData = this.backend.get( texture );
  53785. const mipmaps = texture.mipmaps;
  53786. const { textureDescriptorGPU } = textureData;
  53787. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  53788. return;
  53789. // transfer texture data
  53790. if ( texture.isDataTexture ) {
  53791. if ( mipmaps.length > 0 ) {
  53792. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  53793. const mipmap = mipmaps[ i ];
  53794. this._copyBufferToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, 0, i );
  53795. }
  53796. } else {
  53797. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  53798. }
  53799. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  53800. if ( texture.layerUpdates && texture.layerUpdates.size > 0 ) {
  53801. for ( const layerIndex of texture.layerUpdates ) {
  53802. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, layerIndex, texture.flipY, layerIndex );
  53803. }
  53804. texture.clearLayerUpdates();
  53805. } else {
  53806. for ( let i = 0; i < options.image.depth; i ++ ) {
  53807. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  53808. }
  53809. }
  53810. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  53811. if ( texture.isCompressedArrayTexture && texture.layerUpdates.size > 0 ) {
  53812. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU, texture.layerUpdates );
  53813. texture.clearLayerUpdates();
  53814. } else {
  53815. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  53816. }
  53817. } else if ( texture.isCubeTexture ) {
  53818. this._copyCubeMapToTexture( texture, textureData.texture, textureDescriptorGPU );
  53819. } else if ( texture.isHTMLTexture ) {
  53820. const device = this.backend.device;
  53821. const canvas = this.backend.renderer.domElement;
  53822. const image = texture.image;
  53823. if ( typeof device.queue.copyElementImageToTexture !== 'function' ) return;
  53824. // Skip the first frame — the element needs a paint record first.
  53825. if ( ! textureData.hasPaintCallback ) {
  53826. textureData.hasPaintCallback = true;
  53827. canvas.requestPaint();
  53828. return;
  53829. }
  53830. const width = textureDescriptorGPU.size.width;
  53831. const height = textureDescriptorGPU.size.height;
  53832. device.queue.copyElementImageToTexture(
  53833. image, width, height,
  53834. { texture: textureData.texture }
  53835. );
  53836. if ( texture.flipY ) {
  53837. this._flipY( textureData.texture, textureDescriptorGPU );
  53838. }
  53839. } else {
  53840. if ( mipmaps.length > 0 ) {
  53841. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  53842. const mipmap = mipmaps[ i ];
  53843. this._copyImageToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha, i );
  53844. }
  53845. } else {
  53846. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  53847. }
  53848. }
  53849. //
  53850. textureData.version = texture.version;
  53851. }
  53852. /**
  53853. * Returns texture data as a typed array.
  53854. *
  53855. * @async
  53856. * @param {Texture} texture - The texture to copy.
  53857. * @param {number} x - The x coordinate of the copy origin.
  53858. * @param {number} y - The y coordinate of the copy origin.
  53859. * @param {number} width - The width of the copy.
  53860. * @param {number} height - The height of the copy.
  53861. * @param {number} faceIndex - The face index.
  53862. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  53863. */
  53864. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  53865. const device = this.backend.device;
  53866. const textureData = this.backend.get( texture );
  53867. const textureGPU = textureData.texture;
  53868. const format = textureData.textureDescriptorGPU.format;
  53869. const bytesPerTexel = this._getBytesPerTexel( format );
  53870. let bytesPerRow = width * bytesPerTexel;
  53871. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  53872. _bufferDescriptor$4.size = ( ( height - 1 ) * bytesPerRow ) + ( width * bytesPerTexel ); // see https://github.com/mrdoob/three.js/issues/31658#issuecomment-3229442010
  53873. _bufferDescriptor$4.usage = GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ;
  53874. const readBuffer = device.createBuffer( _bufferDescriptor$4 );
  53875. _bufferDescriptor$4.reset();
  53876. const encoder = device.createCommandEncoder( _commandEncoderDescriptor$3 );
  53877. _texelCopyTextureInfo.texture = textureGPU;
  53878. _texelCopyTextureInfo.origin.x = x;
  53879. _texelCopyTextureInfo.origin.y = y;
  53880. _texelCopyTextureInfo.origin.z = faceIndex;
  53881. _texelCopyBufferInfo.buffer = readBuffer;
  53882. _texelCopyBufferInfo.bytesPerRow = bytesPerRow;
  53883. _extent3D$1.width = width;
  53884. _extent3D$1.height = height;
  53885. encoder.copyTextureToBuffer(
  53886. _texelCopyTextureInfo,
  53887. _texelCopyBufferInfo,
  53888. _extent3D$1
  53889. );
  53890. _texelCopyTextureInfo.reset();
  53891. _texelCopyBufferInfo.reset();
  53892. _extent3D$1.reset();
  53893. const typedArrayType = this._getTypedArrayType( format );
  53894. submit( device, encoder.finish() );
  53895. await readBuffer.mapAsync( GPUMapMode.READ );
  53896. const buffer = readBuffer.getMappedRange().slice();
  53897. readBuffer.destroy();
  53898. return new typedArrayType( buffer );
  53899. }
  53900. /**
  53901. * Frees all internal resources.
  53902. */
  53903. dispose() {
  53904. this._samplerCache.clear();
  53905. }
  53906. /**
  53907. * Returns the default GPU texture for the given format.
  53908. *
  53909. * @private
  53910. * @param {string} format - The GPU format.
  53911. * @return {GPUTexture} The GPU texture.
  53912. */
  53913. _getDefaultTextureGPU( format ) {
  53914. let defaultTexture = this.defaultTexture[ format ];
  53915. if ( defaultTexture === undefined ) {
  53916. const texture = new Texture();
  53917. texture.minFilter = NearestFilter;
  53918. texture.magFilter = NearestFilter;
  53919. this.createTexture( texture, { width: 1, height: 1, format } );
  53920. this.defaultTexture[ format ] = defaultTexture = texture;
  53921. }
  53922. return this.backend.get( defaultTexture ).texture;
  53923. }
  53924. /**
  53925. * Returns the default GPU cube texture for the given format.
  53926. *
  53927. * @private
  53928. * @param {string} format - The GPU format.
  53929. * @return {GPUTexture} The GPU texture.
  53930. */
  53931. _getDefaultCubeTextureGPU( format ) {
  53932. let defaultCubeTexture = this.defaultCubeTexture[ format ];
  53933. if ( defaultCubeTexture === undefined ) {
  53934. const texture = new CubeTexture();
  53935. texture.minFilter = NearestFilter;
  53936. texture.magFilter = NearestFilter;
  53937. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  53938. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  53939. }
  53940. return this.backend.get( defaultCubeTexture ).texture;
  53941. }
  53942. /**
  53943. * Uploads cube texture image data to the GPU memory.
  53944. *
  53945. * @private
  53946. * @param {CubeTexture} texture - The cube texture.
  53947. * @param {GPUTexture} textureGPU - The GPU texture.
  53948. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  53949. */
  53950. _copyCubeMapToTexture( texture, textureGPU, textureDescriptorGPU ) {
  53951. const images = texture.images;
  53952. const mipmaps = texture.mipmaps;
  53953. for ( let i = 0; i < 6; i ++ ) {
  53954. const image = images[ i ];
  53955. const flipIndex = texture.flipY === true ? _flipMap[ i ] : i;
  53956. if ( image.isDataTexture ) {
  53957. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY );
  53958. } else {
  53959. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha );
  53960. }
  53961. for ( let j = 0; j < mipmaps.length; j ++ ) {
  53962. const mipmap = mipmaps[ j ];
  53963. const image = mipmap.images[ i ];
  53964. if ( image.isDataTexture ) {
  53965. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, 0, j + 1 );
  53966. } else {
  53967. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha, j + 1 );
  53968. }
  53969. }
  53970. }
  53971. }
  53972. /**
  53973. * Uploads texture image data to the GPU memory.
  53974. *
  53975. * @private
  53976. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  53977. * @param {GPUTexture} textureGPU - The GPU texture.
  53978. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  53979. * @param {number} originDepth - The origin depth.
  53980. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  53981. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  53982. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  53983. */
  53984. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha, mipLevel = 0 ) {
  53985. const device = this.backend.device;
  53986. const width = ( mipLevel > 0 ) ? image.width : textureDescriptorGPU.size.width;
  53987. const height = ( mipLevel > 0 ) ? image.height : textureDescriptorGPU.size.height;
  53988. _copyExternalImageSourceInfo.source = image;
  53989. _copyExternalImageSourceInfo.flipY = flipY;
  53990. _copyExternalImageDestInfo.texture = textureGPU;
  53991. _copyExternalImageDestInfo.mipLevel = mipLevel;
  53992. _copyExternalImageDestInfo.origin.z = originDepth;
  53993. _copyExternalImageDestInfo.premultipliedAlpha = premultiplyAlpha;
  53994. _extent3D$1.width = width;
  53995. _extent3D$1.height = height;
  53996. try {
  53997. device.queue.copyExternalImageToTexture(
  53998. _copyExternalImageSourceInfo,
  53999. _copyExternalImageDestInfo,
  54000. _extent3D$1
  54001. );
  54002. // try/catch has been added to fix bad video frame data on certain devices, see #32391
  54003. } catch ( _ ) {
  54004. } finally {
  54005. _copyExternalImageSourceInfo.reset();
  54006. _copyExternalImageDestInfo.reset();
  54007. _extent3D$1.reset();
  54008. }
  54009. }
  54010. /**
  54011. * Returns the pass utils singleton.
  54012. *
  54013. * @private
  54014. * @return {WebGPUTexturePassUtils} The utils instance.
  54015. */
  54016. _getPassUtils() {
  54017. let passUtils = this._passUtils;
  54018. if ( passUtils === null ) {
  54019. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  54020. }
  54021. return passUtils;
  54022. }
  54023. /**
  54024. * Generates mipmaps for the given GPU texture.
  54025. *
  54026. * @private
  54027. * @param {GPUTexture} textureGPU - The GPU texture object.
  54028. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  54029. */
  54030. _generateMipmaps( textureGPU, encoder = null ) {
  54031. this._getPassUtils().generateMipmaps( textureGPU, encoder );
  54032. }
  54033. /**
  54034. * Flip the contents of the given GPU texture along its vertical axis.
  54035. *
  54036. * @private
  54037. * @param {GPUTexture} textureGPU - The GPU texture object.
  54038. * @param {Object} textureDescriptorGPU - The texture descriptor.
  54039. * @param {number} [originDepth=0] - The origin depth.
  54040. */
  54041. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  54042. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  54043. }
  54044. /**
  54045. * Uploads texture buffer data to the GPU memory.
  54046. *
  54047. * @private
  54048. * @param {Object} image - An object defining the image buffer data.
  54049. * @param {GPUTexture} textureGPU - The GPU texture.
  54050. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  54051. * @param {number} originDepth - The origin depth.
  54052. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  54053. * @param {number} [depth=0] - The depth offset when copying array or 3D texture data.
  54054. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  54055. */
  54056. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0, mipLevel = 0 ) {
  54057. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  54058. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  54059. const device = this.backend.device;
  54060. const data = image.data;
  54061. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  54062. const bytesPerRow = image.width * bytesPerTexel;
  54063. _texelCopyTextureInfo.texture = textureGPU;
  54064. _texelCopyTextureInfo.mipLevel = mipLevel;
  54065. _texelCopyTextureInfo.origin.z = originDepth;
  54066. _texelCopyBufferLayout.offset = image.width * image.height * bytesPerTexel * depth;
  54067. _texelCopyBufferLayout.bytesPerRow = bytesPerRow;
  54068. _extent3D$1.width = image.width;
  54069. _extent3D$1.height = image.height;
  54070. device.queue.writeTexture(
  54071. _texelCopyTextureInfo,
  54072. data,
  54073. _texelCopyBufferLayout,
  54074. _extent3D$1
  54075. );
  54076. _texelCopyTextureInfo.reset();
  54077. _texelCopyBufferLayout.reset();
  54078. _extent3D$1.reset();
  54079. if ( flipY === true ) {
  54080. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  54081. }
  54082. }
  54083. /**
  54084. * Uploads compressed texture data to the GPU memory.
  54085. *
  54086. * @private
  54087. * @param {Array<Object>} mipmaps - An array with mipmap data.
  54088. * @param {GPUTexture} textureGPU - The GPU texture.
  54089. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  54090. * @param {?Set<number>} [layerUpdates=null] - The layer indices to update.
  54091. */
  54092. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU, layerUpdates = null ) {
  54093. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  54094. const device = this.backend.device;
  54095. const blockData = this._getBlockData( textureDescriptorGPU.format );
  54096. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  54097. const activeLayerUpdates = layerUpdates && layerUpdates.size > 0 ? layerUpdates : null;
  54098. for ( let i = 0; i < mipmaps.length; i ++ ) {
  54099. const mipmap = mipmaps[ i ];
  54100. const width = mipmap.width;
  54101. const height = mipmap.height;
  54102. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  54103. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  54104. const rowsPerImage = Math.ceil( height / blockData.height );
  54105. const bytesPerImage = bytesPerRow * rowsPerImage;
  54106. const textureWidth = Math.ceil( width / blockData.width ) * blockData.width;
  54107. const textureHeight = rowsPerImage * blockData.height;
  54108. if ( activeLayerUpdates !== null ) {
  54109. for ( const layerIndex of activeLayerUpdates ) {
  54110. writeTextureLayer( device, textureGPU, i, layerIndex, mipmap, bytesPerImage, bytesPerRow, rowsPerImage, textureWidth, textureHeight );
  54111. }
  54112. } else {
  54113. for ( let layerIndex = 0; layerIndex < depth; layerIndex ++ ) {
  54114. writeTextureLayer( device, textureGPU, i, layerIndex, mipmap, bytesPerImage, bytesPerRow, rowsPerImage, textureWidth, textureHeight );
  54115. }
  54116. }
  54117. }
  54118. }
  54119. /**
  54120. * This method is only relevant for compressed texture formats. It returns a block
  54121. * data descriptor for the given GPU compressed texture format.
  54122. *
  54123. * @private
  54124. * @param {string} format - The GPU compressed texture format.
  54125. * @return {Object} The block data descriptor.
  54126. */
  54127. _getBlockData( format ) {
  54128. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  54129. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  54130. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  54131. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  54132. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  54133. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  54134. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  54135. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  54136. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  54137. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  54138. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  54139. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  54140. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  54141. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  54142. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  54143. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  54144. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  54145. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  54146. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  54147. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  54148. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  54149. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  54150. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  54151. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  54152. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  54153. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  54154. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  54155. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  54156. }
  54157. /**
  54158. * Converts the three.js uv wrapping constants to GPU address mode constants.
  54159. *
  54160. * @private
  54161. * @param {number} value - The three.js constant defining a uv wrapping mode.
  54162. * @return {string} The GPU address mode.
  54163. */
  54164. _convertAddressMode( value ) {
  54165. let addressMode = GPUAddressMode.ClampToEdge;
  54166. if ( value === RepeatWrapping ) {
  54167. addressMode = GPUAddressMode.Repeat;
  54168. } else if ( value === MirroredRepeatWrapping ) {
  54169. addressMode = GPUAddressMode.MirrorRepeat;
  54170. }
  54171. return addressMode;
  54172. }
  54173. /**
  54174. * Converts the three.js filter constants to GPU filter constants.
  54175. *
  54176. * @private
  54177. * @param {number} value - The three.js constant defining a filter mode.
  54178. * @return {string} The GPU filter mode.
  54179. */
  54180. _convertFilterMode( value ) {
  54181. let filterMode = GPUFilterMode.Linear;
  54182. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  54183. filterMode = GPUFilterMode.Nearest;
  54184. }
  54185. return filterMode;
  54186. }
  54187. /**
  54188. * Converts the three.js filter constants to a GPU mipmap filter constant.
  54189. * Unlike `_convertFilterMode`, this extracts the between-mip-level filtering
  54190. * axis from the combined three.js constant rather than the within-level axis.
  54191. *
  54192. * @private
  54193. * @param {number} value - The three.js constant defining a filter mode.
  54194. * @return {string} The GPU mipmap filter mode.
  54195. */
  54196. _convertMipmapFilterMode( value ) {
  54197. if ( value === NearestMipmapLinearFilter || value === LinearMipmapLinearFilter ) {
  54198. return GPUFilterMode.Linear;
  54199. }
  54200. return GPUFilterMode.Nearest;
  54201. }
  54202. /**
  54203. * Returns the bytes-per-texel value for the given GPU texture format.
  54204. *
  54205. * @private
  54206. * @param {string} format - The GPU texture format.
  54207. * @return {number} The bytes-per-texel.
  54208. */
  54209. _getBytesPerTexel( format ) {
  54210. // 8-bit formats
  54211. if ( format === GPUTextureFormat.R8Unorm ||
  54212. format === GPUTextureFormat.R8Snorm ||
  54213. format === GPUTextureFormat.R8Uint ||
  54214. format === GPUTextureFormat.R8Sint ) return 1;
  54215. // 16-bit formats
  54216. if ( format === GPUTextureFormat.R16Uint ||
  54217. format === GPUTextureFormat.R16Sint ||
  54218. format === GPUTextureFormat.R16Float ||
  54219. format === GPUTextureFormat.RG8Unorm ||
  54220. format === GPUTextureFormat.RG8Snorm ||
  54221. format === GPUTextureFormat.RG8Uint ||
  54222. format === GPUTextureFormat.RG8Sint ||
  54223. format === GPUTextureFormat.R16Unorm ||
  54224. format === GPUTextureFormat.R16Snorm ) return 2;
  54225. // 32-bit formats
  54226. if ( format === GPUTextureFormat.R32Uint ||
  54227. format === GPUTextureFormat.R32Sint ||
  54228. format === GPUTextureFormat.R32Float ||
  54229. format === GPUTextureFormat.RG16Uint ||
  54230. format === GPUTextureFormat.RG16Sint ||
  54231. format === GPUTextureFormat.RG16Float ||
  54232. format === GPUTextureFormat.RGBA8Unorm ||
  54233. format === GPUTextureFormat.RGBA8UnormSRGB ||
  54234. format === GPUTextureFormat.RGBA8Snorm ||
  54235. format === GPUTextureFormat.RGBA8Uint ||
  54236. format === GPUTextureFormat.RGBA8Sint ||
  54237. format === GPUTextureFormat.BGRA8Unorm ||
  54238. format === GPUTextureFormat.BGRA8UnormSRGB ||
  54239. format === GPUTextureFormat.RG16Unorm ||
  54240. format === GPUTextureFormat.RG16Snorm ||
  54241. // Packed 32-bit formats
  54242. format === GPUTextureFormat.RGB9E5UFloat ||
  54243. format === GPUTextureFormat.RGB10A2Unorm ||
  54244. format === GPUTextureFormat.RG11B10UFloat ||
  54245. format === GPUTextureFormat.Depth32Float ||
  54246. format === GPUTextureFormat.Depth24Plus ||
  54247. format === GPUTextureFormat.Depth24PlusStencil8 ||
  54248. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  54249. // 64-bit formats
  54250. if ( format === GPUTextureFormat.RG32Uint ||
  54251. format === GPUTextureFormat.RG32Sint ||
  54252. format === GPUTextureFormat.RG32Float ||
  54253. format === GPUTextureFormat.RGBA16Uint ||
  54254. format === GPUTextureFormat.RGBA16Sint ||
  54255. format === GPUTextureFormat.RGBA16Float ||
  54256. format === GPUTextureFormat.RGBA16Unorm ||
  54257. format === GPUTextureFormat.RGBA16Snorm ) return 8;
  54258. // 128-bit formats
  54259. if ( format === GPUTextureFormat.RGBA32Uint ||
  54260. format === GPUTextureFormat.RGBA32Sint ||
  54261. format === GPUTextureFormat.RGBA32Float ) return 16;
  54262. }
  54263. /**
  54264. * Returns the corresponding typed array type for the given GPU texture format.
  54265. *
  54266. * @private
  54267. * @param {string} format - The GPU texture format.
  54268. * @return {TypedArray.constructor} The typed array type.
  54269. */
  54270. _getTypedArrayType( format ) {
  54271. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  54272. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  54273. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  54274. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  54275. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  54276. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  54277. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  54278. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  54279. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  54280. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  54281. if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return Uint8Array;
  54282. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  54283. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  54284. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  54285. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  54286. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  54287. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  54288. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  54289. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  54290. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  54291. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  54292. if ( format === GPUTextureFormat.R16Unorm ) return Uint16Array;
  54293. if ( format === GPUTextureFormat.R16Snorm ) return Int16Array;
  54294. if ( format === GPUTextureFormat.RG16Unorm ) return Uint16Array;
  54295. if ( format === GPUTextureFormat.RG16Snorm ) return Int16Array;
  54296. if ( format === GPUTextureFormat.RGBA16Unorm ) return Uint16Array;
  54297. if ( format === GPUTextureFormat.RGBA16Snorm ) return Int16Array;
  54298. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  54299. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  54300. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  54301. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  54302. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  54303. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  54304. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  54305. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  54306. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  54307. if ( format === GPUTextureFormat.BGRA8Unorm || format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  54308. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  54309. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  54310. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  54311. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  54312. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  54313. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  54314. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  54315. }
  54316. /**
  54317. * Returns the GPU dimensions for the given texture.
  54318. *
  54319. * @private
  54320. * @param {Texture} texture - The texture.
  54321. * @return {string} The GPU dimension.
  54322. */
  54323. _getDimension( texture ) {
  54324. let dimension;
  54325. if ( texture.is3DTexture || texture.isData3DTexture ) {
  54326. dimension = GPUTextureDimension.ThreeD;
  54327. } else {
  54328. dimension = GPUTextureDimension.TwoD;
  54329. }
  54330. return dimension;
  54331. }
  54332. }
  54333. /**
  54334. * Returns the GPU format for the given texture.
  54335. *
  54336. * @param {Texture} texture - The texture.
  54337. * @param {GPUDevice} [device] - The GPU device which is used for feature detection.
  54338. * @return {string} The GPU format.
  54339. */
  54340. function getFormat( texture, device ) {
  54341. const format = texture.format;
  54342. const type = texture.type;
  54343. const normalized = texture.normalized;
  54344. const colorSpace = texture.colorSpace;
  54345. const transfer = ColorManagement.getTransfer( colorSpace );
  54346. let formatGPU;
  54347. let textureFormatsTier1 = false;
  54348. if ( normalized ) {
  54349. textureFormatsTier1 = device.features.has( GPUFeatureName.TextureFormatsTier1 );
  54350. if ( textureFormatsTier1 === false ) {
  54351. warn( 'WebGPURenderer: Unable to use normalized textures without texture-formats-tier1 feature.' );
  54352. }
  54353. }
  54354. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  54355. switch ( format ) {
  54356. case RGB_S3TC_DXT1_Format:
  54357. case RGBA_S3TC_DXT1_Format:
  54358. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  54359. break;
  54360. case RGBA_S3TC_DXT3_Format:
  54361. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  54362. break;
  54363. case RGBA_S3TC_DXT5_Format:
  54364. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  54365. break;
  54366. case RED_RGTC1_Format:
  54367. formatGPU = GPUTextureFormat.BC4RUnorm;
  54368. break;
  54369. case SIGNED_RED_RGTC1_Format:
  54370. formatGPU = GPUTextureFormat.BC4RSnorm;
  54371. break;
  54372. case RED_GREEN_RGTC2_Format:
  54373. formatGPU = GPUTextureFormat.BC5RGUnorm;
  54374. break;
  54375. case SIGNED_RED_GREEN_RGTC2_Format:
  54376. formatGPU = GPUTextureFormat.BC5RGSnorm;
  54377. break;
  54378. case RGBA_BPTC_Format:
  54379. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC7RGBAUnormSRGB : GPUTextureFormat.BC7RGBAUnorm;
  54380. break;
  54381. case RGB_BPTC_SIGNED_Format:
  54382. formatGPU = GPUTextureFormat.BC6HRGBFloat;
  54383. break;
  54384. case RGB_BPTC_UNSIGNED_Format:
  54385. formatGPU = GPUTextureFormat.BC6HRGBUFloat;
  54386. break;
  54387. case RGB_ETC2_Format:
  54388. case RGB_ETC1_Format:
  54389. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  54390. break;
  54391. case RGBA_ETC2_EAC_Format:
  54392. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  54393. break;
  54394. case R11_EAC_Format:
  54395. formatGPU = GPUTextureFormat.EACR11Unorm;
  54396. break;
  54397. case SIGNED_R11_EAC_Format:
  54398. formatGPU = GPUTextureFormat.EACR11Snorm;
  54399. break;
  54400. case RG11_EAC_Format:
  54401. formatGPU = GPUTextureFormat.EACRG11Unorm;
  54402. break;
  54403. case SIGNED_RG11_EAC_Format:
  54404. formatGPU = GPUTextureFormat.EACRG11Snorm;
  54405. break;
  54406. case RGBA_ASTC_4x4_Format:
  54407. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  54408. break;
  54409. case RGBA_ASTC_5x4_Format:
  54410. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  54411. break;
  54412. case RGBA_ASTC_5x5_Format:
  54413. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  54414. break;
  54415. case RGBA_ASTC_6x5_Format:
  54416. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  54417. break;
  54418. case RGBA_ASTC_6x6_Format:
  54419. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  54420. break;
  54421. case RGBA_ASTC_8x5_Format:
  54422. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  54423. break;
  54424. case RGBA_ASTC_8x6_Format:
  54425. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  54426. break;
  54427. case RGBA_ASTC_8x8_Format:
  54428. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  54429. break;
  54430. case RGBA_ASTC_10x5_Format:
  54431. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  54432. break;
  54433. case RGBA_ASTC_10x6_Format:
  54434. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  54435. break;
  54436. case RGBA_ASTC_10x8_Format:
  54437. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  54438. break;
  54439. case RGBA_ASTC_10x10_Format:
  54440. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  54441. break;
  54442. case RGBA_ASTC_12x10_Format:
  54443. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  54444. break;
  54445. case RGBA_ASTC_12x12_Format:
  54446. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  54447. break;
  54448. case RGBAFormat:
  54449. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  54450. break;
  54451. default:
  54452. error( 'WebGPURenderer: Unsupported texture format.', format );
  54453. }
  54454. } else {
  54455. switch ( format ) {
  54456. case RGBAFormat:
  54457. switch ( type ) {
  54458. case ByteType:
  54459. formatGPU = GPUTextureFormat.RGBA8Snorm;
  54460. break;
  54461. case ShortType:
  54462. formatGPU = textureFormatsTier1 ? GPUTextureFormat.RGBA16Snorm : GPUTextureFormat.RGBA16Sint;
  54463. break;
  54464. case UnsignedShortType:
  54465. formatGPU = textureFormatsTier1 ? GPUTextureFormat.RGBA16Unorm : GPUTextureFormat.RGBA16Uint;
  54466. break;
  54467. case UnsignedIntType:
  54468. formatGPU = GPUTextureFormat.RGBA32Uint;
  54469. break;
  54470. case IntType:
  54471. formatGPU = GPUTextureFormat.RGBA32Sint;
  54472. break;
  54473. case UnsignedByteType:
  54474. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  54475. break;
  54476. case HalfFloatType:
  54477. formatGPU = GPUTextureFormat.RGBA16Float;
  54478. break;
  54479. case FloatType:
  54480. formatGPU = GPUTextureFormat.RGBA32Float;
  54481. break;
  54482. default:
  54483. error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  54484. }
  54485. break;
  54486. case RGBFormat:
  54487. switch ( type ) {
  54488. case UnsignedInt5999Type:
  54489. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  54490. break;
  54491. case UnsignedInt101111Type:
  54492. formatGPU = GPUTextureFormat.RG11B10UFloat;
  54493. break;
  54494. default:
  54495. error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  54496. }
  54497. break;
  54498. case RedFormat:
  54499. switch ( type ) {
  54500. case ByteType:
  54501. formatGPU = GPUTextureFormat.R8Snorm;
  54502. break;
  54503. case ShortType:
  54504. formatGPU = textureFormatsTier1 ? GPUTextureFormat.R16Snorm : GPUTextureFormat.R16Sint;
  54505. break;
  54506. case UnsignedShortType:
  54507. formatGPU = textureFormatsTier1 ? GPUTextureFormat.R16Unorm : GPUTextureFormat.R16Uint;
  54508. break;
  54509. case UnsignedIntType:
  54510. formatGPU = GPUTextureFormat.R32Uint;
  54511. break;
  54512. case IntType:
  54513. formatGPU = GPUTextureFormat.R32Sint;
  54514. break;
  54515. case UnsignedByteType:
  54516. formatGPU = GPUTextureFormat.R8Unorm;
  54517. break;
  54518. case HalfFloatType:
  54519. formatGPU = GPUTextureFormat.R16Float;
  54520. break;
  54521. case FloatType:
  54522. formatGPU = GPUTextureFormat.R32Float;
  54523. break;
  54524. default:
  54525. error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  54526. }
  54527. break;
  54528. case RGFormat:
  54529. switch ( type ) {
  54530. case ByteType:
  54531. formatGPU = GPUTextureFormat.RG8Snorm;
  54532. break;
  54533. case ShortType:
  54534. formatGPU = textureFormatsTier1 ? GPUTextureFormat.RG16Snorm : GPUTextureFormat.RG16Sint;
  54535. break;
  54536. case UnsignedShortType:
  54537. formatGPU = textureFormatsTier1 ? GPUTextureFormat.RG16Unorm : GPUTextureFormat.RG16Uint;
  54538. break;
  54539. case UnsignedIntType:
  54540. formatGPU = GPUTextureFormat.RG32Uint;
  54541. break;
  54542. case IntType:
  54543. formatGPU = GPUTextureFormat.RG32Sint;
  54544. break;
  54545. case UnsignedByteType:
  54546. formatGPU = GPUTextureFormat.RG8Unorm;
  54547. break;
  54548. case HalfFloatType:
  54549. formatGPU = GPUTextureFormat.RG16Float;
  54550. break;
  54551. case FloatType:
  54552. formatGPU = GPUTextureFormat.RG32Float;
  54553. break;
  54554. default:
  54555. error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  54556. }
  54557. break;
  54558. case DepthFormat:
  54559. switch ( type ) {
  54560. case UnsignedShortType:
  54561. formatGPU = GPUTextureFormat.Depth16Unorm;
  54562. break;
  54563. case UnsignedIntType:
  54564. formatGPU = GPUTextureFormat.Depth24Plus;
  54565. break;
  54566. case FloatType:
  54567. formatGPU = GPUTextureFormat.Depth32Float;
  54568. break;
  54569. default:
  54570. error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  54571. }
  54572. break;
  54573. case DepthStencilFormat:
  54574. switch ( type ) {
  54575. case UnsignedInt248Type:
  54576. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  54577. break;
  54578. case FloatType:
  54579. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  54580. error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  54581. }
  54582. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  54583. break;
  54584. default:
  54585. error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  54586. }
  54587. break;
  54588. case RedIntegerFormat:
  54589. switch ( type ) {
  54590. case IntType:
  54591. formatGPU = GPUTextureFormat.R32Sint;
  54592. break;
  54593. case UnsignedIntType:
  54594. formatGPU = GPUTextureFormat.R32Uint;
  54595. break;
  54596. default:
  54597. error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  54598. }
  54599. break;
  54600. case RGIntegerFormat:
  54601. switch ( type ) {
  54602. case IntType:
  54603. formatGPU = GPUTextureFormat.RG32Sint;
  54604. break;
  54605. case UnsignedIntType:
  54606. formatGPU = GPUTextureFormat.RG32Uint;
  54607. break;
  54608. default:
  54609. error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  54610. }
  54611. break;
  54612. case RGBAIntegerFormat:
  54613. switch ( type ) {
  54614. case IntType:
  54615. formatGPU = GPUTextureFormat.RGBA32Sint;
  54616. break;
  54617. case UnsignedIntType:
  54618. formatGPU = GPUTextureFormat.RGBA32Uint;
  54619. break;
  54620. default:
  54621. error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  54622. }
  54623. break;
  54624. default:
  54625. error( 'WebGPURenderer: Unsupported texture format.', format );
  54626. }
  54627. }
  54628. return formatGPU;
  54629. }
  54630. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  54631. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  54632. const wgslTypeLib$1 = {
  54633. 'f32': 'float',
  54634. 'i32': 'int',
  54635. 'u32': 'uint',
  54636. 'bool': 'bool',
  54637. 'vec2<f32>': 'vec2',
  54638. 'vec2<i32>': 'ivec2',
  54639. 'vec2<u32>': 'uvec2',
  54640. 'vec2<bool>': 'bvec2',
  54641. 'vec2f': 'vec2',
  54642. 'vec2i': 'ivec2',
  54643. 'vec2u': 'uvec2',
  54644. 'vec2b': 'bvec2',
  54645. 'vec3<f32>': 'vec3',
  54646. 'vec3<i32>': 'ivec3',
  54647. 'vec3<u32>': 'uvec3',
  54648. 'vec3<bool>': 'bvec3',
  54649. 'vec3f': 'vec3',
  54650. 'vec3i': 'ivec3',
  54651. 'vec3u': 'uvec3',
  54652. 'vec3b': 'bvec3',
  54653. 'vec4<f32>': 'vec4',
  54654. 'vec4<i32>': 'ivec4',
  54655. 'vec4<u32>': 'uvec4',
  54656. 'vec4<bool>': 'bvec4',
  54657. 'vec4f': 'vec4',
  54658. 'vec4i': 'ivec4',
  54659. 'vec4u': 'uvec4',
  54660. 'vec4b': 'bvec4',
  54661. 'mat2x2<f32>': 'mat2',
  54662. 'mat2x2f': 'mat2',
  54663. 'mat3x3<f32>': 'mat3',
  54664. 'mat3x3f': 'mat3',
  54665. 'mat4x4<f32>': 'mat4',
  54666. 'mat4x4f': 'mat4',
  54667. 'sampler': 'sampler',
  54668. 'texture_1d': 'texture',
  54669. 'texture_2d': 'texture',
  54670. 'texture_2d_array': 'texture',
  54671. 'texture_multisampled_2d': 'cubeTexture',
  54672. 'texture_depth_2d': 'depthTexture',
  54673. 'texture_depth_2d_array': 'depthTexture',
  54674. 'texture_depth_multisampled_2d': 'depthTexture',
  54675. 'texture_depth_cube': 'depthTexture',
  54676. 'texture_depth_cube_array': 'depthTexture',
  54677. 'texture_3d': 'texture3D',
  54678. 'texture_cube': 'cubeTexture',
  54679. 'texture_cube_array': 'cubeTexture',
  54680. 'texture_storage_1d': 'storageTexture',
  54681. 'texture_storage_2d': 'storageTexture',
  54682. 'texture_storage_2d_array': 'storageTexture',
  54683. 'texture_storage_3d': 'storageTexture'
  54684. };
  54685. const parse = ( source ) => {
  54686. source = source.trim();
  54687. const declaration = source.match( declarationRegexp );
  54688. if ( declaration !== null && declaration.length === 4 ) {
  54689. const inputsCode = declaration[ 2 ];
  54690. const propsMatches = [];
  54691. let match = null;
  54692. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  54693. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  54694. }
  54695. // Process matches to correctly pair names and types
  54696. const inputs = [];
  54697. for ( let i = 0; i < propsMatches.length; i ++ ) {
  54698. const { name, type } = propsMatches[ i ];
  54699. let resolvedType = type;
  54700. if ( resolvedType.startsWith( 'ptr' ) ) {
  54701. resolvedType = 'pointer';
  54702. } else {
  54703. if ( resolvedType.startsWith( 'texture' ) ) {
  54704. resolvedType = type.split( '<' )[ 0 ];
  54705. }
  54706. resolvedType = wgslTypeLib$1[ resolvedType ];
  54707. }
  54708. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  54709. }
  54710. const blockCode = source.substring( declaration[ 0 ].length );
  54711. const outputType = declaration[ 3 ] || 'void';
  54712. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  54713. const type = wgslTypeLib$1[ outputType ] || outputType;
  54714. return {
  54715. type,
  54716. inputs,
  54717. name,
  54718. inputsCode,
  54719. blockCode,
  54720. outputType
  54721. };
  54722. } else {
  54723. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  54724. }
  54725. };
  54726. /**
  54727. * This class represents a WSL node function.
  54728. *
  54729. * @augments NodeFunction
  54730. */
  54731. class WGSLNodeFunction extends NodeFunction {
  54732. /**
  54733. * Constructs a new WGSL node function.
  54734. *
  54735. * @param {string} source - The WGSL source.
  54736. */
  54737. constructor( source ) {
  54738. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  54739. super( type, inputs, name );
  54740. this.inputsCode = inputsCode;
  54741. this.blockCode = blockCode;
  54742. this.outputType = outputType;
  54743. }
  54744. /**
  54745. * This method returns the WGSL code of the node function.
  54746. *
  54747. * @param {string} [name=this.name] - The function's name.
  54748. * @return {string} The shader code.
  54749. */
  54750. getCode( name = this.name ) {
  54751. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  54752. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  54753. }
  54754. }
  54755. /**
  54756. * A WGSL node parser.
  54757. *
  54758. * @augments NodeParser
  54759. */
  54760. class WGSLNodeParser extends NodeParser {
  54761. /**
  54762. * The method parses the given WGSL code an returns a node function.
  54763. *
  54764. * @param {string} source - The WGSL code.
  54765. * @return {WGSLNodeFunction} A node function.
  54766. */
  54767. parseFunction( source ) {
  54768. return new WGSLNodeFunction( source );
  54769. }
  54770. }
  54771. const accessNames = {
  54772. [ NodeAccess.READ_ONLY ]: 'read',
  54773. [ NodeAccess.WRITE_ONLY ]: 'write',
  54774. [ NodeAccess.READ_WRITE ]: 'read_write'
  54775. };
  54776. const wrapNames = {
  54777. [ RepeatWrapping ]: 'repeat',
  54778. [ ClampToEdgeWrapping ]: 'clamp',
  54779. [ MirroredRepeatWrapping ]: 'mirror'
  54780. };
  54781. const gpuShaderStageLib = {
  54782. 'vertex': GPUShaderStage.VERTEX,
  54783. 'fragment': GPUShaderStage.FRAGMENT,
  54784. 'compute': GPUShaderStage.COMPUTE
  54785. };
  54786. const supports = {
  54787. instance: true,
  54788. swizzleAssign: false,
  54789. storageBuffer: true
  54790. };
  54791. const wgslFnOpLib = {
  54792. '^^': 'tsl_xor'
  54793. };
  54794. const wgslTypeLib = {
  54795. float: 'f32',
  54796. int: 'i32',
  54797. uint: 'u32',
  54798. bool: 'bool',
  54799. color: 'vec3<f32>',
  54800. vec2: 'vec2<f32>',
  54801. ivec2: 'vec2<i32>',
  54802. uvec2: 'vec2<u32>',
  54803. bvec2: 'vec2<bool>',
  54804. vec3: 'vec3<f32>',
  54805. ivec3: 'vec3<i32>',
  54806. uvec3: 'vec3<u32>',
  54807. bvec3: 'vec3<bool>',
  54808. vec4: 'vec4<f32>',
  54809. ivec4: 'vec4<i32>',
  54810. uvec4: 'vec4<u32>',
  54811. bvec4: 'vec4<bool>',
  54812. mat2: 'mat2x2<f32>',
  54813. mat3: 'mat3x3<f32>',
  54814. mat4: 'mat4x4<f32>'
  54815. };
  54816. const wgslCodeCache = {};
  54817. const wgslPolyfill = {
  54818. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  54819. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  54820. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  54821. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  54822. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  54823. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  54824. 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 ); }' ),
  54825. 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 ); }' ),
  54826. 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 ); }' ),
  54827. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  54828. 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 ); }' ),
  54829. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  54830. biquadraticTexture: new CodeNode( /* wgsl */`
  54831. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  54832. let res = vec2f( iRes );
  54833. let uvScaled = coord * res;
  54834. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  54835. // https://www.shadertoy.com/view/WtyXRy
  54836. let uv = uvWrapping - 0.5;
  54837. let iuv = floor( uv );
  54838. let f = fract( uv );
  54839. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  54840. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  54841. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  54842. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  54843. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  54844. }
  54845. ` ),
  54846. biquadraticTextureArray: new CodeNode( /* wgsl */`
  54847. fn tsl_biquadraticTexture_array( map : texture_2d_array<f32>, coord : vec2f, iRes : vec2u, layer : u32, level : u32 ) -> vec4f {
  54848. let res = vec2f( iRes );
  54849. let uvScaled = coord * res;
  54850. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  54851. // https://www.shadertoy.com/view/WtyXRy
  54852. let uv = uvWrapping - 0.5;
  54853. let iuv = floor( uv );
  54854. let f = fract( uv );
  54855. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, layer, level );
  54856. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level );
  54857. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level );
  54858. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level );
  54859. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  54860. }
  54861. ` )
  54862. };
  54863. const wgslMethods = {
  54864. dFdx: 'dpdx',
  54865. dFdy: '- dpdy',
  54866. mod_float: 'tsl_mod_float',
  54867. mod_vec2: 'tsl_mod_vec2',
  54868. mod_vec3: 'tsl_mod_vec3',
  54869. mod_vec4: 'tsl_mod_vec4',
  54870. equals_bool: 'tsl_equals_bool',
  54871. equals_bvec2: 'tsl_equals_bvec2',
  54872. equals_bvec3: 'tsl_equals_bvec3',
  54873. equals_bvec4: 'tsl_equals_bvec4',
  54874. inversesqrt: 'inverseSqrt',
  54875. bitcast: 'bitcast<f32>',
  54876. floatpack_snorm_2x16: 'pack2x16snorm',
  54877. floatpack_unorm_2x16: 'pack2x16unorm',
  54878. floatpack_float16_2x16: 'pack2x16float',
  54879. floatunpack_snorm_2x16: 'unpack2x16snorm',
  54880. floatunpack_unorm_2x16: 'unpack2x16unorm',
  54881. floatunpack_float16_2x16: 'unpack2x16float'
  54882. };
  54883. //
  54884. let diagnostics = '';
  54885. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  54886. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  54887. }
  54888. /**
  54889. * A node builder targeting WGSL.
  54890. *
  54891. * This module generates WGSL shader code from node materials and also
  54892. * generates the respective bindings and vertex buffer definitions. These
  54893. * data are later used by the renderer to create render and compute pipelines
  54894. * for render objects.
  54895. *
  54896. * @augments NodeBuilder
  54897. */
  54898. class WGSLNodeBuilder extends NodeBuilder {
  54899. /**
  54900. * Constructs a new WGSL node builder renderer.
  54901. *
  54902. * @param {Object3D} object - The 3D object.
  54903. * @param {Renderer} renderer - The renderer.
  54904. */
  54905. constructor( object, renderer ) {
  54906. super( object, renderer, new WGSLNodeParser() );
  54907. /**
  54908. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  54909. * another dictionary which manages UBOs per group ('render','frame','object').
  54910. *
  54911. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  54912. */
  54913. this.uniformGroups = {};
  54914. /**
  54915. * A dictionary that holds the assigned binding indices for each uniform group.
  54916. * This ensures the same binding index is used across all shader stages.
  54917. *
  54918. * @type {Object<string,{index: number, id: number}>}
  54919. */
  54920. this.uniformGroupsBindings = {};
  54921. /**
  54922. * A dictionary that holds for each shader stage a Map of builtins.
  54923. *
  54924. * @type {Object<string,Map<string,Object>>}
  54925. */
  54926. this.builtins = {};
  54927. /**
  54928. * A dictionary that holds for each shader stage a Set of directives.
  54929. *
  54930. * @type {Object<string,Set<string>>}
  54931. */
  54932. this.directives = {};
  54933. /**
  54934. * A map for managing scope arrays. Only relevant for when using
  54935. * {@link WorkgroupInfoNode} in context of compute shaders.
  54936. *
  54937. * @type {Map<string,Object>}
  54938. */
  54939. this.scopedArrays = new Map();
  54940. /**
  54941. * A flag that indicates that early returns are allowed.
  54942. *
  54943. * @type {boolean}
  54944. * @default true
  54945. */
  54946. this.allowEarlyReturns = true;
  54947. /**
  54948. * A flag that indicates that global variables are allowed.
  54949. *
  54950. * @type {boolean}
  54951. * @default true
  54952. */
  54953. this.allowGlobalVariables = true;
  54954. }
  54955. /**
  54956. * Generates the WGSL snippet for sampled textures.
  54957. *
  54958. * @private
  54959. * @param {Texture} texture - The texture.
  54960. * @param {string} textureProperty - The name of the texture uniform in the shader.
  54961. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  54962. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  54963. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  54964. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  54965. * @return {string} The WGSL snippet.
  54966. */
  54967. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  54968. if ( shaderStage === 'fragment' ) {
  54969. if ( depthSnippet ) {
  54970. if ( offsetSnippet ) {
  54971. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ offsetSnippet } )`;
  54972. }
  54973. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  54974. } else {
  54975. if ( offsetSnippet ) {
  54976. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ offsetSnippet } )`;
  54977. }
  54978. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  54979. }
  54980. } else {
  54981. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  54982. }
  54983. }
  54984. /**
  54985. * Generates the WGSL snippet when sampling textures with explicit mip level.
  54986. *
  54987. * @private
  54988. * @param {Texture} texture - The texture.
  54989. * @param {string} textureProperty - The name of the texture uniform in the shader.
  54990. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  54991. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  54992. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  54993. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  54994. * @return {string} The WGSL snippet.
  54995. */
  54996. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  54997. if ( this.isUnfilterable( texture ) === false ) {
  54998. if ( depthSnippet ) {
  54999. if ( offsetSnippet ) {
  55000. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  55001. }
  55002. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  55003. } else {
  55004. if ( offsetSnippet ) {
  55005. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  55006. }
  55007. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  55008. }
  55009. } else if ( this.isFilteredTexture( texture ) ) {
  55010. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet, depthSnippet );
  55011. } else {
  55012. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  55013. }
  55014. }
  55015. /**
  55016. * Generates a wrap function used in context of textures.
  55017. *
  55018. * @param {Texture} texture - The texture to generate the function for.
  55019. * @return {string} The name of the generated function.
  55020. */
  55021. generateWrapFunction( texture ) {
  55022. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }T_${ texture.is3DTexture || texture.isData3DTexture ? '3d' : '2d' }`;
  55023. let nodeCode = wgslCodeCache[ functionName ];
  55024. if ( nodeCode === undefined ) {
  55025. const includes = [];
  55026. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  55027. const coordType = texture.is3DTexture || texture.isData3DTexture ? 'vec3f' : 'vec2f';
  55028. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  55029. const addWrapSnippet = ( wrap, axis ) => {
  55030. if ( wrap === RepeatWrapping ) {
  55031. includes.push( wgslPolyfill.repeatWrapping_float );
  55032. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  55033. } else if ( wrap === ClampToEdgeWrapping ) {
  55034. includes.push( wgslPolyfill.clampWrapping_float );
  55035. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  55036. } else if ( wrap === MirroredRepeatWrapping ) {
  55037. includes.push( wgslPolyfill.mirrorWrapping_float );
  55038. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  55039. } else {
  55040. code += `\t\tcoord.${ axis }`;
  55041. warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  55042. }
  55043. };
  55044. addWrapSnippet( texture.wrapS, 'x' );
  55045. code += ',\n';
  55046. addWrapSnippet( texture.wrapT, 'y' );
  55047. if ( texture.is3DTexture || texture.isData3DTexture ) {
  55048. code += ',\n';
  55049. addWrapSnippet( texture.wrapR, 'z' );
  55050. }
  55051. code += '\n\t);\n\n}\n';
  55052. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  55053. }
  55054. nodeCode.build( this );
  55055. return functionName;
  55056. }
  55057. /**
  55058. * Generates the array declaration string.
  55059. *
  55060. * @param {string} type - The type.
  55061. * @param {?number} [count] - The count.
  55062. * @return {string} The generated value as a shader string.
  55063. */
  55064. generateArrayDeclaration( type, count ) {
  55065. return `array< ${ this.getType( type ) }, ${ count } >`;
  55066. }
  55067. /**
  55068. * Generates a WGSL variable that holds the texture dimension of the given texture.
  55069. * It also returns information about the number of layers (elements) of an arrayed
  55070. * texture as well as the cube face count of cube textures.
  55071. *
  55072. * @param {Texture} texture - The texture to generate the function for.
  55073. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  55074. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  55075. * @return {string} The name of the dimension variable.
  55076. */
  55077. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  55078. const textureData = this.getDataFromNode( texture, this.shaderStage, this.cache );
  55079. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  55080. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  55081. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  55082. let textureDimensionsParams;
  55083. let dimensionType;
  55084. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  55085. const isMultisampled = primarySamples > 1;
  55086. if ( texture.is3DTexture || texture.isData3DTexture ) {
  55087. dimensionType = 'vec3<u32>';
  55088. } else {
  55089. // Regular 2D textures, depth textures, etc.
  55090. dimensionType = 'vec2<u32>';
  55091. }
  55092. // Build parameters string based on texture type and multisampling
  55093. if ( isMultisampled || texture.isStorageTexture ) {
  55094. textureDimensionsParams = textureProperty;
  55095. } else {
  55096. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  55097. }
  55098. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  55099. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  55100. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.is3DTexture || texture.isData3DTexture ) {
  55101. textureData.arrayLayerCount = new VarNode(
  55102. new ExpressionNode(
  55103. `textureNumLayers(${textureProperty})`,
  55104. 'u32'
  55105. )
  55106. );
  55107. }
  55108. // For cube textures, we know it's always 6 faces
  55109. if ( texture.isTextureCube ) {
  55110. textureData.cubeFaceCount = new VarNode(
  55111. new ExpressionNode( '6u', 'u32' )
  55112. );
  55113. }
  55114. }
  55115. return textureDimensionNode.build( this );
  55116. }
  55117. /**
  55118. * Generates the WGSL snippet for a manual filtered texture.
  55119. *
  55120. * @param {Texture} texture - The texture.
  55121. * @param {string} textureProperty - The name of the texture uniform in the shader.
  55122. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  55123. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  55124. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  55125. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  55126. * @return {string} The WGSL snippet.
  55127. */
  55128. generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet = '0u', depthSnippet ) {
  55129. const wrapFunction = this.generateWrapFunction( texture );
  55130. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  55131. if ( offsetSnippet ) {
  55132. uvSnippet = `${ uvSnippet } + vec2<f32>(${ offsetSnippet }) / ${ textureDimension }`;
  55133. }
  55134. if ( depthSnippet ) {
  55135. this._include( 'biquadraticTextureArray' );
  55136. return `tsl_biquadraticTexture_array( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ depthSnippet } ), u32( ${ levelSnippet } ) )`;
  55137. }
  55138. this._include( 'biquadraticTexture' );
  55139. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  55140. }
  55141. /**
  55142. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  55143. * Since it's a lookup, no sampling or filtering is applied.
  55144. *
  55145. * @param {Texture} texture - The texture.
  55146. * @param {string} textureProperty - The name of the texture uniform in the shader.
  55147. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  55148. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  55149. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  55150. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  55151. * @return {string} The WGSL snippet.
  55152. */
  55153. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet = '0u' ) {
  55154. // Cube textures cannot use textureLoad in WGSL, must use textureSampleLevel
  55155. if ( texture.isCubeTexture === true ) {
  55156. if ( offsetSnippet ) {
  55157. uvSnippet = `${ uvSnippet } + vec3<f32>(${ offsetSnippet })`;
  55158. }
  55159. // Depth textures require integer level, regular textures use float
  55160. const levelType = texture.isDepthTexture ? 'u32' : 'f32';
  55161. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelType }( ${ levelSnippet } ) )`;
  55162. }
  55163. const wrapFunction = this.generateWrapFunction( texture );
  55164. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  55165. const vecType = texture.is3DTexture || texture.isData3DTexture ? 'vec3' : 'vec2';
  55166. const textureDimensionMargin = ( vecType === 'vec3' ) ? 'vec3<u32>( 1, 1, 1 )' : 'vec2<u32>( 1, 1 )';
  55167. if ( offsetSnippet ) {
  55168. uvSnippet = `${ uvSnippet } + ${ vecType }<f32>(${ offsetSnippet }) / ${ vecType }<f32>( ${ textureDimension } )`;
  55169. }
  55170. const clampMin = `${ vecType }<f32>( 0 )`;
  55171. const clampMax = `${ vecType }<f32>( ${ textureDimension } - ${ textureDimensionMargin } )`;
  55172. uvSnippet = `${ vecType }<u32>( clamp( floor( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) ), ${ clampMin }, ${ clampMax } ) )`;
  55173. return this.generateTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, null );
  55174. }
  55175. /**
  55176. * Generates the WGSL snippet that reads a single texel from a storage texture.
  55177. *
  55178. * @param {Texture} texture - The texture.
  55179. * @param {string} textureProperty - The name of the texture uniform in the shader.
  55180. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  55181. * @param {?string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  55182. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  55183. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  55184. * @return {string} The WGSL snippet.
  55185. */
  55186. generateStorageTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  55187. if ( offsetSnippet ) {
  55188. uvIndexSnippet = `${ uvIndexSnippet } + ${ offsetSnippet }`;
  55189. }
  55190. let snippet;
  55191. if ( depthSnippet ) {
  55192. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet } )`;
  55193. } else {
  55194. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  55195. }
  55196. return snippet;
  55197. }
  55198. /**
  55199. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  55200. *
  55201. * @param {Texture} texture - The texture.
  55202. * @param {string} textureProperty - The name of the texture uniform in the shader.
  55203. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  55204. * @param {?string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  55205. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  55206. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  55207. * @return {string} The WGSL snippet.
  55208. */
  55209. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  55210. if ( levelSnippet === null ) levelSnippet = '0u';
  55211. if ( offsetSnippet ) {
  55212. uvIndexSnippet = `${ uvIndexSnippet } + ${ offsetSnippet }`;
  55213. }
  55214. let snippet;
  55215. if ( depthSnippet ) {
  55216. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  55217. } else {
  55218. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  55219. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  55220. snippet += '.x';
  55221. }
  55222. }
  55223. return snippet;
  55224. }
  55225. /**
  55226. * Generates the WGSL snippet that writes a single texel to a texture.
  55227. *
  55228. * @param {Texture} texture - The texture.
  55229. * @param {string} textureProperty - The name of the texture uniform in the shader.
  55230. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  55231. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  55232. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  55233. * @return {string} The WGSL snippet.
  55234. */
  55235. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  55236. let snippet;
  55237. if ( depthSnippet ) {
  55238. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  55239. } else {
  55240. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  55241. }
  55242. return snippet;
  55243. }
  55244. /**
  55245. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  55246. *
  55247. * @param {Texture} texture - The texture.
  55248. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  55249. */
  55250. isSampleCompare( texture ) {
  55251. return texture.isDepthTexture === true && texture.compareFunction !== null && this.renderer.hasCompatibility( Compatibility.TEXTURE_COMPARE );
  55252. }
  55253. /**
  55254. * Returns `true` if the given texture is unfilterable.
  55255. *
  55256. * @param {Texture} texture - The texture.
  55257. * @return {boolean} Whether the given texture is unfilterable or not.
  55258. */
  55259. isUnfilterable( texture ) {
  55260. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  55261. ( ! this.isAvailable( 'float32Filterable' ) && texture.type === FloatType ) ||
  55262. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  55263. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  55264. }
  55265. /**
  55266. * Generates the WGSL snippet for sampling/loading the given texture.
  55267. *
  55268. * @param {Texture} texture - The texture.
  55269. * @param {string} textureProperty - The name of the texture uniform in the shader.
  55270. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  55271. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  55272. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  55273. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  55274. * @return {string} The WGSL snippet.
  55275. */
  55276. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  55277. let snippet = null;
  55278. if ( this.isUnfilterable( texture ) ) {
  55279. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, '0', shaderStage );
  55280. } else {
  55281. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage );
  55282. }
  55283. return snippet;
  55284. }
  55285. /**
  55286. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  55287. *
  55288. * @param {Texture} texture - The texture.
  55289. * @param {string} textureProperty - The name of the texture uniform in the shader.
  55290. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  55291. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  55292. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  55293. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  55294. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  55295. * @return {string} The WGSL snippet.
  55296. */
  55297. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  55298. if ( shaderStage === 'fragment' ) {
  55299. if ( depthSnippet ) {
  55300. if ( offsetSnippet ) {
  55301. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  55302. }
  55303. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  55304. } else {
  55305. if ( offsetSnippet ) {
  55306. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  55307. }
  55308. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  55309. }
  55310. } else {
  55311. error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  55312. }
  55313. }
  55314. /**
  55315. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  55316. * against a reference value.
  55317. *
  55318. * @param {Texture} texture - The texture.
  55319. * @param {string} textureProperty - The name of the texture uniform in the shader.
  55320. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  55321. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  55322. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  55323. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  55324. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  55325. * @return {string} The WGSL snippet.
  55326. */
  55327. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  55328. if ( shaderStage === 'fragment' ) {
  55329. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  55330. if ( offsetSnippet ) {
  55331. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  55332. }
  55333. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  55334. }
  55335. if ( offsetSnippet ) {
  55336. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  55337. }
  55338. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  55339. } else {
  55340. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  55341. }
  55342. }
  55343. /**
  55344. * Generates the WGSL snippet for gathering four texels from the given texture.
  55345. *
  55346. * @param {Texture} texture - The texture.
  55347. * @param {string} textureProperty - The name of the texture uniform in the shader.
  55348. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  55349. * @param {string} gatherSnippet - A WGSL snippet that represents the index of the channel to read.
  55350. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  55351. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  55352. * @param {?string} flipYSnippet - A WGSL snippet that represents the y-flip. Only used for WebGL.
  55353. * @return {string} The WGSL snippet.
  55354. */
  55355. generateTextureGather( texture, textureProperty, uvSnippet, gatherSnippet, depthSnippet, offsetSnippet ) {
  55356. const componentSnippet = texture.isDepthTexture === true ? '' : `${gatherSnippet}, `;
  55357. if ( depthSnippet ) {
  55358. if ( offsetSnippet ) {
  55359. return `textureGather( ${componentSnippet}${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ offsetSnippet } )`;
  55360. }
  55361. return `textureGather( ${componentSnippet}${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  55362. }
  55363. if ( offsetSnippet ) {
  55364. return `textureGather( ${componentSnippet}${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ offsetSnippet } )`;
  55365. }
  55366. return `textureGather( ${componentSnippet}${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet })`;
  55367. }
  55368. /**
  55369. * Generates the WGSL snippet for performing a depth comparison on four texels in the given depth texture.
  55370. *
  55371. * @param {Texture} texture - The texture.
  55372. * @param {string} textureProperty - The name of the texture uniform in the shader.
  55373. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  55374. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  55375. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  55376. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  55377. * @param {?string} flipYSnippet - A WGSL snippet that represents the y-flip. Only used for WebGL.
  55378. * @return {string} The WGSL snippet.
  55379. */
  55380. generateTextureGatherCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet ) {
  55381. if ( depthSnippet ) {
  55382. if ( offsetSnippet ) {
  55383. return `textureGatherCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  55384. }
  55385. return `textureGatherCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet })`;
  55386. }
  55387. if ( offsetSnippet ) {
  55388. return `textureGatherCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  55389. }
  55390. return `textureGatherCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet })`;
  55391. }
  55392. /**
  55393. * Generates the WGSL snippet when sampling textures with explicit mip level.
  55394. *
  55395. * @param {Texture} texture - The texture.
  55396. * @param {string} textureProperty - The name of the texture uniform in the shader.
  55397. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  55398. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  55399. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  55400. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  55401. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  55402. * @return {string} The WGSL snippet.
  55403. */
  55404. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  55405. if ( this.isUnfilterable( texture ) === false ) {
  55406. if ( depthSnippet ) {
  55407. if ( offsetSnippet ) {
  55408. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  55409. }
  55410. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  55411. } else {
  55412. if ( offsetSnippet ) {
  55413. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  55414. }
  55415. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  55416. }
  55417. } else if ( this.isFilteredTexture( texture ) ) {
  55418. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet, depthSnippet );
  55419. } else {
  55420. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  55421. }
  55422. }
  55423. /**
  55424. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  55425. *
  55426. * @param {Texture} texture - The texture.
  55427. * @param {string} textureProperty - The name of the texture uniform in the shader.
  55428. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  55429. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  55430. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  55431. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  55432. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  55433. * @return {string} The WGSL snippet.
  55434. */
  55435. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  55436. if ( shaderStage === 'fragment' ) {
  55437. if ( depthSnippet ) {
  55438. if ( offsetSnippet ) {
  55439. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  55440. }
  55441. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ biasSnippet } )`;
  55442. } else {
  55443. if ( offsetSnippet ) {
  55444. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  55445. }
  55446. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  55447. }
  55448. } else {
  55449. error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  55450. }
  55451. }
  55452. /**
  55453. * Returns a WGSL snippet that represents the property name of the given node.
  55454. *
  55455. * @param {Node} node - The node.
  55456. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  55457. * @return {string} The property name.
  55458. */
  55459. getPropertyName( node, shaderStage = this.shaderStage ) {
  55460. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  55461. if ( shaderStage === 'vertex' ) {
  55462. return `varyings.${ node.name }`;
  55463. }
  55464. } else if ( node.isNodeUniform === true ) {
  55465. const name = node.name;
  55466. const type = node.type;
  55467. if ( type === 'texture' || type === 'cubeTexture' || type === 'cubeDepthTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  55468. return name;
  55469. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  55470. if ( this.isCustomStruct( node ) ) {
  55471. return name;
  55472. }
  55473. return name + '.value';
  55474. } else {
  55475. return node.groupNode.name + '.' + name;
  55476. }
  55477. }
  55478. return super.getPropertyName( node );
  55479. }
  55480. /**
  55481. * Returns the output struct name.
  55482. *
  55483. * @return {string} The name of the output struct.
  55484. */
  55485. getOutputStructName() {
  55486. return 'output';
  55487. }
  55488. /**
  55489. * Returns the native shader operator name for a given generic name.
  55490. *
  55491. * @param {string} op - The operator name to resolve.
  55492. * @return {?string} The resolved operator name.
  55493. */
  55494. getFunctionOperator( op ) {
  55495. const fnOp = wgslFnOpLib[ op ];
  55496. if ( fnOp !== undefined ) {
  55497. this._include( fnOp );
  55498. return fnOp;
  55499. }
  55500. return null;
  55501. }
  55502. /**
  55503. * Returns the node access for the given node and shader stage.
  55504. *
  55505. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  55506. * @param {string} shaderStage - The shader stage.
  55507. * @return {string} The node access.
  55508. */
  55509. getNodeAccess( node, shaderStage ) {
  55510. if ( shaderStage !== 'compute' ) {
  55511. if ( node.isAtomic === true ) {
  55512. warn( 'WebGPURenderer: Atomic operations are only supported in compute shaders.' );
  55513. return NodeAccess.READ_WRITE;
  55514. }
  55515. return NodeAccess.READ_ONLY;
  55516. }
  55517. return node.access;
  55518. }
  55519. /**
  55520. * Returns A WGSL snippet representing the storage access.
  55521. *
  55522. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  55523. * @param {string} shaderStage - The shader stage.
  55524. * @return {string} The WGSL snippet representing the storage access.
  55525. */
  55526. getStorageAccess( node, shaderStage ) {
  55527. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  55528. }
  55529. /**
  55530. * This method is one of the more important ones since it's responsible
  55531. * for generating a matching binding instance for the given uniform node.
  55532. *
  55533. * These bindings are later used in the renderer to create bind groups
  55534. * and layouts.
  55535. *
  55536. * @param {UniformNode} node - The uniform node.
  55537. * @param {string} type - The node data type.
  55538. * @param {string} shaderStage - The shader stage.
  55539. * @param {?string} [name=null] - An optional uniform name.
  55540. * @return {NodeUniform} The node uniform object.
  55541. */
  55542. getUniformFromNode( node, type, shaderStage, name = null ) {
  55543. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  55544. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  55545. if ( nodeData.uniformGPU === undefined ) {
  55546. let uniformGPU;
  55547. const group = node.groupNode;
  55548. const groupName = group.name;
  55549. const bindings = this.getBindGroupArray( groupName, shaderStage );
  55550. if ( type === 'texture' || type === 'cubeTexture' || type === 'cubeDepthTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  55551. let texture = null;
  55552. const access = this.getNodeAccess( node, shaderStage );
  55553. if ( type === 'texture' || type === 'storageTexture' ) {
  55554. if ( node.value.is3DTexture === true ) {
  55555. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  55556. } else {
  55557. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  55558. }
  55559. } else if ( type === 'cubeTexture' || type === 'cubeDepthTexture' ) {
  55560. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  55561. } else if ( type === 'texture3D' ) {
  55562. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  55563. }
  55564. texture.store = node.isStorageTextureNode === true;
  55565. texture.mipLevel = texture.store ? node.mipLevel : 0;
  55566. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  55567. // Cube textures always need samplers (they use textureSampleLevel, not textureLoad)
  55568. // Also textureGather always need sampler.
  55569. const needsSampler = node.value.isCubeTexture === true || ( this.isUnfilterable( node.value ) === false && texture.store === false ) || node.gatherNode !== null;
  55570. if ( needsSampler ) {
  55571. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  55572. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  55573. bindings.push( sampler, texture );
  55574. uniformGPU = [ sampler, texture ];
  55575. } else {
  55576. bindings.push( texture );
  55577. uniformGPU = [ texture ];
  55578. }
  55579. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  55580. const sharedData = this.getSharedDataFromNode( node );
  55581. let buffer = sharedData.buffer;
  55582. if ( buffer === undefined ) {
  55583. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  55584. buffer = new bufferClass( node, group );
  55585. sharedData.buffer = buffer;
  55586. }
  55587. buffer.setVisibility( buffer.getVisibility() | gpuShaderStageLib[ shaderStage ] );
  55588. bindings.push( buffer );
  55589. uniformGPU = buffer;
  55590. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  55591. } else {
  55592. let uniformsGroup = this.uniformGroups[ groupName ];
  55593. if ( uniformsGroup === undefined ) {
  55594. uniformsGroup = new NodeUniformsGroup( groupName, group );
  55595. uniformsGroup.setVisibility( GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT | GPUShaderStage.COMPUTE );
  55596. this.uniformGroups[ groupName ] = uniformsGroup;
  55597. }
  55598. // Add to bindings for this stage if not already present
  55599. if ( bindings.indexOf( uniformsGroup ) === -1 ) {
  55600. bindings.push( uniformsGroup );
  55601. }
  55602. uniformGPU = this.getNodeUniform( uniformNode, type );
  55603. // Only add uniform if not already present in the group (check by name to avoid duplicates across stages)
  55604. const uniformName = uniformGPU.name;
  55605. const alreadyExists = uniformsGroup.uniforms.some( u => u.name === uniformName );
  55606. if ( ! alreadyExists ) {
  55607. uniformsGroup.addUniform( uniformGPU );
  55608. }
  55609. }
  55610. nodeData.uniformGPU = uniformGPU;
  55611. }
  55612. return uniformNode;
  55613. }
  55614. /**
  55615. * This method should be used whenever builtins are required in nodes.
  55616. * The internal builtins data structure will make sure builtins are
  55617. * defined in the WGSL source.
  55618. *
  55619. * @param {string} name - The builtin name.
  55620. * @param {string} property - The property name.
  55621. * @param {string} type - The node data type.
  55622. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  55623. * @return {string} The property name.
  55624. */
  55625. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  55626. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  55627. if ( map.has( name ) === false ) {
  55628. map.set( name, {
  55629. name,
  55630. property,
  55631. type
  55632. } );
  55633. }
  55634. return property;
  55635. }
  55636. /**
  55637. * Returns `true` if the given builtin is defined in the given shader stage.
  55638. *
  55639. * @param {string} name - The builtin name.
  55640. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  55641. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  55642. */
  55643. hasBuiltin( name, shaderStage = this.shaderStage ) {
  55644. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  55645. }
  55646. /**
  55647. * Returns the vertex index builtin.
  55648. *
  55649. * @return {string} The vertex index.
  55650. */
  55651. getVertexIndex() {
  55652. if ( this.shaderStage === 'vertex' ) {
  55653. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  55654. }
  55655. return 'vertexIndex';
  55656. }
  55657. /**
  55658. * Builds the given shader node.
  55659. *
  55660. * @param {ShaderNodeInternal} shaderNode - The shader node.
  55661. * @return {string} The WGSL function code.
  55662. */
  55663. buildFunctionCode( shaderNode ) {
  55664. const layout = shaderNode.layout;
  55665. const flowData = this.flowShaderNode( shaderNode );
  55666. const parameters = [];
  55667. for ( const input of layout.inputs ) {
  55668. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  55669. }
  55670. //
  55671. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  55672. ${ flowData.vars }
  55673. ${ flowData.code }
  55674. `;
  55675. if ( flowData.result ) {
  55676. code += `\treturn ${ flowData.result };\n`;
  55677. }
  55678. code += '\n}\n';
  55679. //
  55680. return code;
  55681. }
  55682. /**
  55683. * Contextually returns either the vertex stage instance index builtin
  55684. * or the linearized index of an compute invocation within a grid of workgroups.
  55685. *
  55686. * @return {string} The instance index.
  55687. */
  55688. getInstanceIndex() {
  55689. if ( this.shaderStage === 'vertex' ) {
  55690. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  55691. }
  55692. return 'instanceIndex';
  55693. }
  55694. /**
  55695. * Returns a builtin representing the index of a compute invocation within the scope of a workgroup load.
  55696. *
  55697. * @return {string} The invocation local index.
  55698. */
  55699. getInvocationLocalIndex() {
  55700. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  55701. }
  55702. /**
  55703. * Returns a builtin representing the size of a subgroup within the current shader.
  55704. *
  55705. * @return {string} The subgroup size.
  55706. */
  55707. getSubgroupSize() {
  55708. this.enableSubGroups();
  55709. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  55710. }
  55711. /**
  55712. * Returns a builtin representing the index of a compute invocation within the scope of a subgroup.
  55713. *
  55714. * @return {string} The invocation subgroup index.
  55715. */
  55716. getInvocationSubgroupIndex() {
  55717. this.enableSubGroups();
  55718. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  55719. }
  55720. /**
  55721. * Returns a builtin representing the index of a compute invocation's subgroup within its workgroup.
  55722. *
  55723. * @return {string} The subgroup index.
  55724. */
  55725. getSubgroupIndex() {
  55726. this.enableSubGroups();
  55727. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  55728. }
  55729. /**
  55730. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  55731. *
  55732. * @return {null} Null.
  55733. */
  55734. getDrawIndex() {
  55735. return null;
  55736. }
  55737. /**
  55738. * Returns the front facing builtin.
  55739. *
  55740. * @return {string} The front facing builtin.
  55741. */
  55742. getFrontFacing() {
  55743. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  55744. }
  55745. /**
  55746. * Returns the frag coord builtin.
  55747. *
  55748. * @return {string} The frag coord builtin.
  55749. */
  55750. getFragCoord() {
  55751. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  55752. }
  55753. /**
  55754. * Returns the frag depth builtin.
  55755. *
  55756. * @return {string} The frag depth builtin.
  55757. */
  55758. getFragDepth() {
  55759. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  55760. }
  55761. /**
  55762. * Returns the clip distances builtin.
  55763. *
  55764. * @return {string} The clip distances builtin.
  55765. */
  55766. getClipDistance() {
  55767. return 'varyings.hw_clip_distances';
  55768. }
  55769. /**
  55770. * Whether to flip texture data along its vertical axis or not.
  55771. *
  55772. * @return {boolean} Returns always `false` in context of WGSL.
  55773. */
  55774. isFlipY() {
  55775. return false;
  55776. }
  55777. /**
  55778. * Enables the given directive for the given shader stage.
  55779. *
  55780. * @param {string} name - The directive name.
  55781. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  55782. */
  55783. enableDirective( name, shaderStage = this.shaderStage ) {
  55784. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  55785. stage.add( name );
  55786. }
  55787. /**
  55788. * Returns the directives of the given shader stage as a WGSL string.
  55789. *
  55790. * @param {string} shaderStage - The shader stage.
  55791. * @return {string} A WGSL snippet that enables the directives of the given stage.
  55792. */
  55793. getDirectives( shaderStage ) {
  55794. const snippets = [];
  55795. const directives = this.directives[ shaderStage ];
  55796. if ( directives !== undefined ) {
  55797. for ( const directive of directives ) {
  55798. snippets.push( `enable ${directive};` );
  55799. }
  55800. }
  55801. return snippets.join( '\n' );
  55802. }
  55803. /**
  55804. * Enables the 'subgroups' directive.
  55805. */
  55806. enableSubGroups() {
  55807. this.enableDirective( 'subgroups' );
  55808. }
  55809. /**
  55810. * Enables the 'subgroups-f16' directive.
  55811. */
  55812. enableSubgroupsF16() {
  55813. this.enableDirective( 'subgroups-f16' );
  55814. }
  55815. /**
  55816. * Enables the 'clip_distances' directive.
  55817. */
  55818. enableClipDistances() {
  55819. this.enableDirective( 'clip_distances' );
  55820. }
  55821. /**
  55822. * Enables the 'f16' directive.
  55823. */
  55824. enableShaderF16() {
  55825. this.enableDirective( 'f16' );
  55826. }
  55827. /**
  55828. * Enables the 'dual_source_blending' directive.
  55829. */
  55830. enableDualSourceBlending() {
  55831. this.enableDirective( 'dual_source_blending' );
  55832. }
  55833. /**
  55834. * Enables hardware clipping.
  55835. *
  55836. * @param {string} planeCount - The clipping plane count.
  55837. */
  55838. enableHardwareClipping( planeCount ) {
  55839. this.enableClipDistances();
  55840. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  55841. }
  55842. /**
  55843. * Returns the builtins of the given shader stage as a WGSL string.
  55844. *
  55845. * @param {string} shaderStage - The shader stage.
  55846. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  55847. */
  55848. getBuiltins( shaderStage ) {
  55849. const snippets = [];
  55850. const builtins = this.builtins[ shaderStage ];
  55851. if ( builtins !== undefined ) {
  55852. for ( const { name, property, type } of builtins.values() ) {
  55853. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  55854. }
  55855. }
  55856. return snippets.join( ',\n\t' );
  55857. }
  55858. /**
  55859. * This method should be used when a new scoped buffer is used in context of
  55860. * compute shaders. It adds the array to the internal data structure which is
  55861. * later used to generate the respective WGSL.
  55862. *
  55863. * @param {string} name - The array name.
  55864. * @param {string} scope - The scope.
  55865. * @param {string} bufferType - The buffer type.
  55866. * @param {string} bufferCount - The buffer count.
  55867. * @return {string} The array name.
  55868. */
  55869. getScopedArray( name, scope, bufferType, bufferCount ) {
  55870. if ( this.scopedArrays.has( name ) === false ) {
  55871. this.scopedArrays.set( name, {
  55872. name,
  55873. scope,
  55874. bufferType,
  55875. bufferCount
  55876. } );
  55877. }
  55878. return name;
  55879. }
  55880. /**
  55881. * Returns the scoped arrays of the given shader stage as a WGSL string.
  55882. *
  55883. * @param {string} shaderStage - The shader stage.
  55884. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  55885. * Returns `undefined` when used in the vertex or fragment stage.
  55886. */
  55887. getScopedArrays( shaderStage ) {
  55888. if ( shaderStage !== 'compute' ) {
  55889. return;
  55890. }
  55891. const snippets = [];
  55892. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  55893. const type = this.getType( bufferType );
  55894. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  55895. }
  55896. return snippets.join( '\n' );
  55897. }
  55898. /**
  55899. * Returns the shader attributes of the given shader stage as a WGSL string.
  55900. *
  55901. * @param {string} shaderStage - The shader stage.
  55902. * @return {string} The WGSL snippet that defines the shader attributes.
  55903. */
  55904. getAttributes( shaderStage ) {
  55905. const snippets = [];
  55906. if ( shaderStage === 'compute' ) {
  55907. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  55908. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  55909. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  55910. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  55911. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  55912. this.enableDirective( 'subgroups', shaderStage );
  55913. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  55914. }
  55915. }
  55916. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  55917. const builtins = this.getBuiltins( 'attribute' );
  55918. if ( builtins ) snippets.push( builtins );
  55919. const attributes = this.getAttributesArray();
  55920. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  55921. const attribute = attributes[ index ];
  55922. const name = attribute.name;
  55923. const type = this.getType( attribute.type );
  55924. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  55925. }
  55926. }
  55927. return snippets.join( ',\n\t' );
  55928. }
  55929. /**
  55930. * Returns the members of the given struct type node as a WGSL string.
  55931. *
  55932. * @param {StructTypeNode} struct - The struct type node.
  55933. * @return {string} The WGSL snippet that defines the struct members.
  55934. */
  55935. getStructMembers( struct ) {
  55936. const snippets = [];
  55937. for ( const member of struct.members ) {
  55938. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  55939. let type = this.getType( member.type );
  55940. if ( member.atomic ) {
  55941. type = 'atomic< ' + type + ' >';
  55942. }
  55943. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  55944. }
  55945. if ( struct.output ) {
  55946. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  55947. }
  55948. return snippets.join( ',\n' );
  55949. }
  55950. /**
  55951. * Returns the structs of the given shader stage as a WGSL string.
  55952. *
  55953. * @param {string} shaderStage - The shader stage.
  55954. * @return {string} The WGSL snippet that defines the structs.
  55955. */
  55956. getStructs( shaderStage ) {
  55957. let result = '';
  55958. const structs = this.structs[ shaderStage ];
  55959. if ( structs.length > 0 ) {
  55960. const snippets = [];
  55961. for ( const struct of structs ) {
  55962. let snippet = `struct ${ struct.name } {\n`;
  55963. snippet += this.getStructMembers( struct );
  55964. snippet += '\n};';
  55965. snippets.push( snippet );
  55966. }
  55967. result = '\n' + snippets.join( '\n\n' ) + '\n';
  55968. }
  55969. return result;
  55970. }
  55971. /**
  55972. * Returns a WGSL string representing a variable.
  55973. *
  55974. * @param {string} type - The variable's type.
  55975. * @param {string} name - The variable's name.
  55976. * @param {?number} [count=null] - The array length.
  55977. * @param {string} [qualifier=''] - The variable's qualifier.
  55978. * @return {string} The WGSL snippet that defines a variable.
  55979. */
  55980. getVar( type, name, count = null, qualifier = '' ) {
  55981. let snippet = `var${ qualifier } ${ name } : `;
  55982. if ( count !== null ) {
  55983. snippet += this.generateArrayDeclaration( type, count );
  55984. } else {
  55985. snippet += this.getType( type );
  55986. }
  55987. return snippet;
  55988. }
  55989. /**
  55990. * Returns the variables of the given shader stage as a WGSL string.
  55991. *
  55992. * @param {string} shaderStage - The shader stage.
  55993. * @return {string} The WGSL snippet that defines the variables.
  55994. */
  55995. getVars( shaderStage, global = false ) {
  55996. let qualifier = '';
  55997. if ( global ) {
  55998. qualifier = '<private>';
  55999. }
  56000. const snippets = [];
  56001. const vars = this.vars[ shaderStage ];
  56002. if ( vars !== undefined ) {
  56003. for ( const variable of vars ) {
  56004. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count, qualifier ) };` );
  56005. }
  56006. }
  56007. return global ? snippets.join( '\n' ) : `\n\t${ snippets.join( '\n\t' ) }\n`;
  56008. }
  56009. /**
  56010. * Returns the varyings of the given shader stage as a WGSL string.
  56011. *
  56012. * @param {string} shaderStage - The shader stage.
  56013. * @return {string} The WGSL snippet that defines the varyings.
  56014. */
  56015. getVaryings( shaderStage ) {
  56016. const snippets = [];
  56017. if ( shaderStage === 'vertex' ) {
  56018. this.getBuiltin( 'position', 'builtinClipSpace', 'vec4<f32>', 'vertex' );
  56019. }
  56020. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  56021. const varyings = this.varyings;
  56022. const vars = this.vars[ shaderStage ];
  56023. let varyingIndex = 0;
  56024. for ( let index = 0; index < varyings.length; index ++ ) {
  56025. const varying = varyings[ index ];
  56026. if ( varying.needsInterpolation ) {
  56027. let attributesSnippet = `@location( ${ varyingIndex ++ } )`;
  56028. if ( varying.interpolationType ) {
  56029. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  56030. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  56031. // Otherwise, optimize interpolation when sensible
  56032. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  56033. attributesSnippet += ' @interpolate(flat, either)';
  56034. }
  56035. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  56036. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  56037. vars.push( varying );
  56038. }
  56039. }
  56040. }
  56041. const builtins = this.getBuiltins( shaderStage );
  56042. if ( builtins ) snippets.push( builtins );
  56043. const code = snippets.join( ',\n\t' );
  56044. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  56045. }
  56046. isCustomStruct( nodeUniform ) {
  56047. const attribute = nodeUniform.value;
  56048. const bufferNode = nodeUniform.node;
  56049. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  56050. const isStructArray =
  56051. ( bufferNode.value && bufferNode.value.array ) &&
  56052. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  56053. return isAttributeStructType && ! isStructArray;
  56054. }
  56055. /**
  56056. * Returns the uniforms of the given shader stage as a WGSL string.
  56057. *
  56058. * @param {string} shaderStage - The shader stage.
  56059. * @return {string} The WGSL snippet that defines the uniforms.
  56060. */
  56061. getUniforms( shaderStage ) {
  56062. const backend = this.renderer.backend;
  56063. const uniforms = this.uniforms[ shaderStage ];
  56064. const bindingSnippets = [];
  56065. const bufferSnippets = [];
  56066. const structSnippets = [];
  56067. const uniformGroups = {};
  56068. for ( const uniform of uniforms ) {
  56069. const groupName = uniform.groupNode.name;
  56070. const uniformIndexes = this.bindingsIndexes[ groupName ];
  56071. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'cubeDepthTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  56072. const textureNode = uniform.node;
  56073. const texture = textureNode.value;
  56074. // Cube textures always need samplers (they use textureSampleLevel, not textureLoad)
  56075. // Also textureGather always need sampler.
  56076. const needsSampler = texture.isCubeTexture === true || ( this.isUnfilterable( texture ) === false && textureNode.isStorageTextureNode !== true ) || textureNode.gatherNode !== null;
  56077. if ( needsSampler ) {
  56078. if ( this.isSampleCompare( texture ) && textureNode.compareNode !== null ) {
  56079. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  56080. } else {
  56081. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  56082. }
  56083. }
  56084. let textureType;
  56085. let multisampled = '';
  56086. const { primarySamples } = backend.utils.getTextureSampleData( texture );
  56087. if ( primarySamples > 1 ) {
  56088. multisampled = '_multisampled';
  56089. }
  56090. if ( texture.isCubeTexture === true && texture.isDepthTexture === true ) {
  56091. textureType = 'texture_depth_cube';
  56092. } else if ( texture.isCubeTexture === true ) {
  56093. textureType = 'texture_cube<f32>';
  56094. } else if ( texture.isDepthTexture === true ) {
  56095. if ( backend.compatibilityMode && texture.compareFunction === null ) {
  56096. textureType = `texture${ multisampled }_2d<f32>`;
  56097. } else {
  56098. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  56099. }
  56100. } else if ( uniform.node.isStorageTextureNode === true ) {
  56101. const format = getFormat( texture, backend.device );
  56102. const access = this.getStorageAccess( uniform.node, shaderStage );
  56103. const is3D = uniform.node.value.is3DTexture;
  56104. const isArrayTexture = uniform.node.value.isArrayTexture;
  56105. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  56106. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  56107. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  56108. textureType = 'texture_2d_array<f32>';
  56109. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  56110. textureType = 'texture_3d<f32>';
  56111. } else {
  56112. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  56113. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  56114. }
  56115. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  56116. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  56117. const bufferNode = uniform.node;
  56118. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  56119. const bufferCount = bufferNode.bufferCount;
  56120. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  56121. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  56122. if ( this.isCustomStruct( uniform ) ) {
  56123. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  56124. } else {
  56125. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  56126. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  56127. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  56128. }
  56129. } else {
  56130. const groupName = uniform.groupNode.name;
  56131. // Check if this group has already been processed in this shader stage
  56132. if ( uniformGroups[ groupName ] === undefined ) {
  56133. // Get the shared uniform group that contains uniforms from all stages
  56134. const sharedUniformGroup = this.uniformGroups[ groupName ];
  56135. if ( sharedUniformGroup !== undefined ) {
  56136. // Generate snippets for ALL uniforms in this shared group
  56137. const snippets = [];
  56138. for ( const sharedUniform of sharedUniformGroup.uniforms ) {
  56139. const type = sharedUniform.getType();
  56140. const vectorType = this.getType( this.getVectorType( type ) );
  56141. snippets.push( `\t${ sharedUniform.name } : ${ vectorType }` );
  56142. }
  56143. // Check if this group already has an assigned binding index (from another shader stage)
  56144. let groupBinding = this.uniformGroupsBindings[ groupName ];
  56145. if ( groupBinding === undefined ) {
  56146. // First time processing this group - assign a new binding index
  56147. groupBinding = {
  56148. index: uniformIndexes.binding ++,
  56149. id: uniformIndexes.group
  56150. };
  56151. this.uniformGroupsBindings[ groupName ] = groupBinding;
  56152. }
  56153. uniformGroups[ groupName ] = {
  56154. index: groupBinding.index,
  56155. id: groupBinding.id,
  56156. snippets: snippets
  56157. };
  56158. }
  56159. }
  56160. }
  56161. }
  56162. for ( const name in uniformGroups ) {
  56163. const group = uniformGroups[ name ];
  56164. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  56165. }
  56166. const code = [ ...bindingSnippets, ...bufferSnippets, ...structSnippets ].join( '\n' );
  56167. return code;
  56168. }
  56169. /**
  56170. * Controls the code build of the shader stages.
  56171. */
  56172. buildCode() {
  56173. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  56174. this.sortBindingGroups();
  56175. for ( const shaderStage in shadersData ) {
  56176. this.shaderStage = shaderStage;
  56177. const allowGlobal = this.allowGlobalVariables;
  56178. const stageData = shadersData[ shaderStage ];
  56179. stageData.uniforms = this.getUniforms( shaderStage );
  56180. stageData.attributes = this.getAttributes( shaderStage );
  56181. stageData.varyings = this.getVaryings( shaderStage );
  56182. stageData.structs = this.getStructs( shaderStage );
  56183. stageData.vars = this.getVars( shaderStage, allowGlobal );
  56184. stageData.codes = this.getCodes( shaderStage );
  56185. stageData.directives = this.getDirectives( shaderStage );
  56186. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  56187. //
  56188. let flow = '// code\n\n';
  56189. flow += this.flowCode[ shaderStage ];
  56190. const flowNodes = this.flowNodes[ shaderStage ];
  56191. const mainNode = flowNodes[ flowNodes.length - 1 ];
  56192. const outputNode = mainNode.outputNode;
  56193. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  56194. for ( const node of flowNodes ) {
  56195. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  56196. const slotName = node.name;
  56197. if ( slotName ) {
  56198. if ( flow.length > 0 ) flow += '\n';
  56199. flow += `\t// flow -> ${ slotName }\n`;
  56200. }
  56201. flow += `${ flowSlotData.code }\n\t`;
  56202. if ( node === mainNode && shaderStage !== 'compute' ) {
  56203. flow += '// result\n\n\t';
  56204. if ( shaderStage === 'vertex' ) {
  56205. flow += `varyings.builtinClipSpace = ${ flowSlotData.result };`;
  56206. } else if ( shaderStage === 'fragment' ) {
  56207. if ( isOutputStruct ) {
  56208. stageData.returnType = outputNode.getNodeType( this );
  56209. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  56210. flow += `return ${ flowSlotData.result };`;
  56211. } else {
  56212. let structSnippet = '\t@location( 0 ) color: vec4<f32>';
  56213. const builtins = this.getBuiltins( 'output' );
  56214. if ( builtins ) structSnippet += ',\n\t' + builtins;
  56215. stageData.returnType = 'OutputStruct';
  56216. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  56217. stageData.structs += '\nvar<private> output : OutputStruct;';
  56218. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  56219. }
  56220. }
  56221. }
  56222. }
  56223. stageData.flow = flow;
  56224. }
  56225. this.shaderStage = null;
  56226. if ( this.material !== null ) {
  56227. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  56228. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  56229. } else {
  56230. // Early strictly validated in computeNode
  56231. const workgroupSize = this.object.workgroupSize;
  56232. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  56233. }
  56234. }
  56235. /**
  56236. * Returns the native shader method name for a given generic name.
  56237. *
  56238. * @param {string} method - The method name to resolve.
  56239. * @param {?string} [output=null] - An optional output.
  56240. * @return {string} The resolved WGSL method name.
  56241. */
  56242. getMethod( method, output = null ) {
  56243. let wgslMethod;
  56244. if ( output !== null ) {
  56245. wgslMethod = this._getWGSLMethod( method + '_' + output );
  56246. }
  56247. if ( wgslMethod === undefined ) {
  56248. wgslMethod = this._getWGSLMethod( method );
  56249. }
  56250. return wgslMethod || method;
  56251. }
  56252. /**
  56253. * Returns the bitcast method name for a given input and outputType.
  56254. *
  56255. * @param {string} type - The output type to bitcast to.
  56256. * @return {string} The resolved WGSL bitcast invocation.
  56257. */
  56258. getBitcastMethod( type ) {
  56259. const dataType = this.getType( type );
  56260. return `bitcast<${ dataType }>`;
  56261. }
  56262. /**
  56263. * Returns the float packing method name for a given numeric encoding.
  56264. *
  56265. * @param {string} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  56266. * @returns {string} The resolve WGSL float packing method name.
  56267. */
  56268. getFloatPackingMethod( encoding ) {
  56269. return this.getMethod( `floatpack_${ encoding }_2x16` );
  56270. }
  56271. /**
  56272. * Returns the float unpacking method name for a given numeric encoding.
  56273. *
  56274. * @param {string} encoding - The numeric encoding that describes how the integer values are mapped to the float range.
  56275. * @returns {string} The resolve WGSL float unpacking method name.
  56276. */
  56277. getFloatUnpackingMethod( encoding ) {
  56278. return this.getMethod( `floatunpack_${ encoding }_2x16` );
  56279. }
  56280. /**
  56281. * Returns the native snippet for a ternary operation.
  56282. *
  56283. * @param {string} condSnippet - The condition determining which expression gets resolved.
  56284. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  56285. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  56286. * @return {string} The resolved method name.
  56287. */
  56288. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  56289. return `select( ${elseSnippet}, ${ifSnippet}, ${condSnippet} )`;
  56290. }
  56291. /**
  56292. * Returns the WGSL type of the given node data type.
  56293. *
  56294. * @param {string} type - The node data type.
  56295. * @return {string} The WGSL type.
  56296. */
  56297. getType( type ) {
  56298. return wgslTypeLib[ type ] || type;
  56299. }
  56300. /**
  56301. * Whether the requested feature is available or not.
  56302. *
  56303. * @param {string} name - The requested feature.
  56304. * @return {boolean} Whether the requested feature is supported or not.
  56305. */
  56306. isAvailable( name ) {
  56307. let result = supports[ name ];
  56308. if ( result === undefined ) {
  56309. if ( name === 'float32Filterable' ) {
  56310. result = this.renderer.hasFeature( 'float32-filterable' );
  56311. } else if ( name === 'clipDistance' ) {
  56312. result = this.renderer.hasFeature( 'clip-distances' );
  56313. }
  56314. supports[ name ] = result;
  56315. }
  56316. return result;
  56317. }
  56318. /**
  56319. * Returns the native shader method name for a given generic name.
  56320. *
  56321. * @private
  56322. * @param {string} method - The method name to resolve.
  56323. * @return {string} The resolved WGSL method name.
  56324. */
  56325. _getWGSLMethod( method ) {
  56326. if ( wgslPolyfill[ method ] !== undefined ) {
  56327. this._include( method );
  56328. }
  56329. return wgslMethods[ method ];
  56330. }
  56331. /**
  56332. * Includes the given method name into the current
  56333. * function node.
  56334. *
  56335. * @private
  56336. * @param {string} name - The method name to include.
  56337. * @return {CodeNode} The respective code node.
  56338. */
  56339. _include( name ) {
  56340. const codeNode = wgslPolyfill[ name ];
  56341. codeNode.build( this );
  56342. this.addInclude( codeNode );
  56343. return codeNode;
  56344. }
  56345. /**
  56346. * Returns a WGSL vertex shader based on the given shader data.
  56347. *
  56348. * @private
  56349. * @param {Object} shaderData - The shader data.
  56350. * @return {string} The vertex shader.
  56351. */
  56352. _getWGSLVertexCode( shaderData ) {
  56353. return `${ this.getSignature() }
  56354. // directives
  56355. ${shaderData.directives}
  56356. // structs
  56357. ${shaderData.structs}
  56358. // uniforms
  56359. ${shaderData.uniforms}
  56360. // varyings
  56361. ${shaderData.varyings}
  56362. var<private> varyings : VaryingsStruct;
  56363. // vars
  56364. ${shaderData.vars}
  56365. // codes
  56366. ${shaderData.codes}
  56367. @vertex
  56368. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  56369. // flow
  56370. ${shaderData.flow}
  56371. return varyings;
  56372. }
  56373. `;
  56374. }
  56375. /**
  56376. * Returns a WGSL fragment shader based on the given shader data.
  56377. *
  56378. * @private
  56379. * @param {Object} shaderData - The shader data.
  56380. * @return {string} The vertex shader.
  56381. */
  56382. _getWGSLFragmentCode( shaderData ) {
  56383. return `${ this.getSignature() }
  56384. // global
  56385. ${ diagnostics }
  56386. // structs
  56387. ${shaderData.structs}
  56388. // uniforms
  56389. ${shaderData.uniforms}
  56390. // vars
  56391. ${shaderData.vars}
  56392. // codes
  56393. ${shaderData.codes}
  56394. @fragment
  56395. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  56396. // flow
  56397. ${shaderData.flow}
  56398. }
  56399. `;
  56400. }
  56401. /**
  56402. * Returns a WGSL compute shader based on the given shader data.
  56403. *
  56404. * @private
  56405. * @param {Object} shaderData - The shader data.
  56406. * @param {string} workgroupSize - The workgroup size.
  56407. * @return {string} The vertex shader.
  56408. */
  56409. _getWGSLComputeCode( shaderData, workgroupSize ) {
  56410. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  56411. return `${ this.getSignature() }
  56412. // directives
  56413. ${ shaderData.directives }
  56414. // system
  56415. var<private> instanceIndex : u32;
  56416. // locals
  56417. ${ shaderData.scopedArrays }
  56418. // structs
  56419. ${ shaderData.structs }
  56420. // uniforms
  56421. ${ shaderData.uniforms }
  56422. // vars
  56423. ${ this.allowGlobalVariables ? shaderData.vars : '' }
  56424. // codes
  56425. ${ shaderData.codes }
  56426. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  56427. fn main( ${ shaderData.attributes } ) {
  56428. // local vars
  56429. ${ this.allowGlobalVariables ? '' : shaderData.vars }
  56430. // system
  56431. instanceIndex = globalId.x
  56432. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  56433. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  56434. // flow
  56435. ${ shaderData.flow }
  56436. }
  56437. `;
  56438. }
  56439. /**
  56440. * Returns a WGSL struct based on the given name and variables.
  56441. *
  56442. * @private
  56443. * @param {string} name - The struct name.
  56444. * @param {string} vars - The struct variables.
  56445. * @return {string} The WGSL snippet representing a struct.
  56446. */
  56447. _getWGSLStruct( name, vars ) {
  56448. return `
  56449. struct ${name} {
  56450. ${vars}
  56451. };`;
  56452. }
  56453. /**
  56454. * Returns a WGSL struct binding.
  56455. *
  56456. * @private
  56457. * @param {string} name - The struct name.
  56458. * @param {string} vars - The struct variables.
  56459. * @param {string} access - The access.
  56460. * @param {number} [binding=0] - The binding index.
  56461. * @param {number} [group=0] - The group index.
  56462. * @return {string} The WGSL snippet representing a struct binding.
  56463. */
  56464. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  56465. const structName = name + 'Struct';
  56466. const structSnippet = this._getWGSLStruct( structName, vars );
  56467. return `${structSnippet}
  56468. @binding( ${ binding } ) @group( ${ group } )
  56469. var<${access}> ${ name } : ${ structName };`;
  56470. }
  56471. }
  56472. const _bufferDescriptor$3 = new GPUBufferDescriptor();
  56473. const _commandEncoderDescriptor$2 = new GPUCommandEncoderDescriptor();
  56474. const typedArraysToVertexFormatPrefix = new Map( [
  56475. [ Int8Array, [ 'sint8', 'snorm8' ]],
  56476. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  56477. [ Int16Array, [ 'sint16', 'snorm16' ]],
  56478. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  56479. [ Int32Array, [ 'sint32', 'snorm32' ]],
  56480. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  56481. [ Float32Array, [ 'float32', ]],
  56482. ] );
  56483. if ( typeof Float16Array !== 'undefined' ) {
  56484. typedArraysToVertexFormatPrefix.set( Float16Array, [ 'float16' ] );
  56485. }
  56486. const typedAttributeToVertexFormatPrefix = new Map( [
  56487. [ Float16BufferAttribute, [ 'float16', ]],
  56488. ] );
  56489. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  56490. [ Int32Array, 'sint32' ],
  56491. [ Int16Array, 'sint32' ], // patch for INT16
  56492. [ Uint32Array, 'uint32' ],
  56493. [ Uint16Array, 'uint32' ], // patch for UINT16
  56494. [ Float32Array, 'float32' ]
  56495. ] );
  56496. /**
  56497. * A WebGPU backend utility module for managing shader attributes.
  56498. *
  56499. * @private
  56500. */
  56501. class WebGPUAttributeUtils {
  56502. /**
  56503. * Constructs a new utility object.
  56504. *
  56505. * @param {WebGPUBackend} backend - The WebGPU backend.
  56506. */
  56507. constructor( backend ) {
  56508. /**
  56509. * A reference to the WebGPU backend.
  56510. *
  56511. * @type {WebGPUBackend}
  56512. */
  56513. this.backend = backend;
  56514. }
  56515. /**
  56516. * Creates the GPU buffer for the given buffer attribute.
  56517. *
  56518. * @param {BufferAttribute} attribute - The buffer attribute.
  56519. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  56520. */
  56521. createAttribute( attribute, usage ) {
  56522. const bufferAttribute = this._getBufferAttribute( attribute );
  56523. const backend = this.backend;
  56524. const bufferData = backend.get( bufferAttribute );
  56525. let buffer = bufferData.buffer;
  56526. if ( buffer === undefined ) {
  56527. const device = backend.device;
  56528. let array = bufferAttribute.array;
  56529. // patch for INT16 and UINT16
  56530. if ( attribute.normalized === false ) {
  56531. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  56532. array = new Int32Array( array );
  56533. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  56534. array = new Uint32Array( array );
  56535. if ( usage & GPUBufferUsage.INDEX ) {
  56536. for ( let i = 0; i < array.length; i ++ ) {
  56537. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  56538. }
  56539. }
  56540. }
  56541. }
  56542. bufferAttribute.array = array;
  56543. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  56544. array = new array.constructor( bufferAttribute.count * 4 );
  56545. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  56546. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  56547. }
  56548. // Update BufferAttribute
  56549. bufferAttribute.itemSize = 4;
  56550. bufferAttribute.array = array;
  56551. bufferData._force3to4BytesAlignment = true;
  56552. }
  56553. // ensure 4 byte alignment
  56554. const byteLength = array.byteLength;
  56555. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  56556. _bufferDescriptor$3.label = bufferAttribute.name;
  56557. _bufferDescriptor$3.size = size;
  56558. _bufferDescriptor$3.usage = usage;
  56559. _bufferDescriptor$3.mappedAtCreation = true;
  56560. buffer = device.createBuffer( _bufferDescriptor$3 );
  56561. _bufferDescriptor$3.reset();
  56562. new array.constructor( buffer.getMappedRange() ).set( array );
  56563. buffer.unmap();
  56564. bufferData.buffer = buffer;
  56565. }
  56566. }
  56567. /**
  56568. * Updates the GPU buffer of the given buffer attribute.
  56569. *
  56570. * @param {BufferAttribute} attribute - The buffer attribute.
  56571. */
  56572. updateAttribute( attribute ) {
  56573. const bufferAttribute = this._getBufferAttribute( attribute );
  56574. const backend = this.backend;
  56575. const device = backend.device;
  56576. const bufferData = backend.get( bufferAttribute );
  56577. const buffer = backend.get( bufferAttribute ).buffer;
  56578. let array = bufferAttribute.array;
  56579. // if storage buffer ensure 4 byte alignment
  56580. if ( bufferData._force3to4BytesAlignment === true ) {
  56581. array = new array.constructor( bufferAttribute.count * 4 );
  56582. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  56583. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  56584. }
  56585. bufferAttribute.array = array;
  56586. }
  56587. const updateRanges = bufferAttribute.updateRanges;
  56588. if ( updateRanges.length === 0 ) {
  56589. // Not using update ranges
  56590. device.queue.writeBuffer(
  56591. buffer,
  56592. 0,
  56593. array,
  56594. 0
  56595. );
  56596. } else {
  56597. const isTyped = isTypedArray( array );
  56598. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  56599. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  56600. const range = updateRanges[ i ];
  56601. let dataOffset, size;
  56602. if ( bufferData._force3to4BytesAlignment === true ) {
  56603. const vertexStart = Math.floor( range.start / 3 );
  56604. const vertexCount = Math.ceil( range.count / 3 );
  56605. dataOffset = vertexStart * 4 * byteOffsetFactor;
  56606. size = vertexCount * 4 * byteOffsetFactor;
  56607. } else {
  56608. dataOffset = range.start * byteOffsetFactor;
  56609. size = range.count * byteOffsetFactor;
  56610. }
  56611. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  56612. device.queue.writeBuffer(
  56613. buffer,
  56614. bufferOffset,
  56615. array,
  56616. dataOffset,
  56617. size
  56618. );
  56619. }
  56620. bufferAttribute.clearUpdateRanges();
  56621. }
  56622. }
  56623. /**
  56624. * This method creates the vertex buffer layout data which are
  56625. * require when creating a render pipeline for the given render object.
  56626. *
  56627. * @param {RenderObject} renderObject - The render object.
  56628. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  56629. */
  56630. createShaderVertexBuffers( renderObject ) {
  56631. const attributes = renderObject.getAttributes();
  56632. const vertexBuffers = new Map();
  56633. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  56634. const geometryAttribute = attributes[ slot ];
  56635. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  56636. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  56637. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  56638. if ( vertexBufferLayout === undefined ) {
  56639. let arrayStride, stepMode;
  56640. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  56641. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  56642. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  56643. } else {
  56644. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  56645. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  56646. }
  56647. // patch for INT16 and UINT16
  56648. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  56649. arrayStride = 4;
  56650. }
  56651. vertexBufferLayout = {
  56652. arrayStride,
  56653. attributes: [],
  56654. stepMode
  56655. };
  56656. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  56657. }
  56658. const format = this._getVertexFormat( geometryAttribute );
  56659. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  56660. vertexBufferLayout.attributes.push( {
  56661. shaderLocation: slot,
  56662. offset,
  56663. format
  56664. } );
  56665. }
  56666. return Array.from( vertexBuffers.values() );
  56667. }
  56668. /**
  56669. * Destroys the GPU buffer of the given buffer attribute.
  56670. *
  56671. * @param {BufferAttribute} attribute - The buffer attribute.
  56672. */
  56673. destroyAttribute( attribute ) {
  56674. const backend = this.backend;
  56675. const data = backend.get( this._getBufferAttribute( attribute ) );
  56676. data.buffer.destroy();
  56677. backend.delete( attribute );
  56678. }
  56679. /**
  56680. * This method performs a readback operation by moving buffer data from
  56681. * a storage buffer attribute from the GPU to the CPU. ReadbackBuffer can
  56682. * be used to retain and reuse handles to the intermediate buffers and prevent
  56683. * new allocation.
  56684. *
  56685. * @async
  56686. * @param {BufferAttribute} attribute - The storage buffer attribute to read frm.
  56687. * @param {number} count - The offset from which to start reading the
  56688. * @param {number} offset - The storage buffer attribute.
  56689. * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute.
  56690. * @return {Promise<ArrayBuffer|ReadbackBuffer>} A promise that resolves with the buffer data when the data are ready.
  56691. */
  56692. async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) {
  56693. const backend = this.backend;
  56694. const device = backend.device;
  56695. const data = backend.get( this._getBufferAttribute( attribute ) );
  56696. const bufferGPU = data.buffer;
  56697. const byteLength = count === -1 ? bufferGPU.size - offset : count;
  56698. let readBufferGPU;
  56699. if ( target !== null && target.isReadbackBuffer ) {
  56700. const readbackInfo = backend.get( target );
  56701. if ( target._mapped === true ) {
  56702. throw new Error( 'WebGPURenderer: ReadbackBuffer must be released before being used again.' );
  56703. }
  56704. target._mapped = true;
  56705. // initialize the GPU-side read copy buffer if it is not present
  56706. if ( readbackInfo.readBufferGPU === undefined ) {
  56707. _bufferDescriptor$3.label = `${ target.name }_readback`;
  56708. _bufferDescriptor$3.size = target.maxByteLength;
  56709. _bufferDescriptor$3.usage = GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ;
  56710. readBufferGPU = device.createBuffer( _bufferDescriptor$3 );
  56711. _bufferDescriptor$3.reset();
  56712. // release / dispose
  56713. const releaseCallback = () => {
  56714. target.buffer = null;
  56715. target._mapped = false;
  56716. readBufferGPU.unmap();
  56717. };
  56718. const disposeCallback = () => {
  56719. target.buffer = null;
  56720. target._mapped = false;
  56721. readBufferGPU.destroy();
  56722. backend.delete( target );
  56723. target.removeEventListener( 'release', releaseCallback );
  56724. target.removeEventListener( 'dispose', disposeCallback );
  56725. };
  56726. target.addEventListener( 'release', releaseCallback );
  56727. target.addEventListener( 'dispose', disposeCallback );
  56728. // register
  56729. readbackInfo.readBufferGPU = readBufferGPU;
  56730. } else {
  56731. readBufferGPU = readbackInfo.readBufferGPU;
  56732. }
  56733. } else {
  56734. // create a new temp buffer for array buffers otherwise
  56735. _bufferDescriptor$3.label = `${ attribute.name }_readback`;
  56736. _bufferDescriptor$3.size = byteLength;
  56737. _bufferDescriptor$3.usage = GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ;
  56738. readBufferGPU = device.createBuffer( _bufferDescriptor$3 );
  56739. _bufferDescriptor$3.reset();
  56740. }
  56741. // copy the data
  56742. _commandEncoderDescriptor$2.label = `readback_encoder_${ attribute.name }`;
  56743. const cmdEncoder = device.createCommandEncoder( _commandEncoderDescriptor$2 );
  56744. _commandEncoderDescriptor$2.reset();
  56745. cmdEncoder.copyBufferToBuffer(
  56746. bufferGPU,
  56747. offset,
  56748. readBufferGPU,
  56749. 0,
  56750. byteLength,
  56751. );
  56752. const gpuCommands = cmdEncoder.finish();
  56753. submit( device, gpuCommands );
  56754. // map the data to the CPU
  56755. await readBufferGPU.mapAsync( GPUMapMode.READ, 0, byteLength );
  56756. if ( target === null ) {
  56757. // return a new array buffer and clean up the gpu handles
  56758. const arrayBuffer = readBufferGPU.getMappedRange( 0, byteLength );
  56759. const result = arrayBuffer.slice();
  56760. readBufferGPU.destroy();
  56761. return result;
  56762. } else if ( target.isReadbackBuffer ) {
  56763. // assign the data to the read back handle
  56764. target.buffer = readBufferGPU.getMappedRange( 0, byteLength );
  56765. return target;
  56766. } else {
  56767. // copy the data into the target array buffer
  56768. const arrayBuffer = readBufferGPU.getMappedRange( 0, byteLength );
  56769. new Uint8Array( target ).set( new Uint8Array( arrayBuffer ) );
  56770. readBufferGPU.destroy();
  56771. return target;
  56772. }
  56773. }
  56774. /**
  56775. * Returns the vertex format of the given buffer attribute.
  56776. *
  56777. * @private
  56778. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  56779. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  56780. */
  56781. _getVertexFormat( geometryAttribute ) {
  56782. const { itemSize, normalized } = geometryAttribute;
  56783. const ArrayType = geometryAttribute.array.constructor;
  56784. const AttributeType = geometryAttribute.constructor;
  56785. let format;
  56786. if ( itemSize === 1 ) {
  56787. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  56788. } else {
  56789. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  56790. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  56791. if ( prefix ) {
  56792. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  56793. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  56794. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  56795. if ( paddedItemSize % 1 ) {
  56796. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  56797. }
  56798. format = `${prefix}x${paddedItemSize}`;
  56799. }
  56800. }
  56801. if ( ! format ) {
  56802. error( 'WebGPUAttributeUtils: Vertex format not supported yet.' );
  56803. }
  56804. return format;
  56805. }
  56806. /**
  56807. * Utility method for handling interleaved buffer attributes correctly.
  56808. * To process them, their `InterleavedBuffer` is returned.
  56809. *
  56810. * @private
  56811. * @param {BufferAttribute} attribute - The attribute.
  56812. * @return {BufferAttribute|InterleavedBuffer}
  56813. */
  56814. _getBufferAttribute( attribute ) {
  56815. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  56816. return attribute;
  56817. }
  56818. }
  56819. const _bindGroupDescriptor = new GPUBindGroupDescriptor();
  56820. const _bufferDescriptor$2 = new GPUBufferDescriptor();
  56821. const _viewDescriptor$1 = new GPUTextureViewDescriptor();
  56822. /**
  56823. * Class representing a WebGPU bind group layout.
  56824. *
  56825. * @private
  56826. */
  56827. class BindGroupLayout {
  56828. /**
  56829. * Constructs a new layout.
  56830. *
  56831. * @param {GPUBindGroupLayout} layoutGPU - A GPU Bind Group Layout.
  56832. */
  56833. constructor( layoutGPU ) {
  56834. /**
  56835. * The current GPUBindGroupLayout.
  56836. *
  56837. * @type {GPUBindGroupLayout}
  56838. */
  56839. this.layoutGPU = layoutGPU;
  56840. /**
  56841. * The number of bind groups that use this layout.
  56842. *
  56843. * @type {number}
  56844. */
  56845. this.usedTimes = 0;
  56846. }
  56847. }
  56848. /**
  56849. * A WebGPU backend utility module for managing bindings.
  56850. *
  56851. * When reading the documentation it's helpful to keep in mind that
  56852. * all class definitions starting with 'GPU*' are modules from the
  56853. * WebGPU API. So for example `BindGroup` is a class from the engine
  56854. * whereas `GPUBindGroup` is a class from WebGPU.
  56855. *
  56856. * @private
  56857. */
  56858. class WebGPUBindingUtils {
  56859. /**
  56860. * Constructs a new utility object.
  56861. *
  56862. * @param {WebGPUBackend} backend - The WebGPU backend.
  56863. */
  56864. constructor( backend ) {
  56865. /**
  56866. * A reference to the WebGPU backend.
  56867. *
  56868. * @type {WebGPUBackend}
  56869. */
  56870. this.backend = backend;
  56871. /**
  56872. * A cache that maps combinations of layout entries to existing bind group layouts.
  56873. *
  56874. * @private
  56875. * @type {Map<string, BindGroupLayout>}
  56876. */
  56877. this._bindGroupLayoutCache = new Map();
  56878. }
  56879. /**
  56880. * Creates a GPU bind group layout for the given bind group.
  56881. *
  56882. * @param {BindGroup} bindGroup - The bind group.
  56883. * @return {GPUBindGroupLayout} The GPU bind group layout.
  56884. */
  56885. createBindingsLayout( bindGroup ) {
  56886. const backend = this.backend;
  56887. const device = backend.device;
  56888. const bindingsData = backend.get( bindGroup );
  56889. // check if the the bind group already has a layout
  56890. if ( bindingsData.layout ) {
  56891. return bindingsData.layout.layoutGPU;
  56892. }
  56893. // if not, assing one
  56894. const entries = this._createLayoutEntries( bindGroup );
  56895. const bindGroupLayoutKey = hashString( JSON.stringify( entries ) );
  56896. // try to find an existing layout in the cache
  56897. let bindGroupLayout = this._bindGroupLayoutCache.get( bindGroupLayoutKey );
  56898. // if not create a new one
  56899. if ( bindGroupLayout === undefined ) {
  56900. bindGroupLayout = new BindGroupLayout( device.createBindGroupLayout( { entries } ) );
  56901. this._bindGroupLayoutCache.set( bindGroupLayoutKey, bindGroupLayout );
  56902. }
  56903. bindGroupLayout.usedTimes ++;
  56904. bindingsData.layout = bindGroupLayout;
  56905. bindingsData.layoutKey = bindGroupLayoutKey;
  56906. return bindGroupLayout.layoutGPU;
  56907. }
  56908. /**
  56909. * Creates bindings from the given bind group definition.
  56910. *
  56911. * @param {BindGroup} bindGroup - The bind group.
  56912. * @param {Array<BindGroup>} bindings - Array of bind groups.
  56913. * @param {number} cacheIndex - The cache index.
  56914. * @param {number} version - The version.
  56915. */
  56916. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  56917. const { backend } = this;
  56918. const bindingsData = backend.get( bindGroup );
  56919. // setup (static) binding layout and (dynamic) binding group
  56920. const bindLayoutGPU = this.createBindingsLayout( bindGroup );
  56921. let bindGroupGPU;
  56922. if ( cacheIndex > 0 ) {
  56923. if ( bindingsData.groups === undefined ) {
  56924. bindingsData.groups = [];
  56925. bindingsData.versions = [];
  56926. }
  56927. if ( bindingsData.versions[ cacheIndex ] === version ) {
  56928. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  56929. }
  56930. }
  56931. if ( bindGroupGPU === undefined ) {
  56932. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  56933. if ( cacheIndex > 0 ) {
  56934. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  56935. bindingsData.versions[ cacheIndex ] = version;
  56936. }
  56937. }
  56938. bindingsData.group = bindGroupGPU;
  56939. }
  56940. /**
  56941. * Updates a buffer binding.
  56942. *
  56943. * @param {Buffer} binding - The buffer binding to update.
  56944. */
  56945. updateBinding( binding ) {
  56946. const backend = this.backend;
  56947. const device = backend.device;
  56948. const array = binding.buffer; // cpu
  56949. const buffer = backend.get( binding ).buffer; // gpu
  56950. const updateRanges = binding.updateRanges;
  56951. if ( updateRanges.length === 0 ) {
  56952. device.queue.writeBuffer(
  56953. buffer,
  56954. 0,
  56955. array,
  56956. 0
  56957. );
  56958. } else {
  56959. const isTyped = isTypedArray( array );
  56960. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  56961. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  56962. const range = updateRanges[ i ];
  56963. const dataOffset = range.start * byteOffsetFactor;
  56964. const size = range.count * byteOffsetFactor;
  56965. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  56966. device.queue.writeBuffer(
  56967. buffer,
  56968. bufferOffset,
  56969. array,
  56970. dataOffset,
  56971. size
  56972. );
  56973. }
  56974. }
  56975. }
  56976. /**
  56977. * Creates a GPU bind group for the camera index.
  56978. *
  56979. * @param {Uint32Array} data - The index data.
  56980. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  56981. * @return {GPUBindGroup} The GPU bind group.
  56982. */
  56983. createBindGroupIndex( data, layoutGPU ) {
  56984. const backend = this.backend;
  56985. const device = backend.device;
  56986. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  56987. const index = data[ 0 ];
  56988. _bufferDescriptor$2.label = 'bindingCameraIndex_' + index;
  56989. _bufferDescriptor$2.size = 16; // uint(4) * 4
  56990. _bufferDescriptor$2.usage = usage;
  56991. const buffer = device.createBuffer( _bufferDescriptor$2 );
  56992. _bufferDescriptor$2.reset();
  56993. device.queue.writeBuffer( buffer, 0, data, 0 );
  56994. _bindGroupDescriptor.label = 'bindGroupCameraIndex_' + index;
  56995. _bindGroupDescriptor.layout = layoutGPU;
  56996. _bindGroupDescriptor.entries.push( { binding: 0, resource: { buffer } } );
  56997. const bindGroup = device.createBindGroup( _bindGroupDescriptor );
  56998. _bindGroupDescriptor.reset();
  56999. return bindGroup;
  57000. }
  57001. /**
  57002. * Creates a GPU bind group for the given bind group and GPU layout.
  57003. *
  57004. * @param {BindGroup} bindGroup - The bind group.
  57005. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  57006. * @return {GPUBindGroup} The GPU bind group.
  57007. */
  57008. createBindGroup( bindGroup, layoutGPU ) {
  57009. const backend = this.backend;
  57010. const device = backend.device;
  57011. let bindingPoint = 0;
  57012. _bindGroupDescriptor.label = 'bindGroup_' + bindGroup.name;
  57013. _bindGroupDescriptor.layout = layoutGPU;
  57014. for ( const binding of bindGroup.bindings ) {
  57015. if ( binding.isUniformBuffer ) {
  57016. const bindingData = backend.get( binding );
  57017. _bindGroupDescriptor.entries.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  57018. } else if ( binding.isStorageBuffer ) {
  57019. const buffer = backend.get( binding.attribute ).buffer;
  57020. _bindGroupDescriptor.entries.push( { binding: bindingPoint, resource: { buffer: buffer } } );
  57021. } else if ( binding.isSampledTexture ) {
  57022. const textureData = backend.get( binding.texture );
  57023. let resourceGPU;
  57024. if ( textureData.externalTexture !== undefined ) {
  57025. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  57026. } else {
  57027. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  57028. const baseMipLevel = binding.store ? binding.mipLevel : 0;
  57029. let propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }`;
  57030. if ( textureData.texture.depthOrArrayLayers > 1 ) {
  57031. propertyName += `-${ textureData.texture.depthOrArrayLayers }`;
  57032. }
  57033. propertyName += `-${ mipLevelCount }-${ baseMipLevel }`;
  57034. resourceGPU = textureData[ propertyName ];
  57035. if ( resourceGPU === undefined ) {
  57036. const aspectGPU = GPUTextureAspect.All;
  57037. let dimensionViewGPU;
  57038. if ( binding.isSampledCubeTexture ) {
  57039. dimensionViewGPU = GPUTextureViewDimension.Cube;
  57040. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  57041. // Prefer the texture's actual array flag over the cached 3D binding type.
  57042. // Layered render targets can become array textures after shader compilation.
  57043. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  57044. } else if ( binding.isSampledTexture3D ) {
  57045. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  57046. } else {
  57047. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  57048. }
  57049. _viewDescriptor$1.aspect = aspectGPU;
  57050. _viewDescriptor$1.dimension = dimensionViewGPU;
  57051. _viewDescriptor$1.mipLevelCount = mipLevelCount;
  57052. _viewDescriptor$1.baseMipLevel = baseMipLevel;
  57053. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( _viewDescriptor$1 );
  57054. _viewDescriptor$1.reset();
  57055. }
  57056. }
  57057. _bindGroupDescriptor.entries.push( { binding: bindingPoint, resource: resourceGPU } );
  57058. } else if ( binding.isSampler ) {
  57059. const textureGPU = backend.get( binding.texture );
  57060. _bindGroupDescriptor.entries.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  57061. }
  57062. bindingPoint ++;
  57063. }
  57064. const bindGroupGPU = device.createBindGroup( _bindGroupDescriptor );
  57065. _bindGroupDescriptor.reset();
  57066. return bindGroupGPU;
  57067. }
  57068. /**
  57069. * Creates a GPU bind group layout entries for the given bind group.
  57070. *
  57071. * @private
  57072. * @param {BindGroup} bindGroup - The bind group.
  57073. * @return {Array<GPUBindGroupLayoutEntry>} The GPU bind group layout entries.
  57074. */
  57075. _createLayoutEntries( bindGroup ) {
  57076. const entries = [];
  57077. let index = 0;
  57078. for ( const binding of bindGroup.bindings ) {
  57079. const backend = this.backend;
  57080. const bindingGPU = {
  57081. binding: index,
  57082. visibility: binding.visibility
  57083. };
  57084. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  57085. const buffer = {}; // GPUBufferBindingLayout
  57086. if ( binding.isStorageBuffer ) {
  57087. if ( binding.visibility & GPUShaderStage.COMPUTE ) {
  57088. // compute
  57089. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  57090. buffer.type = GPUBufferBindingType.Storage;
  57091. } else {
  57092. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  57093. }
  57094. } else {
  57095. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  57096. }
  57097. }
  57098. bindingGPU.buffer = buffer;
  57099. } else if ( binding.isSampledTexture && binding.store ) {
  57100. const storageTexture = {}; // GPUStorageTextureBindingLayout
  57101. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  57102. const access = binding.access;
  57103. if ( access === NodeAccess.READ_WRITE ) {
  57104. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  57105. } else if ( access === NodeAccess.WRITE_ONLY ) {
  57106. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  57107. } else {
  57108. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  57109. }
  57110. if ( binding.texture.isArrayTexture ) {
  57111. storageTexture.viewDimension = GPUTextureViewDimension.TwoDArray;
  57112. } else if ( binding.texture.is3DTexture ) {
  57113. storageTexture.viewDimension = GPUTextureViewDimension.ThreeD;
  57114. }
  57115. bindingGPU.storageTexture = storageTexture;
  57116. } else if ( binding.isSampledTexture ) {
  57117. const texture = {}; // GPUTextureBindingLayout
  57118. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  57119. if ( primarySamples > 1 ) {
  57120. texture.multisampled = true;
  57121. if ( ! binding.texture.isDepthTexture ) {
  57122. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  57123. }
  57124. }
  57125. if ( binding.texture.isDepthTexture ) {
  57126. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  57127. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  57128. } else {
  57129. texture.sampleType = GPUTextureSampleType.Depth;
  57130. }
  57131. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture || binding.texture.isStorageTexture ) {
  57132. const type = binding.texture.type;
  57133. if ( type === IntType ) {
  57134. texture.sampleType = GPUTextureSampleType.SInt;
  57135. } else if ( type === UnsignedIntType ) {
  57136. texture.sampleType = GPUTextureSampleType.UInt;
  57137. } else if ( type === FloatType ) {
  57138. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  57139. texture.sampleType = GPUTextureSampleType.Float;
  57140. } else {
  57141. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  57142. }
  57143. }
  57144. }
  57145. if ( binding.isSampledCubeTexture ) {
  57146. texture.viewDimension = GPUTextureViewDimension.Cube;
  57147. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  57148. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  57149. } else if ( binding.isSampledTexture3D ) {
  57150. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  57151. }
  57152. bindingGPU.texture = texture;
  57153. } else if ( binding.isSampler ) {
  57154. const sampler = {}; // GPUSamplerBindingLayout
  57155. if ( binding.texture.isDepthTexture ) {
  57156. if ( binding.texture.compareFunction !== null && binding.textureNode.compareNode !== null && backend.hasCompatibility( Compatibility.TEXTURE_COMPARE ) ) {
  57157. sampler.type = GPUSamplerBindingType.Comparison;
  57158. } else {
  57159. // Depth textures without compare must use non-filtering sampler
  57160. sampler.type = GPUSamplerBindingType.NonFiltering;
  57161. }
  57162. }
  57163. bindingGPU.sampler = sampler;
  57164. } else {
  57165. error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  57166. }
  57167. entries.push( bindingGPU );
  57168. index ++;
  57169. }
  57170. return entries;
  57171. }
  57172. /**
  57173. * Delete the data associated with a bind group.
  57174. *
  57175. * @param {BindGroup} bindGroup - The bind group.
  57176. */
  57177. deleteBindGroupData( bindGroup ) {
  57178. const { backend } = this;
  57179. const bindingsData = backend.get( bindGroup );
  57180. if ( bindingsData.layout ) {
  57181. bindingsData.layout.usedTimes --;
  57182. if ( bindingsData.layout.usedTimes === 0 ) {
  57183. this._bindGroupLayoutCache.delete( bindingsData.layoutKey );
  57184. }
  57185. bindingsData.layout = undefined;
  57186. bindingsData.layoutKey = undefined;
  57187. }
  57188. }
  57189. /**
  57190. * Frees internal resources.
  57191. */
  57192. dispose() {
  57193. this._bindGroupLayoutCache.clear();
  57194. }
  57195. }
  57196. /**
  57197. * A WebGPU backend utility module for managing the device's capabilities.
  57198. *
  57199. * @private
  57200. */
  57201. class WebGPUCapabilities {
  57202. /**
  57203. * Constructs a new utility object.
  57204. *
  57205. * @param {WebGPUBackend} backend - The WebGPU backend.
  57206. */
  57207. constructor( backend ) {
  57208. /**
  57209. * A reference to the WebGPU backend.
  57210. *
  57211. * @type {WebGPUBackend}
  57212. */
  57213. this.backend = backend;
  57214. }
  57215. /**
  57216. * Returns the maximum anisotropy texture filtering value.
  57217. *
  57218. * @return {number} The maximum anisotropy texture filtering value.
  57219. */
  57220. getMaxAnisotropy() {
  57221. return 16;
  57222. }
  57223. /**
  57224. * Returns the maximum number of bytes available for uniform buffers.
  57225. *
  57226. * @return {number} The maximum number of bytes available for uniform buffers.
  57227. */
  57228. getUniformBufferLimit() {
  57229. return this.backend.device.limits.maxUniformBufferBindingSize;
  57230. }
  57231. }
  57232. /**
  57233. * Reusable descriptor for `GPUDevice.createComputePipeline()`.
  57234. *
  57235. * @private
  57236. */
  57237. class GPUComputePipelineDescriptor {
  57238. constructor() {
  57239. /**
  57240. * The label of the compute pipeline.
  57241. *
  57242. * @type {string}
  57243. */
  57244. this.label = '';
  57245. /**
  57246. * The pipeline layout the pipeline conforms to, or `'auto'`.
  57247. *
  57248. * @type {?GPUPipelineLayout|string}
  57249. * @default null
  57250. */
  57251. this.layout = null;
  57252. /**
  57253. * The programmable compute stage.
  57254. *
  57255. * @type {?Object}
  57256. * @default null
  57257. */
  57258. this.compute = null;
  57259. }
  57260. /**
  57261. * Resets the descriptor to its default state.
  57262. */
  57263. reset() {
  57264. this.label = '';
  57265. this.layout = null;
  57266. this.compute = null;
  57267. }
  57268. }
  57269. /**
  57270. * Reusable descriptor for `GPUDevice.createPipelineLayout()`.
  57271. *
  57272. * @private
  57273. */
  57274. class GPUPipelineLayoutDescriptor {
  57275. constructor() {
  57276. /**
  57277. * The label of the pipeline layout.
  57278. *
  57279. * @type {string}
  57280. */
  57281. this.label = '';
  57282. /**
  57283. * The set of bind group layouts the pipeline layout describes.
  57284. *
  57285. * @type {?Array<?GPUBindGroupLayout>}
  57286. * @default null
  57287. */
  57288. this.bindGroupLayouts = null;
  57289. }
  57290. /**
  57291. * Resets the descriptor to its default state.
  57292. */
  57293. reset() {
  57294. this.label = '';
  57295. this.bindGroupLayouts = null;
  57296. }
  57297. }
  57298. const _computePipelineDescriptor = new GPUComputePipelineDescriptor();
  57299. const _pipelineLayoutDescriptor = new GPUPipelineLayoutDescriptor();
  57300. const _renderBundleEncoderDescriptor = new GPURenderBundleEncoderDescriptor();
  57301. const _renderPipelineDescriptor = new GPURenderPipelineDescriptor();
  57302. /**
  57303. * A WebGPU backend utility module for managing pipelines.
  57304. *
  57305. * @private
  57306. */
  57307. class WebGPUPipelineUtils {
  57308. /**
  57309. * Constructs a new utility object.
  57310. *
  57311. * @param {WebGPUBackend} backend - The WebGPU backend.
  57312. */
  57313. constructor( backend ) {
  57314. /**
  57315. * A reference to the WebGPU backend.
  57316. *
  57317. * @type {WebGPUBackend}
  57318. */
  57319. this.backend = backend;
  57320. /**
  57321. * A Weak Map that tracks the active pipeline for render or compute passes.
  57322. *
  57323. * @private
  57324. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  57325. */
  57326. this._activePipelines = new WeakMap();
  57327. }
  57328. /**
  57329. * Sets the given pipeline for the given pass. The method makes sure to only set the
  57330. * pipeline when necessary.
  57331. *
  57332. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  57333. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  57334. */
  57335. setPipeline( pass, pipeline ) {
  57336. const currentPipeline = this._activePipelines.get( pass );
  57337. if ( currentPipeline !== pipeline ) {
  57338. pass.setPipeline( pipeline );
  57339. this._activePipelines.set( pass, pipeline );
  57340. }
  57341. }
  57342. /**
  57343. * Returns the sample count derived from the given render context.
  57344. *
  57345. * @private
  57346. * @param {RenderContext} renderContext - The render context.
  57347. * @return {number} The sample count.
  57348. */
  57349. _getSampleCount( renderContext ) {
  57350. return this.backend.utils.getSampleCountRenderContext( renderContext );
  57351. }
  57352. /**
  57353. * Creates a render pipeline for the given render object.
  57354. *
  57355. * @param {RenderObject} renderObject - The render object.
  57356. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  57357. */
  57358. createRenderPipeline( renderObject, promises ) {
  57359. const { object, material, geometry, pipeline } = renderObject;
  57360. const { vertexProgram, fragmentProgram } = pipeline;
  57361. const backend = this.backend;
  57362. const device = backend.device;
  57363. const utils = backend.utils;
  57364. const pipelineData = backend.get( pipeline );
  57365. // bind group layouts
  57366. const bindGroupLayouts = [];
  57367. for ( const bindGroup of renderObject.getBindings() ) {
  57368. const bindingsData = backend.get( bindGroup );
  57369. const { layoutGPU } = bindingsData.layout;
  57370. bindGroupLayouts.push( layoutGPU );
  57371. }
  57372. // vertex buffers
  57373. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  57374. // material blending
  57375. let materialBlending;
  57376. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  57377. materialBlending = this._getBlending( material );
  57378. }
  57379. // stencil
  57380. let stencilFront = {};
  57381. if ( material.stencilWrite === true ) {
  57382. stencilFront = {
  57383. compare: this._getStencilCompare( material ),
  57384. failOp: this._getStencilOperation( material.stencilFail ),
  57385. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  57386. passOp: this._getStencilOperation( material.stencilZPass )
  57387. };
  57388. }
  57389. const colorWriteMask = this._getColorWriteMask( material );
  57390. const targets = [];
  57391. if ( renderObject.context.textures !== null ) {
  57392. const textures = renderObject.context.textures;
  57393. const mrt = renderObject.context.mrt;
  57394. for ( let i = 0; i < textures.length; i ++ ) {
  57395. const texture = textures[ i ];
  57396. const colorFormat = utils.getTextureFormatGPU( texture );
  57397. // mrt blending
  57398. let blending;
  57399. if ( mrt !== null ) {
  57400. if ( this.backend.compatibilityMode !== true ) {
  57401. const blendMode = mrt.getBlendMode( texture.name );
  57402. if ( blendMode.blending === MaterialBlending ) {
  57403. blending = materialBlending;
  57404. } else if ( blendMode.blending !== NoBlending ) {
  57405. blending = this._getBlending( blendMode );
  57406. }
  57407. } else {
  57408. 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.' );
  57409. blending = materialBlending;
  57410. }
  57411. } else {
  57412. blending = materialBlending;
  57413. }
  57414. targets.push( {
  57415. format: colorFormat,
  57416. blend: blending,
  57417. writeMask: colorWriteMask
  57418. } );
  57419. }
  57420. } else {
  57421. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  57422. targets.push( {
  57423. format: colorFormat,
  57424. blend: materialBlending,
  57425. writeMask: colorWriteMask
  57426. } );
  57427. }
  57428. const vertexModule = backend.get( vertexProgram ).module;
  57429. const fragmentModule = backend.get( fragmentProgram ).module;
  57430. const primitiveState = this._getPrimitiveState( object, geometry, material );
  57431. const depthCompare = this._getDepthCompare( material );
  57432. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  57433. const sampleCount = this._getSampleCount( renderObject.context );
  57434. _pipelineLayoutDescriptor.bindGroupLayouts = bindGroupLayouts;
  57435. const pipelineLayout = device.createPipelineLayout( _pipelineLayoutDescriptor );
  57436. _pipelineLayoutDescriptor.reset();
  57437. _renderPipelineDescriptor.label = `renderPipeline_${ material.name || material.type }_${ material.id }`;
  57438. _renderPipelineDescriptor.vertex = Object.assign( {}, vertexModule, { buffers: vertexBuffers } );
  57439. _renderPipelineDescriptor.fragment = Object.assign( {}, fragmentModule, { targets } );
  57440. _renderPipelineDescriptor.primitive = primitiveState;
  57441. _renderPipelineDescriptor.multisample.count = sampleCount;
  57442. _renderPipelineDescriptor.multisample.alphaToCoverageEnabled = material.alphaToCoverage && sampleCount > 1;
  57443. _renderPipelineDescriptor.layout = pipelineLayout;
  57444. const depthStencil = {};
  57445. const renderDepth = renderObject.context.depth;
  57446. const renderStencil = renderObject.context.stencil;
  57447. if ( renderDepth === true || renderStencil === true ) {
  57448. if ( renderDepth === true ) {
  57449. depthStencil.format = depthStencilFormat;
  57450. depthStencil.depthWriteEnabled = material.depthWrite;
  57451. depthStencil.depthCompare = depthCompare;
  57452. }
  57453. if ( renderStencil === true ) {
  57454. depthStencil.stencilFront = stencilFront;
  57455. depthStencil.stencilBack = stencilFront; // apply the same stencil ops to both faces, matching gl.stencilOp() which is not face-separated
  57456. depthStencil.stencilReadMask = material.stencilFuncMask;
  57457. depthStencil.stencilWriteMask = material.stencilWriteMask;
  57458. }
  57459. if ( material.polygonOffset === true && ( primitiveState.topology === GPUPrimitiveTopology.TriangleList ) ) {
  57460. depthStencil.depthBias = material.polygonOffsetUnits;
  57461. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  57462. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  57463. }
  57464. _renderPipelineDescriptor.depthStencil = depthStencil;
  57465. }
  57466. // create pipeline
  57467. device.pushErrorScope( 'validation' );
  57468. const stages = [
  57469. { program: vertexProgram, module: vertexModule.module },
  57470. { program: fragmentProgram, module: fragmentModule.module }
  57471. ];
  57472. const pipelineLabel = _renderPipelineDescriptor.label;
  57473. if ( promises === null ) {
  57474. pipelineData.pipeline = device.createRenderPipeline( _renderPipelineDescriptor );
  57475. _renderPipelineDescriptor.reset();
  57476. device.popErrorScope().then( ( err ) => {
  57477. if ( err !== null ) {
  57478. pipelineData.error = true;
  57479. error( `WebGPURenderer: Render pipeline creation failed (${ pipelineLabel }): ${ err.message }` );
  57480. this._reportShaderDiagnostics( stages, pipelineLabel );
  57481. }
  57482. } );
  57483. } else {
  57484. const p = new Promise( async ( resolve /*, reject*/ ) => {
  57485. try {
  57486. let asyncError = null;
  57487. try {
  57488. pipelineData.pipeline = await device.createRenderPipelineAsync( _renderPipelineDescriptor );
  57489. } catch ( err ) {
  57490. asyncError = err;
  57491. }
  57492. const errorScope = await device.popErrorScope();
  57493. if ( errorScope !== null || asyncError !== null ) {
  57494. pipelineData.error = true;
  57495. const reason = ( errorScope && errorScope.message ) || ( asyncError && asyncError.message ) || 'unknown';
  57496. error( `WebGPURenderer: Async render pipeline creation failed (${ pipelineLabel }): ${ reason }` );
  57497. await this._reportShaderDiagnostics( stages, pipelineLabel );
  57498. }
  57499. } finally {
  57500. _renderPipelineDescriptor.reset();
  57501. // Guarantee resolution so `compileAsync`'s Promise.all cannot hang on an
  57502. // unexpected throw from any await above.
  57503. resolve();
  57504. }
  57505. } );
  57506. promises.push( p );
  57507. }
  57508. }
  57509. /**
  57510. * Creates GPU render bundle encoder for the given render context.
  57511. *
  57512. * @param {RenderContext} renderContext - The render context.
  57513. * @param {?string} [label='renderBundleEncoder'] - The label.
  57514. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  57515. */
  57516. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  57517. const backend = this.backend;
  57518. const { utils, device } = backend;
  57519. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  57520. const colorFormats = utils.getCurrentColorFormats( renderContext );
  57521. const sampleCount = this._getSampleCount( renderContext );
  57522. _renderBundleEncoderDescriptor.label = label;
  57523. _renderBundleEncoderDescriptor.colorFormats = colorFormats;
  57524. _renderBundleEncoderDescriptor.depthStencilFormat = depthStencilFormat;
  57525. _renderBundleEncoderDescriptor.sampleCount = sampleCount;
  57526. const bundleEncoder = device.createRenderBundleEncoder( _renderBundleEncoderDescriptor );
  57527. _renderBundleEncoderDescriptor.reset();
  57528. return bundleEncoder;
  57529. }
  57530. /**
  57531. * Creates a compute pipeline for the given compute node.
  57532. *
  57533. * @param {ComputePipeline} pipeline - The compute pipeline.
  57534. * @param {Array<BindGroup>} bindings - The bindings.
  57535. */
  57536. createComputePipeline( pipeline, bindings ) {
  57537. const backend = this.backend;
  57538. const device = backend.device;
  57539. const computeProgram = backend.get( pipeline.computeProgram ).module;
  57540. const pipelineGPU = backend.get( pipeline );
  57541. // bind group layouts
  57542. const bindGroupLayouts = [];
  57543. for ( const bindingsGroup of bindings ) {
  57544. const bindingsData = backend.get( bindingsGroup );
  57545. const { layoutGPU } = bindingsData.layout;
  57546. bindGroupLayouts.push( layoutGPU );
  57547. }
  57548. const computeStage = pipeline.computeProgram;
  57549. const pipelineLabel = `computePipeline_${ computeStage.stage }${ computeStage.name ? `_${ computeStage.name }` : '' }`;
  57550. device.pushErrorScope( 'validation' );
  57551. _pipelineLayoutDescriptor.bindGroupLayouts = bindGroupLayouts;
  57552. const pipelineLayout = device.createPipelineLayout( _pipelineLayoutDescriptor );
  57553. _pipelineLayoutDescriptor.reset();
  57554. _computePipelineDescriptor.label = pipelineLabel;
  57555. _computePipelineDescriptor.compute = computeProgram;
  57556. _computePipelineDescriptor.layout = pipelineLayout;
  57557. pipelineGPU.pipeline = device.createComputePipeline( _computePipelineDescriptor );
  57558. _computePipelineDescriptor.reset();
  57559. device.popErrorScope().then( ( err ) => {
  57560. if ( err !== null ) {
  57561. pipelineGPU.error = true;
  57562. error( `WebGPURenderer: Compute pipeline creation failed (${ pipelineLabel }): ${ err.message }` );
  57563. this._reportShaderDiagnostics( [ { program: computeStage, module: computeProgram.module } ], pipelineLabel );
  57564. }
  57565. } );
  57566. }
  57567. /**
  57568. * Reads line-accurate diagnostics from shader modules and logs them.
  57569. * Called from pipeline creation error paths to turn opaque validation
  57570. * failures into actionable WGSL feedback.
  57571. *
  57572. * @private
  57573. * @param {Array<{program: ProgrammableStage, module: GPUShaderModule}>} stages - Pairs of program + compiled shader module.
  57574. * @param {string} pipelineLabel - Label of the owning pipeline, used as log prefix.
  57575. * @return {Promise<void>}
  57576. */
  57577. async _reportShaderDiagnostics( stages, pipelineLabel ) {
  57578. for ( const { program, module } of stages ) {
  57579. const info = await module.getCompilationInfo();
  57580. if ( info.messages.length === 0 ) continue;
  57581. const sourceLines = program.code.split( '\n' );
  57582. for ( const msg of info.messages ) {
  57583. const location = msg.lineNum > 0
  57584. ? ` at line ${ msg.lineNum }${ msg.linePos > 0 ? `:${ msg.linePos }` : '' }`
  57585. : '';
  57586. const header = `WebGPURenderer [${ pipelineLabel } / ${ program.stage } ${ msg.type }]${ location }: ${ msg.message }`;
  57587. let excerpt = '';
  57588. if ( msg.lineNum > 0 && msg.lineNum <= sourceLines.length ) {
  57589. excerpt = `\n ${ sourceLines[ msg.lineNum - 1 ] }`;
  57590. if ( msg.linePos > 0 ) excerpt += `\n ${ ' '.repeat( msg.linePos - 1 ) }^`;
  57591. }
  57592. ( msg.type === 'error' ? error : warn )( header + excerpt );
  57593. }
  57594. }
  57595. }
  57596. /**
  57597. * Returns the blending state as a descriptor object required
  57598. * for the pipeline creation.
  57599. *
  57600. * @private
  57601. * @param {Material|BlendMode} object - The object containing blending information.
  57602. * @return {Object} The blending state.
  57603. */
  57604. _getBlending( object ) {
  57605. let color, alpha;
  57606. const blending = object.blending;
  57607. const blendSrc = object.blendSrc;
  57608. const blendDst = object.blendDst;
  57609. const blendEquation = object.blendEquation;
  57610. if ( blending === CustomBlending ) {
  57611. const blendSrcAlpha = object.blendSrcAlpha !== null ? object.blendSrcAlpha : blendSrc;
  57612. const blendDstAlpha = object.blendDstAlpha !== null ? object.blendDstAlpha : blendDst;
  57613. const blendEquationAlpha = object.blendEquationAlpha !== null ? object.blendEquationAlpha : blendEquation;
  57614. color = {
  57615. srcFactor: this._getBlendFactor( blendSrc ),
  57616. dstFactor: this._getBlendFactor( blendDst ),
  57617. operation: this._getBlendOperation( blendEquation )
  57618. };
  57619. alpha = {
  57620. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  57621. dstFactor: this._getBlendFactor( blendDstAlpha ),
  57622. operation: this._getBlendOperation( blendEquationAlpha )
  57623. };
  57624. } else {
  57625. const premultipliedAlpha = object.premultipliedAlpha;
  57626. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  57627. color = {
  57628. srcFactor: srcRGB,
  57629. dstFactor: dstRGB,
  57630. operation: GPUBlendOperation.Add
  57631. };
  57632. alpha = {
  57633. srcFactor: srcAlpha,
  57634. dstFactor: dstAlpha,
  57635. operation: GPUBlendOperation.Add
  57636. };
  57637. };
  57638. if ( premultipliedAlpha ) {
  57639. switch ( blending ) {
  57640. case NormalBlending:
  57641. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  57642. break;
  57643. case AdditiveBlending:
  57644. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  57645. break;
  57646. case SubtractiveBlending:
  57647. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  57648. break;
  57649. case MultiplyBlending:
  57650. setBlend( GPUBlendFactor.Dst, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.Zero, GPUBlendFactor.One );
  57651. break;
  57652. }
  57653. } else {
  57654. switch ( blending ) {
  57655. case NormalBlending:
  57656. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  57657. break;
  57658. case AdditiveBlending:
  57659. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  57660. break;
  57661. case SubtractiveBlending:
  57662. error( `WebGPURenderer: "SubtractiveBlending" requires "${ object.isMaterial ? 'material' : 'blendMode' }.premultipliedAlpha = true".` );
  57663. break;
  57664. case MultiplyBlending:
  57665. error( `WebGPURenderer: "MultiplyBlending" requires "${ object.isMaterial ? 'material' : 'blendMode' }.premultipliedAlpha = true".` );
  57666. break;
  57667. }
  57668. }
  57669. }
  57670. if ( color !== undefined && alpha !== undefined ) {
  57671. return { color, alpha };
  57672. } else {
  57673. error( 'WebGPURenderer: Invalid blending: ', blending );
  57674. }
  57675. }
  57676. /**
  57677. * Returns the GPU blend factor which is required for the pipeline creation.
  57678. *
  57679. * @private
  57680. * @param {number} blend - The blend factor as a three.js constant.
  57681. * @return {string} The GPU blend factor.
  57682. */
  57683. _getBlendFactor( blend ) {
  57684. let blendFactor;
  57685. switch ( blend ) {
  57686. case ZeroFactor:
  57687. blendFactor = GPUBlendFactor.Zero;
  57688. break;
  57689. case OneFactor:
  57690. blendFactor = GPUBlendFactor.One;
  57691. break;
  57692. case SrcColorFactor:
  57693. blendFactor = GPUBlendFactor.Src;
  57694. break;
  57695. case OneMinusSrcColorFactor:
  57696. blendFactor = GPUBlendFactor.OneMinusSrc;
  57697. break;
  57698. case SrcAlphaFactor:
  57699. blendFactor = GPUBlendFactor.SrcAlpha;
  57700. break;
  57701. case OneMinusSrcAlphaFactor:
  57702. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  57703. break;
  57704. case DstColorFactor:
  57705. blendFactor = GPUBlendFactor.Dst;
  57706. break;
  57707. case OneMinusDstColorFactor:
  57708. blendFactor = GPUBlendFactor.OneMinusDst;
  57709. break;
  57710. case DstAlphaFactor:
  57711. blendFactor = GPUBlendFactor.DstAlpha;
  57712. break;
  57713. case OneMinusDstAlphaFactor:
  57714. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  57715. break;
  57716. case SrcAlphaSaturateFactor:
  57717. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  57718. break;
  57719. case BlendColorFactor:
  57720. blendFactor = GPUBlendFactor.Constant;
  57721. break;
  57722. case OneMinusBlendColorFactor:
  57723. blendFactor = GPUBlendFactor.OneMinusConstant;
  57724. break;
  57725. default:
  57726. error( 'WebGPURenderer: Blend factor not supported.', blend );
  57727. }
  57728. return blendFactor;
  57729. }
  57730. /**
  57731. * Returns the GPU stencil compare function which is required for the pipeline creation.
  57732. *
  57733. * @private
  57734. * @param {Material} material - The material.
  57735. * @return {string} The GPU stencil compare function.
  57736. */
  57737. _getStencilCompare( material ) {
  57738. let stencilCompare;
  57739. const stencilFunc = material.stencilFunc;
  57740. switch ( stencilFunc ) {
  57741. case NeverStencilFunc:
  57742. stencilCompare = GPUCompareFunction.Never;
  57743. break;
  57744. case AlwaysStencilFunc:
  57745. stencilCompare = GPUCompareFunction.Always;
  57746. break;
  57747. case LessStencilFunc:
  57748. stencilCompare = GPUCompareFunction.Less;
  57749. break;
  57750. case LessEqualStencilFunc:
  57751. stencilCompare = GPUCompareFunction.LessEqual;
  57752. break;
  57753. case EqualStencilFunc:
  57754. stencilCompare = GPUCompareFunction.Equal;
  57755. break;
  57756. case GreaterEqualStencilFunc:
  57757. stencilCompare = GPUCompareFunction.GreaterEqual;
  57758. break;
  57759. case GreaterStencilFunc:
  57760. stencilCompare = GPUCompareFunction.Greater;
  57761. break;
  57762. case NotEqualStencilFunc:
  57763. stencilCompare = GPUCompareFunction.NotEqual;
  57764. break;
  57765. default:
  57766. error( 'WebGPURenderer: Invalid stencil function.', stencilFunc );
  57767. }
  57768. return stencilCompare;
  57769. }
  57770. /**
  57771. * Returns the GPU stencil operation which is required for the pipeline creation.
  57772. *
  57773. * @private
  57774. * @param {number} op - A three.js constant defining the stencil operation.
  57775. * @return {string} The GPU stencil operation.
  57776. */
  57777. _getStencilOperation( op ) {
  57778. let stencilOperation;
  57779. switch ( op ) {
  57780. case KeepStencilOp:
  57781. stencilOperation = GPUStencilOperation.Keep;
  57782. break;
  57783. case ZeroStencilOp:
  57784. stencilOperation = GPUStencilOperation.Zero;
  57785. break;
  57786. case ReplaceStencilOp:
  57787. stencilOperation = GPUStencilOperation.Replace;
  57788. break;
  57789. case InvertStencilOp:
  57790. stencilOperation = GPUStencilOperation.Invert;
  57791. break;
  57792. case IncrementStencilOp:
  57793. stencilOperation = GPUStencilOperation.IncrementClamp;
  57794. break;
  57795. case DecrementStencilOp:
  57796. stencilOperation = GPUStencilOperation.DecrementClamp;
  57797. break;
  57798. case IncrementWrapStencilOp:
  57799. stencilOperation = GPUStencilOperation.IncrementWrap;
  57800. break;
  57801. case DecrementWrapStencilOp:
  57802. stencilOperation = GPUStencilOperation.DecrementWrap;
  57803. break;
  57804. default:
  57805. error( 'WebGPURenderer: Invalid stencil operation.', stencilOperation );
  57806. }
  57807. return stencilOperation;
  57808. }
  57809. /**
  57810. * Returns the GPU blend operation which is required for the pipeline creation.
  57811. *
  57812. * @private
  57813. * @param {number} blendEquation - A three.js constant defining the blend equation.
  57814. * @return {string} The GPU blend operation.
  57815. */
  57816. _getBlendOperation( blendEquation ) {
  57817. let blendOperation;
  57818. switch ( blendEquation ) {
  57819. case AddEquation:
  57820. blendOperation = GPUBlendOperation.Add;
  57821. break;
  57822. case SubtractEquation:
  57823. blendOperation = GPUBlendOperation.Subtract;
  57824. break;
  57825. case ReverseSubtractEquation:
  57826. blendOperation = GPUBlendOperation.ReverseSubtract;
  57827. break;
  57828. case MinEquation:
  57829. blendOperation = GPUBlendOperation.Min;
  57830. break;
  57831. case MaxEquation:
  57832. blendOperation = GPUBlendOperation.Max;
  57833. break;
  57834. default:
  57835. error( 'WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  57836. }
  57837. return blendOperation;
  57838. }
  57839. /**
  57840. * Returns the primitive state as a descriptor object required
  57841. * for the pipeline creation.
  57842. *
  57843. * @private
  57844. * @param {Object3D} object - The 3D object.
  57845. * @param {BufferGeometry} geometry - The geometry.
  57846. * @param {Material} material - The material.
  57847. * @return {Object} The primitive state.
  57848. */
  57849. _getPrimitiveState( object, geometry, material ) {
  57850. const descriptor = {};
  57851. const utils = this.backend.utils;
  57852. //
  57853. descriptor.topology = utils.getPrimitiveTopology( object, material );
  57854. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  57855. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  57856. }
  57857. //
  57858. let flipSided = ( material.side === BackSide );
  57859. if ( object.isMesh && object.matrixWorld.determinant() < 0 ) flipSided = ! flipSided;
  57860. descriptor.frontFace = ( flipSided === true ) ? GPUFrontFace.CW : GPUFrontFace.CCW;
  57861. //
  57862. descriptor.cullMode = ( material.side === DoubleSide ) ? GPUCullMode.None : GPUCullMode.Back;
  57863. return descriptor;
  57864. }
  57865. /**
  57866. * Returns the GPU color write mask which is required for the pipeline creation.
  57867. *
  57868. * @private
  57869. * @param {Material} material - The material.
  57870. * @return {number} The GPU color write mask.
  57871. */
  57872. _getColorWriteMask( material ) {
  57873. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  57874. }
  57875. /**
  57876. * Returns the GPU depth compare function which is required for the pipeline creation.
  57877. *
  57878. * @private
  57879. * @param {Material} material - The material.
  57880. * @return {string} The GPU depth compare function.
  57881. */
  57882. _getDepthCompare( material ) {
  57883. let depthCompare;
  57884. if ( material.depthTest === false ) {
  57885. depthCompare = GPUCompareFunction.Always;
  57886. } else {
  57887. const depthFunc = ( this.backend.parameters.reversedDepthBuffer ) ? ReversedDepthFuncs[ material.depthFunc ] : material.depthFunc;
  57888. switch ( depthFunc ) {
  57889. case NeverDepth:
  57890. depthCompare = GPUCompareFunction.Never;
  57891. break;
  57892. case AlwaysDepth:
  57893. depthCompare = GPUCompareFunction.Always;
  57894. break;
  57895. case LessDepth:
  57896. depthCompare = GPUCompareFunction.Less;
  57897. break;
  57898. case LessEqualDepth:
  57899. depthCompare = GPUCompareFunction.LessEqual;
  57900. break;
  57901. case EqualDepth:
  57902. depthCompare = GPUCompareFunction.Equal;
  57903. break;
  57904. case GreaterEqualDepth:
  57905. depthCompare = GPUCompareFunction.GreaterEqual;
  57906. break;
  57907. case GreaterDepth:
  57908. depthCompare = GPUCompareFunction.Greater;
  57909. break;
  57910. case NotEqualDepth:
  57911. depthCompare = GPUCompareFunction.NotEqual;
  57912. break;
  57913. default:
  57914. error( 'WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  57915. }
  57916. }
  57917. return depthCompare;
  57918. }
  57919. }
  57920. /**
  57921. * Reusable descriptor for `GPUDevice.createQuerySet()`.
  57922. *
  57923. * @private
  57924. */
  57925. class GPUQuerySetDescriptor {
  57926. constructor() {
  57927. /**
  57928. * The label of the query set.
  57929. *
  57930. * @type {string}
  57931. */
  57932. this.label = '';
  57933. /**
  57934. * The type of queries managed by the set.
  57935. *
  57936. * @type {string|undefined}
  57937. */
  57938. this.type = undefined;
  57939. /**
  57940. * The number of queries managed by the set.
  57941. *
  57942. * @type {number}
  57943. * @default 0
  57944. */
  57945. this.count = 0;
  57946. }
  57947. /**
  57948. * Resets the descriptor to its default state.
  57949. */
  57950. reset() {
  57951. this.label = '';
  57952. this.type = undefined;
  57953. this.count = 0;
  57954. }
  57955. }
  57956. const _bufferDescriptor$1 = new GPUBufferDescriptor();
  57957. const _commandEncoderDescriptor$1 = new GPUCommandEncoderDescriptor();
  57958. const _querySetDescriptor$1 = new GPUQuerySetDescriptor();
  57959. /**
  57960. * Manages a pool of WebGPU timestamp queries for performance measurement.
  57961. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  57962. *
  57963. * @augments TimestampQueryPool
  57964. */
  57965. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  57966. /**
  57967. * Creates a new WebGPU timestamp query pool.
  57968. *
  57969. * @param {GPUDevice} device - The WebGPU device to create queries on.
  57970. * @param {string} type - The type identifier for this query pool.
  57971. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  57972. */
  57973. constructor( device, type, maxQueries = 2048 ) {
  57974. super( maxQueries );
  57975. this.device = device;
  57976. this.type = type;
  57977. _querySetDescriptor$1.label = `queryset_global_timestamp_${type}`;
  57978. _querySetDescriptor$1.type = 'timestamp';
  57979. _querySetDescriptor$1.count = this.maxQueries;
  57980. this.querySet = this.device.createQuerySet( _querySetDescriptor$1 );
  57981. _querySetDescriptor$1.reset();
  57982. const bufferSize = this.maxQueries * 8;
  57983. _bufferDescriptor$1.label = `buffer_timestamp_resolve_${type}`;
  57984. _bufferDescriptor$1.size = bufferSize;
  57985. _bufferDescriptor$1.usage = GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC;
  57986. this.resolveBuffer = this.device.createBuffer( _bufferDescriptor$1 );
  57987. _bufferDescriptor$1.reset();
  57988. _bufferDescriptor$1.label = `buffer_timestamp_result_${type}`;
  57989. _bufferDescriptor$1.size = bufferSize;
  57990. _bufferDescriptor$1.usage = GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ;
  57991. this.resultBuffer = this.device.createBuffer( _bufferDescriptor$1 );
  57992. _bufferDescriptor$1.reset();
  57993. }
  57994. /**
  57995. * Allocates a pair of queries for a given render context.
  57996. *
  57997. * @param {string} uid - A unique identifier for the render context.
  57998. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  57999. */
  58000. allocateQueriesForContext( uid ) {
  58001. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  58002. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  58003. 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() } ).` );
  58004. return null;
  58005. }
  58006. const baseOffset = this.currentQueryIndex;
  58007. this.currentQueryIndex += 2;
  58008. this.queryOffsets.set( uid, baseOffset );
  58009. return baseOffset;
  58010. }
  58011. /**
  58012. * Asynchronously resolves all pending queries and returns the total duration.
  58013. * If there's already a pending resolve operation, returns that promise instead.
  58014. *
  58015. * @async
  58016. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  58017. */
  58018. async resolveQueriesAsync() {
  58019. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  58020. return this.lastValue;
  58021. }
  58022. if ( this.pendingResolve ) {
  58023. return this.pendingResolve;
  58024. }
  58025. this.pendingResolve = this._resolveQueries();
  58026. try {
  58027. const result = await this.pendingResolve;
  58028. return result;
  58029. } finally {
  58030. this.pendingResolve = null;
  58031. }
  58032. }
  58033. /**
  58034. * Internal method to resolve queries and calculate total duration.
  58035. *
  58036. * @async
  58037. * @private
  58038. * @returns {Promise<number>} The total duration in milliseconds.
  58039. */
  58040. async _resolveQueries() {
  58041. if ( this.isDisposed ) {
  58042. return this.lastValue;
  58043. }
  58044. try {
  58045. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  58046. return this.lastValue;
  58047. }
  58048. const currentOffsets = new Map( this.queryOffsets );
  58049. const queryCount = this.currentQueryIndex;
  58050. const bytesUsed = queryCount * 8;
  58051. // Reset state before GPU work
  58052. this.currentQueryIndex = 0;
  58053. this.queryOffsets.clear();
  58054. const commandEncoder = this.device.createCommandEncoder( _commandEncoderDescriptor$1 );
  58055. commandEncoder.resolveQuerySet(
  58056. this.querySet,
  58057. 0,
  58058. queryCount,
  58059. this.resolveBuffer,
  58060. 0
  58061. );
  58062. commandEncoder.copyBufferToBuffer(
  58063. this.resolveBuffer,
  58064. 0,
  58065. this.resultBuffer,
  58066. 0,
  58067. bytesUsed
  58068. );
  58069. const commandBuffer = commandEncoder.finish();
  58070. submit( this.device, commandBuffer );
  58071. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  58072. return this.lastValue;
  58073. }
  58074. // Create and track the mapping operation
  58075. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  58076. if ( this.isDisposed ) {
  58077. if ( this.resultBuffer.mapState === 'mapped' ) {
  58078. this.resultBuffer.unmap();
  58079. }
  58080. return this.lastValue;
  58081. }
  58082. //
  58083. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  58084. const framesDuration = {};
  58085. const frames = [];
  58086. for ( const [ uid, baseOffset ] of currentOffsets ) {
  58087. const match = uid.match( /^(.*):f(\d+)$/ );
  58088. const frame = parseInt( match[ 2 ] );
  58089. if ( frames.includes( frame ) === false ) {
  58090. frames.push( frame );
  58091. }
  58092. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  58093. const startTime = times[ baseOffset ];
  58094. const endTime = times[ baseOffset + 1 ];
  58095. const duration = Number( endTime - startTime ) / 1e6;
  58096. this.timestamps.set( uid, duration );
  58097. framesDuration[ frame ] += duration;
  58098. }
  58099. // Return the total duration of the last frame
  58100. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  58101. this.resultBuffer.unmap();
  58102. this.lastValue = totalDuration;
  58103. this.frames = frames;
  58104. return totalDuration;
  58105. } catch ( e ) {
  58106. error( 'Error resolving queries:', e );
  58107. if ( this.resultBuffer.mapState === 'mapped' ) {
  58108. this.resultBuffer.unmap();
  58109. }
  58110. return this.lastValue;
  58111. }
  58112. }
  58113. /**
  58114. * Dispose of the query pool.
  58115. *
  58116. * @async
  58117. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  58118. */
  58119. async dispose() {
  58120. if ( this.isDisposed ) {
  58121. return;
  58122. }
  58123. this.isDisposed = true;
  58124. // Wait for pending resolve operation
  58125. if ( this.pendingResolve ) {
  58126. try {
  58127. await this.pendingResolve;
  58128. } catch ( e ) {
  58129. error( 'Error waiting for pending resolve:', e );
  58130. }
  58131. }
  58132. // Ensure buffer is unmapped before destroying
  58133. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  58134. try {
  58135. this.resultBuffer.unmap();
  58136. } catch ( e ) {
  58137. error( 'Error unmapping buffer:', e );
  58138. }
  58139. }
  58140. // Destroy resources
  58141. if ( this.querySet ) {
  58142. this.querySet.destroy();
  58143. this.querySet = null;
  58144. }
  58145. if ( this.resolveBuffer ) {
  58146. this.resolveBuffer.destroy();
  58147. this.resolveBuffer = null;
  58148. }
  58149. if ( this.resultBuffer ) {
  58150. this.resultBuffer.destroy();
  58151. this.resultBuffer = null;
  58152. }
  58153. this.queryOffsets.clear();
  58154. this.pendingResolve = null;
  58155. }
  58156. }
  58157. /**
  58158. * Reusable descriptor for `GPUCommandEncoder.beginComputePass()`.
  58159. *
  58160. * @private
  58161. */
  58162. class GPUComputePassDescriptor {
  58163. constructor() {
  58164. /**
  58165. * The label of the compute pass.
  58166. *
  58167. * @type {string}
  58168. */
  58169. this.label = '';
  58170. /**
  58171. * Defines which timestamp values are written and where.
  58172. *
  58173. * @type {Object|undefined}
  58174. */
  58175. this.timestampWrites = undefined;
  58176. }
  58177. /**
  58178. * Resets the descriptor to its default state.
  58179. */
  58180. reset() {
  58181. this.label = '';
  58182. this.timestampWrites = undefined;
  58183. }
  58184. }
  58185. /**
  58186. * Reusable descriptor for `GPURenderPassDepthStencilAttachment`, the
  58187. * `depthStencilAttachment` field of `GPURenderPassDescriptor`.
  58188. *
  58189. * @private
  58190. */
  58191. class GPURenderPassDepthStencilAttachment {
  58192. constructor() {
  58193. /**
  58194. * The depth/stencil texture view the pass renders into.
  58195. *
  58196. * @type {?GPUTextureView}
  58197. * @default null
  58198. */
  58199. this.view = null;
  58200. /**
  58201. * The load operation applied to the depth aspect at the start of the pass.
  58202. *
  58203. * @type {string|undefined}
  58204. */
  58205. this.depthLoadOp = undefined;
  58206. /**
  58207. * The store operation applied to the depth aspect at the end of the pass.
  58208. *
  58209. * @type {string|undefined}
  58210. */
  58211. this.depthStoreOp = undefined;
  58212. /**
  58213. * The clear value used when `depthLoadOp` is `'clear'`.
  58214. *
  58215. * @type {number|undefined}
  58216. */
  58217. this.depthClearValue = undefined;
  58218. /**
  58219. * Whether the depth aspect is read-only.
  58220. *
  58221. * @type {boolean}
  58222. * @default false
  58223. */
  58224. this.depthReadOnly = false;
  58225. /**
  58226. * The load operation applied to the stencil aspect at the start of the pass.
  58227. *
  58228. * @type {string|undefined}
  58229. */
  58230. this.stencilLoadOp = undefined;
  58231. /**
  58232. * The store operation applied to the stencil aspect at the end of the pass.
  58233. *
  58234. * @type {string|undefined}
  58235. */
  58236. this.stencilStoreOp = undefined;
  58237. /**
  58238. * The clear value used when `stencilLoadOp` is `'clear'`.
  58239. *
  58240. * @type {number}
  58241. * @default 0
  58242. */
  58243. this.stencilClearValue = 0;
  58244. /**
  58245. * Whether the stencil aspect is read-only.
  58246. *
  58247. * @type {boolean}
  58248. * @default false
  58249. */
  58250. this.stencilReadOnly = false;
  58251. }
  58252. /**
  58253. * Resets the descriptor to its default state.
  58254. */
  58255. reset() {
  58256. this.view = null;
  58257. this.depthLoadOp = undefined;
  58258. this.depthStoreOp = undefined;
  58259. this.depthClearValue = undefined;
  58260. this.depthReadOnly = false;
  58261. this.stencilLoadOp = undefined;
  58262. this.stencilStoreOp = undefined;
  58263. this.stencilClearValue = 0;
  58264. this.stencilReadOnly = false;
  58265. }
  58266. }
  58267. /**
  58268. * Reusable descriptor for `GPURenderPassTimestampWrites`, the
  58269. * `timestampWrites` field of `GPURenderPassDescriptor`. The same shape is
  58270. * also accepted as `GPUComputePassTimestampWrites`.
  58271. *
  58272. * @private
  58273. */
  58274. class GPURenderPassTimestampWrites {
  58275. constructor() {
  58276. /**
  58277. * The query set the timestamps are written to.
  58278. *
  58279. * @type {?GPUQuerySet}
  58280. * @default null
  58281. */
  58282. this.querySet = null;
  58283. /**
  58284. * The index in the query set the beginning timestamp is written to.
  58285. *
  58286. * @type {number|undefined}
  58287. */
  58288. this.beginningOfPassWriteIndex = undefined;
  58289. /**
  58290. * The index in the query set the ending timestamp is written to.
  58291. *
  58292. * @type {number|undefined}
  58293. */
  58294. this.endOfPassWriteIndex = undefined;
  58295. }
  58296. /**
  58297. * Resets the descriptor to its default state.
  58298. */
  58299. reset() {
  58300. this.querySet = null;
  58301. this.beginningOfPassWriteIndex = undefined;
  58302. this.endOfPassWriteIndex = undefined;
  58303. }
  58304. }
  58305. // debugger tools
  58306. // import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  58307. const _clearValue = { r: 0, g: 0, b: 0, a: 1 };
  58308. const _bufferDescriptor = new GPUBufferDescriptor();
  58309. const _commandEncoderDescriptor = new GPUCommandEncoderDescriptor();
  58310. const _computePassDescriptor = new GPUComputePassDescriptor();
  58311. const _querySetDescriptor = new GPUQuerySetDescriptor();
  58312. const _shaderModuleDescriptor = new GPUShaderModuleDescriptor();
  58313. const _renderPassTimestampWrites = new GPURenderPassTimestampWrites();
  58314. const _texelCopyTextureInfoSrc = new GPUTexelCopyTextureInfo();
  58315. const _texelCopyTextureInfoDst = new GPUTexelCopyTextureInfo();
  58316. const _viewDescriptor = new GPUTextureViewDescriptor();
  58317. const _extent3D = new GPUExtent3D();
  58318. /**
  58319. * A backend implementation targeting WebGPU.
  58320. *
  58321. * @private
  58322. * @augments Backend
  58323. */
  58324. class WebGPUBackend extends Backend {
  58325. /**
  58326. * WebGPUBackend options.
  58327. *
  58328. * @typedef {Object} WebGPUBackend~Options
  58329. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  58330. * @property {boolean} [reversedDepthBuffer=false] - Whether reversed depth buffer is enabled or not.
  58331. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  58332. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  58333. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  58334. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  58335. * @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.
  58336. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  58337. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  58338. * @property {string} [powerPreference=undefined] - The power preference.
  58339. * @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.
  58340. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  58341. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  58342. */
  58343. /**
  58344. * Constructs a new WebGPU backend.
  58345. *
  58346. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  58347. */
  58348. constructor( parameters = {} ) {
  58349. super( parameters );
  58350. /**
  58351. * This flag can be used for type testing.
  58352. *
  58353. * @type {boolean}
  58354. * @readonly
  58355. * @default true
  58356. */
  58357. this.isWebGPUBackend = true;
  58358. // some parameters require default values other than "undefined"
  58359. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  58360. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  58361. /**
  58362. * Indicates whether the backend is in WebGPU compatibility mode or not.
  58363. * The backend must be initialized before the property can be evaluated.
  58364. *
  58365. * @type {?boolean}
  58366. * @readonly
  58367. * @default null
  58368. */
  58369. this.compatibilityMode = null;
  58370. /**
  58371. * A reference to the device.
  58372. *
  58373. * @type {?GPUDevice}
  58374. * @default null
  58375. */
  58376. this.device = null;
  58377. /**
  58378. * A reference to the default render pass descriptor.
  58379. *
  58380. * @type {?Object}
  58381. * @default null
  58382. */
  58383. this.defaultRenderPassdescriptor = null;
  58384. /**
  58385. * A reference to a backend module holding common utility functions.
  58386. *
  58387. * @type {WebGPUUtils}
  58388. */
  58389. this.utils = new WebGPUUtils( this );
  58390. /**
  58391. * A reference to a backend module holding shader attribute-related
  58392. * utility functions.
  58393. *
  58394. * @type {WebGPUAttributeUtils}
  58395. */
  58396. this.attributeUtils = new WebGPUAttributeUtils( this );
  58397. /**
  58398. * A reference to a backend module holding shader binding-related
  58399. * utility functions.
  58400. *
  58401. * @type {WebGPUBindingUtils}
  58402. */
  58403. this.bindingUtils = new WebGPUBindingUtils( this );
  58404. /**
  58405. * A reference to a backend module holding device capability related
  58406. * utility functions.
  58407. *
  58408. * @type {WebGPUCapabilities}
  58409. */
  58410. this.capabilities = new WebGPUCapabilities( this );
  58411. /**
  58412. * A reference to a backend module holding shader pipeline-related
  58413. * utility functions.
  58414. *
  58415. * @type {WebGPUPipelineUtils}
  58416. */
  58417. this.pipelineUtils = new WebGPUPipelineUtils( this );
  58418. /**
  58419. * A reference to a backend module holding shader texture-related
  58420. * utility functions.
  58421. *
  58422. * @type {WebGPUTextureUtils}
  58423. */
  58424. this.textureUtils = new WebGPUTextureUtils( this );
  58425. /**
  58426. * A map that manages the resolve buffers for occlusion queries.
  58427. *
  58428. * @type {Map<number,GPUBuffer>}
  58429. */
  58430. this.occludedResolveCache = new Map();
  58431. // compatibility checks
  58432. const compatibilityTextureCompare = typeof navigator === 'undefined' ? true : /Android/.test( navigator.userAgent ) === false;
  58433. /**
  58434. * A map of compatibility checks.
  58435. *
  58436. * @type {Object}
  58437. */
  58438. this._compatibility = {
  58439. [ Compatibility.TEXTURE_COMPARE ]: compatibilityTextureCompare
  58440. };
  58441. }
  58442. /**
  58443. * Initializes the backend so it is ready for usage.
  58444. *
  58445. * @async
  58446. * @param {Renderer} renderer - The renderer.
  58447. * @return {Promise} A Promise that resolves when the backend has been initialized.
  58448. */
  58449. async init( renderer ) {
  58450. await super.init( renderer );
  58451. //
  58452. const parameters = this.parameters;
  58453. // create the device if it is not passed with parameters
  58454. let device;
  58455. if ( parameters.device === undefined ) {
  58456. const adapterOptions = {
  58457. powerPreference: parameters.powerPreference,
  58458. featureLevel: 'compatibility'
  58459. };
  58460. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  58461. if ( adapter === null ) {
  58462. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  58463. }
  58464. // feature support
  58465. const features = Object.values( GPUFeatureName );
  58466. const supportedFeatures = [];
  58467. for ( const name of features ) {
  58468. if ( adapter.features.has( name ) ) {
  58469. supportedFeatures.push( name );
  58470. }
  58471. }
  58472. const deviceDescriptor = {
  58473. requiredFeatures: supportedFeatures,
  58474. requiredLimits: parameters.requiredLimits
  58475. };
  58476. device = await adapter.requestDevice( deviceDescriptor );
  58477. } else {
  58478. device = parameters.device;
  58479. }
  58480. this.compatibilityMode = ! device.features.has( 'core-features-and-limits' );
  58481. if ( this.compatibilityMode ) {
  58482. renderer._samples = 0;
  58483. }
  58484. device.lost.then( ( info ) => {
  58485. if ( info.reason === 'destroyed' ) return;
  58486. const deviceLossInfo = {
  58487. api: 'WebGPU',
  58488. message: info.message || 'Unknown reason',
  58489. reason: info.reason || null,
  58490. originalEvent: info
  58491. };
  58492. renderer.onDeviceLost( deviceLossInfo );
  58493. } );
  58494. device.onuncapturederror = ( event ) => {
  58495. const gpuError = event.error;
  58496. const type = gpuError && gpuError.constructor ? gpuError.constructor.name : 'GPUError';
  58497. const message = ( gpuError && gpuError.message ) || 'Unknown uncaptured GPU error';
  58498. renderer.onError( {
  58499. api: 'WebGPU',
  58500. type,
  58501. message,
  58502. originalEvent: event
  58503. } );
  58504. };
  58505. this.device = device;
  58506. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  58507. this.updateSize();
  58508. }
  58509. /**
  58510. * A reference to the context.
  58511. *
  58512. * @type {?GPUCanvasContext}
  58513. * @default null
  58514. */
  58515. get context() {
  58516. const canvasTarget = this.renderer.getCanvasTarget();
  58517. const canvasData = this.get( canvasTarget );
  58518. let context = canvasData.context;
  58519. if ( context === undefined ) {
  58520. const parameters = this.parameters;
  58521. if ( canvasTarget.isDefaultCanvasTarget === true && parameters.context !== undefined ) {
  58522. context = parameters.context;
  58523. } else {
  58524. context = canvasTarget.domElement.getContext( 'webgpu' );
  58525. }
  58526. // OffscreenCanvas does not have setAttribute, see #22811
  58527. if ( 'setAttribute' in canvasTarget.domElement ) canvasTarget.domElement.setAttribute( 'data-engine', `three.js r${ REVISION } webgpu` );
  58528. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  58529. const toneMappingMode = parameters.outputType === HalfFloatType ? 'extended' : 'standard';
  58530. context.configure( {
  58531. device: this.device,
  58532. format: this.utils.getPreferredCanvasFormat(),
  58533. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  58534. alphaMode: alphaMode,
  58535. toneMapping: {
  58536. mode: toneMappingMode
  58537. }
  58538. } );
  58539. canvasData.context = context;
  58540. }
  58541. return context;
  58542. }
  58543. /**
  58544. * The coordinate system of the backend.
  58545. *
  58546. * @type {number}
  58547. * @readonly
  58548. */
  58549. get coordinateSystem() {
  58550. return WebGPUCoordinateSystem;
  58551. }
  58552. /**
  58553. * This method performs a readback operation by moving buffer data from
  58554. * a storage buffer attribute from the GPU to the CPU. ReadbackBuffer can
  58555. * be used to retain and reuse handles to the intermediate buffers and prevent
  58556. * new allocation.
  58557. *
  58558. * @async
  58559. * @param {BufferAttribute} attribute - The storage buffer attribute to read frm.
  58560. * @param {number} count - The offset from which to start reading the
  58561. * @param {number} offset - The storage buffer attribute.
  58562. * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute.
  58563. * @return {Promise<ArrayBuffer|ReadbackBuffer>} A promise that resolves with the buffer data when the data are ready.
  58564. */
  58565. async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) {
  58566. return await this.attributeUtils.getArrayBufferAsync( attribute, target, offset, count );
  58567. }
  58568. /**
  58569. * Returns the backend's rendering context.
  58570. *
  58571. * @return {GPUCanvasContext} The rendering context.
  58572. */
  58573. getContext() {
  58574. return this.context;
  58575. }
  58576. /**
  58577. * Returns the default render pass descriptor.
  58578. *
  58579. * In WebGPU, the default framebuffer must be configured
  58580. * like custom framebuffers so the backend needs a render
  58581. * pass descriptor even when rendering directly to screen.
  58582. *
  58583. * @private
  58584. * @return {Object} The render pass descriptor.
  58585. */
  58586. _getDefaultRenderPassDescriptor() {
  58587. const renderer = this.renderer;
  58588. const canvasTarget = renderer.getCanvasTarget();
  58589. const canvasData = this.get( canvasTarget );
  58590. const samples = renderer.currentSamples;
  58591. let descriptor = canvasData.descriptor;
  58592. if ( descriptor === undefined || canvasData.samples !== samples ) {
  58593. descriptor = new GPURenderPassDescriptor();
  58594. descriptor.colorAttachments.push( new GPURenderPassColorAttachment() );
  58595. if ( renderer.depth === true || renderer.stencil === true ) {
  58596. const depthStencilAttachment = new GPURenderPassDepthStencilAttachment();
  58597. depthStencilAttachment.view = this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView();
  58598. descriptor.depthStencilAttachment = depthStencilAttachment;
  58599. }
  58600. const colorAttachment = descriptor.colorAttachments[ 0 ];
  58601. if ( samples > 0 ) {
  58602. colorAttachment.view = this.textureUtils.getColorBuffer().createView();
  58603. } else {
  58604. colorAttachment.resolveTarget = undefined;
  58605. }
  58606. canvasData.descriptor = descriptor;
  58607. canvasData.samples = samples;
  58608. }
  58609. const colorAttachment = descriptor.colorAttachments[ 0 ];
  58610. if ( samples > 0 ) {
  58611. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  58612. } else {
  58613. colorAttachment.view = this.context.getCurrentTexture().createView();
  58614. }
  58615. return descriptor;
  58616. }
  58617. /**
  58618. * Returns whether the render target is a render target array with depth 2D array texture.
  58619. *
  58620. * @param {RenderContext} renderContext - The render context.
  58621. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  58622. *
  58623. * @private
  58624. */
  58625. _isRenderCameraDepthArray( renderContext ) {
  58626. const camera = renderContext.camera;
  58627. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture === true && camera !== null && camera.isArrayCamera === true;
  58628. }
  58629. /**
  58630. * Returns the render pass descriptor for the given render context.
  58631. *
  58632. * @private
  58633. * @param {RenderContext} renderContext - The render context.
  58634. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  58635. * @return {Object} The render pass descriptor.
  58636. */
  58637. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  58638. const renderTarget = renderContext.renderTarget;
  58639. const renderTargetData = this.get( renderTarget );
  58640. let descriptors = renderTargetData.descriptors;
  58641. if ( descriptors === undefined ||
  58642. renderTargetData.width !== renderTarget.width ||
  58643. renderTargetData.height !== renderTarget.height ||
  58644. renderTargetData.samples !== renderTarget.samples
  58645. ) {
  58646. descriptors = {};
  58647. renderTargetData.descriptors = descriptors;
  58648. }
  58649. const cacheKey = renderContext.getCacheKey();
  58650. let descriptorBase = descriptors[ cacheKey ];
  58651. if ( descriptorBase === undefined ) {
  58652. const textures = renderContext.textures;
  58653. const textureViews = [];
  58654. let sliceIndex;
  58655. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  58656. for ( let i = 0; i < textures.length; i ++ ) {
  58657. const textureData = this.get( textures[ i ] );
  58658. _viewDescriptor.label = `colorAttachment_${ i }`;
  58659. _viewDescriptor.baseMipLevel = renderContext.activeMipmapLevel;
  58660. _viewDescriptor.mipLevelCount = 1;
  58661. _viewDescriptor.baseArrayLayer = renderContext.activeCubeFace;
  58662. _viewDescriptor.arrayLayerCount = 1;
  58663. _viewDescriptor.dimension = GPUTextureViewDimension.TwoD;
  58664. if ( renderTarget.isRenderTarget3D ) {
  58665. sliceIndex = renderContext.activeCubeFace;
  58666. _viewDescriptor.baseArrayLayer = 0;
  58667. _viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  58668. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  58669. if ( isRenderCameraDepthArray === true ) {
  58670. const cameras = renderContext.camera.cameras;
  58671. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  58672. _viewDescriptor.baseArrayLayer = layer;
  58673. _viewDescriptor.arrayLayerCount = 1;
  58674. _viewDescriptor.dimension = GPUTextureViewDimension.TwoD;
  58675. const textureView = textureData.texture.createView( _viewDescriptor );
  58676. textureViews.push( {
  58677. view: textureView,
  58678. resolveTarget: undefined,
  58679. depthSlice: undefined
  58680. } );
  58681. }
  58682. } else {
  58683. _viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  58684. }
  58685. }
  58686. if ( isRenderCameraDepthArray !== true ) {
  58687. const textureView = textureData.texture.createView( _viewDescriptor );
  58688. let view, resolveTarget;
  58689. if ( textureData.msaaTexture !== undefined ) {
  58690. view = textureData.msaaTexture.createView();
  58691. resolveTarget = textureView;
  58692. } else {
  58693. view = textureView;
  58694. resolveTarget = undefined;
  58695. }
  58696. textureViews.push( {
  58697. view,
  58698. resolveTarget,
  58699. depthSlice: sliceIndex
  58700. } );
  58701. }
  58702. _viewDescriptor.reset();
  58703. }
  58704. const colorAttachments = [];
  58705. for ( let i = 0; i < textureViews.length; i ++ ) {
  58706. const viewInfo = textureViews[ i ];
  58707. const attachment = new GPURenderPassColorAttachment();
  58708. attachment.view = viewInfo.view;
  58709. attachment.depthSlice = viewInfo.depthSlice;
  58710. attachment.resolveTarget = viewInfo.resolveTarget;
  58711. colorAttachments.push( attachment );
  58712. }
  58713. descriptorBase = {
  58714. textureViews,
  58715. colorAttachments,
  58716. descriptor: new GPURenderPassDescriptor()
  58717. };
  58718. if ( renderContext.depth ) {
  58719. const depthTextureData = this.get( renderContext.depthTexture );
  58720. if ( renderContext.depthTexture.isArrayTexture || renderContext.depthTexture.isCubeTexture ) {
  58721. _viewDescriptor.dimension = GPUTextureViewDimension.TwoD;
  58722. _viewDescriptor.arrayLayerCount = 1;
  58723. _viewDescriptor.baseArrayLayer = renderContext.activeCubeFace;
  58724. }
  58725. const depthStencilAttachment = new GPURenderPassDepthStencilAttachment();
  58726. depthStencilAttachment.view = depthTextureData.texture.createView( _viewDescriptor );
  58727. descriptorBase.depthStencilAttachment = depthStencilAttachment;
  58728. _viewDescriptor.reset();
  58729. }
  58730. descriptors[ cacheKey ] = descriptorBase;
  58731. renderTargetData.width = renderTarget.width;
  58732. renderTargetData.height = renderTarget.height;
  58733. renderTargetData.samples = renderTarget.samples;
  58734. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  58735. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  58736. }
  58737. const descriptor = descriptorBase.descriptor;
  58738. descriptor.reset();
  58739. // Apply dynamic properties to cached attachments
  58740. for ( let i = 0; i < descriptorBase.colorAttachments.length; i ++ ) {
  58741. const attachment = descriptorBase.colorAttachments[ i ];
  58742. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  58743. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  58744. clearValue = colorAttachmentsConfig.clearValue;
  58745. }
  58746. attachment.loadOp = colorAttachmentsConfig.loadOp || GPULoadOp.Load;
  58747. attachment.storeOp = colorAttachmentsConfig.storeOp || GPUStoreOp.Store;
  58748. attachment.clearValue = clearValue;
  58749. descriptor.colorAttachments.push( attachment );
  58750. }
  58751. if ( descriptorBase.depthStencilAttachment ) {
  58752. descriptor.depthStencilAttachment = descriptorBase.depthStencilAttachment;
  58753. }
  58754. return descriptor;
  58755. }
  58756. /**
  58757. * This method is executed at the beginning of a render call and prepares
  58758. * the WebGPU state for upcoming render calls
  58759. *
  58760. * @param {RenderContext} renderContext - The render context.
  58761. */
  58762. beginRender( renderContext ) {
  58763. const renderContextData = this.get( renderContext );
  58764. //
  58765. const device = this.device;
  58766. const occlusionQueryCount = renderContext.occlusionQueryCount;
  58767. let occlusionQuerySet;
  58768. if ( occlusionQueryCount > 0 ) {
  58769. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  58770. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  58771. // Get a reference to the array of objects with queries. The renderContextData property
  58772. // can be changed by another render pass before the buffer.mapAsyc() completes.
  58773. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  58774. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  58775. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  58776. //
  58777. _querySetDescriptor.label = `occlusionQuerySet_${ renderContext.id }`;
  58778. _querySetDescriptor.type = 'occlusion';
  58779. _querySetDescriptor.count = occlusionQueryCount;
  58780. occlusionQuerySet = device.createQuerySet( _querySetDescriptor );
  58781. _querySetDescriptor.reset();
  58782. renderContextData.occlusionQuerySet = occlusionQuerySet;
  58783. renderContextData.occlusionQueryIndex = 0;
  58784. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  58785. renderContextData.lastOcclusionObject = null;
  58786. }
  58787. let descriptor;
  58788. if ( renderContext.textures === null ) {
  58789. descriptor = this._getDefaultRenderPassDescriptor();
  58790. } else {
  58791. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  58792. }
  58793. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ), descriptor );
  58794. descriptor.occlusionQuerySet = occlusionQuerySet;
  58795. const depthStencilAttachment = descriptor.depthStencilAttachment;
  58796. if ( renderContext.textures !== null ) {
  58797. const colorAttachments = descriptor.colorAttachments;
  58798. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  58799. const colorAttachment = colorAttachments[ i ];
  58800. if ( renderContext.clearColor ) {
  58801. if ( i === 0 ) {
  58802. colorAttachment.clearValue = renderContext.clearColorValue;
  58803. } else {
  58804. _clearValue.r = 0;
  58805. _clearValue.g = 0;
  58806. _clearValue.b = 0;
  58807. _clearValue.a = 1;
  58808. colorAttachment.clearValue = _clearValue;
  58809. }
  58810. colorAttachment.loadOp = GPULoadOp.Clear;
  58811. } else {
  58812. colorAttachment.loadOp = GPULoadOp.Load;
  58813. }
  58814. colorAttachment.storeOp = GPUStoreOp.Store;
  58815. }
  58816. } else {
  58817. const colorAttachment = descriptor.colorAttachments[ 0 ];
  58818. if ( renderContext.clearColor ) {
  58819. colorAttachment.clearValue = renderContext.clearColorValue;
  58820. colorAttachment.loadOp = GPULoadOp.Clear;
  58821. } else {
  58822. colorAttachment.loadOp = GPULoadOp.Load;
  58823. }
  58824. colorAttachment.storeOp = GPUStoreOp.Store;
  58825. }
  58826. //
  58827. if ( renderContext.depth ) {
  58828. if ( renderContext.clearDepth ) {
  58829. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  58830. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  58831. } else {
  58832. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  58833. }
  58834. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  58835. }
  58836. if ( renderContext.stencil ) {
  58837. if ( renderContext.clearStencil ) {
  58838. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  58839. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  58840. } else {
  58841. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  58842. }
  58843. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  58844. }
  58845. //
  58846. _commandEncoderDescriptor.label = 'renderContext_' + renderContext.id;
  58847. const encoder = device.createCommandEncoder( _commandEncoderDescriptor );
  58848. _commandEncoderDescriptor.reset();
  58849. // Layered render targets: prepare bundle encoders for each camera in the array camera.
  58850. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  58851. const cameras = renderContext.camera.cameras;
  58852. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  58853. this._createArrayCameraLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  58854. } else {
  58855. this._updateArrayCameraLayerDescriptors( renderContext, renderContextData, cameras );
  58856. }
  58857. // Create bundle encoders for each layer
  58858. renderContextData.bundleEncoders = [];
  58859. renderContextData.bundleSets = [];
  58860. // Create separate bundle encoders for each camera in the array
  58861. for ( let i = 0; i < cameras.length; i ++ ) {
  58862. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  58863. renderContext,
  58864. 'renderBundleArrayCamera_' + i
  58865. );
  58866. // Initialize state tracking for this bundle
  58867. const bundleSets = {
  58868. attributes: {},
  58869. bindingGroups: [],
  58870. pipeline: null,
  58871. index: null
  58872. };
  58873. renderContextData.bundleEncoders.push( bundleEncoder );
  58874. renderContextData.bundleSets.push( bundleSets );
  58875. }
  58876. // We'll complete the bundles in finishRender
  58877. renderContextData.currentPass = null;
  58878. } else {
  58879. const currentPass = encoder.beginRenderPass( descriptor );
  58880. renderContextData.currentPass = currentPass;
  58881. if ( renderContext.viewport ) {
  58882. this.updateViewport( renderContext );
  58883. }
  58884. if ( renderContext.scissor ) {
  58885. this.updateScissor( renderContext );
  58886. }
  58887. }
  58888. //
  58889. renderContextData.descriptor = descriptor;
  58890. renderContextData.encoder = encoder;
  58891. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  58892. renderContextData.renderBundles = [];
  58893. }
  58894. /**
  58895. * Creates render pass descriptors for each camera in an array camera.
  58896. *
  58897. * @param {RenderContext} renderContext - The render context.
  58898. * @param {Object} renderContextData - The render context data.
  58899. * @param {Object} descriptor - The render pass descriptor.
  58900. * @param {ArrayCamera} cameras - The array camera.
  58901. *
  58902. * @private
  58903. */
  58904. _createArrayCameraLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  58905. const depthStencilAttachment = descriptor.depthStencilAttachment;
  58906. renderContextData.layerDescriptors = [];
  58907. const depthTextureData = this.get( renderContext.depthTexture );
  58908. if ( ! depthTextureData.viewCache ) {
  58909. depthTextureData.viewCache = [];
  58910. }
  58911. for ( let i = 0; i < cameras.length; i ++ ) {
  58912. const sourceAttachment = descriptor.colorAttachments[ 0 ];
  58913. const layerColorAttachment = new GPURenderPassColorAttachment();
  58914. layerColorAttachment.view = descriptor.colorAttachments[ i ].view;
  58915. layerColorAttachment.depthSlice = sourceAttachment.depthSlice;
  58916. layerColorAttachment.resolveTarget = sourceAttachment.resolveTarget;
  58917. layerColorAttachment.loadOp = sourceAttachment.loadOp;
  58918. layerColorAttachment.storeOp = sourceAttachment.storeOp;
  58919. layerColorAttachment.clearValue = sourceAttachment.clearValue;
  58920. const layerDescriptor = new GPURenderPassDescriptor();
  58921. layerDescriptor.label = descriptor.label;
  58922. layerDescriptor.occlusionQuerySet = descriptor.occlusionQuerySet;
  58923. layerDescriptor.timestampWrites = descriptor.timestampWrites;
  58924. layerDescriptor.colorAttachments.push( layerColorAttachment );
  58925. if ( descriptor.depthStencilAttachment ) {
  58926. const layerIndex = i;
  58927. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  58928. _viewDescriptor.dimension = GPUTextureViewDimension.TwoD;
  58929. _viewDescriptor.baseArrayLayer = i;
  58930. _viewDescriptor.arrayLayerCount = 1;
  58931. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( _viewDescriptor );
  58932. _viewDescriptor.reset();
  58933. }
  58934. const layerDepthStencilAttachment = new GPURenderPassDepthStencilAttachment();
  58935. layerDepthStencilAttachment.view = depthTextureData.viewCache[ layerIndex ];
  58936. layerDepthStencilAttachment.depthLoadOp = depthStencilAttachment.depthLoadOp || GPULoadOp.Clear;
  58937. layerDepthStencilAttachment.depthStoreOp = depthStencilAttachment.depthStoreOp || GPUStoreOp.Store;
  58938. layerDepthStencilAttachment.depthClearValue = depthStencilAttachment.depthClearValue || 1.0;
  58939. if ( renderContext.stencil ) {
  58940. layerDepthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  58941. layerDepthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  58942. layerDepthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  58943. }
  58944. layerDescriptor.depthStencilAttachment = layerDepthStencilAttachment;
  58945. } else {
  58946. const layerDepthStencilAttachment = new GPURenderPassDepthStencilAttachment();
  58947. layerDepthStencilAttachment.view = depthStencilAttachment.view;
  58948. layerDepthStencilAttachment.depthLoadOp = depthStencilAttachment.depthLoadOp;
  58949. layerDepthStencilAttachment.depthStoreOp = depthStencilAttachment.depthStoreOp;
  58950. layerDepthStencilAttachment.depthClearValue = depthStencilAttachment.depthClearValue;
  58951. layerDepthStencilAttachment.depthReadOnly = depthStencilAttachment.depthReadOnly;
  58952. layerDepthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  58953. layerDepthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  58954. layerDepthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  58955. layerDepthStencilAttachment.stencilReadOnly = depthStencilAttachment.stencilReadOnly;
  58956. layerDescriptor.depthStencilAttachment = layerDepthStencilAttachment;
  58957. }
  58958. renderContextData.layerDescriptors.push( layerDescriptor );
  58959. }
  58960. }
  58961. /**
  58962. * Updates render pass descriptors for each camera in an array camera.
  58963. *
  58964. * @param {RenderContext} renderContext - The render context.
  58965. * @param {Object} renderContextData - The render context data.
  58966. * @param {ArrayCamera} cameras - The array camera.
  58967. *
  58968. */
  58969. _updateArrayCameraLayerDescriptors( renderContext, renderContextData, cameras ) {
  58970. for ( let i = 0; i < cameras.length; i ++ ) {
  58971. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  58972. if ( layerDescriptor.depthStencilAttachment ) {
  58973. const depthAttachment = layerDescriptor.depthStencilAttachment;
  58974. if ( renderContext.depth ) {
  58975. if ( renderContext.clearDepth ) {
  58976. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  58977. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  58978. } else {
  58979. depthAttachment.depthLoadOp = GPULoadOp.Load;
  58980. }
  58981. }
  58982. if ( renderContext.stencil ) {
  58983. if ( renderContext.clearStencil ) {
  58984. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  58985. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  58986. } else {
  58987. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  58988. }
  58989. }
  58990. }
  58991. }
  58992. }
  58993. /**
  58994. * This method is executed at the end of a render call and finalizes work
  58995. * after draw calls.
  58996. *
  58997. * @param {RenderContext} renderContext - The render context.
  58998. */
  58999. finishRender( renderContext ) {
  59000. const renderContextData = this.get( renderContext );
  59001. const occlusionQueryCount = renderContext.occlusionQueryCount;
  59002. if ( renderContextData.renderBundles.length > 0 ) {
  59003. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  59004. }
  59005. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  59006. renderContextData.currentPass.endOcclusionQuery();
  59007. }
  59008. // Layered render targets: execute the bundle for each layer.
  59009. const encoder = renderContextData.encoder;
  59010. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  59011. const bundles = [];
  59012. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  59013. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  59014. bundles.push( bundleEncoder.finish() );
  59015. }
  59016. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  59017. if ( i < bundles.length ) {
  59018. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  59019. const renderPass = encoder.beginRenderPass( layerDescriptor );
  59020. if ( renderContext.viewport ) {
  59021. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  59022. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  59023. }
  59024. if ( renderContext.scissor ) {
  59025. const { x, y, width, height } = renderContext.scissorValue;
  59026. renderPass.setScissorRect( x, y, width, height );
  59027. }
  59028. renderPass.executeBundles( [ bundles[ i ] ] );
  59029. renderPass.end();
  59030. }
  59031. }
  59032. } else if ( renderContextData.currentPass ) {
  59033. renderContextData.currentPass.end();
  59034. }
  59035. if ( occlusionQueryCount > 0 ) {
  59036. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  59037. //
  59038. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  59039. if ( queryResolveBuffer === undefined ) {
  59040. _bufferDescriptor.size = bufferSize;
  59041. _bufferDescriptor.usage = GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC;
  59042. queryResolveBuffer = this.device.createBuffer( _bufferDescriptor );
  59043. _bufferDescriptor.reset();
  59044. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  59045. }
  59046. //
  59047. _bufferDescriptor.size = bufferSize;
  59048. _bufferDescriptor.usage = GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ;
  59049. const readBuffer = this.device.createBuffer( _bufferDescriptor );
  59050. _bufferDescriptor.reset();
  59051. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  59052. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  59053. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  59054. renderContextData.occlusionQueryBuffer = readBuffer;
  59055. //
  59056. this.resolveOccludedAsync( renderContext );
  59057. }
  59058. submit( this.device, renderContextData.encoder.finish() );
  59059. //
  59060. if ( renderContext.textures !== null ) {
  59061. const textures = renderContext.textures;
  59062. for ( let i = 0; i < textures.length; i ++ ) {
  59063. const texture = textures[ i ];
  59064. if ( texture.generateMipmaps === true ) {
  59065. this.textureUtils.generateMipmaps( texture );
  59066. }
  59067. }
  59068. }
  59069. }
  59070. /**
  59071. * Returns `true` if the given 3D object is fully occluded by other
  59072. * 3D objects in the scene.
  59073. *
  59074. * @param {RenderContext} renderContext - The render context.
  59075. * @param {Object3D} object - The 3D object to test.
  59076. * @return {boolean} Whether the 3D object is fully occluded or not.
  59077. */
  59078. isOccluded( renderContext, object ) {
  59079. const renderContextData = this.get( renderContext );
  59080. return renderContextData.occluded && renderContextData.occluded.has( object );
  59081. }
  59082. /**
  59083. * This method processes the result of occlusion queries and writes it
  59084. * into render context data.
  59085. *
  59086. * @async
  59087. * @param {RenderContext} renderContext - The render context.
  59088. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  59089. */
  59090. async resolveOccludedAsync( renderContext ) {
  59091. const renderContextData = this.get( renderContext );
  59092. // handle occlusion query results
  59093. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  59094. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  59095. const occluded = new WeakSet();
  59096. renderContextData.currentOcclusionQueryObjects = null;
  59097. renderContextData.currentOcclusionQueryBuffer = null;
  59098. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  59099. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  59100. const results = new BigUint64Array( buffer );
  59101. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  59102. if ( results[ i ] === BigInt( 0 ) ) {
  59103. occluded.add( currentOcclusionQueryObjects[ i ] );
  59104. }
  59105. }
  59106. currentOcclusionQueryBuffer.destroy();
  59107. renderContextData.occluded = occluded;
  59108. }
  59109. }
  59110. /**
  59111. * Updates the viewport with the values from the given render context.
  59112. *
  59113. * @param {RenderContext} renderContext - The render context.
  59114. */
  59115. updateViewport( renderContext ) {
  59116. const { currentPass } = this.get( renderContext );
  59117. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  59118. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  59119. }
  59120. /**
  59121. * Updates the scissor with the values from the given render context.
  59122. *
  59123. * @param {RenderContext} renderContext - The render context.
  59124. */
  59125. updateScissor( renderContext ) {
  59126. const { currentPass } = this.get( renderContext );
  59127. const { x, y, width, height } = renderContext.scissorValue;
  59128. currentPass.setScissorRect( x, y, width, height );
  59129. }
  59130. /**
  59131. * Returns the clear color and alpha into a single
  59132. * color object.
  59133. *
  59134. * @return {Color4} The clear color.
  59135. */
  59136. getClearColor() {
  59137. const clearColor = super.getClearColor();
  59138. // only premultiply alpha when alphaMode is "premultiplied"
  59139. if ( this.renderer.alpha === true ) {
  59140. clearColor.r *= clearColor.a;
  59141. clearColor.g *= clearColor.a;
  59142. clearColor.b *= clearColor.a;
  59143. }
  59144. return clearColor;
  59145. }
  59146. /**
  59147. * Performs a clear operation.
  59148. *
  59149. * @param {boolean} color - Whether the color buffer should be cleared or not.
  59150. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  59151. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  59152. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  59153. */
  59154. clear( color, depth, stencil, renderTargetContext = null ) {
  59155. const device = this.device;
  59156. const renderer = this.renderer;
  59157. let colorAttachments = [];
  59158. let depthStencilAttachment;
  59159. let supportsDepth;
  59160. let supportsStencil;
  59161. if ( color ) {
  59162. const clearColor = this.getClearColor();
  59163. _clearValue.r = clearColor.r;
  59164. _clearValue.g = clearColor.g;
  59165. _clearValue.b = clearColor.b;
  59166. _clearValue.a = clearColor.a;
  59167. }
  59168. if ( renderTargetContext === null ) {
  59169. supportsDepth = renderer.depth;
  59170. supportsStencil = renderer.stencil;
  59171. const descriptor = this._getDefaultRenderPassDescriptor();
  59172. if ( color ) {
  59173. colorAttachments = descriptor.colorAttachments;
  59174. const colorAttachment = colorAttachments[ 0 ];
  59175. colorAttachment.clearValue = _clearValue;
  59176. colorAttachment.loadOp = GPULoadOp.Clear;
  59177. colorAttachment.storeOp = GPUStoreOp.Store;
  59178. }
  59179. if ( supportsDepth || supportsStencil ) {
  59180. depthStencilAttachment = descriptor.depthStencilAttachment;
  59181. }
  59182. } else {
  59183. supportsDepth = renderTargetContext.depth;
  59184. supportsStencil = renderTargetContext.stencil;
  59185. const clearConfig = {
  59186. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  59187. clearValue: color ? _clearValue : undefined
  59188. };
  59189. if ( supportsDepth ) {
  59190. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  59191. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  59192. clearConfig.depthStoreOp = GPUStoreOp.Store;
  59193. }
  59194. if ( supportsStencil ) {
  59195. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  59196. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  59197. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  59198. }
  59199. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  59200. colorAttachments = descriptor.colorAttachments;
  59201. depthStencilAttachment = descriptor.depthStencilAttachment;
  59202. }
  59203. if ( supportsDepth && depthStencilAttachment ) {
  59204. if ( depth ) {
  59205. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  59206. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  59207. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  59208. } else {
  59209. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  59210. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  59211. }
  59212. }
  59213. //
  59214. if ( supportsStencil && depthStencilAttachment ) {
  59215. if ( stencil ) {
  59216. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  59217. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  59218. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  59219. } else {
  59220. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  59221. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  59222. }
  59223. }
  59224. //
  59225. _commandEncoderDescriptor.label = 'clear';
  59226. const encoder = device.createCommandEncoder( _commandEncoderDescriptor );
  59227. _commandEncoderDescriptor.reset();
  59228. const currentPass = encoder.beginRenderPass( {
  59229. colorAttachments,
  59230. depthStencilAttachment
  59231. } );
  59232. currentPass.end();
  59233. submit( device, encoder.finish() );
  59234. }
  59235. // compute
  59236. /**
  59237. * This method is executed at the beginning of a compute call and
  59238. * prepares the state for upcoming compute tasks.
  59239. *
  59240. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  59241. */
  59242. beginCompute( computeGroup ) {
  59243. const groupGPU = this.get( computeGroup );
  59244. //
  59245. const label = 'computeGroup_' + computeGroup.id;
  59246. _computePassDescriptor.label = label;
  59247. _commandEncoderDescriptor.label = label;
  59248. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ), _computePassDescriptor );
  59249. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( _commandEncoderDescriptor );
  59250. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( _computePassDescriptor );
  59251. _commandEncoderDescriptor.reset();
  59252. _computePassDescriptor.reset();
  59253. }
  59254. /**
  59255. * Executes a compute command for the given compute node.
  59256. *
  59257. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  59258. * @param {Node} computeNode - The compute node.
  59259. * @param {Array<BindGroup>} bindings - The bindings.
  59260. * @param {ComputePipeline} pipeline - The compute pipeline.
  59261. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  59262. * - A single number representing count, or
  59263. * - An array [x, y, z] representing dispatch size, or
  59264. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  59265. */
  59266. compute( computeGroup, computeNode, bindings, pipeline, dispatchSize = null ) {
  59267. const computeNodeData = this.get( computeNode );
  59268. const { passEncoderGPU } = this.get( computeGroup );
  59269. // pipeline
  59270. const pipelineGPU = this.get( pipeline ).pipeline;
  59271. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  59272. // bind groups
  59273. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  59274. const bindGroup = bindings[ i ];
  59275. const bindingsData = this.get( bindGroup );
  59276. passEncoderGPU.setBindGroup( i, bindingsData.group );
  59277. }
  59278. if ( dispatchSize === null ) {
  59279. dispatchSize = computeNode.dispatchSize || computeNode.count;
  59280. }
  59281. // When the dispatchSize is set with a StorageBuffer from the GPU.
  59282. if ( dispatchSize && dispatchSize.isIndirectStorageBufferAttribute ) {
  59283. const dispatchBuffer = this.get( dispatchSize ).buffer;
  59284. passEncoderGPU.dispatchWorkgroupsIndirect( dispatchBuffer, 0 );
  59285. return;
  59286. }
  59287. if ( typeof dispatchSize === 'number' ) {
  59288. // If a single number is given, we calculate the dispatch size based on the workgroup size
  59289. const count = dispatchSize;
  59290. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  59291. // cache dispatch size to avoid recalculating it every time
  59292. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  59293. computeNodeData.count = count;
  59294. const workgroupSize = computeNode.workgroupSize;
  59295. let size = workgroupSize[ 0 ];
  59296. for ( let i = 1; i < workgroupSize.length; i ++ )
  59297. size *= workgroupSize[ i ];
  59298. const dispatchCount = Math.ceil( count / size );
  59299. //
  59300. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  59301. dispatchSize = [ dispatchCount, 1, 1 ];
  59302. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  59303. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  59304. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  59305. }
  59306. computeNodeData.dispatchSize = dispatchSize;
  59307. }
  59308. dispatchSize = computeNodeData.dispatchSize;
  59309. }
  59310. //
  59311. passEncoderGPU.dispatchWorkgroups(
  59312. dispatchSize[ 0 ],
  59313. dispatchSize[ 1 ] || 1,
  59314. dispatchSize[ 2 ] || 1
  59315. );
  59316. }
  59317. /**
  59318. * This method is executed at the end of a compute call and
  59319. * finalizes work after compute tasks.
  59320. *
  59321. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  59322. */
  59323. finishCompute( computeGroup ) {
  59324. const groupData = this.get( computeGroup );
  59325. groupData.passEncoderGPU.end();
  59326. submit( this.device, groupData.cmdEncoderGPU.finish() );
  59327. }
  59328. /**
  59329. * Internal draw function that performs the draw with the given pass encoder.
  59330. *
  59331. * @private
  59332. * @param {RenderObject} renderObject - The render object.
  59333. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  59334. * @param {Object} renderContextData - The render context data object, holding current pass state and occlusion query tracking.
  59335. * @param {GPURenderPipeline} pipelineGPU - The GPU render pipeline.
  59336. * @param {Array<BindGroup>} bindings - The bind groups.
  59337. * @param {Array<BufferAttribute>} vertexBuffers - The vertex buffers.
  59338. * @param {{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} drawParams - The draw parameters.
  59339. * @param {GPURenderPassEncoder|GPURenderBundleEncoder} passEncoderGPU - The GPU pass encoder used for recording draw commands.
  59340. * @param {Object} currentSets - Tracking object for currently set pipeline, attributes, bind groups, and index state.
  59341. */
  59342. _draw( renderObject, info, renderContextData, pipelineGPU, bindings, vertexBuffers, drawParams, passEncoderGPU, currentSets ) {
  59343. const { object, material, context } = renderObject;
  59344. const index = renderObject.getIndex();
  59345. const hasIndex = ( index !== null );
  59346. // pipeline
  59347. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  59348. currentSets.pipeline = pipelineGPU;
  59349. // bind groups
  59350. const currentBindingGroups = currentSets.bindingGroups;
  59351. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  59352. const bindGroup = bindings[ i ];
  59353. const bindingsData = this.get( bindGroup );
  59354. if ( currentBindingGroups[ i ] !== bindGroup.id ) {
  59355. passEncoderGPU.setBindGroup( i, bindingsData.group );
  59356. currentBindingGroups[ i ] = bindGroup.id;
  59357. }
  59358. }
  59359. // attributes
  59360. // index
  59361. if ( hasIndex === true ) {
  59362. if ( currentSets.index !== index ) {
  59363. const buffer = this.get( index ).buffer;
  59364. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  59365. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  59366. currentSets.index = index;
  59367. }
  59368. }
  59369. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  59370. const vertexBuffer = vertexBuffers[ i ];
  59371. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  59372. const buffer = this.get( vertexBuffer ).buffer;
  59373. passEncoderGPU.setVertexBuffer( i, buffer );
  59374. currentSets.attributes[ i ] = vertexBuffer;
  59375. }
  59376. }
  59377. // stencil
  59378. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  59379. passEncoderGPU.setStencilReference( material.stencilRef );
  59380. renderContextData.currentStencilRef = material.stencilRef;
  59381. }
  59382. if ( object.isBatchedMesh === true ) {
  59383. const starts = object._multiDrawStarts;
  59384. const counts = object._multiDrawCounts;
  59385. const drawCount = object._multiDrawCount;
  59386. let bytesPerElement = ( hasIndex === true ) ? index.array.BYTES_PER_ELEMENT : 1;
  59387. if ( material.wireframe ) {
  59388. bytesPerElement = object.geometry.attributes.position.count > 65535 ? 4 : 2;
  59389. }
  59390. for ( let i = 0; i < drawCount; i ++ ) {
  59391. if ( hasIndex === true ) {
  59392. passEncoderGPU.drawIndexed( counts[ i ], 1, starts[ i ] / bytesPerElement, 0, i );
  59393. } else {
  59394. passEncoderGPU.draw( counts[ i ], 1, starts[ i ], i );
  59395. }
  59396. info.update( object, counts[ i ], 1 );
  59397. }
  59398. } else if ( hasIndex === true ) {
  59399. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  59400. const indirect = renderObject.getIndirect();
  59401. if ( indirect !== null ) {
  59402. const buffer = this.get( indirect ).buffer;
  59403. const indirectOffset = renderObject.getIndirectOffset();
  59404. const indirectOffsets = Array.isArray( indirectOffset ) ? indirectOffset : [ indirectOffset ];
  59405. for ( let i = 0; i < indirectOffsets.length; i ++ ) {
  59406. passEncoderGPU.drawIndexedIndirect( buffer, indirectOffsets[ i ] );
  59407. }
  59408. } else {
  59409. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  59410. }
  59411. info.update( object, indexCount, instanceCount );
  59412. } else {
  59413. const { vertexCount, instanceCount, firstVertex } = drawParams;
  59414. const indirect = renderObject.getIndirect();
  59415. if ( indirect !== null ) {
  59416. const buffer = this.get( indirect ).buffer;
  59417. const indirectOffset = renderObject.getIndirectOffset();
  59418. const indirectOffsets = Array.isArray( indirectOffset ) ? indirectOffset : [ indirectOffset ];
  59419. for ( let i = 0; i < indirectOffsets.length; i ++ ) {
  59420. passEncoderGPU.drawIndirect( buffer, indirectOffsets[ i ] );
  59421. }
  59422. } else {
  59423. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  59424. }
  59425. info.update( object, vertexCount, instanceCount );
  59426. }
  59427. }
  59428. // render object
  59429. /**
  59430. * Executes a draw command for the given render object.
  59431. *
  59432. * @param {RenderObject} renderObject - The render object to draw.
  59433. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  59434. */
  59435. draw( renderObject, info ) {
  59436. const { object, context, pipeline } = renderObject;
  59437. const renderContextData = this.get( context );
  59438. const pipelineData = this.get( pipeline );
  59439. const pipelineGPU = pipelineData.pipeline;
  59440. // Skip if pipeline has error
  59441. if ( pipelineData.error === true ) return;
  59442. const drawParams = renderObject.getDrawParameters();
  59443. if ( drawParams === null ) return;
  59444. const bindings = renderObject.getBindings();
  59445. // vertex buffers
  59446. const vertexBuffers = renderObject.getVertexBuffers();
  59447. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  59448. const cameraData = this.get( renderObject.camera );
  59449. const cameras = renderObject.camera.cameras;
  59450. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  59451. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  59452. const bindingsData = this.get( cameraIndex );
  59453. const indexesGPU = [];
  59454. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  59455. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  59456. data[ 0 ] = i;
  59457. const { layoutGPU } = bindingsData.layout;
  59458. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, layoutGPU );
  59459. indexesGPU.push( bindGroupIndex );
  59460. }
  59461. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  59462. }
  59463. const pixelRatio = this.renderer.getPixelRatio();
  59464. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  59465. const subCamera = cameras[ i ];
  59466. if ( object.layers.test( subCamera.layers ) ) {
  59467. const vp = subCamera.viewport;
  59468. let pass = renderContextData.currentPass;
  59469. let sets = renderContextData.currentSets;
  59470. const isBundleEncoder = renderContextData.bundleEncoders !== undefined;
  59471. if ( isBundleEncoder ) {
  59472. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  59473. const bundleSets = renderContextData.bundleSets[ i ];
  59474. pass = bundleEncoder;
  59475. sets = bundleSets;
  59476. }
  59477. // GPURenderBundleEncoder does not support setViewport, only GPURenderPassEncoder does
  59478. if ( vp && ! isBundleEncoder ) {
  59479. pass.setViewport(
  59480. Math.floor( vp.x * pixelRatio ),
  59481. Math.floor( vp.y * pixelRatio ),
  59482. Math.floor( vp.width * pixelRatio ),
  59483. Math.floor( vp.height * pixelRatio ),
  59484. context.viewportValue.minDepth,
  59485. context.viewportValue.maxDepth
  59486. );
  59487. }
  59488. // Set camera index binding for this layer
  59489. if ( cameraIndex && cameraData.indexesGPU ) {
  59490. const indexPos = bindings.indexOf( cameraIndex );
  59491. pass.setBindGroup( indexPos, cameraData.indexesGPU[ i ] );
  59492. sets.bindingGroups[ indexPos ] = cameraIndex.id;
  59493. }
  59494. this._draw( renderObject, info, renderContextData, pipelineGPU, bindings, vertexBuffers, drawParams, pass, sets );
  59495. }
  59496. }
  59497. } else {
  59498. // Regular single camera rendering
  59499. if ( renderContextData.currentPass ) {
  59500. // Handle occlusion queries
  59501. if ( renderContextData.occlusionQuerySet !== undefined ) {
  59502. const lastObject = renderContextData.lastOcclusionObject;
  59503. if ( lastObject !== object ) {
  59504. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  59505. renderContextData.currentPass.endOcclusionQuery();
  59506. renderContextData.occlusionQueryIndex ++;
  59507. }
  59508. if ( object.occlusionTest === true ) {
  59509. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  59510. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  59511. }
  59512. renderContextData.lastOcclusionObject = object;
  59513. }
  59514. }
  59515. this._draw( renderObject, info, renderContextData, pipelineGPU, bindings, vertexBuffers, drawParams, renderContextData.currentPass, renderContextData.currentSets );
  59516. }
  59517. }
  59518. }
  59519. // cache key
  59520. /**
  59521. * Returns `true` if the render pipeline requires an update.
  59522. *
  59523. * @param {RenderObject} renderObject - The render object.
  59524. * @return {boolean} Whether the render pipeline requires an update or not.
  59525. */
  59526. needsRenderUpdate( renderObject ) {
  59527. const data = this.get( renderObject );
  59528. const { object, material } = renderObject;
  59529. const utils = this.utils;
  59530. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  59531. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  59532. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  59533. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  59534. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  59535. let needsUpdate = false;
  59536. if ( data.material !== material || data.materialVersion !== material.version ||
  59537. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  59538. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  59539. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  59540. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  59541. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  59542. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  59543. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  59544. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  59545. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  59546. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  59547. data.primitiveTopology !== primitiveTopology ||
  59548. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  59549. ) {
  59550. data.material = material; data.materialVersion = material.version;
  59551. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  59552. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  59553. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  59554. data.colorWrite = material.colorWrite;
  59555. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  59556. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  59557. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  59558. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  59559. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  59560. data.sampleCount = sampleCount;
  59561. data.colorSpace = colorSpace;
  59562. data.colorFormat = colorFormat;
  59563. data.depthStencilFormat = depthStencilFormat;
  59564. data.primitiveTopology = primitiveTopology;
  59565. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  59566. needsUpdate = true;
  59567. }
  59568. return needsUpdate;
  59569. }
  59570. /**
  59571. * Returns a cache key that is used to identify render pipelines.
  59572. *
  59573. * @param {RenderObject} renderObject - The render object.
  59574. * @return {string} The cache key.
  59575. */
  59576. getRenderCacheKey( renderObject ) {
  59577. const { object, material } = renderObject;
  59578. const utils = this.utils;
  59579. const renderContext = renderObject.context;
  59580. // meshes with negative scale have a different frontFace render pipeline
  59581. // descriptor value so the following must be honored in the cache key
  59582. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  59583. return [
  59584. material.transparent, material.blending, material.premultipliedAlpha,
  59585. material.blendSrc, material.blendDst, material.blendEquation,
  59586. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  59587. material.colorWrite,
  59588. material.depthWrite, material.depthTest, material.depthFunc,
  59589. material.stencilWrite, material.stencilFunc,
  59590. material.stencilFail, material.stencilZFail, material.stencilZPass,
  59591. material.stencilFuncMask, material.stencilWriteMask,
  59592. material.side,
  59593. frontFaceCW,
  59594. utils.getSampleCountRenderContext( renderContext ),
  59595. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  59596. utils.getPrimitiveTopology( object, material ),
  59597. renderObject.getGeometryCacheKey(),
  59598. renderObject.clippingContextCacheKey
  59599. ].join();
  59600. }
  59601. // textures
  59602. /**
  59603. * Updates a GPU sampler for the given texture.
  59604. *
  59605. * @param {Texture} texture - The texture to update the sampler for.
  59606. * @param {TextureNode} textureNode - The texture node to update the sampler with.
  59607. * @return {string} The current sampler key.
  59608. */
  59609. updateSampler( texture, textureNode ) {
  59610. return this.textureUtils.updateSampler( texture, textureNode );
  59611. }
  59612. /**
  59613. * Creates a default texture for the given texture that can be used
  59614. * as a placeholder until the actual texture is ready for usage.
  59615. *
  59616. * @param {Texture} texture - The texture to create a default texture for.
  59617. * @return {boolean} Whether the sampler has been updated or not.
  59618. */
  59619. createDefaultTexture( texture ) {
  59620. return this.textureUtils.createDefaultTexture( texture );
  59621. }
  59622. /**
  59623. * Defines a texture on the GPU for the given texture object.
  59624. *
  59625. * @param {Texture} texture - The texture.
  59626. * @param {Object} [options={}] - Optional configuration parameter.
  59627. */
  59628. createTexture( texture, options ) {
  59629. this.textureUtils.createTexture( texture, options );
  59630. }
  59631. /**
  59632. * Uploads the updated texture data to the GPU.
  59633. *
  59634. * @param {Texture} texture - The texture.
  59635. * @param {Object} [options={}] - Optional configuration parameter.
  59636. */
  59637. updateTexture( texture, options ) {
  59638. this.textureUtils.updateTexture( texture, options );
  59639. }
  59640. /**
  59641. * Generates mipmaps for the given texture.
  59642. *
  59643. * @param {Texture} texture - The texture.
  59644. */
  59645. generateMipmaps( texture ) {
  59646. this.textureUtils.generateMipmaps( texture );
  59647. }
  59648. /**
  59649. * Destroys the GPU data for the given texture object.
  59650. *
  59651. * @param {Texture} texture - The texture.
  59652. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  59653. */
  59654. destroyTexture( texture, isDefaultTexture = false ) {
  59655. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  59656. }
  59657. /**
  59658. * Returns texture data as a typed array.
  59659. *
  59660. * @async
  59661. * @param {Texture} texture - The texture to copy.
  59662. * @param {number} x - The x coordinate of the copy origin.
  59663. * @param {number} y - The y coordinate of the copy origin.
  59664. * @param {number} width - The width of the copy.
  59665. * @param {number} height - The height of the copy.
  59666. * @param {number} faceIndex - The face index.
  59667. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  59668. */
  59669. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  59670. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  59671. }
  59672. /**
  59673. * Inits a time stamp query for the given render context.
  59674. *
  59675. * @param {string} type - The type of the timestamp query (e.g. 'render', 'compute').
  59676. * @param {number} uid - Unique id for the context (e.g. render context id).
  59677. * @param {Object} descriptor - The query descriptor.
  59678. */
  59679. initTimestampQuery( type, uid, descriptor ) {
  59680. if ( ! this.trackTimestamp ) return;
  59681. if ( ! this.timestampQueryPool[ type ] ) {
  59682. // TODO: Variable maxQueries?
  59683. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  59684. }
  59685. const timestampQueryPool = this.timestampQueryPool[ type ];
  59686. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  59687. _renderPassTimestampWrites.querySet = timestampQueryPool.querySet;
  59688. _renderPassTimestampWrites.beginningOfPassWriteIndex = baseOffset;
  59689. _renderPassTimestampWrites.endOfPassWriteIndex = baseOffset + 1;
  59690. descriptor.timestampWrites = _renderPassTimestampWrites;
  59691. }
  59692. // node builder
  59693. /**
  59694. * Returns a node builder for the given render object.
  59695. *
  59696. * @param {RenderObject} object - The render object.
  59697. * @param {Renderer} renderer - The renderer.
  59698. * @return {WGSLNodeBuilder} The node builder.
  59699. */
  59700. createNodeBuilder( object, renderer ) {
  59701. return new WGSLNodeBuilder( object, renderer );
  59702. }
  59703. // program
  59704. /**
  59705. * Creates a shader program from the given programmable stage.
  59706. *
  59707. * @param {ProgrammableStage} program - The programmable stage.
  59708. */
  59709. createProgram( program ) {
  59710. const programGPU = this.get( program );
  59711. _shaderModuleDescriptor.label = program.stage + ( program.name !== '' ? `_${ program.name }` : '' );
  59712. _shaderModuleDescriptor.code = program.code;
  59713. programGPU.module = {
  59714. module: this.device.createShaderModule( _shaderModuleDescriptor ),
  59715. entryPoint: 'main'
  59716. };
  59717. _shaderModuleDescriptor.reset();
  59718. }
  59719. /**
  59720. * Destroys the shader program of the given programmable stage.
  59721. *
  59722. * @param {ProgrammableStage} program - The programmable stage.
  59723. */
  59724. destroyProgram( program ) {
  59725. this.delete( program );
  59726. }
  59727. // pipelines
  59728. /**
  59729. * Creates a render pipeline for the given render object.
  59730. *
  59731. * @param {RenderObject} renderObject - The render object.
  59732. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  59733. */
  59734. createRenderPipeline( renderObject, promises ) {
  59735. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  59736. }
  59737. /**
  59738. * Creates a compute pipeline for the given compute node.
  59739. *
  59740. * @param {ComputePipeline} computePipeline - The compute pipeline.
  59741. * @param {Array<BindGroup>} bindings - The bindings.
  59742. */
  59743. createComputePipeline( computePipeline, bindings ) {
  59744. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  59745. }
  59746. /**
  59747. * Prepares the state for encoding render bundles.
  59748. *
  59749. * @param {RenderContext} renderContext - The render context.
  59750. */
  59751. beginBundle( renderContext ) {
  59752. const renderContextData = this.get( renderContext );
  59753. renderContextData._currentPass = renderContextData.currentPass;
  59754. renderContextData._currentSets = renderContextData.currentSets;
  59755. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  59756. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  59757. }
  59758. /**
  59759. * After processing render bundles this method finalizes related work.
  59760. *
  59761. * @param {RenderContext} renderContext - The render context.
  59762. * @param {RenderBundle} bundle - The render bundle.
  59763. */
  59764. finishBundle( renderContext, bundle ) {
  59765. const renderContextData = this.get( renderContext );
  59766. const bundleEncoder = renderContextData.currentPass;
  59767. const bundleGPU = bundleEncoder.finish();
  59768. this.get( bundle ).bundleGPU = bundleGPU;
  59769. // restore render pass state
  59770. renderContextData.currentSets = renderContextData._currentSets;
  59771. renderContextData.currentPass = renderContextData._currentPass;
  59772. }
  59773. /**
  59774. * Adds a render bundle to the render context data.
  59775. *
  59776. * @param {RenderContext} renderContext - The render context.
  59777. * @param {RenderBundle} bundle - The render bundle to add.
  59778. */
  59779. addBundle( renderContext, bundle ) {
  59780. const renderContextData = this.get( renderContext );
  59781. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  59782. }
  59783. // bindings
  59784. /**
  59785. * Creates a uniform buffer.
  59786. *
  59787. * @param {Buffer} uniformBuffer - The uniform buffer.
  59788. */
  59789. createUniformBuffer( uniformBuffer ) {
  59790. const uniformBufferData = this.get( uniformBuffer );
  59791. if ( uniformBufferData.buffer === undefined ) {
  59792. const byteLength = uniformBuffer.byteLength;
  59793. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  59794. const visibilities = [];
  59795. if ( uniformBuffer.visibility & GPUShaderStage.VERTEX ) {
  59796. visibilities.push( 'vertex' );
  59797. }
  59798. if ( uniformBuffer.visibility & GPUShaderStage.FRAGMENT ) {
  59799. visibilities.push( 'fragment' );
  59800. }
  59801. if ( uniformBuffer.visibility & GPUShaderStage.COMPUTE ) {
  59802. visibilities.push( 'compute' );
  59803. }
  59804. const bufferVisibility = `(${visibilities.join( ',' )})`;
  59805. _bufferDescriptor.label = `bindingBuffer${uniformBuffer.id}_${uniformBuffer.name}_${bufferVisibility}`;
  59806. _bufferDescriptor.size = byteLength;
  59807. _bufferDescriptor.usage = usage;
  59808. const bufferGPU = this.device.createBuffer( _bufferDescriptor );
  59809. _bufferDescriptor.reset();
  59810. uniformBufferData.buffer = bufferGPU;
  59811. }
  59812. }
  59813. /**
  59814. * Destroys the GPU data for the given uniform buffer.
  59815. *
  59816. * @param {Buffer} uniformBuffer - The uniform buffer.
  59817. */
  59818. destroyUniformBuffer( uniformBuffer ) {
  59819. const uniformBufferData = this.get( uniformBuffer );
  59820. uniformBufferData.buffer.destroy();
  59821. this.delete( uniformBuffer );
  59822. }
  59823. /**
  59824. * Creates bindings from the given bind group definition.
  59825. *
  59826. * @param {BindGroup} bindGroup - The bind group.
  59827. * @param {Array<BindGroup>} bindings - Array of bind groups.
  59828. * @param {number} cacheIndex - The cache index.
  59829. * @param {number} version - The version.
  59830. */
  59831. createBindings( bindGroup, bindings, cacheIndex, version ) {
  59832. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  59833. }
  59834. /**
  59835. * Updates the given bind group definition.
  59836. *
  59837. * @param {BindGroup} bindGroup - The bind group.
  59838. * @param {Array<BindGroup>} bindings - Array of bind groups.
  59839. * @param {number} cacheIndex - The cache index.
  59840. * @param {number} version - The version.
  59841. */
  59842. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  59843. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  59844. }
  59845. /**
  59846. * Updates a buffer binding.
  59847. *
  59848. * @param {Buffer} binding - The buffer binding to update.
  59849. */
  59850. updateBinding( binding ) {
  59851. this.bindingUtils.updateBinding( binding );
  59852. }
  59853. /**
  59854. * Delete data associated with the current bind group.
  59855. *
  59856. * @param {BindGroup} bindGroup - The bind group.
  59857. */
  59858. deleteBindGroupData( bindGroup ) {
  59859. this.bindingUtils.deleteBindGroupData( bindGroup );
  59860. }
  59861. // attributes
  59862. /**
  59863. * Creates the buffer of an indexed shader attribute.
  59864. *
  59865. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  59866. */
  59867. createIndexAttribute( attribute ) {
  59868. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  59869. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  59870. usage |= GPUBufferUsage.STORAGE;
  59871. }
  59872. this.attributeUtils.createAttribute( attribute, usage );
  59873. }
  59874. /**
  59875. * Creates the GPU buffer of a shader attribute.
  59876. *
  59877. * @param {BufferAttribute} attribute - The buffer attribute.
  59878. */
  59879. createAttribute( attribute ) {
  59880. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  59881. }
  59882. /**
  59883. * Creates the GPU buffer of a storage attribute.
  59884. *
  59885. * @param {BufferAttribute} attribute - The buffer attribute.
  59886. */
  59887. createStorageAttribute( attribute ) {
  59888. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  59889. }
  59890. /**
  59891. * Creates the GPU buffer of an indirect storage attribute.
  59892. *
  59893. * @param {BufferAttribute} attribute - The buffer attribute.
  59894. */
  59895. createIndirectStorageAttribute( attribute ) {
  59896. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  59897. }
  59898. /**
  59899. * Updates the GPU buffer of a shader attribute.
  59900. *
  59901. * @param {BufferAttribute} attribute - The buffer attribute to update.
  59902. */
  59903. updateAttribute( attribute ) {
  59904. this.attributeUtils.updateAttribute( attribute );
  59905. }
  59906. /**
  59907. * Destroys the GPU buffer of a shader attribute.
  59908. *
  59909. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  59910. */
  59911. destroyAttribute( attribute ) {
  59912. this.attributeUtils.destroyAttribute( attribute );
  59913. }
  59914. // canvas
  59915. /**
  59916. * Triggers an update of the default render pass descriptor.
  59917. */
  59918. updateSize() {
  59919. this.delete( this.renderer.getCanvasTarget() );
  59920. }
  59921. // utils public
  59922. /**
  59923. * Checks if the given feature is supported by the backend.
  59924. *
  59925. * @param {string} name - The feature's name.
  59926. * @return {boolean} Whether the feature is supported or not.
  59927. */
  59928. hasFeature( name ) {
  59929. if ( GPUFeatureMap[ name ] !== undefined ) name = GPUFeatureMap[ name ];
  59930. return this.device.features.has( name );
  59931. }
  59932. /**
  59933. * Copies data of the given source texture to the given destination texture.
  59934. *
  59935. * @param {Texture} srcTexture - The source texture.
  59936. * @param {Texture} dstTexture - The destination texture.
  59937. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  59938. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  59939. * @param {number} [srcLevel=0] - The mipmap level to copy.
  59940. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  59941. */
  59942. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  59943. let dstX = 0;
  59944. let dstY = 0;
  59945. let dstZ = 0;
  59946. let srcX = 0;
  59947. let srcY = 0;
  59948. let srcZ = 0;
  59949. let srcWidth = srcTexture.image.width;
  59950. let srcHeight = srcTexture.image.height;
  59951. let srcDepth = 1;
  59952. if ( srcRegion !== null ) {
  59953. if ( srcRegion.isBox3 === true ) {
  59954. srcX = srcRegion.min.x;
  59955. srcY = srcRegion.min.y;
  59956. srcZ = srcRegion.min.z;
  59957. srcWidth = srcRegion.max.x - srcRegion.min.x;
  59958. srcHeight = srcRegion.max.y - srcRegion.min.y;
  59959. srcDepth = srcRegion.max.z - srcRegion.min.z;
  59960. } else {
  59961. // Assume it's a Box2
  59962. srcX = srcRegion.min.x;
  59963. srcY = srcRegion.min.y;
  59964. srcWidth = srcRegion.max.x - srcRegion.min.x;
  59965. srcHeight = srcRegion.max.y - srcRegion.min.y;
  59966. srcDepth = 1;
  59967. }
  59968. }
  59969. if ( dstPosition !== null ) {
  59970. dstX = dstPosition.x;
  59971. dstY = dstPosition.y;
  59972. dstZ = dstPosition.z || 0;
  59973. }
  59974. _commandEncoderDescriptor.label = 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id;
  59975. const encoder = this.device.createCommandEncoder( _commandEncoderDescriptor );
  59976. _commandEncoderDescriptor.reset();
  59977. const sourceGPU = this.get( srcTexture ).texture;
  59978. const destinationGPU = this.get( dstTexture ).texture;
  59979. _texelCopyTextureInfoSrc.texture = sourceGPU;
  59980. _texelCopyTextureInfoSrc.mipLevel = srcLevel;
  59981. _texelCopyTextureInfoSrc.origin.x = srcX;
  59982. _texelCopyTextureInfoSrc.origin.y = srcY;
  59983. _texelCopyTextureInfoSrc.origin.z = srcZ;
  59984. _texelCopyTextureInfoDst.texture = destinationGPU;
  59985. _texelCopyTextureInfoDst.mipLevel = dstLevel;
  59986. _texelCopyTextureInfoDst.origin.x = dstX;
  59987. _texelCopyTextureInfoDst.origin.y = dstY;
  59988. _texelCopyTextureInfoDst.origin.z = dstZ;
  59989. _extent3D.width = srcWidth;
  59990. _extent3D.height = srcHeight;
  59991. _extent3D.depthOrArrayLayers = srcDepth;
  59992. encoder.copyTextureToTexture(
  59993. _texelCopyTextureInfoSrc,
  59994. _texelCopyTextureInfoDst,
  59995. _extent3D
  59996. );
  59997. _texelCopyTextureInfoSrc.reset();
  59998. _texelCopyTextureInfoDst.reset();
  59999. _extent3D.reset();
  60000. submit( this.device, encoder.finish() );
  60001. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  60002. this.textureUtils.generateMipmaps( dstTexture );
  60003. }
  60004. }
  60005. /**
  60006. * Copies the current bound framebuffer to the given texture.
  60007. *
  60008. * @param {Texture} texture - The destination texture.
  60009. * @param {RenderContext} renderContext - The render context.
  60010. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  60011. */
  60012. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  60013. const renderContextData = this.get( renderContext );
  60014. let sourceGPU = null;
  60015. if ( renderContext.renderTarget ) {
  60016. if ( texture.isDepthTexture ) {
  60017. sourceGPU = this.get( renderContext.depthTexture ).texture;
  60018. } else {
  60019. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  60020. }
  60021. } else {
  60022. if ( texture.isDepthTexture ) {
  60023. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  60024. } else {
  60025. sourceGPU = this.context.getCurrentTexture();
  60026. }
  60027. }
  60028. const destinationGPU = this.get( texture ).texture;
  60029. if ( sourceGPU.format !== destinationGPU.format ) {
  60030. error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  60031. return;
  60032. }
  60033. let encoder;
  60034. if ( renderContextData.currentPass ) {
  60035. renderContextData.currentPass.end();
  60036. encoder = renderContextData.encoder;
  60037. } else {
  60038. _commandEncoderDescriptor.label = 'copyFramebufferToTexture_' + texture.id;
  60039. encoder = this.device.createCommandEncoder( _commandEncoderDescriptor );
  60040. _commandEncoderDescriptor.reset();
  60041. }
  60042. _texelCopyTextureInfoSrc.texture = sourceGPU;
  60043. _texelCopyTextureInfoSrc.origin.x = rectangle.x;
  60044. _texelCopyTextureInfoSrc.origin.y = rectangle.y;
  60045. _texelCopyTextureInfoDst.texture = destinationGPU;
  60046. _extent3D.width = rectangle.z;
  60047. _extent3D.height = rectangle.w;
  60048. encoder.copyTextureToTexture(
  60049. _texelCopyTextureInfoSrc,
  60050. _texelCopyTextureInfoDst,
  60051. _extent3D
  60052. );
  60053. _texelCopyTextureInfoSrc.reset();
  60054. _texelCopyTextureInfoDst.reset();
  60055. _extent3D.reset();
  60056. // mipmaps must be genereated with the same encoder otherwise the copied texture data
  60057. // might be out-of-sync, see #31768
  60058. if ( texture.generateMipmaps ) {
  60059. this.textureUtils.generateMipmaps( texture, encoder );
  60060. }
  60061. if ( renderContextData.currentPass ) {
  60062. const { descriptor } = renderContextData;
  60063. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  60064. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  60065. }
  60066. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  60067. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  60068. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  60069. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  60070. if ( renderContext.viewport ) {
  60071. this.updateViewport( renderContext );
  60072. }
  60073. if ( renderContext.scissor ) {
  60074. this.updateScissor( renderContext );
  60075. }
  60076. } else {
  60077. submit( this.device, encoder.finish() );
  60078. }
  60079. }
  60080. /**
  60081. * Checks if the given compatibility is supported by the backend.
  60082. *
  60083. * @param {string} name - The compatibility name.
  60084. * @return {boolean} Whether the compatibility is supported or not.
  60085. */
  60086. hasCompatibility( name ) {
  60087. if ( this._compatibility[ name ] !== undefined ) {
  60088. return this._compatibility[ name ];
  60089. }
  60090. return super.hasCompatibility( name );
  60091. }
  60092. dispose() {
  60093. this.bindingUtils.dispose();
  60094. this.textureUtils.dispose();
  60095. if ( this.occludedResolveCache ) {
  60096. for ( const buffer of this.occludedResolveCache.values() ) {
  60097. buffer.destroy();
  60098. }
  60099. this.occludedResolveCache.clear();
  60100. }
  60101. if ( this.timestampQueryPool ) {
  60102. for ( const queryPool of Object.values( this.timestampQueryPool ) ) {
  60103. if ( queryPool !== null ) queryPool.dispose();
  60104. }
  60105. }
  60106. if ( this.parameters.device === undefined && this.device !== null ) {
  60107. this.device.destroy();
  60108. }
  60109. }
  60110. }
  60111. /**
  60112. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  60113. *
  60114. * @augments SpotLight
  60115. */
  60116. class IESSpotLight extends SpotLight {
  60117. /**
  60118. * Constructs a new IES spot light.
  60119. *
  60120. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  60121. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  60122. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  60123. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  60124. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  60125. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  60126. */
  60127. constructor( color, intensity, distance, angle, penumbra, decay ) {
  60128. super( color, intensity, distance, angle, penumbra, decay );
  60129. /**
  60130. * The IES map. It's a lookup table that stores normalized attenuation factors
  60131. * (0.0 to 1.0) that represent the light's intensity at a specific angle.
  60132. *
  60133. * @type {?Texture}
  60134. * @default null
  60135. */
  60136. this.iesMap = null;
  60137. }
  60138. copy( source, recursive ) {
  60139. super.copy( source, recursive );
  60140. this.iesMap = source.iesMap;
  60141. return this;
  60142. }
  60143. }
  60144. /**
  60145. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  60146. *
  60147. * @augments SpotLight
  60148. */
  60149. class ProjectorLight extends SpotLight {
  60150. /**
  60151. * Constructs a new projector light.
  60152. *
  60153. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  60154. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  60155. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  60156. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  60157. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  60158. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  60159. */
  60160. constructor( color, intensity, distance, angle, penumbra, decay ) {
  60161. super( color, intensity, distance, angle, penumbra, decay );
  60162. /**
  60163. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  60164. *
  60165. * @type {?number}
  60166. * @default null
  60167. */
  60168. this.aspect = null;
  60169. }
  60170. copy( source, recursive ) {
  60171. super.copy( source, recursive );
  60172. this.aspect = source.aspect;
  60173. return this;
  60174. }
  60175. }
  60176. /**
  60177. * This version of a node library represents the standard version
  60178. * used in {@link WebGPURenderer}. It maps lights, tone mapping
  60179. * techniques and materials to node-based implementations.
  60180. *
  60181. * @private
  60182. * @augments NodeLibrary
  60183. */
  60184. class StandardNodeLibrary extends NodeLibrary {
  60185. /**
  60186. * Constructs a new standard node library.
  60187. */
  60188. constructor() {
  60189. super();
  60190. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  60191. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  60192. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  60193. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  60194. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  60195. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  60196. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  60197. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  60198. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  60199. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  60200. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  60201. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  60202. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  60203. this.addLight( PointLightNode, PointLight );
  60204. this.addLight( DirectionalLightNode, DirectionalLight );
  60205. this.addLight( RectAreaLightNode, RectAreaLight );
  60206. this.addLight( SpotLightNode, SpotLight );
  60207. this.addLight( AmbientLightNode, AmbientLight );
  60208. this.addLight( HemisphereLightNode, HemisphereLight );
  60209. this.addLight( LightProbeNode, LightProbe );
  60210. this.addLight( IESSpotLightNode, IESSpotLight );
  60211. this.addLight( ProjectorLightNode, ProjectorLight );
  60212. this.addToneMapping( linearToneMapping, LinearToneMapping );
  60213. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  60214. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  60215. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  60216. this.addToneMapping( agxToneMapping, AgXToneMapping );
  60217. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  60218. }
  60219. }
  60220. /*
  60221. const debugHandler = {
  60222. get: function ( target, name ) {
  60223. // Add |update
  60224. if ( /^(create|destroy)/.test( name ) ) log( 'WebGPUBackend.' + name );
  60225. return target[ name ];
  60226. }
  60227. };
  60228. */
  60229. /**
  60230. * This renderer is the new alternative of `WebGLRenderer`. `WebGPURenderer` has the ability
  60231. * to target different backends. By default, the renderer tries to use a WebGPU backend if the
  60232. * browser supports WebGPU. If not, `WebGPURenderer` falls backs to a WebGL 2 backend.
  60233. *
  60234. * @augments Renderer
  60235. */
  60236. class WebGPURenderer extends Renderer {
  60237. /**
  60238. * WebGPURenderer options.
  60239. *
  60240. * @typedef {Object} WebGPURenderer~Options
  60241. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  60242. * @property {boolean} [reversedDepthBuffer=false] - Whether reversed depth buffer is enabled or not.
  60243. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  60244. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  60245. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  60246. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  60247. * @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.
  60248. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  60249. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  60250. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  60251. * @property {number} [outputBufferType=HalfFloatType] - Defines the type of output buffers. The default `HalfFloatType` is recommend for best
  60252. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  60253. */
  60254. /**
  60255. * Constructs a new WebGPU renderer.
  60256. *
  60257. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  60258. */
  60259. constructor( parameters = {} ) {
  60260. let BackendClass;
  60261. if ( parameters.forceWebGL ) {
  60262. BackendClass = WebGLBackend;
  60263. } else {
  60264. BackendClass = WebGPUBackend;
  60265. parameters.getFallback = () => {
  60266. warn( 'WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  60267. return new WebGLBackend( parameters );
  60268. };
  60269. }
  60270. const backend = new BackendClass( parameters );
  60271. //super( new Proxy( backend, debugHandler ) );
  60272. super( backend, parameters );
  60273. /**
  60274. * The generic default value is overwritten with the
  60275. * standard node library for type mapping.
  60276. *
  60277. * @type {StandardNodeLibrary}
  60278. */
  60279. this.library = new StandardNodeLibrary();
  60280. /**
  60281. * This flag can be used for type testing.
  60282. *
  60283. * @type {boolean}
  60284. * @readonly
  60285. * @default true
  60286. */
  60287. this.isWebGPURenderer = true;
  60288. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  60289. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  60290. }
  60291. }
  60292. }
  60293. /**
  60294. * A specialized group which enables applications access to the
  60295. * Render Bundle API of WebGPU. The group with all its descendant nodes
  60296. * are considered as one render bundle and processed as such by
  60297. * the renderer.
  60298. *
  60299. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  60300. * With a WebGL backend, the group can technically be rendered but without
  60301. * any performance improvements.
  60302. *
  60303. * @augments Group
  60304. */
  60305. class BundleGroup extends Group {
  60306. /**
  60307. * Constructs a new bundle group.
  60308. */
  60309. constructor() {
  60310. super();
  60311. /**
  60312. * This flag can be used for type testing.
  60313. *
  60314. * @type {boolean}
  60315. * @readonly
  60316. * @default true
  60317. */
  60318. this.isBundleGroup = true;
  60319. /**
  60320. * This property is only relevant for detecting types
  60321. * during serialization/deserialization. It should always
  60322. * match the class name.
  60323. *
  60324. * @type {string}
  60325. * @readonly
  60326. * @default 'BundleGroup'
  60327. */
  60328. this.type = 'BundleGroup';
  60329. /**
  60330. * Whether the bundle is static or not. When set to `true`, the structure
  60331. * is assumed to be static and does not change. E.g. no new objects are
  60332. * added to the group.
  60333. *
  60334. * If a change is required, an update can still be forced by setting the
  60335. * `needsUpdate` flag to `true`.
  60336. *
  60337. * @type {boolean}
  60338. * @default true
  60339. */
  60340. this.static = true;
  60341. /**
  60342. * The bundle group's version.
  60343. *
  60344. * @type {number}
  60345. * @readonly
  60346. * @default 0
  60347. */
  60348. this.version = 0;
  60349. }
  60350. /**
  60351. * Set this property to `true` when the bundle group has changed.
  60352. *
  60353. * @type {boolean}
  60354. * @default false
  60355. * @param {boolean} value
  60356. */
  60357. set needsUpdate( value ) {
  60358. if ( value === true ) this.version ++;
  60359. }
  60360. }
  60361. /**
  60362. * This module is responsible to manage the rendering pipeline setups in apps.
  60363. * You usually create a single instance of this class and use it to define
  60364. * the output of your render pipeline and post processing effect chain.
  60365. * ```js
  60366. * const renderPipeline = new RenderPipeline( renderer );
  60367. *
  60368. * const scenePass = pass( scene, camera );
  60369. *
  60370. * renderPipeline.outputNode = scenePass;
  60371. * ```
  60372. *
  60373. * Note: This module can only be used with `WebGPURenderer`.
  60374. */
  60375. class RenderPipeline {
  60376. /**
  60377. * Constructs a new render pipeline management module.
  60378. *
  60379. * @param {Renderer} renderer - A reference to the renderer.
  60380. * @param {Node<vec4>} outputNode - An optional output node.
  60381. */
  60382. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  60383. /**
  60384. * A reference to the renderer.
  60385. *
  60386. * @type {Renderer}
  60387. */
  60388. this.renderer = renderer;
  60389. /**
  60390. * A node which defines the final output of the rendering
  60391. * pipeline. This is usually the last node in a chain
  60392. * of effect nodes.
  60393. *
  60394. * @type {Node<vec4>}
  60395. */
  60396. this.outputNode = outputNode;
  60397. /**
  60398. * Whether the default output tone mapping and color
  60399. * space transformation should be enabled or not.
  60400. *
  60401. * This is enabled by default but it must be disabled for
  60402. * effects that expect to be executed after tone mapping and color
  60403. * space conversion. A typical example is FXAA which
  60404. * requires sRGB input.
  60405. *
  60406. * When set to `false`, the app must control the output
  60407. * transformation with `RenderOutputNode`.
  60408. *
  60409. * ```js
  60410. * const outputPass = renderOutput( scenePass );
  60411. * ```
  60412. *
  60413. * @type {boolean}
  60414. */
  60415. this.outputColorTransform = true;
  60416. /**
  60417. * Must be set to `true` when the output node changes.
  60418. *
  60419. * @type {Node<vec4>}
  60420. */
  60421. this.needsUpdate = true;
  60422. const material = new NodeMaterial();
  60423. material.name = 'RenderPipeline';
  60424. /**
  60425. * The full screen quad that is used to render
  60426. * the effects.
  60427. *
  60428. * @private
  60429. * @type {QuadMesh}
  60430. */
  60431. this._quadMesh = new QuadMesh( material );
  60432. this._quadMesh.name = 'Render Pipeline';
  60433. /**
  60434. * The context of the render pipeline stack.
  60435. *
  60436. * @private
  60437. * @type {?Object}
  60438. * @default null
  60439. */
  60440. this._context = null;
  60441. /**
  60442. * The current tone mapping.
  60443. *
  60444. * @private
  60445. * @type {ToneMapping}
  60446. */
  60447. this._toneMapping = renderer.toneMapping;
  60448. /**
  60449. * The current output color space.
  60450. *
  60451. * @private
  60452. * @type {ColorSpace}
  60453. */
  60454. this._outputColorSpace = renderer.outputColorSpace;
  60455. }
  60456. /**
  60457. * When `RenderPipeline` is used to apply rendering pipeline and post processing effects,
  60458. * the application must use this version of `render()` inside
  60459. * its animation loop (not the one from the renderer).
  60460. */
  60461. render() {
  60462. const renderer = this.renderer;
  60463. this._update();
  60464. if ( this._context.onBeforeRenderPipeline !== null ) this._context.onBeforeRenderPipeline();
  60465. const toneMapping = renderer.toneMapping;
  60466. const outputColorSpace = renderer.outputColorSpace;
  60467. renderer.toneMapping = NoToneMapping;
  60468. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  60469. //
  60470. const currentXR = renderer.xr.enabled;
  60471. renderer.xr.enabled = false;
  60472. this._quadMesh.render( renderer );
  60473. renderer.xr.enabled = currentXR;
  60474. //
  60475. renderer.toneMapping = toneMapping;
  60476. renderer.outputColorSpace = outputColorSpace;
  60477. if ( this._context.onAfterRenderPipeline !== null ) this._context.onAfterRenderPipeline();
  60478. }
  60479. /**
  60480. * Returns the current context of the render pipeline stack.
  60481. *
  60482. * @readonly
  60483. * @type {?Object}
  60484. */
  60485. get context() {
  60486. return this._context;
  60487. }
  60488. /**
  60489. * Frees internal resources.
  60490. */
  60491. dispose() {
  60492. this._quadMesh.material.dispose();
  60493. }
  60494. /**
  60495. * Updates the state of the module.
  60496. *
  60497. * @private
  60498. */
  60499. _update() {
  60500. if ( this._toneMapping !== this.renderer.toneMapping ) {
  60501. this._toneMapping = this.renderer.toneMapping;
  60502. this.needsUpdate = true;
  60503. }
  60504. if ( this._outputColorSpace !== this.renderer.outputColorSpace ) {
  60505. this._outputColorSpace = this.renderer.outputColorSpace;
  60506. this.needsUpdate = true;
  60507. }
  60508. if ( this.needsUpdate === true ) {
  60509. const toneMapping = this._toneMapping;
  60510. const outputColorSpace = this._outputColorSpace;
  60511. const context = {
  60512. renderPipeline: this,
  60513. onBeforeRenderPipeline: null,
  60514. onAfterRenderPipeline: null
  60515. };
  60516. let outputNode = this.outputNode;
  60517. if ( this.outputColorTransform === true ) {
  60518. outputNode = outputNode.context( context );
  60519. outputNode = renderOutput( outputNode, toneMapping, outputColorSpace );
  60520. } else {
  60521. context.toneMapping = toneMapping;
  60522. context.outputColorSpace = outputColorSpace;
  60523. outputNode = outputNode.context( context );
  60524. }
  60525. this._context = context;
  60526. this._quadMesh.material.fragmentNode = outputNode;
  60527. this._quadMesh.material.needsUpdate = true;
  60528. this.needsUpdate = false;
  60529. }
  60530. }
  60531. /**
  60532. * When `RenderPipeline` is used to apply rendering pipeline and post processing effects,
  60533. * the application must use this version of `renderAsync()` inside
  60534. * its animation loop (not the one from the renderer).
  60535. *
  60536. * @async
  60537. * @deprecated
  60538. * @return {Promise} A Promise that resolves when the render has been finished.
  60539. */
  60540. async renderAsync() {
  60541. warnOnce( 'RenderPipeline: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  60542. await this.renderer.init();
  60543. this.render();
  60544. }
  60545. }
  60546. /**
  60547. * @deprecated since r183. Use {@link RenderPipeline} instead. PostProcessing has been renamed to RenderPipeline.
  60548. *
  60549. * This class is a wrapper for backward compatibility and will be removed in a future version.
  60550. */
  60551. class PostProcessing extends RenderPipeline {
  60552. /**
  60553. * Constructs a new post processing management module.
  60554. *
  60555. * @param {Renderer} renderer - A reference to the renderer.
  60556. * @param {Node<vec4>} outputNode - An optional output node.
  60557. * @deprecated since r183. Use {@link RenderPipeline} instead.
  60558. */
  60559. constructor( renderer, outputNode ) {
  60560. warnOnce( 'PostProcessing: "PostProcessing" has been renamed to "RenderPipeline". Please update your code to use "THREE.RenderPipeline" instead.' ); // @deprecated, r183
  60561. super( renderer, outputNode );
  60562. }
  60563. }
  60564. /**
  60565. * A readback buffer is used to transfer data from the GPU to the CPU.
  60566. * It is primarily used to read back compute shader results.
  60567. *
  60568. * @augments EventDispatcher
  60569. */
  60570. class ReadbackBuffer extends EventDispatcher {
  60571. /**
  60572. * Constructs a new readback buffer.
  60573. *
  60574. * @param {number} maxByteLength - The maximum size of the buffer to be read back.
  60575. */
  60576. constructor( maxByteLength ) {
  60577. super();
  60578. /**
  60579. * Name used for debugging purposes.
  60580. *
  60581. * @type {string}
  60582. */
  60583. this.name = '';
  60584. /**
  60585. * The mapped, read back array buffer.
  60586. *
  60587. * @type {ArrayBuffer|null}
  60588. */
  60589. this.buffer = null;
  60590. /**
  60591. * The maximum size of the buffer to be read back.
  60592. *
  60593. * @type {number}
  60594. */
  60595. this.maxByteLength = maxByteLength;
  60596. /**
  60597. * This flag can be used for type testing.
  60598. *
  60599. * @type {boolean}
  60600. * @readonly
  60601. * @default true
  60602. */
  60603. this.isReadbackBuffer = true;
  60604. this._mapped = false;
  60605. }
  60606. /**
  60607. * Releases the mapped buffer data so the GPU buffer can be
  60608. * used by the GPU again.
  60609. *
  60610. * Note: Any `ArrayBuffer` data associated with this readback buffer
  60611. * are removed and no longer accessible after calling this method.
  60612. */
  60613. release() {
  60614. this.dispatchEvent( { type: 'release' } );
  60615. }
  60616. /**
  60617. * Frees internal resources.
  60618. */
  60619. dispose() {
  60620. this.dispatchEvent( { type: 'dispose' } );
  60621. }
  60622. }
  60623. /**
  60624. * This special type of texture is intended for compute shaders.
  60625. * It can be used to compute the data of a texture with a compute shader.
  60626. *
  60627. * Note: This type of texture can only be used with `WebGPURenderer`
  60628. * and a WebGPU backend.
  60629. *
  60630. * @augments Texture
  60631. */
  60632. class StorageTexture extends Texture {
  60633. /**
  60634. * Constructs a new storage texture.
  60635. *
  60636. * @param {number} [width=1] - The storage texture's width.
  60637. * @param {number} [height=1] - The storage texture's height.
  60638. */
  60639. constructor( width = 1, height = 1 ) {
  60640. super();
  60641. /**
  60642. * The image object which just represents the texture's dimension.
  60643. *
  60644. * @type {{width: number, height: number}}
  60645. */
  60646. this.image = { width, height };
  60647. /**
  60648. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  60649. *
  60650. * @type {number}
  60651. */
  60652. this.magFilter = LinearFilter;
  60653. /**
  60654. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  60655. *
  60656. * @type {number}
  60657. */
  60658. this.minFilter = LinearFilter;
  60659. /**
  60660. * This flag can be used for type testing.
  60661. *
  60662. * @type {boolean}
  60663. * @readonly
  60664. * @default true
  60665. */
  60666. this.isStorageTexture = true;
  60667. /**
  60668. * When `true`, mipmaps will be auto-generated after compute writes.
  60669. * When `false`, mipmaps must be written manually via compute shaders.
  60670. *
  60671. * @type {boolean}
  60672. * @default true
  60673. */
  60674. this.mipmapsAutoUpdate = true;
  60675. }
  60676. /**
  60677. * Sets the size of the storage texture.
  60678. *
  60679. * @param {number} width - The new width of the storage texture.
  60680. * @param {number} height - The new height of the storage texture.
  60681. */
  60682. setSize( width, height ) {
  60683. if ( this.image.width !== width || this.image.height !== height ) {
  60684. this.image.width = width;
  60685. this.image.height = height;
  60686. this.dispose();
  60687. }
  60688. }
  60689. }
  60690. /**
  60691. * This special type of texture is intended for compute shaders.
  60692. * It can be used to compute the data of a texture with a compute shader.
  60693. *
  60694. * Note: This type of texture can only be used with `WebGPURenderer`
  60695. * and a WebGPU backend.
  60696. *
  60697. * @augments Texture
  60698. */
  60699. class Storage3DTexture extends Texture {
  60700. /**
  60701. * Constructs a new storage texture.
  60702. *
  60703. * @param {number} [width=1] - The storage texture's width.
  60704. * @param {number} [height=1] - The storage texture's height.
  60705. * @param {number} [depth=1] - The storage texture's depth.
  60706. */
  60707. constructor( width = 1, height = 1, depth = 1 ) {
  60708. super();
  60709. //inherited from texture. Must be false for 3DTexture
  60710. this.isArrayTexture = false;
  60711. /**
  60712. * The image object which just represents the texture's dimension.
  60713. *
  60714. * @type {{width: number, height: number, depth: number}}
  60715. */
  60716. this.image = { width, height, depth };
  60717. /**
  60718. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  60719. *
  60720. * @type {number}
  60721. */
  60722. this.magFilter = LinearFilter;
  60723. /**
  60724. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  60725. *
  60726. * @type {number}
  60727. */
  60728. this.minFilter = LinearFilter;
  60729. /**
  60730. * This defines how the texture is wrapped in the depth direction and corresponds to
  60731. * *W* in UVW mapping.
  60732. *
  60733. * @type {number}
  60734. */
  60735. this.wrapR = ClampToEdgeWrapping;
  60736. /**
  60737. * This flag can be used for type testing.
  60738. *
  60739. * @type {boolean}
  60740. * @readonly
  60741. * @default true
  60742. */
  60743. this.isStorageTexture = true;
  60744. /**
  60745. * Indicates whether this texture is a 3D texture.
  60746. *
  60747. * @type {boolean}
  60748. *
  60749. */
  60750. this.is3DTexture = true;
  60751. }
  60752. /**
  60753. * Sets the size of the storage 3d texture.
  60754. *
  60755. * @param {number} width - The new width of the storage texture.
  60756. * @param {number} height - The new height of the storage texture.
  60757. * @param {number} depth - The new depth of the storage texture.
  60758. */
  60759. setSize( width, height, depth ) {
  60760. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  60761. this.image.width = width;
  60762. this.image.height = height;
  60763. this.image.depth = depth;
  60764. this.dispose();
  60765. }
  60766. }
  60767. }
  60768. /**
  60769. * This special type of texture is intended for compute shaders.
  60770. * It can be used to compute the data of a texture with a compute shader.
  60771. *
  60772. * Note: This type of texture can only be used with `WebGPURenderer`
  60773. * and a WebGPU backend.
  60774. *
  60775. * @augments Texture
  60776. */
  60777. class StorageArrayTexture extends Texture {
  60778. /**
  60779. * Constructs a new storage texture.
  60780. *
  60781. * @param {number} [width=1] - The storage texture's width.
  60782. * @param {number} [height=1] - The storage texture's height.
  60783. * @param {number} [depth=1] - The storage texture's depth.
  60784. */
  60785. constructor( width = 1, height = 1, depth = 1 ) {
  60786. super();
  60787. //inherited from texture
  60788. this.isArrayTexture = true;
  60789. /**
  60790. * The image object which just represents the texture's dimension.
  60791. *
  60792. * @type {{width: number, height: number, depth: number}}
  60793. */
  60794. this.image = { width, height, depth };
  60795. /**
  60796. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  60797. *
  60798. * @type {number}
  60799. */
  60800. this.magFilter = LinearFilter;
  60801. /**
  60802. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  60803. *
  60804. * @type {number}
  60805. */
  60806. this.minFilter = LinearFilter;
  60807. /**
  60808. * This flag can be used for type testing.
  60809. *
  60810. * @type {boolean}
  60811. * @readonly
  60812. * @default true
  60813. */
  60814. this.isStorageTexture = true;
  60815. }
  60816. /**
  60817. * Sets the size of the storage array texture.
  60818. *
  60819. * @param {number} width - The new width of the storage texture.
  60820. * @param {number} height - The new height of the storage texture.
  60821. * @param {number} depth - The new depth of the storage texture.
  60822. */
  60823. setSize( width, height, depth ) {
  60824. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  60825. this.image.width = width;
  60826. this.image.height = height;
  60827. this.image.depth = depth;
  60828. this.dispose();
  60829. }
  60830. }
  60831. }
  60832. /**
  60833. * This special type of buffer attribute is intended for compute shaders.
  60834. * It can be used to encode draw parameters for indirect draw calls.
  60835. *
  60836. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  60837. * and a WebGPU backend.
  60838. *
  60839. * @augments StorageBufferAttribute
  60840. */
  60841. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  60842. /**
  60843. * Constructs a new storage buffer attribute.
  60844. *
  60845. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  60846. * The subsequent parameter is then obsolete.
  60847. * @param {number} itemSize - The item size.
  60848. */
  60849. constructor( count, itemSize ) {
  60850. super( count, itemSize, Uint32Array );
  60851. /**
  60852. * This flag can be used for type testing.
  60853. *
  60854. * @type {boolean}
  60855. * @readonly
  60856. * @default true
  60857. */
  60858. this.isIndirectStorageBufferAttribute = true;
  60859. }
  60860. }
  60861. /**
  60862. * A loader for loading node objects in the three.js JSON Object/Scene format.
  60863. *
  60864. * @augments Loader
  60865. */
  60866. class NodeLoader extends Loader {
  60867. /**
  60868. * Constructs a new node loader.
  60869. *
  60870. * @param {LoadingManager} [manager] - A reference to a loading manager.
  60871. */
  60872. constructor( manager ) {
  60873. super( manager );
  60874. /**
  60875. * Represents a dictionary of textures.
  60876. *
  60877. * @type {Object<string,Texture>}
  60878. */
  60879. this.textures = {};
  60880. /**
  60881. * Represents a dictionary of node types.
  60882. *
  60883. * @type {Object<string,Node.constructor>}
  60884. */
  60885. this.nodes = {};
  60886. }
  60887. /**
  60888. * Loads the node definitions from the given URL.
  60889. *
  60890. * @param {string} url - The path/URL of the file to be loaded.
  60891. * @param {Function} onLoad - Will be called when load completes.
  60892. * @param {Function} onProgress - Will be called while load progresses.
  60893. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  60894. */
  60895. load( url, onLoad, onProgress, onError ) {
  60896. const loader = new FileLoader( this.manager );
  60897. loader.setPath( this.path );
  60898. loader.setRequestHeader( this.requestHeader );
  60899. loader.setWithCredentials( this.withCredentials );
  60900. loader.load( url, ( text ) => {
  60901. try {
  60902. onLoad( this.parse( JSON.parse( text ) ) );
  60903. } catch ( e ) {
  60904. if ( onError ) {
  60905. onError( e );
  60906. } else {
  60907. error( e );
  60908. }
  60909. this.manager.itemError( url );
  60910. }
  60911. }, onProgress, onError );
  60912. }
  60913. /**
  60914. * Parse the node dependencies for the loaded node.
  60915. *
  60916. * @param {Array<Object>} [json] - The JSON definition
  60917. * @return {Object<string,Node>} A dictionary with node dependencies.
  60918. */
  60919. parseNodes( json ) {
  60920. const nodes = {};
  60921. if ( json !== undefined ) {
  60922. for ( const nodeJSON of json ) {
  60923. const { uuid, type } = nodeJSON;
  60924. nodes[ uuid ] = this.createNodeFromType( type );
  60925. nodes[ uuid ].uuid = uuid;
  60926. }
  60927. const meta = { nodes, textures: this.textures };
  60928. for ( const nodeJSON of json ) {
  60929. nodeJSON.meta = meta;
  60930. const node = nodes[ nodeJSON.uuid ];
  60931. node.deserialize( nodeJSON );
  60932. delete nodeJSON.meta;
  60933. }
  60934. }
  60935. return nodes;
  60936. }
  60937. /**
  60938. * Parses the node from the given JSON.
  60939. *
  60940. * @param {Object} json - The JSON definition
  60941. * @param {string} json.type - The node type.
  60942. * @param {string} json.uuid - The node UUID.
  60943. * @param {Array<Object>} [json.nodes] - The node dependencies.
  60944. * @param {Object} [json.meta] - The meta data.
  60945. * @return {Node} The parsed node.
  60946. */
  60947. parse( json ) {
  60948. const node = this.createNodeFromType( json.type );
  60949. node.uuid = json.uuid;
  60950. const nodes = this.parseNodes( json.nodes );
  60951. const meta = { nodes, textures: this.textures };
  60952. json.meta = meta;
  60953. node.deserialize( json );
  60954. delete json.meta;
  60955. return node;
  60956. }
  60957. /**
  60958. * Defines the dictionary of textures.
  60959. *
  60960. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  60961. * @return {NodeLoader} A reference to this loader.
  60962. */
  60963. setTextures( value ) {
  60964. this.textures = value;
  60965. return this;
  60966. }
  60967. /**
  60968. * Defines the dictionary of node types.
  60969. *
  60970. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  60971. * @return {NodeLoader} A reference to this loader.
  60972. */
  60973. setNodes( value ) {
  60974. this.nodes = value;
  60975. return this;
  60976. }
  60977. /**
  60978. * Creates a node object from the given type.
  60979. *
  60980. * @param {string} type - The node type.
  60981. * @return {Node} The created node instance.
  60982. */
  60983. createNodeFromType( type ) {
  60984. if ( this.nodes[ type ] === undefined ) {
  60985. error( 'NodeLoader: Node type not found:', type );
  60986. return float();
  60987. }
  60988. return new this.nodes[ type ]();
  60989. }
  60990. }
  60991. /**
  60992. * A special type of material loader for loading node materials.
  60993. *
  60994. * @augments MaterialLoader
  60995. */
  60996. class NodeMaterialLoader extends MaterialLoader {
  60997. /**
  60998. * Constructs a new node material loader.
  60999. *
  61000. * @param {LoadingManager} [manager] - A reference to a loading manager.
  61001. */
  61002. constructor( manager ) {
  61003. super( manager );
  61004. /**
  61005. * Represents a dictionary of node types.
  61006. *
  61007. * @type {Object<string,Node.constructor>}
  61008. */
  61009. this.nodes = {};
  61010. /**
  61011. * Represents a dictionary of node material types.
  61012. *
  61013. * @type {Object<string,NodeMaterial.constructor>}
  61014. */
  61015. this.nodeMaterials = {};
  61016. }
  61017. /**
  61018. * Parses the node material from the given JSON.
  61019. *
  61020. * @param {Object} json - The JSON definition
  61021. * @return {NodeMaterial}. The parsed material.
  61022. */
  61023. parse( json ) {
  61024. const material = super.parse( json );
  61025. const nodes = this.nodes;
  61026. const inputNodes = json.inputNodes;
  61027. for ( const property in inputNodes ) {
  61028. const uuid = inputNodes[ property ];
  61029. material[ property ] = nodes[ uuid ];
  61030. }
  61031. return material;
  61032. }
  61033. /**
  61034. * Defines the dictionary of node types.
  61035. *
  61036. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  61037. * @return {NodeLoader} A reference to this loader.
  61038. */
  61039. setNodes( value ) {
  61040. this.nodes = value;
  61041. return this;
  61042. }
  61043. /**
  61044. * Defines the dictionary of node material types.
  61045. *
  61046. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  61047. * @return {NodeLoader} A reference to this loader.
  61048. */
  61049. setNodeMaterials( value ) {
  61050. this.nodeMaterials = value;
  61051. return this;
  61052. }
  61053. /**
  61054. * Creates a node material from the given type.
  61055. *
  61056. * @param {string} type - The node material type.
  61057. * @return {Node} The created node material instance.
  61058. */
  61059. createMaterialFromType( type ) {
  61060. const materialClass = this.nodeMaterials[ type ];
  61061. if ( materialClass !== undefined ) {
  61062. return new materialClass();
  61063. }
  61064. return super.createMaterialFromType( type );
  61065. }
  61066. }
  61067. /**
  61068. * A special type of object loader for loading 3D objects using
  61069. * node materials.
  61070. *
  61071. * @augments ObjectLoader
  61072. */
  61073. class NodeObjectLoader extends ObjectLoader {
  61074. /**
  61075. * Constructs a new node object loader.
  61076. *
  61077. * @param {LoadingManager} [manager] - A reference to a loading manager.
  61078. */
  61079. constructor( manager ) {
  61080. super( manager );
  61081. /**
  61082. * Represents a dictionary of node types.
  61083. *
  61084. * @type {Object<string,Node.constructor>}
  61085. */
  61086. this.nodes = {};
  61087. /**
  61088. * Represents a dictionary of node material types.
  61089. *
  61090. * @type {Object<string,NodeMaterial.constructor>}
  61091. */
  61092. this.nodeMaterials = {};
  61093. /**
  61094. * A reference to hold the `nodes` JSON property.
  61095. *
  61096. * @private
  61097. * @type {?Object[]}
  61098. */
  61099. this._nodesJSON = null;
  61100. }
  61101. /**
  61102. * Defines the dictionary of node types.
  61103. *
  61104. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  61105. * @return {NodeObjectLoader} A reference to this loader.
  61106. */
  61107. setNodes( value ) {
  61108. this.nodes = value;
  61109. return this;
  61110. }
  61111. /**
  61112. * Defines the dictionary of node material types.
  61113. *
  61114. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  61115. * @return {NodeObjectLoader} A reference to this loader.
  61116. */
  61117. setNodeMaterials( value ) {
  61118. this.nodeMaterials = value;
  61119. return this;
  61120. }
  61121. /**
  61122. * Parses the node objects from the given JSON.
  61123. *
  61124. * @param {Object} json - The JSON definition
  61125. * @param {Function} onLoad - The onLoad callback function.
  61126. * @return {Object3D}. The parsed 3D object.
  61127. */
  61128. parse( json, onLoad ) {
  61129. this._nodesJSON = json.nodes;
  61130. const data = super.parse( json, onLoad );
  61131. this._nodesJSON = null; // dispose
  61132. return data;
  61133. }
  61134. /**
  61135. * Async version of {@link NodeObjectLoader#parse}.
  61136. *
  61137. * @param {Object} json - The JSON definition
  61138. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  61139. */
  61140. async parseAsync( json ) {
  61141. this._nodesJSON = json.nodes;
  61142. const data = await super.parseAsync( json );
  61143. this._nodesJSON = null; // dispose
  61144. return data;
  61145. }
  61146. /**
  61147. * Parses the node objects from the given JSON and textures.
  61148. *
  61149. * @param {Object[]} json - The JSON definition
  61150. * @param {Object<string,Texture>} textures - The texture library.
  61151. * @return {Object<string,Node>}. The parsed nodes.
  61152. */
  61153. parseNodes( json, textures ) {
  61154. if ( json !== undefined ) {
  61155. const loader = new NodeLoader();
  61156. loader.setNodes( this.nodes );
  61157. loader.setTextures( textures );
  61158. return loader.parseNodes( json );
  61159. }
  61160. return {};
  61161. }
  61162. /**
  61163. * Parses the node objects from the given JSON and textures.
  61164. *
  61165. * @param {Object} json - The JSON definition
  61166. * @param {Object<string,Texture>} textures - The texture library.
  61167. * @return {Object<string,NodeMaterial>}. The parsed materials.
  61168. */
  61169. parseMaterials( json, textures ) {
  61170. const materials = {};
  61171. if ( json !== undefined ) {
  61172. const nodes = this.parseNodes( this._nodesJSON, textures );
  61173. const loader = new NodeMaterialLoader();
  61174. loader.setTextures( textures );
  61175. loader.setNodes( nodes );
  61176. loader.setNodeMaterials( this.nodeMaterials );
  61177. for ( let i = 0, l = json.length; i < l; i ++ ) {
  61178. const data = json[ i ];
  61179. materials[ data.uuid ] = loader.parse( data );
  61180. }
  61181. }
  61182. return materials;
  61183. }
  61184. }
  61185. /**
  61186. * This version of a node library represents a basic version
  61187. * just focusing on lights and tone mapping techniques.
  61188. *
  61189. * @private
  61190. * @augments NodeLibrary
  61191. */
  61192. class BasicNodeLibrary extends NodeLibrary {
  61193. /**
  61194. * Constructs a new basic node library.
  61195. */
  61196. constructor() {
  61197. super();
  61198. this.addLight( PointLightNode, PointLight );
  61199. this.addLight( DirectionalLightNode, DirectionalLight );
  61200. this.addLight( RectAreaLightNode, RectAreaLight );
  61201. this.addLight( SpotLightNode, SpotLight );
  61202. this.addLight( AmbientLightNode, AmbientLight );
  61203. this.addLight( HemisphereLightNode, HemisphereLight );
  61204. this.addLight( LightProbeNode, LightProbe );
  61205. this.addLight( IESSpotLightNode, IESSpotLight );
  61206. this.addLight( ProjectorLightNode, ProjectorLight );
  61207. this.addToneMapping( linearToneMapping, LinearToneMapping );
  61208. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  61209. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  61210. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  61211. this.addToneMapping( agxToneMapping, AgXToneMapping );
  61212. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  61213. }
  61214. }
  61215. /**
  61216. * In earlier three.js versions, clipping was defined globally
  61217. * on the renderer or on material level. This special version of
  61218. * `THREE.Group` allows to encode the clipping state into the scene
  61219. * graph. Meaning if you create an instance of this group, all
  61220. * descendant 3D objects will be affected by the respective clipping
  61221. * planes.
  61222. *
  61223. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  61224. *
  61225. * @augments Group
  61226. */
  61227. class ClippingGroup extends Group {
  61228. /**
  61229. * Constructs a new clipping group.
  61230. */
  61231. constructor() {
  61232. super();
  61233. /**
  61234. * This flag can be used for type testing.
  61235. *
  61236. * @type {boolean}
  61237. * @readonly
  61238. * @default true
  61239. */
  61240. this.isClippingGroup = true;
  61241. /**
  61242. * An array with clipping planes.
  61243. *
  61244. * @type {Array<Plane>}
  61245. */
  61246. this.clippingPlanes = [];
  61247. /**
  61248. * Whether clipping should be enabled or not.
  61249. *
  61250. * @type {boolean}
  61251. * @default true
  61252. */
  61253. this.enabled = true;
  61254. /**
  61255. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  61256. *
  61257. * @type {boolean}
  61258. * @default false
  61259. */
  61260. this.clipIntersection = false;
  61261. /**
  61262. * Whether shadows should be clipped or not.
  61263. *
  61264. * @type {boolean}
  61265. * @default false
  61266. */
  61267. this.clipShadows = false;
  61268. }
  61269. }
  61270. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AtomicFunctionNode, AttributeNode, BackSide, BarrierNode, BasicEnvironmentNode, BasicLightMapNode, BasicNodeLibrary, BasicShadowMap, BatchNode, BitcastNode, BitcountNode, BlendMode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BuiltinNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CanvasTarget, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, ClippingNode, CodeNode, Color, ColorManagement, ColorSpaceNode, Compatibility, ComputeBuiltinNode, ComputeNode, ConditionalNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeDepthTexture, CubeMapNode, CubeReflectionMapping, CubeRefractionMapping, CubeRenderTarget, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, CylinderGeometry, DataArrayTexture, DataTexture, DebugNode, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, EventDispatcher, EventNode, ExpressionNode, FileLoader, FlipNode, Float16BufferAttribute, Float32BufferAttribute, FloatType, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FrustumArray, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeBuilder, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InputNode, InspectorBase, InspectorNode, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, 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, MorphNode, 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, 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, SkinningNode, Sphere, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StackTrace, StaticDrawUsage, Storage3DTexture, StorageArrayElementNode, StorageArrayTexture, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, 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, WebGLCapabilities, WebGLCoordinateSystem, WebGPUBackend, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, WorkgroupInfoNode, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, error, log$1 as log, shaderStages, vectorComponents, warn, warnOnce };
粤ICP备19079148号