three.webgpu.js 1.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810
  1. /**
  2. * @license
  3. * Copyright 2010-2025 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, NearestFilter, Sphere, BackSide, DoubleSide, Euler, CubeTexture, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, NoNormalPacking, NormalRGPacking, NormalGAPacking, ObjectSpaceNormalMap, RGFormat, RED_GREEN_RGTC2_Format, RG11_EAC_Format, InstancedInterleavedBuffer, InstancedBufferAttribute, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, SRGBColorSpace, WebGLCubeRenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, DataTexture, HalfFloatType, ClampToEdgeWrapping, BufferGeometry, OrthographicCamera, PerspectiveCamera, RenderTarget, LinearSRGBColorSpace, RGBAFormat, CubeUVReflectionMapping, BufferAttribute, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, PointsMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, arrayNeedsUint32, Camera, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, Plane, Object3D, LinearMipMapLinearFilter, Float32BufferAttribute, UVMapping, VSMShadowMap, LessCompare, BasicShadowMap, CubeDepthTexture, SphereGeometry, NormalBlending, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, ArrayCamera, PlaneGeometry, FrontSide, CustomBlending, AddEquation, ZeroFactor, CylinderGeometry, Quaternion, WebXRController, RAD2DEG, PCFShadowMap, FrustumArray, Frustum, RedIntegerFormat, RedFormat, ShortType, ByteType, UnsignedShortType, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, TimestampQuery, createCanvasElement, ReverseSubtractEquation, SubtractEquation, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, DstAlphaFactor, DstColorFactor, SrcAlphaSaturateFactor, SrcAlphaFactor, SrcColorFactor, OneFactor, CullFaceNone, CullFaceBack, CullFaceFront, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, UnsignedInt101111Type, AlphaFormat, 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, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, SIGNED_RED_GREEN_RGTC2_Format, MirroredRepeatWrapping, RepeatWrapping, NearestMipmapNearestFilter, NotEqualCompare, GreaterCompare, GreaterEqualCompare, EqualCompare, LessEqualCompare, 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, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, 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, ExternalTexture, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, 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, PCFSoftShadowMap, Path, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, 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. * This class is used by {@link WebGPURenderer} as management component.
  74. * It's primary purpose is to determine whether render objects require a
  75. * refresh right before they are going to be rendered or not.
  76. */
  77. class NodeMaterialObserver {
  78. /**
  79. * Constructs a new node material observer.
  80. *
  81. * @param {NodeBuilder} builder - The node builder.
  82. */
  83. constructor( builder ) {
  84. /**
  85. * A node material can be used by more than one render object so the
  86. * monitor must maintain a list of render objects.
  87. *
  88. * @type {WeakMap<RenderObject,Object>}
  89. */
  90. this.renderObjects = new WeakMap();
  91. /**
  92. * Whether the material uses node objects or not.
  93. *
  94. * @type {boolean}
  95. */
  96. this.hasNode = this.containsNode( builder );
  97. /**
  98. * Whether the node builder's 3D object is animated or not.
  99. *
  100. * @type {boolean}
  101. */
  102. this.hasAnimation = builder.object.isSkinnedMesh === true;
  103. /**
  104. * A list of all possible material uniforms
  105. *
  106. * @type {Array<string>}
  107. */
  108. this.refreshUniforms = refreshUniforms;
  109. /**
  110. * Holds the current render ID from the node frame.
  111. *
  112. * @type {number}
  113. * @default 0
  114. */
  115. this.renderId = 0;
  116. }
  117. /**
  118. * Returns `true` if the given render object is verified for the first time of this observer.
  119. *
  120. * @param {RenderObject} renderObject - The render object.
  121. * @return {boolean} Whether the given render object is verified for the first time of this observer.
  122. */
  123. firstInitialization( renderObject ) {
  124. const hasInitialized = this.renderObjects.has( renderObject );
  125. if ( hasInitialized === false ) {
  126. this.getRenderObjectData( renderObject );
  127. return true;
  128. }
  129. return false;
  130. }
  131. /**
  132. * Returns `true` if the current rendering produces motion vectors.
  133. *
  134. * @param {Renderer} renderer - The renderer.
  135. * @return {boolean} Whether the current rendering produces motion vectors or not.
  136. */
  137. needsVelocity( renderer ) {
  138. const mrt = renderer.getMRT();
  139. return ( mrt !== null && mrt.has( 'velocity' ) );
  140. }
  141. /**
  142. * Returns monitoring data for the given render object.
  143. *
  144. * @param {RenderObject} renderObject - The render object.
  145. * @return {Object} The monitoring data.
  146. */
  147. getRenderObjectData( renderObject ) {
  148. let data = this.renderObjects.get( renderObject );
  149. if ( data === undefined ) {
  150. const { geometry, material, object } = renderObject;
  151. data = {
  152. material: this.getMaterialData( material ),
  153. geometry: {
  154. id: geometry.id,
  155. attributes: this.getAttributesData( geometry.attributes ),
  156. indexVersion: geometry.index ? geometry.index.version : null,
  157. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  158. },
  159. worldMatrix: object.matrixWorld.clone()
  160. };
  161. if ( object.center ) {
  162. data.center = object.center.clone();
  163. }
  164. if ( object.morphTargetInfluences ) {
  165. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  166. }
  167. if ( renderObject.bundle !== null ) {
  168. data.version = renderObject.bundle.version;
  169. }
  170. if ( data.material.transmission > 0 ) {
  171. const { width, height } = renderObject.context;
  172. data.bufferWidth = width;
  173. data.bufferHeight = height;
  174. }
  175. data.lights = this.getLightsData( renderObject.lightsNode.getLights() );
  176. this.renderObjects.set( renderObject, data );
  177. }
  178. return data;
  179. }
  180. /**
  181. * Returns an attribute data structure holding the attributes versions for
  182. * monitoring.
  183. *
  184. * @param {Object} attributes - The geometry attributes.
  185. * @return {Object} An object for monitoring the versions of attributes.
  186. */
  187. getAttributesData( attributes ) {
  188. const attributesData = {};
  189. for ( const name in attributes ) {
  190. const attribute = attributes[ name ];
  191. attributesData[ name ] = {
  192. version: attribute.version
  193. };
  194. }
  195. return attributesData;
  196. }
  197. /**
  198. * Returns `true` if the node builder's material uses
  199. * node properties.
  200. *
  201. * @param {NodeBuilder} builder - The current node builder.
  202. * @return {boolean} Whether the node builder's material uses node properties or not.
  203. */
  204. containsNode( builder ) {
  205. const material = builder.material;
  206. for ( const property in material ) {
  207. if ( material[ property ] && material[ property ].isNode )
  208. return true;
  209. }
  210. if ( builder.context.modelViewMatrix || builder.context.modelNormalViewMatrix || builder.context.getAO || builder.context.getShadow )
  211. return true;
  212. return false;
  213. }
  214. /**
  215. * Returns a material data structure holding the material property values for
  216. * monitoring.
  217. *
  218. * @param {Material} material - The material.
  219. * @return {Object} An object for monitoring material properties.
  220. */
  221. getMaterialData( material ) {
  222. const data = {};
  223. for ( const property of this.refreshUniforms ) {
  224. const value = material[ property ];
  225. if ( value === null || value === undefined ) continue;
  226. if ( typeof value === 'object' && value.clone !== undefined ) {
  227. if ( value.isTexture === true ) {
  228. data[ property ] = { id: value.id, version: value.version };
  229. } else {
  230. data[ property ] = value.clone();
  231. }
  232. } else {
  233. data[ property ] = value;
  234. }
  235. }
  236. return data;
  237. }
  238. /**
  239. * Returns `true` if the given render object has not changed its state.
  240. *
  241. * @param {RenderObject} renderObject - The render object.
  242. * @param {Array<Light>} lightsData - The current material lights.
  243. * @return {boolean} Whether the given render object has changed its state or not.
  244. */
  245. equals( renderObject, lightsData ) {
  246. const { object, material, geometry } = renderObject;
  247. const renderObjectData = this.getRenderObjectData( renderObject );
  248. // world matrix
  249. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  250. renderObjectData.worldMatrix.copy( object.matrixWorld );
  251. return false;
  252. }
  253. // material
  254. const materialData = renderObjectData.material;
  255. for ( const property in materialData ) {
  256. const value = materialData[ property ];
  257. const mtlValue = material[ property ];
  258. if ( value.equals !== undefined ) {
  259. if ( value.equals( mtlValue ) === false ) {
  260. value.copy( mtlValue );
  261. return false;
  262. }
  263. } else if ( mtlValue.isTexture === true ) {
  264. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  265. value.id = mtlValue.id;
  266. value.version = mtlValue.version;
  267. return false;
  268. }
  269. } else if ( value !== mtlValue ) {
  270. materialData[ property ] = mtlValue;
  271. return false;
  272. }
  273. }
  274. if ( materialData.transmission > 0 ) {
  275. const { width, height } = renderObject.context;
  276. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  277. renderObjectData.bufferWidth = width;
  278. renderObjectData.bufferHeight = height;
  279. return false;
  280. }
  281. }
  282. // geometry
  283. const storedGeometryData = renderObjectData.geometry;
  284. const attributes = geometry.attributes;
  285. const storedAttributes = storedGeometryData.attributes;
  286. const storedAttributeNames = Object.keys( storedAttributes );
  287. const currentAttributeNames = Object.keys( attributes );
  288. if ( storedGeometryData.id !== geometry.id ) {
  289. storedGeometryData.id = geometry.id;
  290. return false;
  291. }
  292. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  293. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  294. return false;
  295. }
  296. // compare each attribute
  297. for ( const name of storedAttributeNames ) {
  298. const storedAttributeData = storedAttributes[ name ];
  299. const attribute = attributes[ name ];
  300. if ( attribute === undefined ) {
  301. // attribute was removed
  302. delete storedAttributes[ name ];
  303. return false;
  304. }
  305. if ( storedAttributeData.version !== attribute.version ) {
  306. storedAttributeData.version = attribute.version;
  307. return false;
  308. }
  309. }
  310. // check index
  311. const index = geometry.index;
  312. const storedIndexVersion = storedGeometryData.indexVersion;
  313. const currentIndexVersion = index ? index.version : null;
  314. if ( storedIndexVersion !== currentIndexVersion ) {
  315. storedGeometryData.indexVersion = currentIndexVersion;
  316. return false;
  317. }
  318. // check drawRange
  319. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  320. storedGeometryData.drawRange.start = geometry.drawRange.start;
  321. storedGeometryData.drawRange.count = geometry.drawRange.count;
  322. return false;
  323. }
  324. // morph targets
  325. if ( renderObjectData.morphTargetInfluences ) {
  326. let morphChanged = false;
  327. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  328. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  329. renderObjectData.morphTargetInfluences[ i ] = object.morphTargetInfluences[ i ];
  330. morphChanged = true;
  331. }
  332. }
  333. if ( morphChanged ) return false;
  334. }
  335. // lights
  336. if ( renderObjectData.lights ) {
  337. for ( let i = 0; i < lightsData.length; i ++ ) {
  338. if ( renderObjectData.lights[ i ].map !== lightsData[ i ].map ) {
  339. return false;
  340. }
  341. }
  342. }
  343. // center
  344. if ( renderObjectData.center ) {
  345. if ( renderObjectData.center.equals( object.center ) === false ) {
  346. renderObjectData.center.copy( object.center );
  347. return true;
  348. }
  349. }
  350. // bundle
  351. if ( renderObject.bundle !== null ) {
  352. renderObjectData.version = renderObject.bundle.version;
  353. }
  354. return true;
  355. }
  356. /**
  357. * Returns the lights data for the given material lights.
  358. *
  359. * @param {Array<Light>} materialLights - The material lights.
  360. * @return {Array<Object>} The lights data for the given material lights.
  361. */
  362. getLightsData( materialLights ) {
  363. const lights = [];
  364. for ( const light of materialLights ) {
  365. if ( light.isSpotLight === true && light.map !== null ) {
  366. // only add lights that have a map
  367. lights.push( { map: light.map.version } );
  368. }
  369. }
  370. return lights;
  371. }
  372. /**
  373. * Returns the lights for the given lights node and render ID.
  374. *
  375. * @param {LightsNode} lightsNode - The lights node.
  376. * @param {number} renderId - The render ID.
  377. * @return {Array<Object>} The lights for the given lights node and render ID.
  378. */
  379. getLights( lightsNode, renderId ) {
  380. if ( _lightsCache.has( lightsNode ) ) {
  381. const cached = _lightsCache.get( lightsNode );
  382. if ( cached.renderId === renderId ) {
  383. return cached.lightsData;
  384. }
  385. }
  386. const lightsData = this.getLightsData( lightsNode.getLights() );
  387. _lightsCache.set( lightsNode, { renderId, lightsData } );
  388. return lightsData;
  389. }
  390. /**
  391. * Checks if the given render object requires a refresh.
  392. *
  393. * @param {RenderObject} renderObject - The render object.
  394. * @param {NodeFrame} nodeFrame - The current node frame.
  395. * @return {boolean} Whether the given render object requires a refresh or not.
  396. */
  397. needsRefresh( renderObject, nodeFrame ) {
  398. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) || this.needsVelocity( nodeFrame.renderer ) )
  399. return true;
  400. const { renderId } = nodeFrame;
  401. if ( this.renderId !== renderId ) {
  402. this.renderId = renderId;
  403. return true;
  404. }
  405. const isStatic = renderObject.object.static === true;
  406. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  407. if ( isStatic || isBundle )
  408. return false;
  409. const lightsData = this.getLights( renderObject.lightsNode, renderId );
  410. const notEqual = this.equals( renderObject, lightsData ) !== true;
  411. return notEqual;
  412. }
  413. }
  414. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  415. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  416. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  417. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  418. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  419. function cyrb53( value, seed = 0 ) {
  420. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  421. if ( value instanceof Array ) {
  422. for ( let i = 0, val; i < value.length; i ++ ) {
  423. val = value[ i ];
  424. h1 = Math.imul( h1 ^ val, 2654435761 );
  425. h2 = Math.imul( h2 ^ val, 1597334677 );
  426. }
  427. } else {
  428. for ( let i = 0, ch; i < value.length; i ++ ) {
  429. ch = value.charCodeAt( i );
  430. h1 = Math.imul( h1 ^ ch, 2654435761 );
  431. h2 = Math.imul( h2 ^ ch, 1597334677 );
  432. }
  433. }
  434. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  435. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  436. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  437. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  438. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  439. }
  440. /**
  441. * Computes a hash for the given string.
  442. *
  443. * @private
  444. * @method
  445. * @param {string} str - The string to be hashed.
  446. * @return {number} The hash.
  447. */
  448. const hashString = ( str ) => cyrb53( str );
  449. /**
  450. * Computes a hash for the given array.
  451. *
  452. * @private
  453. * @method
  454. * @param {Array<number>} array - The array to be hashed.
  455. * @return {number} The hash.
  456. */
  457. const hashArray = ( array ) => cyrb53( array );
  458. /**
  459. * Computes a hash for the given list of parameters.
  460. *
  461. * @private
  462. * @method
  463. * @param {...number} params - A list of parameters.
  464. * @return {number} The hash.
  465. */
  466. const hash$1 = ( ...params ) => cyrb53( params );
  467. const typeFromLength = /*@__PURE__*/ new Map( [
  468. [ 1, 'float' ],
  469. [ 2, 'vec2' ],
  470. [ 3, 'vec3' ],
  471. [ 4, 'vec4' ],
  472. [ 9, 'mat3' ],
  473. [ 16, 'mat4' ]
  474. ] );
  475. const dataFromObject = /*@__PURE__*/ new WeakMap();
  476. /**
  477. * Returns the data type for the given the length.
  478. *
  479. * @private
  480. * @method
  481. * @param {number} length - The length.
  482. * @return {string} The data type.
  483. */
  484. function getTypeFromLength( length ) {
  485. return typeFromLength.get( length );
  486. }
  487. /**
  488. * Returns the typed array for the given data type.
  489. *
  490. * @private
  491. * @method
  492. * @param {string} type - The data type.
  493. * @return {TypedArray} The typed array.
  494. */
  495. function getTypedArrayFromType( type ) {
  496. // Handle component type for vectors and matrices
  497. if ( /[iu]?vec\d/.test( type ) ) {
  498. // Handle int vectors
  499. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  500. // Handle uint vectors
  501. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  502. // Default to float vectors
  503. return Float32Array;
  504. }
  505. // Handle matrices (always float)
  506. if ( /mat\d/.test( type ) ) return Float32Array;
  507. // Basic types
  508. if ( /float/.test( type ) ) return Float32Array;
  509. if ( /uint/.test( type ) ) return Uint32Array;
  510. if ( /int/.test( type ) ) return Int32Array;
  511. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  512. }
  513. /**
  514. * Returns the length for the given data type.
  515. *
  516. * @private
  517. * @method
  518. * @param {string} type - The data type.
  519. * @return {number} The length.
  520. */
  521. function getLengthFromType( type ) {
  522. if ( /float|int|uint/.test( type ) ) return 1;
  523. if ( /vec2/.test( type ) ) return 2;
  524. if ( /vec3/.test( type ) ) return 3;
  525. if ( /vec4/.test( type ) ) return 4;
  526. if ( /mat2/.test( type ) ) return 4;
  527. if ( /mat3/.test( type ) ) return 9;
  528. if ( /mat4/.test( type ) ) return 16;
  529. error( 'TSL: Unsupported type:', type );
  530. }
  531. /**
  532. * Returns the gpu memory length for the given data type.
  533. *
  534. * @private
  535. * @method
  536. * @param {string} type - The data type.
  537. * @return {number} The length.
  538. */
  539. function getMemoryLengthFromType( type ) {
  540. if ( /float|int|uint/.test( type ) ) return 1;
  541. if ( /vec2/.test( type ) ) return 2;
  542. if ( /vec3/.test( type ) ) return 3;
  543. if ( /vec4/.test( type ) ) return 4;
  544. if ( /mat2/.test( type ) ) return 4;
  545. if ( /mat3/.test( type ) ) return 12;
  546. if ( /mat4/.test( type ) ) return 16;
  547. error( 'TSL: Unsupported type:', type );
  548. }
  549. /**
  550. * Returns the alignment requirement for the given data type.
  551. *
  552. * @private
  553. * @method
  554. * @param {string} type - The data type.
  555. * @return {number} The alignment requirement in bytes.
  556. */
  557. function getAlignmentFromType( type ) {
  558. if ( /float|int|uint/.test( type ) ) return 4;
  559. if ( /vec2/.test( type ) ) return 8;
  560. if ( /vec3/.test( type ) ) return 16;
  561. if ( /vec4/.test( type ) ) return 16;
  562. if ( /mat2/.test( type ) ) return 8;
  563. if ( /mat3/.test( type ) ) return 16;
  564. if ( /mat4/.test( type ) ) return 16;
  565. error( 'TSL: Unsupported type:', type );
  566. }
  567. /**
  568. * Returns the data type for the given value.
  569. *
  570. * @private
  571. * @method
  572. * @param {any} value - The value.
  573. * @return {?string} The data type.
  574. */
  575. function getValueType( value ) {
  576. if ( value === undefined || value === null ) return null;
  577. const typeOf = typeof value;
  578. if ( value.isNode === true ) {
  579. return 'node';
  580. } else if ( typeOf === 'number' ) {
  581. return 'float';
  582. } else if ( typeOf === 'boolean' ) {
  583. return 'bool';
  584. } else if ( typeOf === 'string' ) {
  585. return 'string';
  586. } else if ( typeOf === 'function' ) {
  587. return 'shader';
  588. } else if ( value.isVector2 === true ) {
  589. return 'vec2';
  590. } else if ( value.isVector3 === true ) {
  591. return 'vec3';
  592. } else if ( value.isVector4 === true ) {
  593. return 'vec4';
  594. } else if ( value.isMatrix2 === true ) {
  595. return 'mat2';
  596. } else if ( value.isMatrix3 === true ) {
  597. return 'mat3';
  598. } else if ( value.isMatrix4 === true ) {
  599. return 'mat4';
  600. } else if ( value.isColor === true ) {
  601. return 'color';
  602. } else if ( value instanceof ArrayBuffer ) {
  603. return 'ArrayBuffer';
  604. }
  605. return null;
  606. }
  607. /**
  608. * Returns the value/object for the given data type and parameters.
  609. *
  610. * @private
  611. * @method
  612. * @param {string} type - The given type.
  613. * @param {...any} params - A parameter list.
  614. * @return {any} The value/object.
  615. */
  616. function getValueFromType( type, ...params ) {
  617. const last4 = type ? type.slice( -4 ) : undefined;
  618. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  619. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  620. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  621. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  622. }
  623. if ( type === 'color' ) {
  624. return new Color( ...params );
  625. } else if ( last4 === 'vec2' ) {
  626. return new Vector2( ...params );
  627. } else if ( last4 === 'vec3' ) {
  628. return new Vector3( ...params );
  629. } else if ( last4 === 'vec4' ) {
  630. return new Vector4( ...params );
  631. } else if ( last4 === 'mat2' ) {
  632. return new Matrix2( ...params );
  633. } else if ( last4 === 'mat3' ) {
  634. return new Matrix3( ...params );
  635. } else if ( last4 === 'mat4' ) {
  636. return new Matrix4( ...params );
  637. } else if ( type === 'bool' ) {
  638. return params[ 0 ] || false;
  639. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  640. return params[ 0 ] || 0;
  641. } else if ( type === 'string' ) {
  642. return params[ 0 ] || '';
  643. } else if ( type === 'ArrayBuffer' ) {
  644. return base64ToArrayBuffer( params[ 0 ] );
  645. }
  646. return null;
  647. }
  648. /**
  649. * Gets the object data that can be shared between different rendering steps.
  650. *
  651. * @private
  652. * @param {Object} object - The object to get the data for.
  653. * @return {Object} The object data.
  654. */
  655. function getDataFromObject( object ) {
  656. let data = dataFromObject.get( object );
  657. if ( data === undefined ) {
  658. data = {};
  659. dataFromObject.set( object, data );
  660. }
  661. return data;
  662. }
  663. /**
  664. * Converts the given array buffer to a Base64 string.
  665. *
  666. * @private
  667. * @method
  668. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  669. * @return {string} The Base64 string.
  670. */
  671. function arrayBufferToBase64( arrayBuffer ) {
  672. let chars = '';
  673. const array = new Uint8Array( arrayBuffer );
  674. for ( let i = 0; i < array.length; i ++ ) {
  675. chars += String.fromCharCode( array[ i ] );
  676. }
  677. return btoa( chars );
  678. }
  679. /**
  680. * Converts the given Base64 string to an array buffer.
  681. *
  682. * @private
  683. * @method
  684. * @param {string} base64 - The Base64 string.
  685. * @return {ArrayBuffer} The array buffer.
  686. */
  687. function base64ToArrayBuffer( base64 ) {
  688. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  689. }
  690. var NodeUtils = /*#__PURE__*/Object.freeze({
  691. __proto__: null,
  692. arrayBufferToBase64: arrayBufferToBase64,
  693. base64ToArrayBuffer: base64ToArrayBuffer,
  694. getAlignmentFromType: getAlignmentFromType,
  695. getDataFromObject: getDataFromObject,
  696. getLengthFromType: getLengthFromType,
  697. getMemoryLengthFromType: getMemoryLengthFromType,
  698. getTypeFromLength: getTypeFromLength,
  699. getTypedArrayFromType: getTypedArrayFromType,
  700. getValueFromType: getValueFromType,
  701. getValueType: getValueType,
  702. hash: hash$1,
  703. hashArray: hashArray,
  704. hashString: hashString
  705. });
  706. /**
  707. * Possible shader stages.
  708. *
  709. * @property {string} VERTEX The vertex shader stage.
  710. * @property {string} FRAGMENT The fragment shader stage.
  711. */
  712. const NodeShaderStage = {
  713. VERTEX: 'vertex',
  714. FRAGMENT: 'fragment'
  715. };
  716. /**
  717. * Update types of a node.
  718. *
  719. * @property {string} NONE The update method is not executed.
  720. * @property {string} FRAME The update method is executed per frame.
  721. * @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.
  722. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  723. */
  724. const NodeUpdateType = {
  725. NONE: 'none',
  726. FRAME: 'frame',
  727. RENDER: 'render',
  728. OBJECT: 'object'
  729. };
  730. /**
  731. * Data types of a node.
  732. *
  733. * @property {string} BOOLEAN Boolean type.
  734. * @property {string} INTEGER Integer type.
  735. * @property {string} FLOAT Float type.
  736. * @property {string} VECTOR2 Two-dimensional vector type.
  737. * @property {string} VECTOR3 Three-dimensional vector type.
  738. * @property {string} VECTOR4 Four-dimensional vector type.
  739. * @property {string} MATRIX2 2x2 matrix type.
  740. * @property {string} MATRIX3 3x3 matrix type.
  741. * @property {string} MATRIX4 4x4 matrix type.
  742. */
  743. const NodeType = {
  744. BOOLEAN: 'bool',
  745. INTEGER: 'int',
  746. FLOAT: 'float',
  747. VECTOR2: 'vec2',
  748. VECTOR3: 'vec3',
  749. VECTOR4: 'vec4',
  750. MATRIX2: 'mat2',
  751. MATRIX3: 'mat3',
  752. MATRIX4: 'mat4'
  753. };
  754. /**
  755. * Access types of a node. These are relevant for compute and storage usage.
  756. *
  757. * @property {string} READ_ONLY Read-only access
  758. * @property {string} WRITE_ONLY Write-only access.
  759. * @property {string} READ_WRITE Read and write access.
  760. */
  761. const NodeAccess = {
  762. READ_ONLY: 'readOnly',
  763. WRITE_ONLY: 'writeOnly',
  764. READ_WRITE: 'readWrite',
  765. };
  766. const defaultShaderStages = [ 'fragment', 'vertex' ];
  767. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  768. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  769. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  770. const _parentBuildStage = {
  771. analyze: 'setup',
  772. generate: 'analyze'
  773. };
  774. let _nodeId = 0;
  775. /**
  776. * Base class for all nodes.
  777. *
  778. * @augments EventDispatcher
  779. */
  780. class Node extends EventDispatcher {
  781. static get type() {
  782. return 'Node';
  783. }
  784. /**
  785. * Constructs a new node.
  786. *
  787. * @param {?string} nodeType - The node type.
  788. */
  789. constructor( nodeType = null ) {
  790. super();
  791. /**
  792. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  793. *
  794. * @type {?string}
  795. * @default null
  796. */
  797. this.nodeType = nodeType;
  798. /**
  799. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  800. *
  801. * @type {string}
  802. * @default 'none'
  803. */
  804. this.updateType = NodeUpdateType.NONE;
  805. /**
  806. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  807. *
  808. * @type {string}
  809. * @default 'none'
  810. */
  811. this.updateBeforeType = NodeUpdateType.NONE;
  812. /**
  813. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  814. *
  815. * @type {string}
  816. * @default 'none'
  817. */
  818. this.updateAfterType = NodeUpdateType.NONE;
  819. /**
  820. * The UUID of the node.
  821. *
  822. * @type {string}
  823. * @readonly
  824. */
  825. this.uuid = MathUtils.generateUUID();
  826. /**
  827. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  828. *
  829. * @type {number}
  830. * @readonly
  831. * @default 0
  832. */
  833. this.version = 0;
  834. /**
  835. * The name of the node.
  836. *
  837. * @type {string}
  838. * @default ''
  839. */
  840. this.name = '';
  841. /**
  842. * Whether this node is global or not. This property is relevant for the internal
  843. * node caching system. All nodes which should be declared just once should
  844. * set this flag to `true` (a typical example is {@link AttributeNode}).
  845. *
  846. * @type {boolean}
  847. * @default false
  848. */
  849. this.global = false;
  850. /**
  851. * Create a list of parents for this node during the build process.
  852. *
  853. * @type {boolean}
  854. * @default false
  855. */
  856. this.parents = false;
  857. /**
  858. * This flag can be used for type testing.
  859. *
  860. * @type {boolean}
  861. * @readonly
  862. * @default true
  863. */
  864. this.isNode = true;
  865. // private
  866. this._beforeNodes = null;
  867. /**
  868. * The cache key of this node.
  869. *
  870. * @private
  871. * @type {?number}
  872. * @default null
  873. */
  874. this._cacheKey = null;
  875. /**
  876. * The cache key 's version.
  877. *
  878. * @private
  879. * @type {number}
  880. * @default 0
  881. */
  882. this._cacheKeyVersion = 0;
  883. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  884. }
  885. /**
  886. * Set this property to `true` when the node should be regenerated.
  887. *
  888. * @type {boolean}
  889. * @default false
  890. * @param {boolean} value
  891. */
  892. set needsUpdate( value ) {
  893. if ( value === true ) {
  894. this.version ++;
  895. }
  896. }
  897. /**
  898. * The type of the class. The value is usually the constructor name.
  899. *
  900. * @type {string}
  901. * @readonly
  902. */
  903. get type() {
  904. return this.constructor.type;
  905. }
  906. /**
  907. * Convenient method for defining {@link Node#update}.
  908. *
  909. * @param {Function} callback - The update method.
  910. * @param {string} updateType - The update type.
  911. * @return {Node} A reference to this node.
  912. */
  913. onUpdate( callback, updateType ) {
  914. this.updateType = updateType;
  915. this.update = callback.bind( this );
  916. return this;
  917. }
  918. /**
  919. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  920. * this method automatically sets the update type to `FRAME`.
  921. *
  922. * @param {Function} callback - The update method.
  923. * @return {Node} A reference to this node.
  924. */
  925. onFrameUpdate( callback ) {
  926. return this.onUpdate( callback, NodeUpdateType.FRAME );
  927. }
  928. /**
  929. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  930. * this method automatically sets the update type to `RENDER`.
  931. *
  932. * @param {Function} callback - The update method.
  933. * @return {Node} A reference to this node.
  934. */
  935. onRenderUpdate( callback ) {
  936. return this.onUpdate( callback, NodeUpdateType.RENDER );
  937. }
  938. /**
  939. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  940. * this method automatically sets the update type to `OBJECT`.
  941. *
  942. * @param {Function} callback - The update method.
  943. * @return {Node} A reference to this node.
  944. */
  945. onObjectUpdate( callback ) {
  946. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  947. }
  948. /**
  949. * Convenient method for defining {@link Node#updateReference}.
  950. *
  951. * @param {Function} callback - The update method.
  952. * @return {Node} A reference to this node.
  953. */
  954. onReference( callback ) {
  955. this.updateReference = callback.bind( this );
  956. return this;
  957. }
  958. /**
  959. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  960. * to such objects based on a given state (e.g. the current node frame or builder).
  961. *
  962. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  963. * @return {any} The updated reference.
  964. */
  965. updateReference( /*state*/ ) {
  966. return this;
  967. }
  968. /**
  969. * By default this method returns the value of the {@link Node#global} flag. This method
  970. * can be overwritten in derived classes if an analytical way is required to determine the
  971. * global cache referring to the current shader-stage.
  972. *
  973. * @param {NodeBuilder} builder - The current node builder.
  974. * @return {boolean} Whether this node is global or not.
  975. */
  976. isGlobal( /*builder*/ ) {
  977. return this.global;
  978. }
  979. /**
  980. * Generator function that can be used to iterate over the child nodes.
  981. *
  982. * @generator
  983. * @yields {Node} A child node.
  984. */
  985. * getChildren() {
  986. for ( const { childNode } of this._getChildren() ) {
  987. yield childNode;
  988. }
  989. }
  990. /**
  991. * Calling this method dispatches the `dispose` event. This event can be used
  992. * to register event listeners for clean up tasks.
  993. */
  994. dispose() {
  995. this.dispatchEvent( { type: 'dispose' } );
  996. }
  997. /**
  998. * Callback for {@link Node#traverse}.
  999. *
  1000. * @callback traverseCallback
  1001. * @param {Node} node - The current node.
  1002. */
  1003. /**
  1004. * Can be used to traverse through the node's hierarchy.
  1005. *
  1006. * @param {traverseCallback} callback - A callback that is executed per node.
  1007. */
  1008. traverse( callback ) {
  1009. callback( this );
  1010. for ( const childNode of this.getChildren() ) {
  1011. childNode.traverse( callback );
  1012. }
  1013. }
  1014. /**
  1015. * Returns the child nodes of this node.
  1016. *
  1017. * @private
  1018. * @param {Set<Node>} [ignores=new Set()] - A set of nodes to ignore during the search to avoid circular references.
  1019. * @returns {Array<Object>} An array of objects describing the child nodes.
  1020. */
  1021. _getChildren( ignores = new Set() ) {
  1022. const children = [];
  1023. // avoid circular references
  1024. ignores.add( this );
  1025. for ( const property of Object.getOwnPropertyNames( this ) ) {
  1026. const object = this[ property ];
  1027. // Ignore private properties and ignored nodes.
  1028. if ( property.startsWith( '_' ) === true || ignores.has( object ) ) continue;
  1029. if ( Array.isArray( object ) === true ) {
  1030. for ( let i = 0; i < object.length; i ++ ) {
  1031. const child = object[ i ];
  1032. if ( child && child.isNode === true ) {
  1033. children.push( { property, index: i, childNode: child } );
  1034. }
  1035. }
  1036. } else if ( object && object.isNode === true ) {
  1037. children.push( { property, childNode: object } );
  1038. } else if ( object && Object.getPrototypeOf( object ) === Object.prototype ) {
  1039. for ( const subProperty in object ) {
  1040. // Ignore private sub-properties.
  1041. if ( subProperty.startsWith( '_' ) === true ) continue;
  1042. const child = object[ subProperty ];
  1043. if ( child && child.isNode === true ) {
  1044. children.push( { property, index: subProperty, childNode: child } );
  1045. }
  1046. }
  1047. }
  1048. }
  1049. //
  1050. return children;
  1051. }
  1052. /**
  1053. * Returns the cache key for this node.
  1054. *
  1055. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  1056. * @param {Set<Node>} [ignores=null] - A set of nodes to ignore during the computation of the cache key.
  1057. * @return {number} The cache key of the node.
  1058. */
  1059. getCacheKey( force = false, ignores = null ) {
  1060. force = force || this.version !== this._cacheKeyVersion;
  1061. if ( force === true || this._cacheKey === null ) {
  1062. if ( ignores === null ) ignores = new Set();
  1063. //
  1064. const values = [];
  1065. for ( const { property, childNode } of this._getChildren( ignores ) ) {
  1066. values.push( hashString( property.slice( 0, -4 ) ), childNode.getCacheKey( force, ignores ) );
  1067. }
  1068. //
  1069. this._cacheKey = hash$1( hashArray( values ), this.customCacheKey() );
  1070. this._cacheKeyVersion = this.version;
  1071. }
  1072. return this._cacheKey;
  1073. }
  1074. /**
  1075. * Generate a custom cache key for this node.
  1076. *
  1077. * @return {number} The cache key of the node.
  1078. */
  1079. customCacheKey() {
  1080. return this.id;
  1081. }
  1082. /**
  1083. * Returns the references to this node which is by default `this`.
  1084. *
  1085. * @return {Node} A reference to this node.
  1086. */
  1087. getScope() {
  1088. return this;
  1089. }
  1090. /**
  1091. * Returns the hash of the node which is used to identify the node. By default it's
  1092. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  1093. * depending on their implementation.
  1094. *
  1095. * @param {NodeBuilder} builder - The current node builder.
  1096. * @return {string} The hash.
  1097. */
  1098. getHash( /*builder*/ ) {
  1099. return this.uuid;
  1100. }
  1101. /**
  1102. * Returns the update type of {@link Node#update}.
  1103. *
  1104. * @return {NodeUpdateType} The update type.
  1105. */
  1106. getUpdateType() {
  1107. return this.updateType;
  1108. }
  1109. /**
  1110. * Returns the update type of {@link Node#updateBefore}.
  1111. *
  1112. * @return {NodeUpdateType} The update type.
  1113. */
  1114. getUpdateBeforeType() {
  1115. return this.updateBeforeType;
  1116. }
  1117. /**
  1118. * Returns the update type of {@link Node#updateAfter}.
  1119. *
  1120. * @return {NodeUpdateType} The update type.
  1121. */
  1122. getUpdateAfterType() {
  1123. return this.updateAfterType;
  1124. }
  1125. /**
  1126. * Certain types are composed of multiple elements. For example a `vec3`
  1127. * is composed of three `float` values. This method returns the type of
  1128. * these elements.
  1129. *
  1130. * @param {NodeBuilder} builder - The current node builder.
  1131. * @return {string} The type of the node.
  1132. */
  1133. getElementType( builder ) {
  1134. const type = this.getNodeType( builder );
  1135. const elementType = builder.getElementType( type );
  1136. return elementType;
  1137. }
  1138. /**
  1139. * Returns the node member type for the given name.
  1140. *
  1141. * @param {NodeBuilder} builder - The current node builder.
  1142. * @param {string} name - The name of the member.
  1143. * @return {string} The type of the node.
  1144. */
  1145. getMemberType( /*builder, name*/ ) {
  1146. return 'void';
  1147. }
  1148. /**
  1149. * Returns the node's type.
  1150. *
  1151. * @param {NodeBuilder} builder - The current node builder.
  1152. * @return {string} The type of the node.
  1153. */
  1154. getNodeType( builder ) {
  1155. const nodeProperties = builder.getNodeProperties( this );
  1156. if ( nodeProperties.outputNode ) {
  1157. return nodeProperties.outputNode.getNodeType( builder );
  1158. }
  1159. return this.nodeType;
  1160. }
  1161. /**
  1162. * This method is used during the build process of a node and ensures
  1163. * equal nodes are not built multiple times but just once. For example if
  1164. * `attribute( 'uv' )` is used multiple times by the user, the build
  1165. * process makes sure to process just the first node.
  1166. *
  1167. * @param {NodeBuilder} builder - The current node builder.
  1168. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1169. */
  1170. getShared( builder ) {
  1171. const hash = this.getHash( builder );
  1172. const nodeFromHash = builder.getNodeFromHash( hash );
  1173. return nodeFromHash || this;
  1174. }
  1175. /**
  1176. * Returns the number of elements in the node array.
  1177. *
  1178. * @param {NodeBuilder} builder - The current node builder.
  1179. * @return {?number} The number of elements in the node array.
  1180. */
  1181. getArrayCount( /*builder*/ ) {
  1182. return null;
  1183. }
  1184. /**
  1185. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1186. * This method is often overwritten in derived modules to prepare the node which is used as a node's output/result.
  1187. * If an output node is prepared, then it must be returned in the `return` statement of the derived module's setup function.
  1188. *
  1189. * @param {NodeBuilder} builder - The current node builder.
  1190. * @return {?Node} The output node.
  1191. */
  1192. setup( builder ) {
  1193. const nodeProperties = builder.getNodeProperties( this );
  1194. let index = 0;
  1195. for ( const childNode of this.getChildren() ) {
  1196. nodeProperties[ 'node' + index ++ ] = childNode;
  1197. }
  1198. // return a outputNode if exists or null
  1199. return nodeProperties.outputNode || null;
  1200. }
  1201. /**
  1202. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1203. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1204. *
  1205. * @param {NodeBuilder} builder - The current node builder.
  1206. * @param {?Node} output - The target output node.
  1207. */
  1208. analyze( builder, output = null ) {
  1209. const usageCount = builder.increaseUsage( this );
  1210. if ( this.parents === true ) {
  1211. const nodeData = builder.getDataFromNode( this, 'any' );
  1212. nodeData.stages = nodeData.stages || {};
  1213. nodeData.stages[ builder.shaderStage ] = nodeData.stages[ builder.shaderStage ] || [];
  1214. nodeData.stages[ builder.shaderStage ].push( output );
  1215. }
  1216. if ( usageCount === 1 ) {
  1217. // node flow children
  1218. const nodeProperties = builder.getNodeProperties( this );
  1219. for ( const childNode of Object.values( nodeProperties ) ) {
  1220. if ( childNode && childNode.isNode === true ) {
  1221. childNode.build( builder, this );
  1222. }
  1223. }
  1224. }
  1225. }
  1226. /**
  1227. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1228. * This state builds the output node and returns the resulting shader string.
  1229. *
  1230. * @param {NodeBuilder} builder - The current node builder.
  1231. * @param {?string} [output] - Can be used to define the output type.
  1232. * @return {?string} The generated shader string.
  1233. */
  1234. generate( builder, output ) {
  1235. const { outputNode } = builder.getNodeProperties( this );
  1236. if ( outputNode && outputNode.isNode === true ) {
  1237. return outputNode.build( builder, output );
  1238. }
  1239. }
  1240. /**
  1241. * The method can be implemented to update the node's internal state before it is used to render an object.
  1242. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1243. *
  1244. * @abstract
  1245. * @param {NodeFrame} frame - A reference to the current node frame.
  1246. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1247. */
  1248. updateBefore( /*frame*/ ) {
  1249. warn( 'Abstract function.' );
  1250. }
  1251. /**
  1252. * The method can be implemented to update the node's internal state after it was used to render an object.
  1253. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1254. *
  1255. * @abstract
  1256. * @param {NodeFrame} frame - A reference to the current node frame.
  1257. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1258. */
  1259. updateAfter( /*frame*/ ) {
  1260. warn( 'Abstract function.' );
  1261. }
  1262. /**
  1263. * The method can be implemented to update the node's internal state when it is used to render an object.
  1264. * The {@link Node#updateType} property defines how often the update is executed.
  1265. *
  1266. * @abstract
  1267. * @param {NodeFrame} frame - A reference to the current node frame.
  1268. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1269. */
  1270. update( /*frame*/ ) {
  1271. warn( 'Abstract function.' );
  1272. }
  1273. before( node ) {
  1274. if ( this._beforeNodes === null ) this._beforeNodes = [];
  1275. this._beforeNodes.push( node );
  1276. return this;
  1277. }
  1278. /**
  1279. * This method performs the build of a node. The behavior and return value depend on the current build stage:
  1280. * - **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.
  1281. * - **analyze**: Analyzes the node hierarchy for optimizations in the code generation stage. Returns `null`.
  1282. * - **generate**: Generates the shader code for the node. Returns the generated shader string.
  1283. *
  1284. * @param {NodeBuilder} builder - The current node builder.
  1285. * @param {?(string|Node)} [output=null] - Can be used to define the output type.
  1286. * @return {?(Node|string)} The result of the build process, depending on the build stage.
  1287. */
  1288. build( builder, output = null ) {
  1289. const refNode = this.getShared( builder );
  1290. if ( this !== refNode ) {
  1291. return refNode.build( builder, output );
  1292. }
  1293. //
  1294. if ( this._beforeNodes !== null ) {
  1295. const currentBeforeNodes = this._beforeNodes;
  1296. this._beforeNodes = null;
  1297. for ( const beforeNode of currentBeforeNodes ) {
  1298. beforeNode.build( builder, output );
  1299. }
  1300. this._beforeNodes = currentBeforeNodes;
  1301. }
  1302. //
  1303. const nodeData = builder.getDataFromNode( this );
  1304. nodeData.buildStages = nodeData.buildStages || {};
  1305. nodeData.buildStages[ builder.buildStage ] = true;
  1306. const parentBuildStage = _parentBuildStage[ builder.buildStage ];
  1307. if ( parentBuildStage && nodeData.buildStages[ parentBuildStage ] !== true ) {
  1308. // force parent build stage (setup or analyze)
  1309. const previousBuildStage = builder.getBuildStage();
  1310. builder.setBuildStage( parentBuildStage );
  1311. this.build( builder );
  1312. builder.setBuildStage( previousBuildStage );
  1313. }
  1314. //
  1315. builder.addNode( this );
  1316. builder.addChain( this );
  1317. /* Build stages expected results:
  1318. - "setup" -> Node
  1319. - "analyze" -> null
  1320. - "generate" -> String
  1321. */
  1322. let result = null;
  1323. const buildStage = builder.getBuildStage();
  1324. if ( buildStage === 'setup' ) {
  1325. this.updateReference( builder );
  1326. const properties = builder.getNodeProperties( this );
  1327. if ( properties.initialized !== true ) {
  1328. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1329. properties.initialized = true;
  1330. properties.outputNode = this.setup( builder ) || properties.outputNode || null;
  1331. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1332. // !! no outputNode !!
  1333. //outputNode = builder.stack;
  1334. }*/
  1335. for ( const childNode of Object.values( properties ) ) {
  1336. if ( childNode && childNode.isNode === true ) {
  1337. if ( childNode.parents === true ) {
  1338. const childProperties = builder.getNodeProperties( childNode );
  1339. childProperties.parents = childProperties.parents || [];
  1340. childProperties.parents.push( this );
  1341. }
  1342. childNode.build( builder );
  1343. }
  1344. }
  1345. }
  1346. result = properties.outputNode;
  1347. } else if ( buildStage === 'analyze' ) {
  1348. this.analyze( builder, output );
  1349. } else if ( buildStage === 'generate' ) {
  1350. // If generate has just one argument, it means the output type is not required.
  1351. // This means that the node does not handle output conversions internally,
  1352. // so the value is stored in a cache and the builder handles the conversion
  1353. // for all requested output types.
  1354. const isGenerateOnce = this.generate.length < 2;
  1355. if ( isGenerateOnce ) {
  1356. const type = this.getNodeType( builder );
  1357. const nodeData = builder.getDataFromNode( this );
  1358. result = nodeData.snippet;
  1359. if ( result === undefined ) {
  1360. if ( nodeData.generated === undefined ) {
  1361. nodeData.generated = true;
  1362. result = this.generate( builder ) || '';
  1363. nodeData.snippet = result;
  1364. } else {
  1365. warn( 'Node: Recursion detected.', this );
  1366. result = '/* Recursion detected. */';
  1367. }
  1368. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1369. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1370. }
  1371. result = builder.format( result, type, output );
  1372. } else {
  1373. result = this.generate( builder, output ) || '';
  1374. }
  1375. if ( result === '' && output !== null && output !== 'void' && output !== 'OutputType' ) {
  1376. // if no snippet is generated, return a default value
  1377. error( `TSL: Invalid generated code, expected a "${ output }".` );
  1378. result = builder.generateConst( output );
  1379. }
  1380. }
  1381. builder.removeChain( this );
  1382. builder.addSequentialNode( this );
  1383. return result;
  1384. }
  1385. /**
  1386. * Returns the child nodes as a JSON object.
  1387. *
  1388. * @return {Generator<Object>} An iterable list of serialized child objects as JSON.
  1389. */
  1390. getSerializeChildren() {
  1391. return this._getChildren();
  1392. }
  1393. /**
  1394. * Serializes the node to JSON.
  1395. *
  1396. * @param {Object} json - The output JSON object.
  1397. */
  1398. serialize( json ) {
  1399. const nodeChildren = this.getSerializeChildren();
  1400. const inputNodes = {};
  1401. for ( const { property, index, childNode } of nodeChildren ) {
  1402. if ( index !== undefined ) {
  1403. if ( inputNodes[ property ] === undefined ) {
  1404. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1405. }
  1406. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1407. } else {
  1408. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1409. }
  1410. }
  1411. if ( Object.keys( inputNodes ).length > 0 ) {
  1412. json.inputNodes = inputNodes;
  1413. }
  1414. }
  1415. /**
  1416. * Deserializes the node from the given JSON.
  1417. *
  1418. * @param {Object} json - The JSON object.
  1419. */
  1420. deserialize( json ) {
  1421. if ( json.inputNodes !== undefined ) {
  1422. const nodes = json.meta.nodes;
  1423. for ( const property in json.inputNodes ) {
  1424. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1425. const inputArray = [];
  1426. for ( const uuid of json.inputNodes[ property ] ) {
  1427. inputArray.push( nodes[ uuid ] );
  1428. }
  1429. this[ property ] = inputArray;
  1430. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1431. const inputObject = {};
  1432. for ( const subProperty in json.inputNodes[ property ] ) {
  1433. const uuid = json.inputNodes[ property ][ subProperty ];
  1434. inputObject[ subProperty ] = nodes[ uuid ];
  1435. }
  1436. this[ property ] = inputObject;
  1437. } else {
  1438. const uuid = json.inputNodes[ property ];
  1439. this[ property ] = nodes[ uuid ];
  1440. }
  1441. }
  1442. }
  1443. }
  1444. /**
  1445. * Serializes the node into the three.js JSON Object/Scene format.
  1446. *
  1447. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1448. * @return {Object} The serialized node.
  1449. */
  1450. toJSON( meta ) {
  1451. const { uuid, type } = this;
  1452. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1453. if ( isRoot ) {
  1454. meta = {
  1455. textures: {},
  1456. images: {},
  1457. nodes: {}
  1458. };
  1459. }
  1460. // serialize
  1461. let data = meta.nodes[ uuid ];
  1462. if ( data === undefined ) {
  1463. data = {
  1464. uuid,
  1465. type,
  1466. meta,
  1467. metadata: {
  1468. version: 4.7,
  1469. type: 'Node',
  1470. generator: 'Node.toJSON'
  1471. }
  1472. };
  1473. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1474. this.serialize( data );
  1475. delete data.meta;
  1476. }
  1477. // TODO: Copied from Object3D.toJSON
  1478. function extractFromCache( cache ) {
  1479. const values = [];
  1480. for ( const key in cache ) {
  1481. const data = cache[ key ];
  1482. delete data.metadata;
  1483. values.push( data );
  1484. }
  1485. return values;
  1486. }
  1487. if ( isRoot ) {
  1488. const textures = extractFromCache( meta.textures );
  1489. const images = extractFromCache( meta.images );
  1490. const nodes = extractFromCache( meta.nodes );
  1491. if ( textures.length > 0 ) data.textures = textures;
  1492. if ( images.length > 0 ) data.images = images;
  1493. if ( nodes.length > 0 ) data.nodes = nodes;
  1494. }
  1495. return data;
  1496. }
  1497. }
  1498. /**
  1499. * Base class for representing element access on an array-like
  1500. * node data structures.
  1501. *
  1502. * @augments Node
  1503. */
  1504. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1505. static get type() {
  1506. return 'ArrayElementNode';
  1507. }
  1508. /**
  1509. * Constructs an array element node.
  1510. *
  1511. * @param {Node} node - The array-like node.
  1512. * @param {Node} indexNode - The index node that defines the element access.
  1513. */
  1514. constructor( node, indexNode ) {
  1515. super();
  1516. /**
  1517. * The array-like node.
  1518. *
  1519. * @type {Node}
  1520. */
  1521. this.node = node;
  1522. /**
  1523. * The index node that defines the element access.
  1524. *
  1525. * @type {Node}
  1526. */
  1527. this.indexNode = indexNode;
  1528. /**
  1529. * This flag can be used for type testing.
  1530. *
  1531. * @type {boolean}
  1532. * @readonly
  1533. * @default true
  1534. */
  1535. this.isArrayElementNode = true;
  1536. }
  1537. /**
  1538. * This method is overwritten since the node type is inferred from the array-like node.
  1539. *
  1540. * @param {NodeBuilder} builder - The current node builder.
  1541. * @return {string} The node type.
  1542. */
  1543. getNodeType( builder ) {
  1544. return this.node.getElementType( builder );
  1545. }
  1546. /**
  1547. * This method is overwritten since the member type is inferred from the array-like node.
  1548. *
  1549. * @param {NodeBuilder} builder - The current node builder.
  1550. * @param {string} name - The member name.
  1551. * @return {string} The member type.
  1552. */
  1553. getMemberType( builder, name ) {
  1554. return this.node.getMemberType( builder, name );
  1555. }
  1556. generate( builder ) {
  1557. const indexType = this.indexNode.getNodeType( builder );
  1558. const nodeSnippet = this.node.build( builder );
  1559. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1560. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1561. }
  1562. }
  1563. /**
  1564. * This module is part of the TSL core and usually not used in app level code.
  1565. * It represents a convert operation during the shader generation process
  1566. * meaning it converts the data type of a node to a target data type.
  1567. *
  1568. * @augments Node
  1569. */
  1570. class ConvertNode extends Node {
  1571. static get type() {
  1572. return 'ConvertNode';
  1573. }
  1574. /**
  1575. * Constructs a new convert node.
  1576. *
  1577. * @param {Node} node - The node which type should be converted.
  1578. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1579. */
  1580. constructor( node, convertTo ) {
  1581. super();
  1582. /**
  1583. * The node which type should be converted.
  1584. *
  1585. * @type {Node}
  1586. */
  1587. this.node = node;
  1588. /**
  1589. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1590. *
  1591. * @type {string}
  1592. */
  1593. this.convertTo = convertTo;
  1594. }
  1595. /**
  1596. * This method is overwritten since the implementation tries to infer the best
  1597. * matching type from the {@link ConvertNode#convertTo} property.
  1598. *
  1599. * @param {NodeBuilder} builder - The current node builder.
  1600. * @return {string} The node type.
  1601. */
  1602. getNodeType( builder ) {
  1603. const requestType = this.node.getNodeType( builder );
  1604. let convertTo = null;
  1605. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1606. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1607. convertTo = overloadingType;
  1608. }
  1609. }
  1610. return convertTo;
  1611. }
  1612. serialize( data ) {
  1613. super.serialize( data );
  1614. data.convertTo = this.convertTo;
  1615. }
  1616. deserialize( data ) {
  1617. super.deserialize( data );
  1618. this.convertTo = data.convertTo;
  1619. }
  1620. generate( builder, output ) {
  1621. const node = this.node;
  1622. const type = this.getNodeType( builder );
  1623. const snippet = node.build( builder, type );
  1624. return builder.format( snippet, type, output );
  1625. }
  1626. }
  1627. /**
  1628. * This module uses cache management to create temporary variables
  1629. * if the node is used more than once to prevent duplicate calculations.
  1630. *
  1631. * The class acts as a base class for many other nodes types.
  1632. *
  1633. * @augments Node
  1634. */
  1635. class TempNode extends Node {
  1636. static get type() {
  1637. return 'TempNode';
  1638. }
  1639. /**
  1640. * Constructs a temp node.
  1641. *
  1642. * @param {?string} nodeType - The node type.
  1643. */
  1644. constructor( nodeType = null ) {
  1645. super( nodeType );
  1646. /**
  1647. * This flag can be used for type testing.
  1648. *
  1649. * @type {boolean}
  1650. * @readonly
  1651. * @default true
  1652. */
  1653. this.isTempNode = true;
  1654. }
  1655. /**
  1656. * Whether this node is used more than once in context of other nodes.
  1657. *
  1658. * @param {NodeBuilder} builder - The node builder.
  1659. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1660. */
  1661. hasDependencies( builder ) {
  1662. return builder.getDataFromNode( this ).usageCount > 1;
  1663. }
  1664. build( builder, output ) {
  1665. const buildStage = builder.getBuildStage();
  1666. if ( buildStage === 'generate' ) {
  1667. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1668. const nodeData = builder.getDataFromNode( this );
  1669. if ( nodeData.propertyName !== undefined ) {
  1670. return builder.format( nodeData.propertyName, type, output );
  1671. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1672. const snippet = super.build( builder, type );
  1673. const nodeVar = builder.getVarFromNode( this, null, type );
  1674. const propertyName = builder.getPropertyName( nodeVar );
  1675. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1676. nodeData.snippet = snippet;
  1677. nodeData.propertyName = propertyName;
  1678. return builder.format( nodeData.propertyName, type, output );
  1679. }
  1680. }
  1681. return super.build( builder, output );
  1682. }
  1683. }
  1684. /**
  1685. * This module is part of the TSL core and usually not used in app level code.
  1686. * It represents a join operation during the shader generation process.
  1687. * For example in can compose/join two single floats into a `vec2` type.
  1688. *
  1689. * @augments TempNode
  1690. */
  1691. class JoinNode extends TempNode {
  1692. static get type() {
  1693. return 'JoinNode';
  1694. }
  1695. /**
  1696. * Constructs a new join node.
  1697. *
  1698. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1699. * @param {?string} [nodeType=null] - The node type.
  1700. */
  1701. constructor( nodes = [], nodeType = null ) {
  1702. super( nodeType );
  1703. /**
  1704. * An array of nodes that should be joined.
  1705. *
  1706. * @type {Array<Node>}
  1707. */
  1708. this.nodes = nodes;
  1709. }
  1710. /**
  1711. * This method is overwritten since the node type must be inferred from the
  1712. * joined data length if not explicitly defined.
  1713. *
  1714. * @param {NodeBuilder} builder - The current node builder.
  1715. * @return {string} The node type.
  1716. */
  1717. getNodeType( builder ) {
  1718. if ( this.nodeType !== null ) {
  1719. return builder.getVectorType( this.nodeType );
  1720. }
  1721. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1722. }
  1723. generate( builder, output ) {
  1724. const type = this.getNodeType( builder );
  1725. const maxLength = builder.getTypeLength( type );
  1726. const nodes = this.nodes;
  1727. const primitiveType = builder.getComponentType( type );
  1728. const snippetValues = [];
  1729. let length = 0;
  1730. for ( const input of nodes ) {
  1731. if ( length >= maxLength ) {
  1732. error( `TSL: Length of parameters exceeds maximum length of function '${ type }()' type.` );
  1733. break;
  1734. }
  1735. let inputType = input.getNodeType( builder );
  1736. let inputTypeLength = builder.getTypeLength( inputType );
  1737. let inputSnippet;
  1738. if ( length + inputTypeLength > maxLength ) {
  1739. error( `TSL: Length of '${ type }()' data exceeds maximum length of output type.` );
  1740. inputTypeLength = maxLength - length;
  1741. inputType = builder.getTypeFromLength( inputTypeLength );
  1742. }
  1743. length += inputTypeLength;
  1744. inputSnippet = input.build( builder, inputType );
  1745. const inputPrimitiveType = builder.getComponentType( inputType );
  1746. if ( inputPrimitiveType !== primitiveType ) {
  1747. const targetType = builder.getTypeFromLength( inputTypeLength, primitiveType );
  1748. inputSnippet = builder.format( inputSnippet, inputType, targetType );
  1749. }
  1750. snippetValues.push( inputSnippet );
  1751. }
  1752. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1753. return builder.format( snippet, type, output );
  1754. }
  1755. }
  1756. const _stringVectorComponents = vectorComponents.join( '' );
  1757. /**
  1758. * This module is part of the TSL core and usually not used in app level code.
  1759. * `SplitNode` represents a property access operation which means it is
  1760. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1761. * For example:
  1762. * ```js
  1763. * const redValue = color.r;
  1764. * ```
  1765. *
  1766. * @augments Node
  1767. */
  1768. class SplitNode extends Node {
  1769. static get type() {
  1770. return 'SplitNode';
  1771. }
  1772. /**
  1773. * Constructs a new split node.
  1774. *
  1775. * @param {Node} node - The node that should be accessed.
  1776. * @param {string} [components='x'] - The components that should be accessed.
  1777. */
  1778. constructor( node, components = 'x' ) {
  1779. super();
  1780. /**
  1781. * The node that should be accessed.
  1782. *
  1783. * @type {Node}
  1784. */
  1785. this.node = node;
  1786. /**
  1787. * The components that should be accessed.
  1788. *
  1789. * @type {string}
  1790. */
  1791. this.components = components;
  1792. /**
  1793. * This flag can be used for type testing.
  1794. *
  1795. * @type {boolean}
  1796. * @readonly
  1797. * @default true
  1798. */
  1799. this.isSplitNode = true;
  1800. }
  1801. /**
  1802. * Returns the vector length which is computed based on the requested components.
  1803. *
  1804. * @return {number} The vector length.
  1805. */
  1806. getVectorLength() {
  1807. let vectorLength = this.components.length;
  1808. for ( const c of this.components ) {
  1809. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1810. }
  1811. return vectorLength;
  1812. }
  1813. /**
  1814. * Returns the component type of the node's type.
  1815. *
  1816. * @param {NodeBuilder} builder - The current node builder.
  1817. * @return {string} The component type.
  1818. */
  1819. getComponentType( builder ) {
  1820. return builder.getComponentType( this.node.getNodeType( builder ) );
  1821. }
  1822. /**
  1823. * This method is overwritten since the node type is inferred from requested components.
  1824. *
  1825. * @param {NodeBuilder} builder - The current node builder.
  1826. * @return {string} The node type.
  1827. */
  1828. getNodeType( builder ) {
  1829. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1830. }
  1831. /**
  1832. * Returns the scope of the node.
  1833. *
  1834. * @return {Node} The scope of the node.
  1835. */
  1836. getScope() {
  1837. return this.node.getScope();
  1838. }
  1839. generate( builder, output ) {
  1840. const node = this.node;
  1841. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1842. let snippet = null;
  1843. if ( nodeTypeLength > 1 ) {
  1844. let type = null;
  1845. const componentsLength = this.getVectorLength();
  1846. if ( componentsLength >= nodeTypeLength ) {
  1847. // needed expand the input node
  1848. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1849. }
  1850. const nodeSnippet = node.build( builder, type );
  1851. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1852. // unnecessary swizzle
  1853. snippet = builder.format( nodeSnippet, type, output );
  1854. } else {
  1855. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1856. }
  1857. } else {
  1858. // ignore .components if .node returns float/integer
  1859. snippet = node.build( builder, output );
  1860. }
  1861. return snippet;
  1862. }
  1863. serialize( data ) {
  1864. super.serialize( data );
  1865. data.components = this.components;
  1866. }
  1867. deserialize( data ) {
  1868. super.deserialize( data );
  1869. this.components = data.components;
  1870. }
  1871. }
  1872. /**
  1873. * This module is part of the TSL core and usually not used in app level code.
  1874. * `SetNode` represents a set operation which means it is used to implement any
  1875. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1876. * For example:
  1877. * ```js
  1878. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1879. * ```
  1880. *
  1881. * @augments TempNode
  1882. */
  1883. class SetNode extends TempNode {
  1884. static get type() {
  1885. return 'SetNode';
  1886. }
  1887. /**
  1888. * Constructs a new set node.
  1889. *
  1890. * @param {Node} sourceNode - The node that should be updated.
  1891. * @param {string} components - The components that should be updated.
  1892. * @param {Node} targetNode - The value node.
  1893. */
  1894. constructor( sourceNode, components, targetNode ) {
  1895. super();
  1896. /**
  1897. * The node that should be updated.
  1898. *
  1899. * @type {Node}
  1900. */
  1901. this.sourceNode = sourceNode;
  1902. /**
  1903. * The components that should be updated.
  1904. *
  1905. * @type {string}
  1906. */
  1907. this.components = components;
  1908. /**
  1909. * The value node.
  1910. *
  1911. * @type {Node}
  1912. */
  1913. this.targetNode = targetNode;
  1914. }
  1915. /**
  1916. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1917. *
  1918. * @param {NodeBuilder} builder - The current node builder.
  1919. * @return {string} The node type.
  1920. */
  1921. getNodeType( builder ) {
  1922. return this.sourceNode.getNodeType( builder );
  1923. }
  1924. generate( builder ) {
  1925. const { sourceNode, components, targetNode } = this;
  1926. const sourceType = this.getNodeType( builder );
  1927. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1928. const targetType = builder.getTypeFromLength( components.length, componentType );
  1929. const targetSnippet = targetNode.build( builder, targetType );
  1930. const sourceSnippet = sourceNode.build( builder, sourceType );
  1931. const length = builder.getTypeLength( sourceType );
  1932. const snippetValues = [];
  1933. for ( let i = 0; i < length; i ++ ) {
  1934. const component = vectorComponents[ i ];
  1935. if ( component === components[ 0 ] ) {
  1936. snippetValues.push( targetSnippet );
  1937. i += components.length - 1;
  1938. } else {
  1939. snippetValues.push( sourceSnippet + '.' + component );
  1940. }
  1941. }
  1942. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1943. }
  1944. }
  1945. /**
  1946. * This module is part of the TSL core and usually not used in app level code.
  1947. * It represents a flip operation during the shader generation process
  1948. * meaning it flips normalized values with the following formula:
  1949. * ```
  1950. * x = 1 - x;
  1951. * ```
  1952. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1953. * `flipSTPQ()` method invocations on node objects. For example:
  1954. * ```js
  1955. * uvNode = uvNode.flipY();
  1956. * ```
  1957. *
  1958. * @augments TempNode
  1959. */
  1960. class FlipNode extends TempNode {
  1961. static get type() {
  1962. return 'FlipNode';
  1963. }
  1964. /**
  1965. * Constructs a new flip node.
  1966. *
  1967. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1968. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1969. */
  1970. constructor( sourceNode, components ) {
  1971. super();
  1972. /**
  1973. * The node which component(s) should be flipped.
  1974. *
  1975. * @type {Node}
  1976. */
  1977. this.sourceNode = sourceNode;
  1978. /**
  1979. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1980. *
  1981. * @type {string}
  1982. */
  1983. this.components = components;
  1984. }
  1985. /**
  1986. * This method is overwritten since the node type is inferred from the source node.
  1987. *
  1988. * @param {NodeBuilder} builder - The current node builder.
  1989. * @return {string} The node type.
  1990. */
  1991. getNodeType( builder ) {
  1992. return this.sourceNode.getNodeType( builder );
  1993. }
  1994. generate( builder ) {
  1995. const { components, sourceNode } = this;
  1996. const sourceType = this.getNodeType( builder );
  1997. const sourceSnippet = sourceNode.build( builder );
  1998. const sourceCache = builder.getVarFromNode( this );
  1999. const sourceProperty = builder.getPropertyName( sourceCache );
  2000. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  2001. const length = builder.getTypeLength( sourceType );
  2002. const snippetValues = [];
  2003. let componentIndex = 0;
  2004. for ( let i = 0; i < length; i ++ ) {
  2005. const component = vectorComponents[ i ];
  2006. if ( component === components[ componentIndex ] ) {
  2007. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  2008. componentIndex ++;
  2009. } else {
  2010. snippetValues.push( sourceProperty + '.' + component );
  2011. }
  2012. }
  2013. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  2014. }
  2015. }
  2016. /**
  2017. * Base class for representing data input nodes.
  2018. *
  2019. * @augments Node
  2020. */
  2021. class InputNode extends Node {
  2022. static get type() {
  2023. return 'InputNode';
  2024. }
  2025. /**
  2026. * Constructs a new input node.
  2027. *
  2028. * @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).
  2029. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2030. */
  2031. constructor( value, nodeType = null ) {
  2032. super( nodeType );
  2033. /**
  2034. * This flag can be used for type testing.
  2035. *
  2036. * @type {boolean}
  2037. * @readonly
  2038. * @default true
  2039. */
  2040. this.isInputNode = true;
  2041. /**
  2042. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  2043. *
  2044. * @type {any}
  2045. */
  2046. this.value = value;
  2047. /**
  2048. * The precision of the value in the shader.
  2049. *
  2050. * @type {?('low'|'medium'|'high')}
  2051. * @default null
  2052. */
  2053. this.precision = null;
  2054. }
  2055. getNodeType( /*builder*/ ) {
  2056. if ( this.nodeType === null ) {
  2057. return getValueType( this.value );
  2058. }
  2059. return this.nodeType;
  2060. }
  2061. /**
  2062. * Returns the input type of the node which is by default the node type. Derived modules
  2063. * might overwrite this method and use a fixed type or compute one analytically.
  2064. *
  2065. * A typical example for different input and node types are textures. The input type of a
  2066. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  2067. *
  2068. * @param {NodeBuilder} builder - The current node builder.
  2069. * @return {string} The input type.
  2070. */
  2071. getInputType( builder ) {
  2072. return this.getNodeType( builder );
  2073. }
  2074. /**
  2075. * Sets the precision to the given value. The method can be
  2076. * overwritten in derived classes if the final precision must be computed
  2077. * analytically.
  2078. *
  2079. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  2080. * @return {InputNode} A reference to this node.
  2081. */
  2082. setPrecision( precision ) {
  2083. this.precision = precision;
  2084. return this;
  2085. }
  2086. serialize( data ) {
  2087. super.serialize( data );
  2088. data.value = this.value;
  2089. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  2090. data.valueType = getValueType( this.value );
  2091. data.nodeType = this.nodeType;
  2092. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  2093. data.precision = this.precision;
  2094. }
  2095. deserialize( data ) {
  2096. super.deserialize( data );
  2097. this.nodeType = data.nodeType;
  2098. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  2099. this.precision = data.precision || null;
  2100. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  2101. }
  2102. generate( /*builder, output*/ ) {
  2103. warn( 'Abstract function.' );
  2104. }
  2105. }
  2106. const _regNum = /float|u?int/;
  2107. /**
  2108. * Class for representing a constant value in the shader.
  2109. *
  2110. * @augments InputNode
  2111. */
  2112. class ConstNode extends InputNode {
  2113. static get type() {
  2114. return 'ConstNode';
  2115. }
  2116. /**
  2117. * Constructs a new input node.
  2118. *
  2119. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  2120. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2121. */
  2122. constructor( value, nodeType = null ) {
  2123. super( value, nodeType );
  2124. /**
  2125. * This flag can be used for type testing.
  2126. *
  2127. * @type {boolean}
  2128. * @readonly
  2129. * @default true
  2130. */
  2131. this.isConstNode = true;
  2132. }
  2133. /**
  2134. * Generates the shader string of the value with the current node builder.
  2135. *
  2136. * @param {NodeBuilder} builder - The current node builder.
  2137. * @return {string} The generated value as a shader string.
  2138. */
  2139. generateConst( builder ) {
  2140. return builder.generateConst( this.getNodeType( builder ), this.value );
  2141. }
  2142. generate( builder, output ) {
  2143. const type = this.getNodeType( builder );
  2144. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  2145. return builder.generateConst( output, this.value );
  2146. }
  2147. return builder.format( this.generateConst( builder ), type, output );
  2148. }
  2149. }
  2150. /**
  2151. * Base class for representing member access on an object-like
  2152. * node data structures.
  2153. *
  2154. * @augments Node
  2155. */
  2156. class MemberNode extends Node {
  2157. static get type() {
  2158. return 'MemberNode';
  2159. }
  2160. /**
  2161. * Constructs a member node.
  2162. *
  2163. * @param {Node} structNode - The struct node.
  2164. * @param {string} property - The property name.
  2165. */
  2166. constructor( structNode, property ) {
  2167. super();
  2168. /**
  2169. * The struct node.
  2170. *
  2171. * @type {Node}
  2172. */
  2173. this.structNode = structNode;
  2174. /**
  2175. * The property name.
  2176. *
  2177. * @type {Node}
  2178. */
  2179. this.property = property;
  2180. /**
  2181. * This flag can be used for type testing.
  2182. *
  2183. * @type {boolean}
  2184. * @readonly
  2185. * @default true
  2186. */
  2187. this.isMemberNode = true;
  2188. }
  2189. hasMember( builder ) {
  2190. if ( this.structNode.isMemberNode ) {
  2191. if ( this.structNode.hasMember( builder ) === false ) {
  2192. return false;
  2193. }
  2194. }
  2195. return this.structNode.getMemberType( builder, this.property ) !== 'void';
  2196. }
  2197. getNodeType( builder ) {
  2198. if ( this.hasMember( builder ) === false ) {
  2199. // default type if member does not exist
  2200. return 'float';
  2201. }
  2202. return this.structNode.getMemberType( builder, this.property );
  2203. }
  2204. getMemberType( builder, name ) {
  2205. if ( this.hasMember( builder ) === false ) {
  2206. // default type if member does not exist
  2207. return 'float';
  2208. }
  2209. const type = this.getNodeType( builder );
  2210. const struct = builder.getStructTypeNode( type );
  2211. return struct.getMemberType( builder, name );
  2212. }
  2213. generate( builder ) {
  2214. if ( this.hasMember( builder ) === false ) {
  2215. warn( `TSL: Member "${ this.property }" does not exist in struct.` );
  2216. const type = this.getNodeType( builder );
  2217. return builder.generateConst( type );
  2218. }
  2219. const propertyName = this.structNode.build( builder );
  2220. return propertyName + '.' + this.property;
  2221. }
  2222. }
  2223. let currentStack = null;
  2224. const NodeElements = new Map();
  2225. // Extend Node Class for TSL using prototype
  2226. function addMethodChaining( name, nodeElement ) {
  2227. if ( NodeElements.has( name ) ) {
  2228. warn( `TSL: Redefinition of method chaining '${ name }'.` );
  2229. return;
  2230. }
  2231. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2232. NodeElements.set( name, nodeElement );
  2233. if ( name !== 'assign' ) {
  2234. // Changing Node prototype to add method chaining
  2235. Node.prototype[ name ] = function ( ...params ) {
  2236. //if ( name === 'toVarIntent' ) return this;
  2237. return this.isStackNode ? this.addToStack( nodeElement( ...params ) ) : nodeElement( this, ...params );
  2238. };
  2239. // Adding assign method chaining
  2240. Node.prototype[ name + 'Assign' ] = function ( ...params ) {
  2241. return this.isStackNode ? this.assign( params[ 0 ], nodeElement( ...params ) ) : this.assign( nodeElement( this, ...params ) );
  2242. };
  2243. }
  2244. }
  2245. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2246. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2247. Node.prototype.assign = function ( ...params ) {
  2248. if ( this.isStackNode !== true ) {
  2249. if ( currentStack !== null ) {
  2250. currentStack.assign( this, ...params );
  2251. } else {
  2252. error( 'TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().' );
  2253. }
  2254. return this;
  2255. } else {
  2256. const nodeElement = NodeElements.get( 'assign' );
  2257. return this.addToStack( nodeElement( ...params ) );
  2258. }
  2259. };
  2260. Node.prototype.toVarIntent = function () {
  2261. return this;
  2262. };
  2263. Node.prototype.get = function ( value ) {
  2264. return new MemberNode( this, value );
  2265. };
  2266. // Cache prototype for TSL
  2267. const proto = {};
  2268. // Set swizzle properties for xyzw, rgba, and stpq.
  2269. function setProtoSwizzle( property, altA, altB ) {
  2270. // swizzle properties
  2271. proto[ property ] = proto[ altA ] = proto[ altB ] = {
  2272. get() {
  2273. this._cache = this._cache || {};
  2274. //
  2275. let split = this._cache[ property ];
  2276. if ( split === undefined ) {
  2277. split = new SplitNode( this, property );
  2278. this._cache[ property ] = split;
  2279. }
  2280. return split;
  2281. },
  2282. set( value ) {
  2283. this[ property ].assign( nodeObject( value ) );
  2284. }
  2285. };
  2286. // set properties ( swizzle ) and sort to xyzw sequence
  2287. const propUpper = property.toUpperCase();
  2288. const altAUpper = altA.toUpperCase();
  2289. const altBUpper = altB.toUpperCase();
  2290. // Set methods for swizzle properties
  2291. Node.prototype[ 'set' + propUpper ] = Node.prototype[ 'set' + altAUpper ] = Node.prototype[ 'set' + altBUpper ] = function ( value ) {
  2292. const swizzle = parseSwizzleAndSort( property );
  2293. return new SetNode( this, swizzle, nodeObject( value ) );
  2294. };
  2295. // Set methods for flip properties
  2296. Node.prototype[ 'flip' + propUpper ] = Node.prototype[ 'flip' + altAUpper ] = Node.prototype[ 'flip' + altBUpper ] = function () {
  2297. const swizzle = parseSwizzleAndSort( property );
  2298. return new FlipNode( this, swizzle );
  2299. };
  2300. }
  2301. const swizzleA = [ 'x', 'y', 'z', 'w' ];
  2302. const swizzleB = [ 'r', 'g', 'b', 'a' ];
  2303. const swizzleC = [ 's', 't', 'p', 'q' ];
  2304. for ( let a = 0; a < 4; a ++ ) {
  2305. let prop = swizzleA[ a ];
  2306. let altA = swizzleB[ a ];
  2307. let altB = swizzleC[ a ];
  2308. setProtoSwizzle( prop, altA, altB );
  2309. for ( let b = 0; b < 4; b ++ ) {
  2310. prop = swizzleA[ a ] + swizzleA[ b ];
  2311. altA = swizzleB[ a ] + swizzleB[ b ];
  2312. altB = swizzleC[ a ] + swizzleC[ b ];
  2313. setProtoSwizzle( prop, altA, altB );
  2314. for ( let c = 0; c < 4; c ++ ) {
  2315. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ];
  2316. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ];
  2317. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ];
  2318. setProtoSwizzle( prop, altA, altB );
  2319. for ( let d = 0; d < 4; d ++ ) {
  2320. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ] + swizzleA[ d ];
  2321. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ] + swizzleB[ d ];
  2322. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ] + swizzleC[ d ];
  2323. setProtoSwizzle( prop, altA, altB );
  2324. }
  2325. }
  2326. }
  2327. }
  2328. // Set/get static properties for array elements (0-31).
  2329. for ( let i = 0; i < 32; i ++ ) {
  2330. proto[ i ] = {
  2331. get() {
  2332. this._cache = this._cache || {};
  2333. //
  2334. let element = this._cache[ i ];
  2335. if ( element === undefined ) {
  2336. element = new ArrayElementNode( this, new ConstNode( i, 'uint' ) );
  2337. this._cache[ i ] = element;
  2338. }
  2339. return element;
  2340. },
  2341. set( value ) {
  2342. this[ i ].assign( nodeObject( value ) );
  2343. }
  2344. };
  2345. }
  2346. /*
  2347. // Set properties for width, height, and depth.
  2348. function setProtoProperty( property, target ) {
  2349. proto[ property ] = {
  2350. get() {
  2351. this._cache = this._cache || {};
  2352. //
  2353. let split = this._cache[ target ];
  2354. if ( split === undefined ) {
  2355. split = new SplitNode( this, target );
  2356. this._cache[ target ] = split;
  2357. }
  2358. return split;
  2359. },
  2360. set( value ) {
  2361. this[ target ].assign( nodeObject( value ) );
  2362. }
  2363. };
  2364. }
  2365. setProtoProperty( 'width', 'x' );
  2366. setProtoProperty( 'height', 'y' );
  2367. setProtoProperty( 'depth', 'z' );
  2368. */
  2369. Object.defineProperties( Node.prototype, proto );
  2370. // --- FINISH ---
  2371. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2372. const ShaderNodeObject = function ( obj, altType = null ) {
  2373. const type = getValueType( obj );
  2374. if ( type === 'node' ) {
  2375. return obj;
  2376. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2377. return nodeObject( getConstNode( obj, altType ) );
  2378. } else if ( type === 'shader' ) {
  2379. return obj.isFn ? obj : Fn( obj );
  2380. }
  2381. return obj;
  2382. };
  2383. const ShaderNodeObjects = function ( objects, altType = null ) {
  2384. for ( const name in objects ) {
  2385. objects[ name ] = nodeObject( objects[ name ], altType );
  2386. }
  2387. return objects;
  2388. };
  2389. const ShaderNodeArray = function ( array, altType = null ) {
  2390. const len = array.length;
  2391. for ( let i = 0; i < len; i ++ ) {
  2392. array[ i ] = nodeObject( array[ i ], altType );
  2393. }
  2394. return array;
  2395. };
  2396. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2397. function assignNode( node ) {
  2398. if ( settings !== null ) {
  2399. node = nodeObject( Object.assign( node, settings ) );
  2400. if ( settings.intent === true ) {
  2401. node = node.toVarIntent();
  2402. }
  2403. } else {
  2404. node = nodeObject( node );
  2405. }
  2406. return node;
  2407. }
  2408. let fn, name = scope, minParams, maxParams;
  2409. function verifyParamsLimit( params ) {
  2410. let tslName;
  2411. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2412. else tslName = NodeClass.type;
  2413. if ( minParams !== undefined && params.length < minParams ) {
  2414. error( `TSL: "${ tslName }" parameter length is less than minimum required.` );
  2415. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2416. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2417. error( `TSL: "${ tslName }" parameter length exceeds limit.` );
  2418. return params.slice( 0, maxParams );
  2419. }
  2420. return params;
  2421. }
  2422. if ( scope === null ) {
  2423. fn = ( ...params ) => {
  2424. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2425. };
  2426. } else if ( factor !== null ) {
  2427. factor = nodeObject( factor );
  2428. fn = ( ...params ) => {
  2429. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2430. };
  2431. } else {
  2432. fn = ( ...params ) => {
  2433. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2434. };
  2435. }
  2436. fn.setParameterLength = ( ...params ) => {
  2437. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2438. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2439. return fn;
  2440. };
  2441. fn.setName = ( value ) => {
  2442. name = value;
  2443. return fn;
  2444. };
  2445. return fn;
  2446. };
  2447. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2448. return new NodeClass( ...nodeArray( params ) );
  2449. };
  2450. class ShaderCallNodeInternal extends Node {
  2451. constructor( shaderNode, rawInputs ) {
  2452. super();
  2453. this.shaderNode = shaderNode;
  2454. this.rawInputs = rawInputs;
  2455. this.isShaderCallNodeInternal = true;
  2456. }
  2457. getNodeType( builder ) {
  2458. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2459. }
  2460. getElementType( builder ) {
  2461. return this.getOutputNode( builder ).getElementType( builder );
  2462. }
  2463. getMemberType( builder, name ) {
  2464. return this.getOutputNode( builder ).getMemberType( builder, name );
  2465. }
  2466. call( builder ) {
  2467. const { shaderNode, rawInputs } = this;
  2468. const properties = builder.getNodeProperties( shaderNode );
  2469. const subBuild = builder.getClosestSubBuild( shaderNode.subBuilds ) || '';
  2470. const subBuildProperty = subBuild || 'default';
  2471. if ( properties[ subBuildProperty ] ) {
  2472. return properties[ subBuildProperty ];
  2473. }
  2474. //
  2475. const previousSubBuildFn = builder.subBuildFn;
  2476. const previousFnCall = builder.fnCall;
  2477. builder.subBuildFn = subBuild;
  2478. builder.fnCall = this;
  2479. let result = null;
  2480. if ( shaderNode.layout ) {
  2481. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2482. if ( functionNodesCacheMap === undefined ) {
  2483. functionNodesCacheMap = new WeakMap();
  2484. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2485. }
  2486. let functionNode = functionNodesCacheMap.get( shaderNode );
  2487. if ( functionNode === undefined ) {
  2488. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2489. functionNodesCacheMap.set( shaderNode, functionNode );
  2490. }
  2491. builder.addInclude( functionNode );
  2492. //
  2493. const inputs = rawInputs ? getLayoutParameters( rawInputs ) : null;
  2494. result = nodeObject( functionNode.call( inputs ) );
  2495. } else {
  2496. const secureNodeBuilder = new Proxy( builder, {
  2497. get: ( target, property, receiver ) => {
  2498. let value;
  2499. if ( Symbol.iterator === property ) {
  2500. value = function* () {
  2501. yield undefined;
  2502. };
  2503. } else {
  2504. value = Reflect.get( target, property, receiver );
  2505. }
  2506. return value;
  2507. }
  2508. } );
  2509. //
  2510. const inputs = rawInputs ? getProxyParameters( rawInputs ) : null;
  2511. const hasParameters = Array.isArray( rawInputs ) ? rawInputs.length > 0 : rawInputs !== null;
  2512. const jsFunc = shaderNode.jsFunc;
  2513. const outputNode = hasParameters || jsFunc.length > 1 ? jsFunc( inputs, secureNodeBuilder ) : jsFunc( secureNodeBuilder );
  2514. result = nodeObject( outputNode );
  2515. }
  2516. builder.subBuildFn = previousSubBuildFn;
  2517. builder.fnCall = previousFnCall;
  2518. if ( shaderNode.once ) {
  2519. properties[ subBuildProperty ] = result;
  2520. }
  2521. return result;
  2522. }
  2523. setupOutput( builder ) {
  2524. builder.addStack();
  2525. builder.stack.outputNode = this.call( builder );
  2526. return builder.removeStack();
  2527. }
  2528. getOutputNode( builder ) {
  2529. const properties = builder.getNodeProperties( this );
  2530. const subBuildOutput = builder.getSubBuildOutput( this );
  2531. properties[ subBuildOutput ] = properties[ subBuildOutput ] || this.setupOutput( builder );
  2532. properties[ subBuildOutput ].subBuild = builder.getClosestSubBuild( this );
  2533. return properties[ subBuildOutput ];
  2534. }
  2535. build( builder, output = null ) {
  2536. let result = null;
  2537. const buildStage = builder.getBuildStage();
  2538. const properties = builder.getNodeProperties( this );
  2539. const subBuildOutput = builder.getSubBuildOutput( this );
  2540. const outputNode = this.getOutputNode( builder );
  2541. const previousFnCall = builder.fnCall;
  2542. builder.fnCall = this;
  2543. if ( buildStage === 'setup' ) {
  2544. const subBuildInitialized = builder.getSubBuildProperty( 'initialized', this );
  2545. if ( properties[ subBuildInitialized ] !== true ) {
  2546. properties[ subBuildInitialized ] = true;
  2547. properties[ subBuildOutput ] = this.getOutputNode( builder );
  2548. properties[ subBuildOutput ].build( builder );
  2549. // If the shaderNode has subBuilds, add them to the chaining nodes
  2550. // so they can be built later in the build process.
  2551. if ( this.shaderNode.subBuilds ) {
  2552. for ( const node of builder.chaining ) {
  2553. const nodeData = builder.getDataFromNode( node, 'any' );
  2554. nodeData.subBuilds = nodeData.subBuilds || new Set();
  2555. for ( const subBuild of this.shaderNode.subBuilds ) {
  2556. nodeData.subBuilds.add( subBuild );
  2557. }
  2558. //builder.getDataFromNode( node ).subBuilds = nodeData.subBuilds;
  2559. }
  2560. }
  2561. }
  2562. result = properties[ subBuildOutput ];
  2563. } else if ( buildStage === 'analyze' ) {
  2564. outputNode.build( builder, output );
  2565. } else if ( buildStage === 'generate' ) {
  2566. result = outputNode.build( builder, output ) || '';
  2567. }
  2568. builder.fnCall = previousFnCall;
  2569. return result;
  2570. }
  2571. }
  2572. function getLayoutParameters( params ) {
  2573. let output;
  2574. nodeObjects( params );
  2575. const isArrayAsParameter = params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2576. if ( isArrayAsParameter ) {
  2577. output = [ ...params ];
  2578. } else {
  2579. output = params[ 0 ];
  2580. }
  2581. return output;
  2582. }
  2583. function getProxyParameters( params ) {
  2584. let index = 0;
  2585. nodeObjects( params );
  2586. return new Proxy( params, {
  2587. get: ( target, property, receiver ) => {
  2588. let value;
  2589. if ( property === 'length' ) {
  2590. value = params.length;
  2591. return value;
  2592. }
  2593. if ( Symbol.iterator === property ) {
  2594. value = function* () {
  2595. for ( const inputNode of params ) {
  2596. yield nodeObject( inputNode );
  2597. }
  2598. };
  2599. } else {
  2600. if ( params.length > 0 ) {
  2601. if ( Object.getPrototypeOf( params[ 0 ] ) === Object.prototype ) {
  2602. const objectTarget = params[ 0 ];
  2603. if ( objectTarget[ property ] === undefined ) {
  2604. value = objectTarget[ index ++ ];
  2605. } else {
  2606. value = Reflect.get( objectTarget, property, receiver );
  2607. }
  2608. } else if ( params[ 0 ] instanceof Node ) {
  2609. if ( params[ property ] === undefined ) {
  2610. value = params[ index ++ ];
  2611. } else {
  2612. value = Reflect.get( params, property, receiver );
  2613. }
  2614. }
  2615. } else {
  2616. value = Reflect.get( target, property, receiver );
  2617. }
  2618. value = nodeObject( value );
  2619. }
  2620. return value;
  2621. }
  2622. } );
  2623. }
  2624. class ShaderNodeInternal extends Node {
  2625. constructor( jsFunc, nodeType ) {
  2626. super( nodeType );
  2627. this.jsFunc = jsFunc;
  2628. this.layout = null;
  2629. this.global = true;
  2630. this.once = false;
  2631. }
  2632. setLayout( layout ) {
  2633. this.layout = layout;
  2634. return this;
  2635. }
  2636. getLayout() {
  2637. return this.layout;
  2638. }
  2639. call( rawInputs = null ) {
  2640. return new ShaderCallNodeInternal( this, rawInputs );
  2641. }
  2642. setup() {
  2643. return this.call();
  2644. }
  2645. }
  2646. const bools = [ false, true ];
  2647. const uints = [ 0, 1, 2, 3 ];
  2648. const ints = [ -1, -2 ];
  2649. 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 ];
  2650. const boolsCacheMap = new Map();
  2651. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2652. const uintsCacheMap = new Map();
  2653. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2654. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2655. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2656. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2657. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2658. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2659. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2660. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2661. const getConstNode = ( value, type ) => {
  2662. if ( constNodesCacheMap.has( value ) ) {
  2663. return constNodesCacheMap.get( value );
  2664. } else if ( value.isNode === true ) {
  2665. return value;
  2666. } else {
  2667. return new ConstNode( value, type );
  2668. }
  2669. };
  2670. const ConvertType = function ( type, cacheMap = null ) {
  2671. return ( ...params ) => {
  2672. for ( const param of params ) {
  2673. if ( param === undefined ) {
  2674. error( `TSL: Invalid parameter for the type "${ type }".` );
  2675. return new ConstNode( 0, type );
  2676. }
  2677. }
  2678. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => {
  2679. const paramType = typeof param;
  2680. return paramType !== 'object' && paramType !== 'function';
  2681. } ) ) ) {
  2682. params = [ getValueFromType( type, ...params ) ];
  2683. }
  2684. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2685. return nodeObjectIntent( cacheMap.get( params[ 0 ] ) );
  2686. }
  2687. if ( params.length === 1 ) {
  2688. const node = getConstNode( params[ 0 ], type );
  2689. if ( node.nodeType === type ) return nodeObjectIntent( node );
  2690. return nodeObjectIntent( new ConvertNode( node, type ) );
  2691. }
  2692. const nodes = params.map( param => getConstNode( param ) );
  2693. return nodeObjectIntent( new JoinNode( nodes, type ) );
  2694. };
  2695. };
  2696. // exports
  2697. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2698. // utils
  2699. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2700. // shader node base
  2701. function ShaderNode( jsFunc, nodeType ) {
  2702. return new ShaderNodeInternal( jsFunc, nodeType );
  2703. }
  2704. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2705. const nodeObjectIntent = ( val, altType = null ) => /* new */ nodeObject( val, altType ).toVarIntent();
  2706. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2707. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2708. const nodeProxy = ( NodeClass, scope = null, factor = null, settings = null ) => new ShaderNodeProxy( NodeClass, scope, factor, settings );
  2709. const nodeImmutable = ( NodeClass, ...params ) => new ShaderNodeImmutable( NodeClass, ...params );
  2710. const nodeProxyIntent = ( NodeClass, scope = null, factor = null, settings = {} ) => new ShaderNodeProxy( NodeClass, scope, factor, { ...settings, intent: true } );
  2711. let fnId = 0;
  2712. class FnNode extends Node {
  2713. constructor( jsFunc, layout = null ) {
  2714. super();
  2715. let nodeType = null;
  2716. if ( layout !== null ) {
  2717. if ( typeof layout === 'object' ) {
  2718. nodeType = layout.return;
  2719. } else {
  2720. if ( typeof layout === 'string' ) {
  2721. nodeType = layout;
  2722. } else {
  2723. error( 'TSL: Invalid layout type.' );
  2724. }
  2725. layout = null;
  2726. }
  2727. }
  2728. this.shaderNode = new ShaderNode( jsFunc, nodeType );
  2729. if ( layout !== null ) {
  2730. this.setLayout( layout );
  2731. }
  2732. this.isFn = true;
  2733. }
  2734. setLayout( layout ) {
  2735. const nodeType = this.shaderNode.nodeType;
  2736. if ( typeof layout.inputs !== 'object' ) {
  2737. const fullLayout = {
  2738. name: 'fn' + fnId ++,
  2739. type: nodeType,
  2740. inputs: []
  2741. };
  2742. for ( const name in layout ) {
  2743. if ( name === 'return' ) continue;
  2744. fullLayout.inputs.push( {
  2745. name: name,
  2746. type: layout[ name ]
  2747. } );
  2748. }
  2749. layout = fullLayout;
  2750. }
  2751. this.shaderNode.setLayout( layout );
  2752. return this;
  2753. }
  2754. getNodeType( builder ) {
  2755. return this.shaderNode.getNodeType( builder ) || 'float';
  2756. }
  2757. call( ...params ) {
  2758. const fnCall = this.shaderNode.call( params );
  2759. if ( this.shaderNode.nodeType === 'void' ) fnCall.toStack();
  2760. return fnCall.toVarIntent();
  2761. }
  2762. once( subBuilds = null ) {
  2763. this.shaderNode.once = true;
  2764. this.shaderNode.subBuilds = subBuilds;
  2765. return this;
  2766. }
  2767. generate( builder ) {
  2768. const type = this.getNodeType( builder );
  2769. error( 'TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".' );
  2770. return builder.generateConst( type );
  2771. }
  2772. }
  2773. function Fn( jsFunc, layout = null ) {
  2774. const instance = new FnNode( jsFunc, layout );
  2775. return new Proxy( () => {}, {
  2776. apply( target, thisArg, params ) {
  2777. return instance.call( ...params );
  2778. },
  2779. get( target, prop, receiver ) {
  2780. return Reflect.get( instance, prop, receiver );
  2781. },
  2782. set( target, prop, value, receiver ) {
  2783. return Reflect.set( instance, prop, value, receiver );
  2784. }
  2785. } );
  2786. }
  2787. //
  2788. const setCurrentStack = ( stack ) => {
  2789. currentStack = stack;
  2790. };
  2791. const getCurrentStack = () => currentStack;
  2792. /**
  2793. * Represent a conditional node using if/else statements.
  2794. *
  2795. * ```js
  2796. * If( condition, function )
  2797. * .ElseIf( condition, function )
  2798. * .Else( function )
  2799. * ```
  2800. * @tsl
  2801. * @function
  2802. * @param {...any} params - The parameters for the conditional node.
  2803. * @returns {StackNode} The conditional node.
  2804. */
  2805. const If = ( ...params ) => currentStack.If( ...params );
  2806. /**
  2807. * Represent a conditional node using switch/case statements.
  2808. *
  2809. * ```js
  2810. * Switch( value )
  2811. * .Case( 1, function )
  2812. * .Case( 2, 3, 4, function )
  2813. * .Default( function )
  2814. * ```
  2815. * @tsl
  2816. * @function
  2817. * @param {...any} params - The parameters for the conditional node.
  2818. * @returns {StackNode} The conditional node.
  2819. */
  2820. const Switch = ( ...params ) => currentStack.Switch( ...params );
  2821. /**
  2822. * Add the given node to the current stack.
  2823. *
  2824. * @param {Node} node - The node to add.
  2825. * @returns {Node} The node that was added to the stack.
  2826. */
  2827. function Stack( node ) {
  2828. if ( currentStack ) currentStack.addToStack( node );
  2829. return node;
  2830. }
  2831. addMethodChaining( 'toStack', Stack );
  2832. // types
  2833. const color = new ConvertType( 'color' );
  2834. const float = new ConvertType( 'float', cacheMaps.float );
  2835. const int = new ConvertType( 'int', cacheMaps.ints );
  2836. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2837. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2838. const vec2 = new ConvertType( 'vec2' );
  2839. const ivec2 = new ConvertType( 'ivec2' );
  2840. const uvec2 = new ConvertType( 'uvec2' );
  2841. const bvec2 = new ConvertType( 'bvec2' );
  2842. const vec3 = new ConvertType( 'vec3' );
  2843. const ivec3 = new ConvertType( 'ivec3' );
  2844. const uvec3 = new ConvertType( 'uvec3' );
  2845. const bvec3 = new ConvertType( 'bvec3' );
  2846. const vec4 = new ConvertType( 'vec4' );
  2847. const ivec4 = new ConvertType( 'ivec4' );
  2848. const uvec4 = new ConvertType( 'uvec4' );
  2849. const bvec4 = new ConvertType( 'bvec4' );
  2850. const mat2 = new ConvertType( 'mat2' );
  2851. const mat3 = new ConvertType( 'mat3' );
  2852. const mat4 = new ConvertType( 'mat4' );
  2853. const string = ( value = '' ) => new ConstNode( value, 'string' );
  2854. const arrayBuffer = ( value ) => new ConstNode( value, 'ArrayBuffer' );
  2855. addMethodChaining( 'toColor', color );
  2856. addMethodChaining( 'toFloat', float );
  2857. addMethodChaining( 'toInt', int );
  2858. addMethodChaining( 'toUint', uint );
  2859. addMethodChaining( 'toBool', bool );
  2860. addMethodChaining( 'toVec2', vec2 );
  2861. addMethodChaining( 'toIVec2', ivec2 );
  2862. addMethodChaining( 'toUVec2', uvec2 );
  2863. addMethodChaining( 'toBVec2', bvec2 );
  2864. addMethodChaining( 'toVec3', vec3 );
  2865. addMethodChaining( 'toIVec3', ivec3 );
  2866. addMethodChaining( 'toUVec3', uvec3 );
  2867. addMethodChaining( 'toBVec3', bvec3 );
  2868. addMethodChaining( 'toVec4', vec4 );
  2869. addMethodChaining( 'toIVec4', ivec4 );
  2870. addMethodChaining( 'toUVec4', uvec4 );
  2871. addMethodChaining( 'toBVec4', bvec4 );
  2872. addMethodChaining( 'toMat2', mat2 );
  2873. addMethodChaining( 'toMat3', mat3 );
  2874. addMethodChaining( 'toMat4', mat4 );
  2875. // basic nodes
  2876. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  2877. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2878. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2879. addMethodChaining( 'element', element );
  2880. addMethodChaining( 'convert', convert );
  2881. // deprecated
  2882. /**
  2883. * @tsl
  2884. * @function
  2885. * @deprecated since r176. Use {@link Stack} instead.
  2886. *
  2887. * @param {Node} node - The node to add.
  2888. * @returns {Function}
  2889. */
  2890. const append = ( node ) => { // @deprecated, r176
  2891. warn( 'TSL: append() has been renamed to Stack().' );
  2892. return Stack( node );
  2893. };
  2894. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  2895. warn( 'TSL: .append() has been renamed to .toStack().' );
  2896. return Stack( node );
  2897. } );
  2898. /**
  2899. * This class represents a shader property. It can be used
  2900. * to explicitly define a property and assign a value to it.
  2901. *
  2902. * ```js
  2903. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2904. *```
  2905. * `PropertyNode` is used by the engine to predefined common material properties
  2906. * for TSL code.
  2907. *
  2908. * @augments Node
  2909. */
  2910. class PropertyNode extends Node {
  2911. static get type() {
  2912. return 'PropertyNode';
  2913. }
  2914. /**
  2915. * Constructs a new property node.
  2916. *
  2917. * @param {string} nodeType - The type of the node.
  2918. * @param {?string} [name=null] - The name of the property in the shader.
  2919. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2920. */
  2921. constructor( nodeType, name = null, varying = false ) {
  2922. super( nodeType );
  2923. /**
  2924. * The name of the property in the shader. If no name is defined,
  2925. * the node system auto-generates one.
  2926. *
  2927. * @type {?string}
  2928. * @default null
  2929. */
  2930. this.name = name;
  2931. /**
  2932. * Whether this property is a varying or not.
  2933. *
  2934. * @type {boolean}
  2935. * @default false
  2936. */
  2937. this.varying = varying;
  2938. /**
  2939. * This flag can be used for type testing.
  2940. *
  2941. * @type {boolean}
  2942. * @readonly
  2943. * @default true
  2944. */
  2945. this.isPropertyNode = true;
  2946. /**
  2947. * This flag is used for global cache.
  2948. *
  2949. * @type {boolean}
  2950. * @default true
  2951. */
  2952. this.global = true;
  2953. }
  2954. customCacheKey() {
  2955. return hashString( this.type + ':' + ( this.name || '' ) + ':' + ( this.varying ? '1' : '0' ) );
  2956. }
  2957. getHash( builder ) {
  2958. return this.name || super.getHash( builder );
  2959. }
  2960. generate( builder ) {
  2961. let nodeVar;
  2962. if ( this.varying === true ) {
  2963. nodeVar = builder.getVaryingFromNode( this, this.name );
  2964. nodeVar.needsInterpolation = true;
  2965. } else {
  2966. nodeVar = builder.getVarFromNode( this, this.name );
  2967. }
  2968. return builder.getPropertyName( nodeVar );
  2969. }
  2970. }
  2971. /**
  2972. * TSL function for creating a property node.
  2973. *
  2974. * @tsl
  2975. * @function
  2976. * @param {string} type - The type of the node.
  2977. * @param {?string} [name=null] - The name of the property in the shader.
  2978. * @returns {PropertyNode}
  2979. */
  2980. const property = ( type, name ) => new PropertyNode( type, name );
  2981. /**
  2982. * TSL function for creating a varying property node.
  2983. *
  2984. * @tsl
  2985. * @function
  2986. * @param {string} type - The type of the node.
  2987. * @param {?string} [name=null] - The name of the varying in the shader.
  2988. * @returns {PropertyNode}
  2989. */
  2990. const varyingProperty = ( type, name ) => new PropertyNode( type, name, true );
  2991. /**
  2992. * TSL object that represents the shader variable `DiffuseColor`.
  2993. *
  2994. * @tsl
  2995. * @type {PropertyNode<vec4>}
  2996. */
  2997. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2998. /**
  2999. * TSL object that represents the shader variable `DiffuseContribution`.
  3000. *
  3001. * @tsl
  3002. * @type {PropertyNode<vec3>}
  3003. */
  3004. const diffuseContribution = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'DiffuseContribution' );
  3005. /**
  3006. * TSL object that represents the shader variable `EmissiveColor`.
  3007. *
  3008. * @tsl
  3009. * @type {PropertyNode<vec3>}
  3010. */
  3011. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  3012. /**
  3013. * TSL object that represents the shader variable `Roughness`.
  3014. *
  3015. * @tsl
  3016. * @type {PropertyNode<float>}
  3017. */
  3018. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  3019. /**
  3020. * TSL object that represents the shader variable `Metalness`.
  3021. *
  3022. * @tsl
  3023. * @type {PropertyNode<float>}
  3024. */
  3025. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  3026. /**
  3027. * TSL object that represents the shader variable `Clearcoat`.
  3028. *
  3029. * @tsl
  3030. * @type {PropertyNode<float>}
  3031. */
  3032. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  3033. /**
  3034. * TSL object that represents the shader variable `ClearcoatRoughness`.
  3035. *
  3036. * @tsl
  3037. * @type {PropertyNode<float>}
  3038. */
  3039. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  3040. /**
  3041. * TSL object that represents the shader variable `Sheen`.
  3042. *
  3043. * @tsl
  3044. * @type {PropertyNode<vec3>}
  3045. */
  3046. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  3047. /**
  3048. * TSL object that represents the shader variable `SheenRoughness`.
  3049. *
  3050. * @tsl
  3051. * @type {PropertyNode<float>}
  3052. */
  3053. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  3054. /**
  3055. * TSL object that represents the shader variable `Iridescence`.
  3056. *
  3057. * @tsl
  3058. * @type {PropertyNode<float>}
  3059. */
  3060. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  3061. /**
  3062. * TSL object that represents the shader variable `IridescenceIOR`.
  3063. *
  3064. * @tsl
  3065. * @type {PropertyNode<float>}
  3066. */
  3067. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  3068. /**
  3069. * TSL object that represents the shader variable `IridescenceThickness`.
  3070. *
  3071. * @tsl
  3072. * @type {PropertyNode<float>}
  3073. */
  3074. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  3075. /**
  3076. * TSL object that represents the shader variable `AlphaT`.
  3077. *
  3078. * @tsl
  3079. * @type {PropertyNode<float>}
  3080. */
  3081. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  3082. /**
  3083. * TSL object that represents the shader variable `Anisotropy`.
  3084. *
  3085. * @tsl
  3086. * @type {PropertyNode<float>}
  3087. */
  3088. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  3089. /**
  3090. * TSL object that represents the shader variable `AnisotropyT`.
  3091. *
  3092. * @tsl
  3093. * @type {PropertyNode<vec3>}
  3094. */
  3095. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  3096. /**
  3097. * TSL object that represents the shader variable `AnisotropyB`.
  3098. *
  3099. * @tsl
  3100. * @type {PropertyNode<vec3>}
  3101. */
  3102. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  3103. /**
  3104. * TSL object that represents the shader variable `SpecularColor`.
  3105. *
  3106. * @tsl
  3107. * @type {PropertyNode<color>}
  3108. */
  3109. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  3110. /**
  3111. * TSL object that represents the shader variable `SpecularColorBlended`.
  3112. *
  3113. * @tsl
  3114. * @type {PropertyNode<color>}
  3115. */
  3116. const specularColorBlended = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColorBlended' );
  3117. /**
  3118. * TSL object that represents the shader variable `SpecularF90`.
  3119. *
  3120. * @tsl
  3121. * @type {PropertyNode<float>}
  3122. */
  3123. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  3124. /**
  3125. * TSL object that represents the shader variable `Shininess`.
  3126. *
  3127. * @tsl
  3128. * @type {PropertyNode<float>}
  3129. */
  3130. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  3131. /**
  3132. * TSL object that represents the shader variable `Output`.
  3133. *
  3134. * @tsl
  3135. * @type {PropertyNode<vec4>}
  3136. */
  3137. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  3138. /**
  3139. * TSL object that represents the shader variable `dashSize`.
  3140. *
  3141. * @tsl
  3142. * @type {PropertyNode<float>}
  3143. */
  3144. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  3145. /**
  3146. * TSL object that represents the shader variable `gapSize`.
  3147. *
  3148. * @tsl
  3149. * @type {PropertyNode<float>}
  3150. */
  3151. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  3152. /**
  3153. * TSL object that represents the shader variable `pointWidth`.
  3154. *
  3155. * @tsl
  3156. * @type {PropertyNode<float>}
  3157. */
  3158. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  3159. /**
  3160. * TSL object that represents the shader variable `IOR`.
  3161. *
  3162. * @tsl
  3163. * @type {PropertyNode<float>}
  3164. */
  3165. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  3166. /**
  3167. * TSL object that represents the shader variable `Transmission`.
  3168. *
  3169. * @tsl
  3170. * @type {PropertyNode<float>}
  3171. */
  3172. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  3173. /**
  3174. * TSL object that represents the shader variable `Thickness`.
  3175. *
  3176. * @tsl
  3177. * @type {PropertyNode<float>}
  3178. */
  3179. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  3180. /**
  3181. * TSL object that represents the shader variable `AttenuationDistance`.
  3182. *
  3183. * @tsl
  3184. * @type {PropertyNode<float>}
  3185. */
  3186. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  3187. /**
  3188. * TSL object that represents the shader variable `AttenuationColor`.
  3189. *
  3190. * @tsl
  3191. * @type {PropertyNode<color>}
  3192. */
  3193. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  3194. /**
  3195. * TSL object that represents the shader variable `Dispersion`.
  3196. *
  3197. * @tsl
  3198. * @type {PropertyNode<float>}
  3199. */
  3200. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  3201. /**
  3202. * This node can be used to group single instances of {@link UniformNode}
  3203. * and manage them as a uniform buffer.
  3204. *
  3205. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  3206. * will be used when defining the {@link UniformNode#groupNode} property.
  3207. *
  3208. * - `objectGroup`: Uniform buffer per object.
  3209. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  3210. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  3211. *
  3212. * @augments Node
  3213. */
  3214. class UniformGroupNode extends Node {
  3215. static get type() {
  3216. return 'UniformGroupNode';
  3217. }
  3218. /**
  3219. * Constructs a new uniform group node.
  3220. *
  3221. * @param {string} name - The name of the uniform group node.
  3222. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  3223. * @param {number} [order=1] - Influences the internal sorting.
  3224. */
  3225. constructor( name, shared = false, order = 1 ) {
  3226. super( 'string' );
  3227. /**
  3228. * The name of the uniform group node.
  3229. *
  3230. * @type {string}
  3231. */
  3232. this.name = name;
  3233. /**
  3234. * Whether this uniform group node is shared or not.
  3235. *
  3236. * @type {boolean}
  3237. * @default false
  3238. */
  3239. this.shared = shared;
  3240. /**
  3241. * Influences the internal sorting.
  3242. * TODO: Add details when this property should be changed.
  3243. *
  3244. * @type {number}
  3245. * @default 1
  3246. */
  3247. this.order = order;
  3248. /**
  3249. * This flag can be used for type testing.
  3250. *
  3251. * @type {boolean}
  3252. * @readonly
  3253. * @default true
  3254. */
  3255. this.isUniformGroup = true;
  3256. }
  3257. serialize( data ) {
  3258. super.serialize( data );
  3259. data.name = this.name;
  3260. data.version = this.version;
  3261. data.shared = this.shared;
  3262. }
  3263. deserialize( data ) {
  3264. super.deserialize( data );
  3265. this.name = data.name;
  3266. this.version = data.version;
  3267. this.shared = data.shared;
  3268. }
  3269. }
  3270. /**
  3271. * TSL function for creating a uniform group node with the given name.
  3272. *
  3273. * @tsl
  3274. * @function
  3275. * @param {string} name - The name of the uniform group node.
  3276. * @returns {UniformGroupNode}
  3277. */
  3278. const uniformGroup = ( name ) => new UniformGroupNode( name );
  3279. /**
  3280. * TSL function for creating a shared uniform group node with the given name and order.
  3281. *
  3282. * @tsl
  3283. * @function
  3284. * @param {string} name - The name of the uniform group node.
  3285. * @param {number} [order=0] - Influences the internal sorting.
  3286. * @returns {UniformGroupNode}
  3287. */
  3288. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  3289. /**
  3290. * TSL object that represents a shared uniform group node which is updated once per frame.
  3291. *
  3292. * @tsl
  3293. * @type {UniformGroupNode}
  3294. */
  3295. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  3296. /**
  3297. * TSL object that represents a shared uniform group node which is updated once per render.
  3298. *
  3299. * @tsl
  3300. * @type {UniformGroupNode}
  3301. */
  3302. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  3303. /**
  3304. * TSL object that represents a uniform group node which is updated once per object.
  3305. *
  3306. * @tsl
  3307. * @type {UniformGroupNode}
  3308. */
  3309. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  3310. /**
  3311. * Class for representing a uniform.
  3312. *
  3313. * @augments InputNode
  3314. */
  3315. class UniformNode extends InputNode {
  3316. static get type() {
  3317. return 'UniformNode';
  3318. }
  3319. /**
  3320. * Constructs a new uniform node.
  3321. *
  3322. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3323. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3324. */
  3325. constructor( value, nodeType = null ) {
  3326. super( value, nodeType );
  3327. /**
  3328. * This flag can be used for type testing.
  3329. *
  3330. * @type {boolean}
  3331. * @readonly
  3332. * @default true
  3333. */
  3334. this.isUniformNode = true;
  3335. /**
  3336. * The name or label of the uniform.
  3337. *
  3338. * @type {string}
  3339. * @default ''
  3340. */
  3341. this.name = '';
  3342. /**
  3343. * The uniform group of this uniform. By default, uniforms are
  3344. * managed per object but they might belong to a shared group
  3345. * which is updated per frame or render call.
  3346. *
  3347. * @type {UniformGroupNode}
  3348. */
  3349. this.groupNode = objectGroup;
  3350. }
  3351. /**
  3352. * Sets the {@link UniformNode#name} property.
  3353. *
  3354. * @param {string} name - The name of the uniform.
  3355. * @return {UniformNode} A reference to this node.
  3356. */
  3357. setName( name ) {
  3358. this.name = name;
  3359. return this;
  3360. }
  3361. /**
  3362. * Sets the {@link UniformNode#name} property.
  3363. *
  3364. * @deprecated
  3365. * @param {string} name - The name of the uniform.
  3366. * @return {UniformNode} A reference to this node.
  3367. */
  3368. label( name ) {
  3369. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  3370. return this.setName( name );
  3371. }
  3372. /**
  3373. * Sets the {@link UniformNode#groupNode} property.
  3374. *
  3375. * @param {UniformGroupNode} group - The uniform group.
  3376. * @return {UniformNode} A reference to this node.
  3377. */
  3378. setGroup( group ) {
  3379. this.groupNode = group;
  3380. return this;
  3381. }
  3382. /**
  3383. * Returns the {@link UniformNode#groupNode}.
  3384. *
  3385. * @return {UniformGroupNode} The uniform group.
  3386. */
  3387. getGroup() {
  3388. return this.groupNode;
  3389. }
  3390. /**
  3391. * By default, this method returns the result of {@link Node#getHash} but derived
  3392. * classes might overwrite this method with a different implementation.
  3393. *
  3394. * @param {NodeBuilder} builder - The current node builder.
  3395. * @return {string} The uniform hash.
  3396. */
  3397. getUniformHash( builder ) {
  3398. return this.getHash( builder );
  3399. }
  3400. onUpdate( callback, updateType ) {
  3401. callback = callback.bind( this );
  3402. return super.onUpdate( ( frame ) => {
  3403. const value = callback( frame, this );
  3404. if ( value !== undefined ) {
  3405. this.value = value;
  3406. }
  3407. }, updateType );
  3408. }
  3409. getInputType( builder ) {
  3410. let type = super.getInputType( builder );
  3411. if ( type === 'bool' ) {
  3412. type = 'uint';
  3413. }
  3414. return type;
  3415. }
  3416. generate( builder, output ) {
  3417. const type = this.getNodeType( builder );
  3418. const hash = this.getUniformHash( builder );
  3419. let sharedNode = builder.getNodeFromHash( hash );
  3420. if ( sharedNode === undefined ) {
  3421. builder.setHashNode( this, hash );
  3422. sharedNode = this;
  3423. }
  3424. const sharedNodeType = sharedNode.getInputType( builder );
  3425. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.nodeName );
  3426. const uniformName = builder.getPropertyName( nodeUniform );
  3427. if ( builder.context.nodeName !== undefined ) delete builder.context.nodeName;
  3428. //
  3429. let snippet = uniformName;
  3430. if ( type === 'bool' ) {
  3431. // cache to variable
  3432. const nodeData = builder.getDataFromNode( this );
  3433. let propertyName = nodeData.propertyName;
  3434. if ( propertyName === undefined ) {
  3435. const nodeVar = builder.getVarFromNode( this, null, 'bool' );
  3436. propertyName = builder.getPropertyName( nodeVar );
  3437. nodeData.propertyName = propertyName;
  3438. snippet = builder.format( uniformName, sharedNodeType, type );
  3439. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  3440. }
  3441. snippet = propertyName;
  3442. }
  3443. return builder.format( snippet, type, output );
  3444. }
  3445. }
  3446. /**
  3447. * TSL function for creating a uniform node.
  3448. *
  3449. * @tsl
  3450. * @function
  3451. * @param {any|string} value - The value of this uniform or your type. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3452. * @param {string} [type] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3453. * @returns {UniformNode}
  3454. */
  3455. const uniform = ( value, type ) => {
  3456. const nodeType = getConstNodeType( type || value );
  3457. if ( nodeType === value ) {
  3458. // if the value is a type but no having a value
  3459. value = getValueFromType( nodeType );
  3460. }
  3461. if ( value && value.isNode === true ) {
  3462. let v = value.value;
  3463. value.traverse( n => {
  3464. if ( n.isConstNode === true ) {
  3465. v = n.value;
  3466. }
  3467. } );
  3468. value = v;
  3469. }
  3470. return new UniformNode( value, nodeType );
  3471. };
  3472. /**
  3473. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3474. * ```js
  3475. * const colors = array( [
  3476. * vec3( 1, 0, 0 ),
  3477. * vec3( 0, 1, 0 ),
  3478. * vec3( 0, 0, 1 )
  3479. * ] );
  3480. *
  3481. * const redColor = tintColors.element( 0 );
  3482. * ```
  3483. *
  3484. * @augments TempNode
  3485. */
  3486. class ArrayNode extends TempNode {
  3487. static get type() {
  3488. return 'ArrayNode';
  3489. }
  3490. /**
  3491. * Constructs a new array node.
  3492. *
  3493. * @param {?string} nodeType - The data type of the elements.
  3494. * @param {number} count - Size of the array.
  3495. * @param {?Array<Node>} [values=null] - Array default values.
  3496. */
  3497. constructor( nodeType, count, values = null ) {
  3498. super( nodeType );
  3499. /**
  3500. * Array size.
  3501. *
  3502. * @type {number}
  3503. */
  3504. this.count = count;
  3505. /**
  3506. * Array default values.
  3507. *
  3508. * @type {?Array<Node>}
  3509. */
  3510. this.values = values;
  3511. /**
  3512. * This flag can be used for type testing.
  3513. *
  3514. * @type {boolean}
  3515. * @readonly
  3516. * @default true
  3517. */
  3518. this.isArrayNode = true;
  3519. }
  3520. /**
  3521. * Returns the number of elements in the node array.
  3522. *
  3523. * @param {NodeBuilder} builder - The current node builder.
  3524. * @return {number} The number of elements in the node array.
  3525. */
  3526. getArrayCount( /*builder*/ ) {
  3527. return this.count;
  3528. }
  3529. /**
  3530. * Returns the node's type.
  3531. *
  3532. * @param {NodeBuilder} builder - The current node builder.
  3533. * @return {string} The type of the node.
  3534. */
  3535. getNodeType( builder ) {
  3536. if ( this.nodeType === null ) {
  3537. return this.values[ 0 ].getNodeType( builder );
  3538. }
  3539. return this.nodeType;
  3540. }
  3541. /**
  3542. * Returns the node's type.
  3543. *
  3544. * @param {NodeBuilder} builder - The current node builder.
  3545. * @return {string} The type of the node.
  3546. */
  3547. getElementType( builder ) {
  3548. return this.getNodeType( builder );
  3549. }
  3550. /**
  3551. * Returns the type of a member variable.
  3552. *
  3553. * @param {NodeBuilder} builder - The current node builder.
  3554. * @param {string} name - The name of the member variable.
  3555. * @return {string} The type of the member variable.
  3556. */
  3557. getMemberType( builder, name ) {
  3558. if ( this.nodeType === null ) {
  3559. return this.values[ 0 ].getMemberType( builder, name );
  3560. }
  3561. return super.getMemberType( builder, name );
  3562. }
  3563. /**
  3564. * This method builds the output node and returns the resulting array as a shader string.
  3565. *
  3566. * @param {NodeBuilder} builder - The current node builder.
  3567. * @return {string} The generated shader string.
  3568. */
  3569. generate( builder ) {
  3570. const type = this.getNodeType( builder );
  3571. return builder.generateArray( type, this.count, this.values );
  3572. }
  3573. }
  3574. /**
  3575. * TSL function for creating an array node.
  3576. *
  3577. * @tsl
  3578. * @function
  3579. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3580. * or an array containing the default values (e.g., [ vec3() ]).
  3581. * @param {?number} [count] - Size of the array.
  3582. * @returns {ArrayNode}
  3583. */
  3584. const array = ( ...params ) => {
  3585. let node;
  3586. if ( params.length === 1 ) {
  3587. const values = params[ 0 ];
  3588. node = new ArrayNode( null, values.length, values );
  3589. } else {
  3590. const nodeType = params[ 0 ];
  3591. const count = params[ 1 ];
  3592. node = new ArrayNode( nodeType, count );
  3593. }
  3594. return nodeObject( node );
  3595. };
  3596. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3597. /**
  3598. * These node represents an assign operation. Meaning a node is assigned
  3599. * to another node.
  3600. *
  3601. * @augments TempNode
  3602. */
  3603. class AssignNode extends TempNode {
  3604. static get type() {
  3605. return 'AssignNode';
  3606. }
  3607. /**
  3608. * Constructs a new assign node.
  3609. *
  3610. * @param {Node} targetNode - The target node.
  3611. * @param {Node} sourceNode - The source type.
  3612. */
  3613. constructor( targetNode, sourceNode ) {
  3614. super();
  3615. /**
  3616. * The target node.
  3617. *
  3618. * @type {Node}
  3619. */
  3620. this.targetNode = targetNode;
  3621. /**
  3622. * The source node.
  3623. *
  3624. * @type {Node}
  3625. */
  3626. this.sourceNode = sourceNode;
  3627. /**
  3628. * This flag can be used for type testing.
  3629. *
  3630. * @type {boolean}
  3631. * @readonly
  3632. * @default true
  3633. */
  3634. this.isAssignNode = true;
  3635. }
  3636. /**
  3637. * Whether this node is used more than once in context of other nodes. This method
  3638. * is overwritten since it always returns `false` (assigns are unique).
  3639. *
  3640. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3641. */
  3642. hasDependencies() {
  3643. return false;
  3644. }
  3645. getNodeType( builder, output ) {
  3646. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3647. }
  3648. /**
  3649. * Whether a split is required when assigning source to target. This can happen when the component length of
  3650. * target and source data type does not match.
  3651. *
  3652. * @param {NodeBuilder} builder - The current node builder.
  3653. * @return {boolean} Whether a split is required when assigning source to target.
  3654. */
  3655. needsSplitAssign( builder ) {
  3656. const { targetNode } = this;
  3657. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3658. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3659. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3660. return assignDifferentVector;
  3661. }
  3662. return false;
  3663. }
  3664. setup( builder ) {
  3665. const { targetNode, sourceNode } = this;
  3666. const scope = targetNode.getScope();
  3667. const scopeData = builder.getDataFromNode( scope );
  3668. scopeData.assign = true;
  3669. const properties = builder.getNodeProperties( this );
  3670. properties.sourceNode = sourceNode;
  3671. properties.targetNode = targetNode.context( { assign: true } );
  3672. }
  3673. generate( builder, output ) {
  3674. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  3675. const needsSplitAssign = this.needsSplitAssign( builder );
  3676. const target = targetNode.build( builder );
  3677. const targetType = targetNode.getNodeType( builder );
  3678. const source = sourceNode.build( builder, targetType );
  3679. const sourceType = sourceNode.getNodeType( builder );
  3680. const nodeData = builder.getDataFromNode( this );
  3681. //
  3682. let snippet;
  3683. if ( nodeData.initialized === true ) {
  3684. if ( output !== 'void' ) {
  3685. snippet = target;
  3686. }
  3687. } else if ( needsSplitAssign ) {
  3688. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3689. const sourceProperty = builder.getPropertyName( sourceVar );
  3690. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3691. const splitNode = targetNode.node;
  3692. const splitTargetNode = splitNode.node.context( { assign: true } );
  3693. const targetRoot = splitTargetNode.build( builder );
  3694. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  3695. const component = splitNode.components[ i ];
  3696. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3697. }
  3698. if ( output !== 'void' ) {
  3699. snippet = target;
  3700. }
  3701. } else {
  3702. snippet = `${ target } = ${ source }`;
  3703. if ( output === 'void' || sourceType === 'void' ) {
  3704. builder.addLineFlowCode( snippet, this );
  3705. if ( output !== 'void' ) {
  3706. snippet = target;
  3707. }
  3708. }
  3709. }
  3710. nodeData.initialized = true;
  3711. return builder.format( snippet, targetType, output );
  3712. }
  3713. }
  3714. /**
  3715. * TSL function for creating an assign node.
  3716. *
  3717. * @tsl
  3718. * @function
  3719. * @param {Node} targetNode - The target node.
  3720. * @param {Node} sourceNode - The source type.
  3721. * @returns {AssignNode}
  3722. */
  3723. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  3724. addMethodChaining( 'assign', assign );
  3725. /**
  3726. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3727. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3728. * this logic.
  3729. *
  3730. * @augments TempNode
  3731. */
  3732. class FunctionCallNode extends TempNode {
  3733. static get type() {
  3734. return 'FunctionCallNode';
  3735. }
  3736. /**
  3737. * Constructs a new function call node.
  3738. *
  3739. * @param {?FunctionNode} functionNode - The function node.
  3740. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3741. */
  3742. constructor( functionNode = null, parameters = {} ) {
  3743. super();
  3744. /**
  3745. * The function node.
  3746. *
  3747. * @type {?FunctionNode}
  3748. * @default null
  3749. */
  3750. this.functionNode = functionNode;
  3751. /**
  3752. * The parameters of the function call.
  3753. *
  3754. * @type {Object<string, Node>}
  3755. * @default {}
  3756. */
  3757. this.parameters = parameters;
  3758. }
  3759. /**
  3760. * Sets the parameters of the function call node.
  3761. *
  3762. * @param {Object<string, Node>} parameters - The parameters to set.
  3763. * @return {FunctionCallNode} A reference to this node.
  3764. */
  3765. setParameters( parameters ) {
  3766. this.parameters = parameters;
  3767. return this;
  3768. }
  3769. /**
  3770. * Returns the parameters of the function call node.
  3771. *
  3772. * @return {Object<string, Node>} The parameters of this node.
  3773. */
  3774. getParameters() {
  3775. return this.parameters;
  3776. }
  3777. /**
  3778. * Returns the type of this function call node.
  3779. *
  3780. * @param {NodeBuilder} builder - The current node builder.
  3781. * @returns {string} The type of this node.
  3782. */
  3783. getNodeType( builder ) {
  3784. return this.functionNode.getNodeType( builder );
  3785. }
  3786. /**
  3787. * Returns the function node of this function call node.
  3788. *
  3789. * @param {NodeBuilder} builder - The current node builder.
  3790. * @param {string} [name] - The name of the member.
  3791. * @returns {string} The type of the member.
  3792. */
  3793. getMemberType( builder, name ) {
  3794. return this.functionNode.getMemberType( builder, name );
  3795. }
  3796. generate( builder ) {
  3797. const params = [];
  3798. const functionNode = this.functionNode;
  3799. const inputs = functionNode.getInputs( builder );
  3800. const parameters = this.parameters;
  3801. const generateInput = ( node, inputNode ) => {
  3802. const type = inputNode.type;
  3803. const pointer = type === 'pointer';
  3804. let output;
  3805. if ( pointer ) output = '&' + node.build( builder );
  3806. else output = node.build( builder, type );
  3807. return output;
  3808. };
  3809. if ( Array.isArray( parameters ) ) {
  3810. if ( parameters.length > inputs.length ) {
  3811. error( 'TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  3812. parameters.length = inputs.length;
  3813. } else if ( parameters.length < inputs.length ) {
  3814. error( 'TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  3815. while ( parameters.length < inputs.length ) {
  3816. parameters.push( float( 0 ) );
  3817. }
  3818. }
  3819. for ( let i = 0; i < parameters.length; i ++ ) {
  3820. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3821. }
  3822. } else {
  3823. for ( const inputNode of inputs ) {
  3824. const node = parameters[ inputNode.name ];
  3825. if ( node !== undefined ) {
  3826. params.push( generateInput( node, inputNode ) );
  3827. } else {
  3828. error( `TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  3829. params.push( generateInput( float( 0 ), inputNode ) );
  3830. }
  3831. }
  3832. }
  3833. const functionName = functionNode.build( builder, 'property' );
  3834. return `${ functionName }( ${ params.join( ', ' ) } )`;
  3835. }
  3836. }
  3837. const call = ( func, ...params ) => {
  3838. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3839. return new FunctionCallNode( nodeObject( func ), params );
  3840. };
  3841. addMethodChaining( 'call', call );
  3842. const _vectorOperators = {
  3843. '==': 'equal',
  3844. '!=': 'notEqual',
  3845. '<': 'lessThan',
  3846. '>': 'greaterThan',
  3847. '<=': 'lessThanEqual',
  3848. '>=': 'greaterThanEqual',
  3849. '%': 'mod'
  3850. };
  3851. /**
  3852. * This node represents basic mathematical and logical operations like addition,
  3853. * subtraction or comparisons (e.g. `equal()`).
  3854. *
  3855. * @augments TempNode
  3856. */
  3857. class OperatorNode extends TempNode {
  3858. static get type() {
  3859. return 'OperatorNode';
  3860. }
  3861. /**
  3862. * Constructs a new operator node.
  3863. *
  3864. * @param {string} op - The operator.
  3865. * @param {Node} aNode - The first input.
  3866. * @param {Node} bNode - The second input.
  3867. * @param {...Node} params - Additional input parameters.
  3868. */
  3869. constructor( op, aNode, bNode, ...params ) {
  3870. super();
  3871. if ( params.length > 0 ) {
  3872. let finalOp = new OperatorNode( op, aNode, bNode );
  3873. for ( let i = 0; i < params.length - 1; i ++ ) {
  3874. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3875. }
  3876. aNode = finalOp;
  3877. bNode = params[ params.length - 1 ];
  3878. }
  3879. /**
  3880. * The operator.
  3881. *
  3882. * @type {string}
  3883. */
  3884. this.op = op;
  3885. /**
  3886. * The first input.
  3887. *
  3888. * @type {Node}
  3889. */
  3890. this.aNode = aNode;
  3891. /**
  3892. * The second input.
  3893. *
  3894. * @type {Node}
  3895. */
  3896. this.bNode = bNode;
  3897. /**
  3898. * This flag can be used for type testing.
  3899. *
  3900. * @type {boolean}
  3901. * @readonly
  3902. * @default true
  3903. */
  3904. this.isOperatorNode = true;
  3905. }
  3906. /**
  3907. * Returns the operator method name.
  3908. *
  3909. * @param {NodeBuilder} builder - The current node builder.
  3910. * @param {string} output - The output type.
  3911. * @returns {string} The operator method name.
  3912. */
  3913. getOperatorMethod( builder, output ) {
  3914. return builder.getMethod( _vectorOperators[ this.op ], output );
  3915. }
  3916. /**
  3917. * This method is overwritten since the node type is inferred from the operator
  3918. * and the input node types.
  3919. *
  3920. * @param {NodeBuilder} builder - The current node builder.
  3921. * @param {?string} [output=null] - The output type.
  3922. * @return {string} The node type.
  3923. */
  3924. getNodeType( builder, output = null ) {
  3925. const op = this.op;
  3926. const aNode = this.aNode;
  3927. const bNode = this.bNode;
  3928. const typeA = aNode.getNodeType( builder );
  3929. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  3930. if ( typeA === 'void' || typeB === 'void' ) {
  3931. return output || 'void';
  3932. } else if ( op === '%' ) {
  3933. return typeA;
  3934. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3935. return builder.getIntegerType( typeA );
  3936. } else if ( op === '!' || op === '&&' || op === '||' || op === '^^' ) {
  3937. return 'bool';
  3938. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3939. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3940. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3941. } else {
  3942. // Handle matrix operations
  3943. if ( builder.isMatrix( typeA ) ) {
  3944. if ( typeB === 'float' ) {
  3945. return typeA; // matrix * scalar = matrix
  3946. } else if ( builder.isVector( typeB ) ) {
  3947. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3948. } else if ( builder.isMatrix( typeB ) ) {
  3949. return typeA; // matrix * matrix
  3950. }
  3951. } else if ( builder.isMatrix( typeB ) ) {
  3952. if ( typeA === 'float' ) {
  3953. return typeB; // scalar * matrix = matrix
  3954. } else if ( builder.isVector( typeA ) ) {
  3955. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3956. }
  3957. }
  3958. // Handle non-matrix cases
  3959. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3960. // anytype x anytype: use the greater length vector
  3961. return typeB;
  3962. }
  3963. return typeA;
  3964. }
  3965. }
  3966. generate( builder, output ) {
  3967. const op = this.op;
  3968. const { aNode, bNode } = this;
  3969. const type = this.getNodeType( builder, output );
  3970. let typeA = null;
  3971. let typeB = null;
  3972. if ( type !== 'void' ) {
  3973. typeA = aNode.getNodeType( builder );
  3974. typeB = bNode ? bNode.getNodeType( builder ) : null;
  3975. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  3976. if ( builder.isVector( typeA ) ) {
  3977. typeB = typeA;
  3978. } else if ( builder.isVector( typeB ) ) {
  3979. typeA = typeB;
  3980. } else if ( typeA !== typeB ) {
  3981. typeA = typeB = 'float';
  3982. }
  3983. } else if ( op === '>>' || op === '<<' ) {
  3984. typeA = type;
  3985. typeB = builder.changeComponentType( typeB, 'uint' );
  3986. } else if ( op === '%' ) {
  3987. typeA = type;
  3988. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  3989. } else if ( builder.isMatrix( typeA ) ) {
  3990. if ( typeB === 'float' ) {
  3991. // Keep matrix type for typeA, but ensure typeB stays float
  3992. typeB = 'float';
  3993. } else if ( builder.isVector( typeB ) ) {
  3994. // matrix x vector
  3995. typeB = builder.getVectorFromMatrix( typeA );
  3996. } else if ( builder.isMatrix( typeB ) ) ; else {
  3997. typeA = typeB = type;
  3998. }
  3999. } else if ( builder.isMatrix( typeB ) ) {
  4000. if ( typeA === 'float' ) {
  4001. // Keep matrix type for typeB, but ensure typeA stays float
  4002. typeA = 'float';
  4003. } else if ( builder.isVector( typeA ) ) {
  4004. // vector x matrix
  4005. typeA = builder.getVectorFromMatrix( typeB );
  4006. } else {
  4007. typeA = typeB = type;
  4008. }
  4009. } else {
  4010. // anytype x anytype
  4011. typeA = typeB = type;
  4012. }
  4013. } else {
  4014. typeA = typeB = type;
  4015. }
  4016. const a = aNode.build( builder, typeA );
  4017. const b = bNode ? bNode.build( builder, typeB ) : null;
  4018. const fnOpSnippet = builder.getFunctionOperator( op );
  4019. if ( output !== 'void' ) {
  4020. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  4021. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  4022. if ( isGLSL ) {
  4023. if ( builder.isVector( typeA ) ) {
  4024. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  4025. } else {
  4026. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  4027. }
  4028. } else {
  4029. // WGSL
  4030. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  4031. }
  4032. } else if ( op === '%' ) {
  4033. if ( builder.isInteger( typeB ) ) {
  4034. return builder.format( `( ${ a } % ${ b } )`, type, output );
  4035. } else {
  4036. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  4037. }
  4038. } else if ( op === '!' || op === '~' ) {
  4039. return builder.format( `(${op}${a})`, typeA, output );
  4040. } else if ( fnOpSnippet ) {
  4041. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4042. } else {
  4043. // Handle matrix operations
  4044. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4045. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  4046. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  4047. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4048. } else {
  4049. let snippet = `( ${ a } ${ op } ${ b } )`;
  4050. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  4051. snippet = `all${ snippet }`;
  4052. }
  4053. return builder.format( snippet, type, output );
  4054. }
  4055. }
  4056. } else if ( typeA !== 'void' ) {
  4057. if ( fnOpSnippet ) {
  4058. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4059. } else {
  4060. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4061. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  4062. } else {
  4063. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4064. }
  4065. }
  4066. }
  4067. }
  4068. serialize( data ) {
  4069. super.serialize( data );
  4070. data.op = this.op;
  4071. }
  4072. deserialize( data ) {
  4073. super.deserialize( data );
  4074. this.op = data.op;
  4075. }
  4076. }
  4077. /**
  4078. * Returns the addition of two or more value.
  4079. *
  4080. * @tsl
  4081. * @function
  4082. * @param {Node} a - The first input.
  4083. * @param {Node} b - The second input.
  4084. * @param {...Node} params - Additional input parameters.
  4085. * @returns {OperatorNode}
  4086. */
  4087. const add = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  4088. /**
  4089. * Returns the subtraction of two or more value.
  4090. *
  4091. * @tsl
  4092. * @function
  4093. * @param {Node} a - The first input.
  4094. * @param {Node} b - The second input.
  4095. * @param {...Node} params - Additional input parameters.
  4096. * @returns {OperatorNode}
  4097. */
  4098. const sub = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  4099. /**
  4100. * Returns the multiplication of two or more value.
  4101. *
  4102. * @tsl
  4103. * @function
  4104. * @param {Node} a - The first input.
  4105. * @param {Node} b - The second input.
  4106. * @param {...Node} params - Additional input parameters.
  4107. * @returns {OperatorNode}
  4108. */
  4109. const mul = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  4110. /**
  4111. * Returns the division of two or more value.
  4112. *
  4113. * @tsl
  4114. * @function
  4115. * @param {Node} a - The first input.
  4116. * @param {Node} b - The second input.
  4117. * @param {...Node} params - Additional input parameters.
  4118. * @returns {OperatorNode}
  4119. */
  4120. const div = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  4121. /**
  4122. * Computes the remainder of dividing the first node by the second one.
  4123. *
  4124. * @tsl
  4125. * @function
  4126. * @param {Node} a - The first input.
  4127. * @param {Node} b - The second input.
  4128. * @returns {OperatorNode}
  4129. */
  4130. const mod = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  4131. /**
  4132. * Checks if two nodes are equal.
  4133. *
  4134. * @tsl
  4135. * @function
  4136. * @param {Node} a - The first input.
  4137. * @param {Node} b - The second input.
  4138. * @returns {OperatorNode}
  4139. */
  4140. const equal = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  4141. /**
  4142. * Checks if two nodes are not equal.
  4143. *
  4144. * @tsl
  4145. * @function
  4146. * @param {Node} a - The first input.
  4147. * @param {Node} b - The second input.
  4148. * @returns {OperatorNode}
  4149. */
  4150. const notEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  4151. /**
  4152. * Checks if the first node is less than the second.
  4153. *
  4154. * @tsl
  4155. * @function
  4156. * @param {Node} a - The first input.
  4157. * @param {Node} b - The second input.
  4158. * @returns {OperatorNode}
  4159. */
  4160. const lessThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  4161. /**
  4162. * Checks if the first node is greater than the second.
  4163. *
  4164. * @tsl
  4165. * @function
  4166. * @param {Node} a - The first input.
  4167. * @param {Node} b - The second input.
  4168. * @returns {OperatorNode}
  4169. */
  4170. const greaterThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  4171. /**
  4172. * Checks if the first node is less than or equal to the second.
  4173. *
  4174. * @tsl
  4175. * @function
  4176. * @param {Node} a - The first input.
  4177. * @param {Node} b - The second input.
  4178. * @returns {OperatorNode}
  4179. */
  4180. const lessThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  4181. /**
  4182. * Checks if the first node is greater than or equal to the second.
  4183. *
  4184. * @tsl
  4185. * @function
  4186. * @param {Node} a - The first input.
  4187. * @param {Node} b - The second input.
  4188. * @returns {OperatorNode}
  4189. */
  4190. const greaterThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  4191. /**
  4192. * Performs a logical AND operation on multiple nodes.
  4193. *
  4194. * @tsl
  4195. * @function
  4196. * @param {...Node} nodes - The input nodes to be combined using AND.
  4197. * @returns {OperatorNode}
  4198. */
  4199. const and = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  4200. /**
  4201. * Performs a logical OR operation on multiple nodes.
  4202. *
  4203. * @tsl
  4204. * @function
  4205. * @param {...Node} nodes - The input nodes to be combined using OR.
  4206. * @returns {OperatorNode}
  4207. */
  4208. const or = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  4209. /**
  4210. * Performs logical NOT on a node.
  4211. *
  4212. * @tsl
  4213. * @function
  4214. * @param {Node} value - The value.
  4215. * @returns {OperatorNode}
  4216. */
  4217. const not = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  4218. /**
  4219. * Performs logical XOR on two nodes.
  4220. *
  4221. * @tsl
  4222. * @function
  4223. * @param {Node} a - The first input.
  4224. * @param {Node} b - The second input.
  4225. * @returns {OperatorNode}
  4226. */
  4227. const xor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  4228. /**
  4229. * Performs bitwise AND on two nodes.
  4230. *
  4231. * @tsl
  4232. * @function
  4233. * @param {Node} a - The first input.
  4234. * @param {Node} b - The second input.
  4235. * @returns {OperatorNode}
  4236. */
  4237. const bitAnd = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  4238. /**
  4239. * Performs bitwise NOT on a node.
  4240. *
  4241. * @tsl
  4242. * @function
  4243. * @param {Node} a - The first input.
  4244. * @param {Node} b - The second input.
  4245. * @returns {OperatorNode}
  4246. */
  4247. const bitNot = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '~' ).setParameterLength( 1 ).setName( 'bitNot' );
  4248. /**
  4249. * Performs bitwise OR on two nodes.
  4250. *
  4251. * @tsl
  4252. * @function
  4253. * @param {Node} a - The first input.
  4254. * @param {Node} b - The second input.
  4255. * @returns {OperatorNode}
  4256. */
  4257. const bitOr = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  4258. /**
  4259. * Performs bitwise XOR on two nodes.
  4260. *
  4261. * @tsl
  4262. * @function
  4263. * @param {Node} a - The first input.
  4264. * @param {Node} b - The second input.
  4265. * @returns {OperatorNode}
  4266. */
  4267. const bitXor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  4268. /**
  4269. * Shifts a node to the left.
  4270. *
  4271. * @tsl
  4272. * @function
  4273. * @param {Node} a - The node to shift.
  4274. * @param {Node} b - The value to shift.
  4275. * @returns {OperatorNode}
  4276. */
  4277. const shiftLeft = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  4278. /**
  4279. * Shifts a node to the right.
  4280. *
  4281. * @tsl
  4282. * @function
  4283. * @param {Node} a - The node to shift.
  4284. * @param {Node} b - The value to shift.
  4285. * @returns {OperatorNode}
  4286. */
  4287. const shiftRight = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  4288. /**
  4289. * Increments a node by 1.
  4290. *
  4291. * @tsl
  4292. * @function
  4293. * @param {Node} a - The node to increment.
  4294. * @returns {OperatorNode}
  4295. */
  4296. const incrementBefore = Fn( ( [ a ] ) => {
  4297. a.addAssign( 1 );
  4298. return a;
  4299. } );
  4300. /**
  4301. * Decrements a node by 1.
  4302. *
  4303. * @tsl
  4304. * @function
  4305. * @param {Node} a - The node to decrement.
  4306. * @returns {OperatorNode}
  4307. */
  4308. const decrementBefore = Fn( ( [ a ] ) => {
  4309. a.subAssign( 1 );
  4310. return a;
  4311. } );
  4312. /**
  4313. * Increments a node by 1 and returns the previous value.
  4314. *
  4315. * @tsl
  4316. * @function
  4317. * @param {Node} a - The node to increment.
  4318. * @returns {OperatorNode}
  4319. */
  4320. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4321. const temp = int( a ).toConst();
  4322. a.addAssign( 1 );
  4323. return temp;
  4324. } );
  4325. /**
  4326. * Decrements a node by 1 and returns the previous value.
  4327. *
  4328. * @tsl
  4329. * @function
  4330. * @param {Node} a - The node to decrement.
  4331. * @returns {OperatorNode}
  4332. */
  4333. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4334. const temp = int( a ).toConst();
  4335. a.subAssign( 1 );
  4336. return temp;
  4337. } );
  4338. addMethodChaining( 'add', add );
  4339. addMethodChaining( 'sub', sub );
  4340. addMethodChaining( 'mul', mul );
  4341. addMethodChaining( 'div', div );
  4342. addMethodChaining( 'mod', mod );
  4343. addMethodChaining( 'equal', equal );
  4344. addMethodChaining( 'notEqual', notEqual );
  4345. addMethodChaining( 'lessThan', lessThan );
  4346. addMethodChaining( 'greaterThan', greaterThan );
  4347. addMethodChaining( 'lessThanEqual', lessThanEqual );
  4348. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  4349. addMethodChaining( 'and', and );
  4350. addMethodChaining( 'or', or );
  4351. addMethodChaining( 'not', not );
  4352. addMethodChaining( 'xor', xor );
  4353. addMethodChaining( 'bitAnd', bitAnd );
  4354. addMethodChaining( 'bitNot', bitNot );
  4355. addMethodChaining( 'bitOr', bitOr );
  4356. addMethodChaining( 'bitXor', bitXor );
  4357. addMethodChaining( 'shiftLeft', shiftLeft );
  4358. addMethodChaining( 'shiftRight', shiftRight );
  4359. addMethodChaining( 'incrementBefore', incrementBefore );
  4360. addMethodChaining( 'decrementBefore', decrementBefore );
  4361. addMethodChaining( 'increment', increment );
  4362. addMethodChaining( 'decrement', decrement );
  4363. /**
  4364. * @tsl
  4365. * @function
  4366. * @deprecated since r175. Use {@link mod} instead.
  4367. *
  4368. * @param {Node} a - The first input.
  4369. * @param {Node} b - The second input.
  4370. * @returns {OperatorNode}
  4371. */
  4372. const modInt = ( a, b ) => { // @deprecated, r175
  4373. warn( 'TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.' );
  4374. return mod( int( a ), int( b ) );
  4375. };
  4376. addMethodChaining( 'modInt', modInt );
  4377. /**
  4378. * This node represents a variety of mathematical methods available in shaders.
  4379. * They are divided into three categories:
  4380. *
  4381. * - Methods with one input like `sin`, `cos` or `normalize`.
  4382. * - Methods with two inputs like `dot`, `cross` or `pow`.
  4383. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  4384. *
  4385. * @augments TempNode
  4386. */
  4387. class MathNode extends TempNode {
  4388. static get type() {
  4389. return 'MathNode';
  4390. }
  4391. /**
  4392. * Constructs a new math node.
  4393. *
  4394. * @param {string} method - The method name.
  4395. * @param {Node} aNode - The first input.
  4396. * @param {?Node} [bNode=null] - The second input.
  4397. * @param {?Node} [cNode=null] - The third input.
  4398. */
  4399. constructor( method, aNode, bNode = null, cNode = null ) {
  4400. super();
  4401. // Allow the max() and min() functions to take an arbitrary number of arguments.
  4402. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  4403. let finalOp = new MathNode( method, aNode, bNode );
  4404. for ( let i = 2; i < arguments.length - 1; i ++ ) {
  4405. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4406. }
  4407. aNode = finalOp;
  4408. bNode = arguments[ arguments.length - 1 ];
  4409. cNode = null;
  4410. }
  4411. /**
  4412. * The method name.
  4413. *
  4414. * @type {string}
  4415. */
  4416. this.method = method;
  4417. /**
  4418. * The first input.
  4419. *
  4420. * @type {Node}
  4421. */
  4422. this.aNode = aNode;
  4423. /**
  4424. * The second input.
  4425. *
  4426. * @type {?Node}
  4427. * @default null
  4428. */
  4429. this.bNode = bNode;
  4430. /**
  4431. * The third input.
  4432. *
  4433. * @type {?Node}
  4434. * @default null
  4435. */
  4436. this.cNode = cNode;
  4437. /**
  4438. * This flag can be used for type testing.
  4439. *
  4440. * @type {boolean}
  4441. * @readonly
  4442. * @default true
  4443. */
  4444. this.isMathNode = true;
  4445. }
  4446. /**
  4447. * The input type is inferred from the node types of the input nodes.
  4448. *
  4449. * @param {NodeBuilder} builder - The current node builder.
  4450. * @return {string} The input type.
  4451. */
  4452. getInputType( builder ) {
  4453. const aType = this.aNode.getNodeType( builder );
  4454. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4455. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4456. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4457. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4458. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4459. if ( aLen > bLen && aLen > cLen ) {
  4460. return aType;
  4461. } else if ( bLen > cLen ) {
  4462. return bType;
  4463. } else if ( cLen > aLen ) {
  4464. return cType;
  4465. }
  4466. return aType;
  4467. }
  4468. /**
  4469. * The selected method as well as the input type determine the node type of this node.
  4470. *
  4471. * @param {NodeBuilder} builder - The current node builder.
  4472. * @return {string} The node type.
  4473. */
  4474. getNodeType( builder ) {
  4475. const method = this.method;
  4476. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4477. return 'float';
  4478. } else if ( method === MathNode.CROSS ) {
  4479. return 'vec3';
  4480. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4481. return 'bool';
  4482. } else if ( method === MathNode.EQUALS ) {
  4483. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4484. } else {
  4485. return this.getInputType( builder );
  4486. }
  4487. }
  4488. setup( builder ) {
  4489. const { aNode, bNode, method } = this;
  4490. let outputNode = null;
  4491. if ( method === MathNode.ONE_MINUS ) {
  4492. outputNode = sub( 1.0, aNode );
  4493. } else if ( method === MathNode.RECIPROCAL ) {
  4494. outputNode = div( 1.0, aNode );
  4495. } else if ( method === MathNode.DIFFERENCE ) {
  4496. outputNode = abs( sub( aNode, bNode ) );
  4497. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4498. // dir can be either a direction vector or a normal vector
  4499. // upper-left 3x3 of matrix is assumed to be orthogonal
  4500. let tA = aNode;
  4501. let tB = bNode;
  4502. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4503. tB = vec4( vec3( tB ), 0.0 );
  4504. } else {
  4505. tA = vec4( vec3( tA ), 0.0 );
  4506. }
  4507. const mulNode = mul( tA, tB ).xyz;
  4508. outputNode = normalize( mulNode );
  4509. }
  4510. if ( outputNode !== null ) {
  4511. return outputNode;
  4512. } else {
  4513. return super.setup( builder );
  4514. }
  4515. }
  4516. generate( builder, output ) {
  4517. const properties = builder.getNodeProperties( this );
  4518. if ( properties.outputNode ) {
  4519. return super.generate( builder, output );
  4520. }
  4521. let method = this.method;
  4522. const type = this.getNodeType( builder );
  4523. const inputType = this.getInputType( builder );
  4524. const a = this.aNode;
  4525. const b = this.bNode;
  4526. const c = this.cNode;
  4527. const coordinateSystem = builder.renderer.coordinateSystem;
  4528. if ( method === MathNode.NEGATE ) {
  4529. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4530. } else {
  4531. const params = [];
  4532. if ( method === MathNode.CROSS ) {
  4533. params.push(
  4534. a.build( builder, type ),
  4535. b.build( builder, type )
  4536. );
  4537. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4538. params.push(
  4539. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4540. b.build( builder, inputType )
  4541. );
  4542. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4543. params.push(
  4544. a.build( builder, inputType ),
  4545. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4546. );
  4547. } else if ( method === MathNode.REFRACT ) {
  4548. params.push(
  4549. a.build( builder, inputType ),
  4550. b.build( builder, inputType ),
  4551. c.build( builder, 'float' )
  4552. );
  4553. } else if ( method === MathNode.MIX ) {
  4554. params.push(
  4555. a.build( builder, inputType ),
  4556. b.build( builder, inputType ),
  4557. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4558. );
  4559. } else {
  4560. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4561. method = 'atan2';
  4562. }
  4563. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4564. warn( `TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.` );
  4565. method = '/*' + method + '*/';
  4566. }
  4567. params.push( a.build( builder, inputType ) );
  4568. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4569. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4570. }
  4571. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4572. }
  4573. }
  4574. serialize( data ) {
  4575. super.serialize( data );
  4576. data.method = this.method;
  4577. }
  4578. deserialize( data ) {
  4579. super.deserialize( data );
  4580. this.method = data.method;
  4581. }
  4582. }
  4583. // 1 input
  4584. MathNode.ALL = 'all';
  4585. MathNode.ANY = 'any';
  4586. MathNode.RADIANS = 'radians';
  4587. MathNode.DEGREES = 'degrees';
  4588. MathNode.EXP = 'exp';
  4589. MathNode.EXP2 = 'exp2';
  4590. MathNode.LOG = 'log';
  4591. MathNode.LOG2 = 'log2';
  4592. MathNode.SQRT = 'sqrt';
  4593. MathNode.INVERSE_SQRT = 'inversesqrt';
  4594. MathNode.FLOOR = 'floor';
  4595. MathNode.CEIL = 'ceil';
  4596. MathNode.NORMALIZE = 'normalize';
  4597. MathNode.FRACT = 'fract';
  4598. MathNode.SIN = 'sin';
  4599. MathNode.COS = 'cos';
  4600. MathNode.TAN = 'tan';
  4601. MathNode.ASIN = 'asin';
  4602. MathNode.ACOS = 'acos';
  4603. MathNode.ATAN = 'atan';
  4604. MathNode.ABS = 'abs';
  4605. MathNode.SIGN = 'sign';
  4606. MathNode.LENGTH = 'length';
  4607. MathNode.NEGATE = 'negate';
  4608. MathNode.ONE_MINUS = 'oneMinus';
  4609. MathNode.DFDX = 'dFdx';
  4610. MathNode.DFDY = 'dFdy';
  4611. MathNode.ROUND = 'round';
  4612. MathNode.RECIPROCAL = 'reciprocal';
  4613. MathNode.TRUNC = 'trunc';
  4614. MathNode.FWIDTH = 'fwidth';
  4615. MathNode.TRANSPOSE = 'transpose';
  4616. MathNode.DETERMINANT = 'determinant';
  4617. MathNode.INVERSE = 'inverse';
  4618. // 2 inputs
  4619. MathNode.EQUALS = 'equals';
  4620. MathNode.MIN = 'min';
  4621. MathNode.MAX = 'max';
  4622. MathNode.STEP = 'step';
  4623. MathNode.REFLECT = 'reflect';
  4624. MathNode.DISTANCE = 'distance';
  4625. MathNode.DIFFERENCE = 'difference';
  4626. MathNode.DOT = 'dot';
  4627. MathNode.CROSS = 'cross';
  4628. MathNode.POW = 'pow';
  4629. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4630. // 3 inputs
  4631. MathNode.MIX = 'mix';
  4632. MathNode.CLAMP = 'clamp';
  4633. MathNode.REFRACT = 'refract';
  4634. MathNode.SMOOTHSTEP = 'smoothstep';
  4635. MathNode.FACEFORWARD = 'faceforward';
  4636. // 1 inputs
  4637. /**
  4638. * A small value used to handle floating-point precision errors.
  4639. *
  4640. * @tsl
  4641. * @type {Node<float>}
  4642. */
  4643. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4644. /**
  4645. * Represents infinity.
  4646. *
  4647. * @tsl
  4648. * @type {Node<float>}
  4649. */
  4650. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4651. /**
  4652. * Represents PI.
  4653. *
  4654. * @tsl
  4655. * @type {Node<float>}
  4656. */
  4657. const PI = /*@__PURE__*/ float( Math.PI );
  4658. /**
  4659. * Represents PI * 2. Please use the non-deprecated version `TWO_PI`.
  4660. *
  4661. * @tsl
  4662. * @deprecated
  4663. * @type {Node<float>}
  4664. */
  4665. const PI2 = /*@__PURE__*/ float( Math.PI * 2 ); // @deprecated r181
  4666. /**
  4667. * Represents PI * 2.
  4668. *
  4669. * @tsl
  4670. * @type {Node<float>}
  4671. */
  4672. const TWO_PI = /*@__PURE__*/ float( Math.PI * 2 );
  4673. /**
  4674. * Represents PI / 2.
  4675. *
  4676. * @tsl
  4677. * @type {Node<float>}
  4678. */
  4679. const HALF_PI = /*@__PURE__*/ float( Math.PI * 0.5 );
  4680. /**
  4681. * Returns `true` if all components of `x` are `true`.
  4682. *
  4683. * @tsl
  4684. * @function
  4685. * @param {Node | number} x - The parameter.
  4686. * @returns {Node<bool>}
  4687. */
  4688. const all = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4689. /**
  4690. * Returns `true` if any components of `x` are `true`.
  4691. *
  4692. * @tsl
  4693. * @function
  4694. * @param {Node | number} x - The parameter.
  4695. * @returns {Node<bool>}
  4696. */
  4697. const any = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4698. /**
  4699. * Converts a quantity in degrees to radians.
  4700. *
  4701. * @tsl
  4702. * @function
  4703. * @param {Node | number} x - The input in degrees.
  4704. * @returns {Node}
  4705. */
  4706. const radians = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4707. /**
  4708. * Convert a quantity in radians to degrees.
  4709. *
  4710. * @tsl
  4711. * @function
  4712. * @param {Node | number} x - The input in radians.
  4713. * @returns {Node}
  4714. */
  4715. const degrees = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4716. /**
  4717. * Returns the natural exponentiation of the parameter.
  4718. *
  4719. * @tsl
  4720. * @function
  4721. * @param {Node | number} x - The parameter.
  4722. * @returns {Node}
  4723. */
  4724. const exp = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP ).setParameterLength( 1 );
  4725. /**
  4726. * Returns 2 raised to the power of the parameter.
  4727. *
  4728. * @tsl
  4729. * @function
  4730. * @param {Node | number} x - The parameter.
  4731. * @returns {Node}
  4732. */
  4733. const exp2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  4734. /**
  4735. * Returns the natural logarithm of the parameter.
  4736. *
  4737. * @tsl
  4738. * @function
  4739. * @param {Node | number} x - The parameter.
  4740. * @returns {Node}
  4741. */
  4742. const log = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG ).setParameterLength( 1 );
  4743. /**
  4744. * Returns the base 2 logarithm of the parameter.
  4745. *
  4746. * @tsl
  4747. * @function
  4748. * @param {Node | number} x - The parameter.
  4749. * @returns {Node}
  4750. */
  4751. const log2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  4752. /**
  4753. * Returns the square root of the parameter.
  4754. *
  4755. * @tsl
  4756. * @function
  4757. * @param {Node | number} x - The parameter.
  4758. * @returns {Node}
  4759. */
  4760. const sqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  4761. /**
  4762. * Returns the inverse of the square root of the parameter.
  4763. *
  4764. * @tsl
  4765. * @function
  4766. * @param {Node | number} x - The parameter.
  4767. * @returns {Node}
  4768. */
  4769. const inverseSqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  4770. /**
  4771. * Finds the nearest integer less than or equal to the parameter.
  4772. *
  4773. * @tsl
  4774. * @function
  4775. * @param {Node | number} x - The parameter.
  4776. * @returns {Node}
  4777. */
  4778. const floor = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  4779. /**
  4780. * Finds the nearest integer that is greater than or equal to the parameter.
  4781. *
  4782. * @tsl
  4783. * @function
  4784. * @param {Node | number} x - The parameter.
  4785. * @returns {Node}
  4786. */
  4787. const ceil = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  4788. /**
  4789. * Calculates the unit vector in the same direction as the original vector.
  4790. *
  4791. * @tsl
  4792. * @function
  4793. * @param {Node} x - The input vector.
  4794. * @returns {Node}
  4795. */
  4796. const normalize = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  4797. /**
  4798. * Computes the fractional part of the parameter.
  4799. *
  4800. * @tsl
  4801. * @function
  4802. * @param {Node | number} x - The parameter.
  4803. * @returns {Node}
  4804. */
  4805. const fract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  4806. /**
  4807. * Returns the sine of the parameter.
  4808. *
  4809. * @tsl
  4810. * @function
  4811. * @param {Node | number} x - The parameter.
  4812. * @returns {Node}
  4813. */
  4814. const sin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIN ).setParameterLength( 1 );
  4815. /**
  4816. * Returns the cosine of the parameter.
  4817. *
  4818. * @tsl
  4819. * @function
  4820. * @param {Node | number} x - The parameter.
  4821. * @returns {Node}
  4822. */
  4823. const cos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COS ).setParameterLength( 1 );
  4824. /**
  4825. * Returns the tangent of the parameter.
  4826. *
  4827. * @tsl
  4828. * @function
  4829. * @param {Node | number} x - The parameter.
  4830. * @returns {Node}
  4831. */
  4832. const tan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TAN ).setParameterLength( 1 );
  4833. /**
  4834. * Returns the arcsine of the parameter.
  4835. *
  4836. * @tsl
  4837. * @function
  4838. * @param {Node | number} x - The parameter.
  4839. * @returns {Node}
  4840. */
  4841. const asin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  4842. /**
  4843. * Returns the arccosine of the parameter.
  4844. *
  4845. * @tsl
  4846. * @function
  4847. * @param {Node | number} x - The parameter.
  4848. * @returns {Node}
  4849. */
  4850. const acos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  4851. /**
  4852. * Returns the arc-tangent of the parameter.
  4853. * If two parameters are provided, the result is `atan2(y/x)`.
  4854. *
  4855. * @tsl
  4856. * @function
  4857. * @param {Node | number} y - The y parameter.
  4858. * @param {?(Node | number)} x - The x parameter.
  4859. * @returns {Node}
  4860. */
  4861. const atan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  4862. /**
  4863. * Returns the absolute value of the parameter.
  4864. *
  4865. * @tsl
  4866. * @function
  4867. * @param {Node | number} x - The parameter.
  4868. * @returns {Node}
  4869. */
  4870. const abs = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ABS ).setParameterLength( 1 );
  4871. /**
  4872. * Extracts the sign of the parameter.
  4873. *
  4874. * @tsl
  4875. * @function
  4876. * @param {Node | number} x - The parameter.
  4877. * @returns {Node}
  4878. */
  4879. const sign = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  4880. /**
  4881. * Calculates the length of a vector.
  4882. *
  4883. * @tsl
  4884. * @function
  4885. * @param {Node} x - The parameter.
  4886. * @returns {Node<float>}
  4887. */
  4888. const length = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  4889. /**
  4890. * Negates the value of the parameter (-x).
  4891. *
  4892. * @tsl
  4893. * @function
  4894. * @param {Node | number} x - The parameter.
  4895. * @returns {Node}
  4896. */
  4897. const negate = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  4898. /**
  4899. * Return `1` minus the parameter.
  4900. *
  4901. * @tsl
  4902. * @function
  4903. * @param {Node | number} x - The parameter.
  4904. * @returns {Node}
  4905. */
  4906. const oneMinus = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  4907. /**
  4908. * Returns the partial derivative of the parameter with respect to x.
  4909. *
  4910. * @tsl
  4911. * @function
  4912. * @param {Node | number} x - The parameter.
  4913. * @returns {Node}
  4914. */
  4915. const dFdx = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  4916. /**
  4917. * Returns the partial derivative of the parameter with respect to y.
  4918. *
  4919. * @tsl
  4920. * @function
  4921. * @param {Node | number} x - The parameter.
  4922. * @returns {Node}
  4923. */
  4924. const dFdy = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  4925. /**
  4926. * Rounds the parameter to the nearest integer.
  4927. *
  4928. * @tsl
  4929. * @function
  4930. * @param {Node | number} x - The parameter.
  4931. * @returns {Node}
  4932. */
  4933. const round = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  4934. /**
  4935. * Returns the reciprocal of the parameter `(1/x)`.
  4936. *
  4937. * @tsl
  4938. * @function
  4939. * @param {Node | number} x - The parameter.
  4940. * @returns {Node}
  4941. */
  4942. const reciprocal = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  4943. /**
  4944. * Truncates the parameter, removing the fractional part.
  4945. *
  4946. * @tsl
  4947. * @function
  4948. * @param {Node | number} x - The parameter.
  4949. * @returns {Node}
  4950. */
  4951. const trunc = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  4952. /**
  4953. * Returns the sum of the absolute derivatives in x and y.
  4954. *
  4955. * @tsl
  4956. * @function
  4957. * @param {Node | number} x - The parameter.
  4958. * @returns {Node}
  4959. */
  4960. const fwidth = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  4961. /**
  4962. * Returns the transpose of a matrix.
  4963. *
  4964. * @tsl
  4965. * @function
  4966. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4967. * @returns {Node}
  4968. */
  4969. const transpose = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  4970. /**
  4971. * Returns the determinant of a matrix.
  4972. *
  4973. * @tsl
  4974. * @function
  4975. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4976. * @returns {Node<float>}
  4977. */
  4978. const determinant = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DETERMINANT ).setParameterLength( 1 );
  4979. /**
  4980. * Returns the inverse of a matrix.
  4981. *
  4982. * @tsl
  4983. * @function
  4984. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4985. * @returns {Node<mat2|mat3|mat4>}
  4986. */
  4987. const inverse = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE ).setParameterLength( 1 );
  4988. // 2 inputs
  4989. /**
  4990. * Returns `true` if `x` equals `y`.
  4991. *
  4992. * @tsl
  4993. * @function
  4994. * @param {Node | number} x - The first parameter.
  4995. * @param {Node | number} y - The second parameter.
  4996. * @deprecated since r175. Use {@link equal} instead.
  4997. * @returns {Node<bool>}
  4998. */
  4999. const equals = ( x, y ) => { // @deprecated, r172
  5000. warn( 'TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"' );
  5001. return equal( x, y );
  5002. };
  5003. /**
  5004. * Returns the least of the given values.
  5005. *
  5006. * @tsl
  5007. * @function
  5008. * @param {...(Node | number)} values - The values to compare.
  5009. * @returns {Node}
  5010. */
  5011. const min$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  5012. /**
  5013. * Returns the greatest of the given values.
  5014. *
  5015. * @tsl
  5016. * @function
  5017. * @param {...(Node | number)} values - The values to compare.
  5018. * @returns {Node}
  5019. */
  5020. const max$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  5021. /**
  5022. * Generate a step function by comparing two values.
  5023. *
  5024. * @tsl
  5025. * @function
  5026. * @param {Node | number} x - The y parameter.
  5027. * @param {Node | number} y - The x parameter.
  5028. * @returns {Node}
  5029. */
  5030. const step = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.STEP ).setParameterLength( 2 );
  5031. /**
  5032. * Calculates the reflection direction for an incident vector.
  5033. *
  5034. * @tsl
  5035. * @function
  5036. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5037. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5038. * @returns {Node<vec2|vec3|vec4>}
  5039. */
  5040. const reflect = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  5041. /**
  5042. * Calculates the distance between two points.
  5043. *
  5044. * @tsl
  5045. * @function
  5046. * @param {Node<vec2|vec3|vec4>} x - The first point.
  5047. * @param {Node<vec2|vec3|vec4>} y - The second point.
  5048. * @returns {Node<float>}
  5049. */
  5050. const distance = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  5051. /**
  5052. * Calculates the absolute difference between two values.
  5053. *
  5054. * @tsl
  5055. * @function
  5056. * @param {Node | number} x - The first parameter.
  5057. * @param {Node | number} y - The second parameter.
  5058. * @returns {Node}
  5059. */
  5060. const difference = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  5061. /**
  5062. * Calculates the dot product of two vectors.
  5063. *
  5064. * @tsl
  5065. * @function
  5066. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  5067. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  5068. * @returns {Node<float>}
  5069. */
  5070. const dot = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DOT ).setParameterLength( 2 );
  5071. /**
  5072. * Calculates the cross product of two vectors.
  5073. *
  5074. * @tsl
  5075. * @function
  5076. * @param {Node<vec2|vec3>} x - The first vector.
  5077. * @param {Node<vec2|vec3>} y - The second vector.
  5078. * @returns {Node<float|vec3>}
  5079. */
  5080. const cross = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  5081. /**
  5082. * Return the value of the first parameter raised to the power of the second one.
  5083. *
  5084. * @tsl
  5085. * @function
  5086. * @param {Node | number} x - The first parameter.
  5087. * @param {Node | number} y - The second parameter.
  5088. * @returns {Node}
  5089. */
  5090. const pow = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW ).setParameterLength( 2 );
  5091. /**
  5092. * Returns the square of the parameter.
  5093. *
  5094. * @tsl
  5095. * @function
  5096. * @param {Node | number} x - The first parameter.
  5097. * @returns {Node}
  5098. */
  5099. const pow2 = ( x ) => mul( x, x );
  5100. /**
  5101. * Returns the cube of the parameter.
  5102. *
  5103. * @tsl
  5104. * @function
  5105. * @param {Node | number} x - The first parameter.
  5106. * @returns {Node}
  5107. */
  5108. const pow3 = ( x ) => mul( x, x, x );
  5109. /**
  5110. * Returns the fourth power of the parameter.
  5111. *
  5112. * @tsl
  5113. * @function
  5114. * @param {Node | number} x - The first parameter.
  5115. * @returns {Node}
  5116. */
  5117. const pow4 = ( x ) => mul( x, x, x, x );
  5118. /**
  5119. * Transforms the direction of a vector by a matrix and then normalizes the result.
  5120. *
  5121. * @tsl
  5122. * @function
  5123. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  5124. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  5125. * @returns {Node}
  5126. */
  5127. const transformDirection = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  5128. /**
  5129. * Returns the cube root of a number.
  5130. *
  5131. * @tsl
  5132. * @function
  5133. * @param {Node | number} a - The first parameter.
  5134. * @returns {Node}
  5135. */
  5136. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  5137. /**
  5138. * Calculate the squared length of a vector.
  5139. *
  5140. * @tsl
  5141. * @function
  5142. * @param {Node<vec2|vec3|vec4>} a - The vector.
  5143. * @returns {Node<float>}
  5144. */
  5145. const lengthSq = ( a ) => dot( a, a );
  5146. /**
  5147. * Linearly interpolates between two values.
  5148. *
  5149. * @tsl
  5150. * @function
  5151. * @param {Node | number} a - The first parameter.
  5152. * @param {Node | number} b - The second parameter.
  5153. * @param {Node | number} t - The interpolation value.
  5154. * @returns {Node}
  5155. */
  5156. const mix = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIX ).setParameterLength( 3 );
  5157. /**
  5158. * Constrains a value to lie between two further values.
  5159. *
  5160. * @tsl
  5161. * @function
  5162. * @param {Node | number} value - The value to constrain.
  5163. * @param {Node | number} [low=0] - The lower bound.
  5164. * @param {Node | number} [high=1] - The upper bound.
  5165. * @returns {Node}
  5166. */
  5167. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  5168. /**
  5169. * Constrains a value between `0` and `1`.
  5170. *
  5171. * @tsl
  5172. * @function
  5173. * @param {Node | number} value - The value to constrain.
  5174. * @returns {Node}
  5175. */
  5176. const saturate = ( value ) => clamp( value );
  5177. /**
  5178. * Calculates the refraction direction for an incident vector.
  5179. *
  5180. * @tsl
  5181. * @function
  5182. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5183. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5184. * @param {Node<float>} eta - The ratio of indices of refraction.
  5185. * @returns {Node<vec2|vec3|vec4>}
  5186. */
  5187. const refract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  5188. /**
  5189. * Performs a Hermite interpolation between two values.
  5190. *
  5191. * @tsl
  5192. * @function
  5193. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5194. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5195. * @param {Node | number} x - The source value for interpolation.
  5196. * @returns {Node}
  5197. */
  5198. const smoothstep = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  5199. /**
  5200. * Returns a vector pointing in the same direction as another.
  5201. *
  5202. * @tsl
  5203. * @function
  5204. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  5205. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5206. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  5207. * @returns {Node<vec2|vec3|vec4>}
  5208. */
  5209. const faceForward = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  5210. /**
  5211. * Returns a random value for the given uv.
  5212. *
  5213. * @tsl
  5214. * @function
  5215. * @param {Node<vec2>} uv - The uv node.
  5216. * @returns {Node<float>}
  5217. */
  5218. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  5219. const a = 12.9898, b = 78.233, c = 43758.5453;
  5220. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  5221. return fract( sin( sn ).mul( c ) );
  5222. } );
  5223. /**
  5224. * Alias for `mix()` with a different parameter order.
  5225. *
  5226. * @tsl
  5227. * @function
  5228. * @param {Node | number} t - The interpolation value.
  5229. * @param {Node | number} e1 - The first parameter.
  5230. * @param {Node | number} e2 - The second parameter.
  5231. * @returns {Node}
  5232. */
  5233. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  5234. /**
  5235. * Alias for `smoothstep()` with a different parameter order.
  5236. *
  5237. * @tsl
  5238. * @function
  5239. * @param {Node | number} x - The source value for interpolation.
  5240. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5241. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5242. * @returns {Node}
  5243. */
  5244. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  5245. /**
  5246. * Alias for `step()` with a different parameter order.
  5247. *
  5248. * @tsl
  5249. * @function
  5250. * @param {Node | number} x - The source value for interpolation.
  5251. * @param {Node | number} edge - The edge value.
  5252. * @returns {Node}
  5253. */
  5254. const stepElement = ( x, edge ) => step( edge, x );
  5255. /**
  5256. * Returns the arc-tangent of the quotient of its parameters.
  5257. *
  5258. * @tsl
  5259. * @function
  5260. * @deprecated since r172. Use {@link atan} instead.
  5261. *
  5262. * @param {Node | number} y - The y parameter.
  5263. * @param {Node | number} x - The x parameter.
  5264. * @returns {Node}
  5265. */
  5266. const atan2 = ( y, x ) => { // @deprecated, r172
  5267. warn( 'TSL: "atan2" is overloaded. Use "atan" instead.' );
  5268. return atan( y, x );
  5269. };
  5270. // GLSL alias function
  5271. const faceforward = faceForward;
  5272. const inversesqrt = inverseSqrt;
  5273. // Method chaining
  5274. addMethodChaining( 'all', all );
  5275. addMethodChaining( 'any', any );
  5276. addMethodChaining( 'equals', equals );
  5277. addMethodChaining( 'radians', radians );
  5278. addMethodChaining( 'degrees', degrees );
  5279. addMethodChaining( 'exp', exp );
  5280. addMethodChaining( 'exp2', exp2 );
  5281. addMethodChaining( 'log', log );
  5282. addMethodChaining( 'log2', log2 );
  5283. addMethodChaining( 'sqrt', sqrt );
  5284. addMethodChaining( 'inverseSqrt', inverseSqrt );
  5285. addMethodChaining( 'floor', floor );
  5286. addMethodChaining( 'ceil', ceil );
  5287. addMethodChaining( 'normalize', normalize );
  5288. addMethodChaining( 'fract', fract );
  5289. addMethodChaining( 'sin', sin );
  5290. addMethodChaining( 'cos', cos );
  5291. addMethodChaining( 'tan', tan );
  5292. addMethodChaining( 'asin', asin );
  5293. addMethodChaining( 'acos', acos );
  5294. addMethodChaining( 'atan', atan );
  5295. addMethodChaining( 'abs', abs );
  5296. addMethodChaining( 'sign', sign );
  5297. addMethodChaining( 'length', length );
  5298. addMethodChaining( 'lengthSq', lengthSq );
  5299. addMethodChaining( 'negate', negate );
  5300. addMethodChaining( 'oneMinus', oneMinus );
  5301. addMethodChaining( 'dFdx', dFdx );
  5302. addMethodChaining( 'dFdy', dFdy );
  5303. addMethodChaining( 'round', round );
  5304. addMethodChaining( 'reciprocal', reciprocal );
  5305. addMethodChaining( 'trunc', trunc );
  5306. addMethodChaining( 'fwidth', fwidth );
  5307. addMethodChaining( 'atan2', atan2 );
  5308. addMethodChaining( 'min', min$1 );
  5309. addMethodChaining( 'max', max$1 );
  5310. addMethodChaining( 'step', stepElement );
  5311. addMethodChaining( 'reflect', reflect );
  5312. addMethodChaining( 'distance', distance );
  5313. addMethodChaining( 'dot', dot );
  5314. addMethodChaining( 'cross', cross );
  5315. addMethodChaining( 'pow', pow );
  5316. addMethodChaining( 'pow2', pow2 );
  5317. addMethodChaining( 'pow3', pow3 );
  5318. addMethodChaining( 'pow4', pow4 );
  5319. addMethodChaining( 'transformDirection', transformDirection );
  5320. addMethodChaining( 'mix', mixElement );
  5321. addMethodChaining( 'clamp', clamp );
  5322. addMethodChaining( 'refract', refract );
  5323. addMethodChaining( 'smoothstep', smoothstepElement );
  5324. addMethodChaining( 'faceForward', faceForward );
  5325. addMethodChaining( 'difference', difference );
  5326. addMethodChaining( 'saturate', saturate );
  5327. addMethodChaining( 'cbrt', cbrt );
  5328. addMethodChaining( 'transpose', transpose );
  5329. addMethodChaining( 'determinant', determinant );
  5330. addMethodChaining( 'inverse', inverse );
  5331. addMethodChaining( 'rand', rand );
  5332. /**
  5333. * Represents a logical `if/else` statement. Can be used as an alternative
  5334. * to the `If()`/`Else()` syntax.
  5335. *
  5336. * The corresponding TSL `select()` looks like so:
  5337. * ```js
  5338. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  5339. * ```
  5340. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  5341. * determine the outcome of the entire statement.
  5342. *
  5343. * @augments Node
  5344. */
  5345. class ConditionalNode extends Node {
  5346. static get type() {
  5347. return 'ConditionalNode';
  5348. }
  5349. /**
  5350. * Constructs a new conditional node.
  5351. *
  5352. * @param {Node} condNode - The node that defines the condition.
  5353. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5354. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5355. */
  5356. constructor( condNode, ifNode, elseNode = null ) {
  5357. super();
  5358. /**
  5359. * The node that defines the condition.
  5360. *
  5361. * @type {Node}
  5362. */
  5363. this.condNode = condNode;
  5364. /**
  5365. * The node that is evaluate when the condition ends up `true`.
  5366. *
  5367. * @type {Node}
  5368. */
  5369. this.ifNode = ifNode;
  5370. /**
  5371. * The node that is evaluate when the condition ends up `false`.
  5372. *
  5373. * @type {?Node}
  5374. * @default null
  5375. */
  5376. this.elseNode = elseNode;
  5377. }
  5378. /**
  5379. * This method is overwritten since the node type is inferred from the if/else
  5380. * nodes.
  5381. *
  5382. * @param {NodeBuilder} builder - The current node builder.
  5383. * @return {string} The node type.
  5384. */
  5385. getNodeType( builder ) {
  5386. const { ifNode, elseNode } = builder.getNodeProperties( this );
  5387. if ( ifNode === undefined ) {
  5388. // fallback setup
  5389. builder.flowBuildStage( this, 'setup' );
  5390. return this.getNodeType( builder );
  5391. }
  5392. const ifType = ifNode.getNodeType( builder );
  5393. if ( elseNode !== null ) {
  5394. const elseType = elseNode.getNodeType( builder );
  5395. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  5396. return elseType;
  5397. }
  5398. }
  5399. return ifType;
  5400. }
  5401. setup( builder ) {
  5402. const condNode = this.condNode;
  5403. const ifNode = this.ifNode.isolate();
  5404. const elseNode = this.elseNode ? this.elseNode.isolate() : null;
  5405. //
  5406. const currentNodeBlock = builder.context.nodeBlock;
  5407. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  5408. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  5409. //
  5410. const isUniformFlow = builder.context.uniformFlow;
  5411. const properties = builder.getNodeProperties( this );
  5412. properties.condNode = condNode;
  5413. properties.ifNode = isUniformFlow ? ifNode : ifNode.context( { nodeBlock: ifNode } );
  5414. properties.elseNode = elseNode ? ( isUniformFlow ? elseNode : elseNode.context( { nodeBlock: elseNode } ) ) : null;
  5415. }
  5416. generate( builder, output ) {
  5417. const type = this.getNodeType( builder );
  5418. const nodeData = builder.getDataFromNode( this );
  5419. if ( nodeData.nodeProperty !== undefined ) {
  5420. return nodeData.nodeProperty;
  5421. }
  5422. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  5423. const functionNode = builder.currentFunctionNode;
  5424. const needsOutput = output !== 'void';
  5425. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  5426. nodeData.nodeProperty = nodeProperty;
  5427. const nodeSnippet = condNode.build( builder, 'bool' );
  5428. const isUniformFlow = builder.context.uniformFlow;
  5429. if ( isUniformFlow && elseNode !== null ) {
  5430. const ifSnippet = ifNode.build( builder, type );
  5431. const elseSnippet = elseNode.build( builder, type );
  5432. const mathSnippet = builder.getTernary( nodeSnippet, ifSnippet, elseSnippet );
  5433. // TODO: If node property already exists return something else
  5434. return builder.format( mathSnippet, type, output );
  5435. }
  5436. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  5437. let ifSnippet = ifNode.build( builder, type );
  5438. if ( ifSnippet ) {
  5439. if ( needsOutput ) {
  5440. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  5441. } else {
  5442. ifSnippet = 'return ' + ifSnippet + ';';
  5443. if ( functionNode === null ) {
  5444. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5445. ifSnippet = '// ' + ifSnippet;
  5446. }
  5447. }
  5448. }
  5449. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  5450. if ( elseNode !== null ) {
  5451. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5452. let elseSnippet = elseNode.build( builder, type );
  5453. if ( elseSnippet ) {
  5454. if ( needsOutput ) {
  5455. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5456. } else {
  5457. elseSnippet = 'return ' + elseSnippet + ';';
  5458. if ( functionNode === null ) {
  5459. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5460. elseSnippet = '// ' + elseSnippet;
  5461. }
  5462. }
  5463. }
  5464. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5465. } else {
  5466. builder.addFlowCode( '\n\n' );
  5467. }
  5468. return builder.format( nodeProperty, type, output );
  5469. }
  5470. }
  5471. /**
  5472. * TSL function for creating a conditional node.
  5473. *
  5474. * @tsl
  5475. * @function
  5476. * @param {Node} condNode - The node that defines the condition.
  5477. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5478. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5479. * @returns {ConditionalNode}
  5480. */
  5481. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5482. addMethodChaining( 'select', select );
  5483. /**
  5484. * This node can be used as a context management component for another node.
  5485. * {@link NodeBuilder} performs its node building process in a specific context and
  5486. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5487. *
  5488. * ```js
  5489. *node.context( { getUV: () => customCoord } );
  5490. *\// or
  5491. *material.contextNode = context( { getUV: () => customCoord } );
  5492. *\// or
  5493. *renderer.contextNode = context( { getUV: () => customCoord } );
  5494. *\// or
  5495. *scenePass.contextNode = context( { getUV: () => customCoord } );
  5496. *```
  5497. * @augments Node
  5498. */
  5499. class ContextNode extends Node {
  5500. static get type() {
  5501. return 'ContextNode';
  5502. }
  5503. /**
  5504. * Constructs a new context node.
  5505. *
  5506. * @param {Node} node - The node whose context should be modified.
  5507. * @param {Object} [value={}] - The modified context data.
  5508. */
  5509. constructor( node = null, value = {} ) {
  5510. super();
  5511. /**
  5512. * This flag can be used for type testing.
  5513. *
  5514. * @type {boolean}
  5515. * @readonly
  5516. * @default true
  5517. */
  5518. this.isContextNode = true;
  5519. /**
  5520. * The node whose context should be modified.
  5521. *
  5522. * @type {Node}
  5523. */
  5524. this.node = node;
  5525. /**
  5526. * The modified context data.
  5527. *
  5528. * @type {Object}
  5529. * @default {}
  5530. */
  5531. this.value = value;
  5532. }
  5533. /**
  5534. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5535. *
  5536. * @return {Node} A reference to {@link ContextNode#node}.
  5537. */
  5538. getScope() {
  5539. return this.node.getScope();
  5540. }
  5541. /**
  5542. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5543. *
  5544. * @param {NodeBuilder} builder - The current node builder.
  5545. * @return {string} The node type.
  5546. */
  5547. getNodeType( builder ) {
  5548. return this.node.getNodeType( builder );
  5549. }
  5550. /**
  5551. * Gathers the context data from all parent context nodes.
  5552. *
  5553. * @return {Object} The gathered context data.
  5554. */
  5555. getFlowContextData() {
  5556. const children = [];
  5557. this.traverse( ( node ) => {
  5558. if ( node.isContextNode === true ) {
  5559. children.push( node.value );
  5560. }
  5561. } );
  5562. return Object.assign( {}, ...children );
  5563. }
  5564. /**
  5565. * This method is overwritten to ensure it returns the member type of {@link ContextNode#node}.
  5566. *
  5567. * @param {NodeBuilder} builder - The current node builder.
  5568. * @param {string} name - The member name.
  5569. * @returns {string} The member type.
  5570. */
  5571. getMemberType( builder, name ) {
  5572. return this.node.getMemberType( builder, name );
  5573. }
  5574. analyze( builder ) {
  5575. const previousContext = builder.addContext( this.value );
  5576. this.node.build( builder );
  5577. builder.setContext( previousContext );
  5578. }
  5579. setup( builder ) {
  5580. const previousContext = builder.addContext( this.value );
  5581. this.node.build( builder );
  5582. builder.setContext( previousContext );
  5583. }
  5584. generate( builder, output ) {
  5585. const previousContext = builder.addContext( this.value );
  5586. const snippet = this.node.build( builder, output );
  5587. builder.setContext( previousContext );
  5588. return snippet;
  5589. }
  5590. }
  5591. /**
  5592. * TSL function for creating a context node.
  5593. *
  5594. * @tsl
  5595. * @function
  5596. * @param {Node|Object} [nodeOrValue={}] - The node whose context should be modified or the modified context data.
  5597. * @param {Object} [value={}] - The modified context data.
  5598. * @returns {ContextNode}
  5599. */
  5600. const context = ( nodeOrValue = null, value = {} ) => {
  5601. let node = nodeOrValue;
  5602. if ( node === null || node.isNode !== true ) {
  5603. value = node || value;
  5604. node = null;
  5605. }
  5606. return new ContextNode( node, value );
  5607. };
  5608. /**
  5609. * TSL function for defining a uniformFlow context value for a given node.
  5610. *
  5611. * @tsl
  5612. * @function
  5613. * @param {Node} node - The node whose dependencies should all execute within a uniform control-flow path.
  5614. * @returns {ContextNode}
  5615. */
  5616. const uniformFlow = ( node ) => context( node, { uniformFlow: true } );
  5617. /**
  5618. * TSL function for defining a name for the context value for a given node.
  5619. *
  5620. * @tsl
  5621. * @function
  5622. * @param {Node} node - The node whose context should be modified.
  5623. * @param {string} name - The name to set.
  5624. * @returns {ContextNode}
  5625. */
  5626. const setName = ( node, name ) => context( node, { nodeName: name } );
  5627. /**
  5628. * TSL function for defining a built-in shadow context for a given node.
  5629. *
  5630. * @tsl
  5631. * @function
  5632. * @param {ShadowNode} shadowNode - The shadow node representing the light's shadow.
  5633. * @param {Light} light - The light associated with the shadow.
  5634. * @param {Node} [node=null] - The node whose context should be modified.
  5635. * @returns {ContextNode}
  5636. */
  5637. function builtinShadowContext( shadowNode, light, node = null ) {
  5638. return context( node, {
  5639. getShadow: ( { light: shadowLight, shadowColorNode } ) => {
  5640. if ( light === shadowLight ) {
  5641. return shadowColorNode.mul( shadowNode );
  5642. }
  5643. return shadowColorNode;
  5644. }
  5645. } );
  5646. }
  5647. /**
  5648. * TSL function for defining a built-in ambient occlusion context for a given node.
  5649. *
  5650. * @tsl
  5651. * @function
  5652. * @param {Node} aoNode - The ambient occlusion value node to apply.
  5653. * @param {Node} [node=null] - The node whose context should be modified.
  5654. * @returns {ContextNode}
  5655. */
  5656. function builtinAOContext( aoNode, node = null ) {
  5657. return context( node, {
  5658. getAO: ( inputNode, { material } ) => {
  5659. if ( material.transparent === true ) return inputNode;
  5660. return inputNode !== null ? inputNode.mul( aoNode ) : aoNode;
  5661. }
  5662. } );
  5663. }
  5664. /**
  5665. * TSL function for defining a label context value for a given node.
  5666. *
  5667. * @tsl
  5668. * @function
  5669. * @deprecated
  5670. * @param {Node} node - The node whose context should be modified.
  5671. * @param {string} name - The name/label to set.
  5672. * @returns {ContextNode}
  5673. */
  5674. function label( node, name ) {
  5675. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  5676. return setName( node, name );
  5677. }
  5678. addMethodChaining( 'context', context );
  5679. addMethodChaining( 'label', label );
  5680. addMethodChaining( 'uniformFlow', uniformFlow );
  5681. addMethodChaining( 'setName', setName );
  5682. addMethodChaining( 'builtinShadowContext', ( node, shadowNode, light ) => builtinShadowContext( shadowNode, light, node ) );
  5683. addMethodChaining( 'builtinAOContext', ( node, aoValue ) => builtinAOContext( aoValue, node ) );
  5684. /**
  5685. * Class for representing shader variables as nodes. Variables are created from
  5686. * existing nodes like the following:
  5687. *
  5688. * ```js
  5689. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5690. * ```
  5691. *
  5692. * @augments Node
  5693. */
  5694. class VarNode extends Node {
  5695. static get type() {
  5696. return 'VarNode';
  5697. }
  5698. /**
  5699. * Constructs a new variable node.
  5700. *
  5701. * @param {Node} node - The node for which a variable should be created.
  5702. * @param {?string} [name=null] - The name of the variable in the shader.
  5703. * @param {boolean} [readOnly=false] - The read-only flag.
  5704. */
  5705. constructor( node, name = null, readOnly = false ) {
  5706. super();
  5707. /**
  5708. * The node for which a variable should be created.
  5709. *
  5710. * @type {Node}
  5711. */
  5712. this.node = node;
  5713. /**
  5714. * The name of the variable in the shader. If no name is defined,
  5715. * the node system auto-generates one.
  5716. *
  5717. * @type {?string}
  5718. * @default null
  5719. */
  5720. this.name = name;
  5721. /**
  5722. * `VarNode` sets this property to `true` by default.
  5723. *
  5724. * @type {boolean}
  5725. * @default true
  5726. */
  5727. this.global = true;
  5728. /**
  5729. * This flag can be used for type testing.
  5730. *
  5731. * @type {boolean}
  5732. * @readonly
  5733. * @default true
  5734. */
  5735. this.isVarNode = true;
  5736. /**
  5737. *
  5738. * The read-only flag.
  5739. *
  5740. * @type {boolean}
  5741. * @default false
  5742. */
  5743. this.readOnly = readOnly;
  5744. /**
  5745. *
  5746. * Add this flag to the node system to indicate that this node require parents.
  5747. *
  5748. * @type {boolean}
  5749. * @default true
  5750. */
  5751. this.parents = true;
  5752. /**
  5753. * This flag is used to indicate that this node is used for intent.
  5754. *
  5755. * @type {boolean}
  5756. * @default false
  5757. */
  5758. this.intent = false;
  5759. }
  5760. /**
  5761. * Sets the intent flag for this node.
  5762. *
  5763. * This flag is used to indicate that this node is used for intent
  5764. * and should not be built directly. Instead, it is used to indicate that
  5765. * the node should be treated as a variable intent.
  5766. *
  5767. * It's useful for assigning variables without needing creating a new variable node.
  5768. *
  5769. * @param {boolean} value - The value to set for the intent flag.
  5770. * @returns {VarNode} This node.
  5771. */
  5772. setIntent( value ) {
  5773. this.intent = value;
  5774. return this;
  5775. }
  5776. /**
  5777. * Checks if this node is used for intent.
  5778. *
  5779. * @param {NodeBuilder} builder - The node builder.
  5780. * @returns {boolean} Whether this node is used for intent.
  5781. */
  5782. isIntent( builder ) {
  5783. const data = builder.getDataFromNode( this );
  5784. if ( data.forceDeclaration === true ) return false;
  5785. return this.intent;
  5786. }
  5787. /**
  5788. * Returns the intent flag of this node.
  5789. *
  5790. * @return {boolean} The intent flag.
  5791. */
  5792. getIntent() {
  5793. return this.intent;
  5794. }
  5795. getMemberType( builder, name ) {
  5796. return this.node.getMemberType( builder, name );
  5797. }
  5798. getElementType( builder ) {
  5799. return this.node.getElementType( builder );
  5800. }
  5801. getNodeType( builder ) {
  5802. return this.node.getNodeType( builder );
  5803. }
  5804. getArrayCount( builder ) {
  5805. return this.node.getArrayCount( builder );
  5806. }
  5807. isAssign( builder ) {
  5808. const data = builder.getDataFromNode( this );
  5809. return data.assign;
  5810. }
  5811. build( ...params ) {
  5812. const builder = params[ 0 ];
  5813. if ( this._hasStack( builder ) === false && builder.buildStage === 'setup' ) {
  5814. if ( builder.context.nodeLoop || builder.context.nodeBlock ) {
  5815. let addBefore = false;
  5816. if ( this.node.isShaderCallNodeInternal && this.node.shaderNode.getLayout() === null ) {
  5817. if ( builder.fnCall && builder.fnCall.shaderNode ) {
  5818. const shaderNodeData = builder.getDataFromNode( this.node.shaderNode );
  5819. if ( shaderNodeData.hasLoop ) {
  5820. const data = builder.getDataFromNode( this );
  5821. data.forceDeclaration = true;
  5822. addBefore = true;
  5823. }
  5824. }
  5825. }
  5826. const baseStack = builder.getBaseStack();
  5827. if ( addBefore ) {
  5828. baseStack.addToStackBefore( this );
  5829. } else {
  5830. baseStack.addToStack( this );
  5831. }
  5832. }
  5833. }
  5834. if ( this.isIntent( builder ) ) {
  5835. if ( this.isAssign( builder ) !== true ) {
  5836. return this.node.build( ...params );
  5837. }
  5838. }
  5839. return super.build( ...params );
  5840. }
  5841. generate( builder ) {
  5842. const { node, name, readOnly } = this;
  5843. const { renderer } = builder;
  5844. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5845. let isDeterministic = false;
  5846. let shouldTreatAsReadOnly = false;
  5847. if ( readOnly ) {
  5848. isDeterministic = builder.isDeterministic( node );
  5849. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5850. }
  5851. const nodeType = this.getNodeType( builder );
  5852. if ( nodeType == 'void' ) {
  5853. if ( this.isIntent( builder ) !== true ) {
  5854. error( 'TSL: ".toVar()" can not be used with void type.' );
  5855. }
  5856. const snippet = node.build( builder );
  5857. return snippet;
  5858. }
  5859. const vectorType = builder.getVectorType( nodeType );
  5860. const snippet = node.build( builder, vectorType );
  5861. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5862. const propertyName = builder.getPropertyName( nodeVar );
  5863. let declarationPrefix = propertyName;
  5864. if ( shouldTreatAsReadOnly ) {
  5865. if ( isWebGPUBackend ) {
  5866. declarationPrefix = isDeterministic
  5867. ? `const ${ propertyName }`
  5868. : `let ${ propertyName }`;
  5869. } else {
  5870. const count = node.getArrayCount( builder );
  5871. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5872. }
  5873. }
  5874. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5875. return propertyName;
  5876. }
  5877. _hasStack( builder ) {
  5878. const nodeData = builder.getDataFromNode( this );
  5879. return nodeData.stack !== undefined;
  5880. }
  5881. }
  5882. /**
  5883. * TSL function for creating a var node.
  5884. *
  5885. * @tsl
  5886. * @function
  5887. * @param {Node} node - The node for which a variable should be created.
  5888. * @param {?string} name - The name of the variable in the shader.
  5889. * @returns {VarNode}
  5890. */
  5891. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5892. /**
  5893. * TSL function for creating a var node.
  5894. *
  5895. * @tsl
  5896. * @function
  5897. * @param {Node} node - The node for which a variable should be created.
  5898. * @param {?string} name - The name of the variable in the shader.
  5899. * @returns {VarNode}
  5900. */
  5901. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5902. /**
  5903. * TSL function for creating a const node.
  5904. *
  5905. * @tsl
  5906. * @function
  5907. * @param {Node} node - The node for which a constant should be created.
  5908. * @param {?string} name - The name of the constant in the shader.
  5909. * @returns {VarNode}
  5910. */
  5911. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  5912. //
  5913. //
  5914. /**
  5915. * TSL function for creating a var intent node.
  5916. *
  5917. * @tsl
  5918. * @function
  5919. * @param {Node} node - The node for which a variable should be created.
  5920. * @param {?string} name - The name of the variable in the shader.
  5921. * @returns {VarNode}
  5922. */
  5923. const VarIntent = ( node ) => {
  5924. return createVar( node ).setIntent( true ).toStack();
  5925. };
  5926. // Method chaining
  5927. addMethodChaining( 'toVar', Var );
  5928. addMethodChaining( 'toConst', Const );
  5929. addMethodChaining( 'toVarIntent', VarIntent );
  5930. /**
  5931. * This node is used to build a sub-build in the node system.
  5932. *
  5933. * @augments Node
  5934. * @param {Node} node - The node to be built in the sub-build.
  5935. * @param {string} name - The name of the sub-build.
  5936. * @param {?string} [nodeType=null] - The type of the node, if known.
  5937. */
  5938. class SubBuildNode extends Node {
  5939. static get type() {
  5940. return 'SubBuild';
  5941. }
  5942. constructor( node, name, nodeType = null ) {
  5943. super( nodeType );
  5944. /**
  5945. * The node to be built in the sub-build.
  5946. *
  5947. * @type {Node}
  5948. */
  5949. this.node = node;
  5950. /**
  5951. * The name of the sub-build.
  5952. *
  5953. * @type {string}
  5954. */
  5955. this.name = name;
  5956. /**
  5957. * This flag can be used for type testing.
  5958. *
  5959. * @type {boolean}
  5960. * @readonly
  5961. * @default true
  5962. */
  5963. this.isSubBuildNode = true;
  5964. }
  5965. getNodeType( builder ) {
  5966. if ( this.nodeType !== null ) return this.nodeType;
  5967. builder.addSubBuild( this.name );
  5968. const nodeType = this.node.getNodeType( builder );
  5969. builder.removeSubBuild();
  5970. return nodeType;
  5971. }
  5972. build( builder, ...params ) {
  5973. builder.addSubBuild( this.name );
  5974. const data = this.node.build( builder, ...params );
  5975. builder.removeSubBuild();
  5976. return data;
  5977. }
  5978. }
  5979. /**
  5980. * Creates a new sub-build node.
  5981. *
  5982. * @tsl
  5983. * @function
  5984. * @param {Node} node - The node to be built in the sub-build.
  5985. * @param {string} name - The name of the sub-build.
  5986. * @param {?string} [type=null] - The type of the node, if known.
  5987. * @returns {Node} A node object wrapping the SubBuildNode instance.
  5988. */
  5989. const subBuild = ( node, name, type = null ) => nodeObject( new SubBuildNode( nodeObject( node ), name, type ) );
  5990. /**
  5991. * Class for representing shader varyings as nodes. Varyings are create from
  5992. * existing nodes like the following:
  5993. *
  5994. * ```js
  5995. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  5996. * ```
  5997. *
  5998. * @augments Node
  5999. */
  6000. class VaryingNode extends Node {
  6001. static get type() {
  6002. return 'VaryingNode';
  6003. }
  6004. /**
  6005. * Constructs a new varying node.
  6006. *
  6007. * @param {Node} node - The node for which a varying should be created.
  6008. * @param {?string} name - The name of the varying in the shader.
  6009. */
  6010. constructor( node, name = null ) {
  6011. super();
  6012. /**
  6013. * The node for which a varying should be created.
  6014. *
  6015. * @type {Node}
  6016. */
  6017. this.node = node;
  6018. /**
  6019. * The name of the varying in the shader. If no name is defined,
  6020. * the node system auto-generates one.
  6021. *
  6022. * @type {?string}
  6023. * @default null
  6024. */
  6025. this.name = name;
  6026. /**
  6027. * This flag can be used for type testing.
  6028. *
  6029. * @type {boolean}
  6030. * @readonly
  6031. * @default true
  6032. */
  6033. this.isVaryingNode = true;
  6034. /**
  6035. * The interpolation type of the varying data.
  6036. *
  6037. * @type {?string}
  6038. * @default null
  6039. */
  6040. this.interpolationType = null;
  6041. /**
  6042. * The interpolation sampling type of varying data.
  6043. *
  6044. * @type {?string}
  6045. * @default null
  6046. */
  6047. this.interpolationSampling = null;
  6048. /**
  6049. * This flag is used for global cache.
  6050. *
  6051. * @type {boolean}
  6052. * @default true
  6053. */
  6054. this.global = true;
  6055. }
  6056. /**
  6057. * Defines the interpolation type of the varying.
  6058. *
  6059. * @param {string} type - The interpolation type.
  6060. * @param {?string} sampling - The interpolation sampling type
  6061. * @return {VaryingNode} A reference to this node.
  6062. */
  6063. setInterpolation( type, sampling = null ) {
  6064. this.interpolationType = type;
  6065. this.interpolationSampling = sampling;
  6066. return this;
  6067. }
  6068. getHash( builder ) {
  6069. return this.name || super.getHash( builder );
  6070. }
  6071. getNodeType( builder ) {
  6072. // VaryingNode is auto type
  6073. return this.node.getNodeType( builder );
  6074. }
  6075. /**
  6076. * This method performs the setup of a varying node with the current node builder.
  6077. *
  6078. * @param {NodeBuilder} builder - The current node builder.
  6079. * @return {NodeVarying} The node varying from the node builder.
  6080. */
  6081. setupVarying( builder ) {
  6082. const properties = builder.getNodeProperties( this );
  6083. let varying = properties.varying;
  6084. if ( varying === undefined ) {
  6085. const name = this.name;
  6086. const type = this.getNodeType( builder );
  6087. const interpolationType = this.interpolationType;
  6088. const interpolationSampling = this.interpolationSampling;
  6089. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  6090. properties.node = subBuild( this.node, 'VERTEX' );
  6091. }
  6092. // this property can be used to check if the varying can be optimized for a variable
  6093. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  6094. return varying;
  6095. }
  6096. setup( builder ) {
  6097. this.setupVarying( builder );
  6098. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  6099. }
  6100. analyze( builder ) {
  6101. this.setupVarying( builder );
  6102. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  6103. }
  6104. generate( builder ) {
  6105. const propertyKey = builder.getSubBuildProperty( 'property', builder.currentStack );
  6106. const properties = builder.getNodeProperties( this );
  6107. const varying = this.setupVarying( builder );
  6108. if ( properties[ propertyKey ] === undefined ) {
  6109. const type = this.getNodeType( builder );
  6110. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  6111. // force node run in vertex stage
  6112. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, properties.node, type, propertyName );
  6113. properties[ propertyKey ] = propertyName;
  6114. }
  6115. return builder.getPropertyName( varying );
  6116. }
  6117. }
  6118. /**
  6119. * TSL function for creating a varying node.
  6120. *
  6121. * @tsl
  6122. * @function
  6123. * @param {Node} node - The node for which a varying should be created.
  6124. * @param {?string} name - The name of the varying in the shader.
  6125. * @returns {VaryingNode}
  6126. */
  6127. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  6128. /**
  6129. * Computes a node in the vertex stage.
  6130. *
  6131. * @tsl
  6132. * @function
  6133. * @param {Node} node - The node which should be executed in the vertex stage.
  6134. * @returns {VaryingNode}
  6135. */
  6136. const vertexStage = ( node ) => varying( node );
  6137. addMethodChaining( 'toVarying', varying );
  6138. addMethodChaining( 'toVertexStage', vertexStage );
  6139. // Deprecated
  6140. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  6141. warn( 'TSL: .varying() has been renamed to .toVarying().' );
  6142. return varying( ...params );
  6143. } );
  6144. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  6145. warn( 'TSL: .vertexStage() has been renamed to .toVertexStage().' );
  6146. return varying( ...params );
  6147. } );
  6148. /**
  6149. * Converts the given color value from sRGB to linear-sRGB color space.
  6150. *
  6151. * @tsl
  6152. * @function
  6153. * @param {Node<vec3>} color - The sRGB color.
  6154. * @return {Node<vec3>} The linear-sRGB color.
  6155. */
  6156. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6157. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  6158. const b = color.mul( 0.0773993808 );
  6159. const factor = color.lessThanEqual( 0.04045 );
  6160. const rgbResult = mix( a, b, factor );
  6161. return rgbResult;
  6162. } ).setLayout( {
  6163. name: 'sRGBTransferEOTF',
  6164. type: 'vec3',
  6165. inputs: [
  6166. { name: 'color', type: 'vec3' }
  6167. ]
  6168. } );
  6169. /**
  6170. * Converts the given color value from linear-sRGB to sRGB color space.
  6171. *
  6172. * @tsl
  6173. * @function
  6174. * @param {Node<vec3>} color - The linear-sRGB color.
  6175. * @return {Node<vec3>} The sRGB color.
  6176. */
  6177. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6178. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  6179. const b = color.mul( 12.92 );
  6180. const factor = color.lessThanEqual( 0.0031308 );
  6181. const rgbResult = mix( a, b, factor );
  6182. return rgbResult;
  6183. } ).setLayout( {
  6184. name: 'sRGBTransferOETF',
  6185. type: 'vec3',
  6186. inputs: [
  6187. { name: 'color', type: 'vec3' }
  6188. ]
  6189. } );
  6190. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  6191. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  6192. /**
  6193. * This node represents a color space conversion. Meaning it converts
  6194. * a color value from a source to a target color space.
  6195. *
  6196. * @augments TempNode
  6197. */
  6198. class ColorSpaceNode extends TempNode {
  6199. static get type() {
  6200. return 'ColorSpaceNode';
  6201. }
  6202. /**
  6203. * Constructs a new color space node.
  6204. *
  6205. * @param {Node} colorNode - Represents the color to convert.
  6206. * @param {string} source - The source color space.
  6207. * @param {string} target - The target color space.
  6208. */
  6209. constructor( colorNode, source, target ) {
  6210. super( 'vec4' );
  6211. /**
  6212. * Represents the color to convert.
  6213. *
  6214. * @type {Node}
  6215. */
  6216. this.colorNode = colorNode;
  6217. /**
  6218. * The source color space.
  6219. *
  6220. * @type {string}
  6221. */
  6222. this.source = source;
  6223. /**
  6224. * The target color space.
  6225. *
  6226. * @type {string}
  6227. */
  6228. this.target = target;
  6229. }
  6230. /**
  6231. * This method resolves the constants `WORKING_COLOR_SPACE` and
  6232. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  6233. * color management and renderer.
  6234. *
  6235. * @param {NodeBuilder} builder - The current node builder.
  6236. * @param {string} colorSpace - The color space to resolve.
  6237. * @return {string} The resolved color space.
  6238. */
  6239. resolveColorSpace( builder, colorSpace ) {
  6240. if ( colorSpace === WORKING_COLOR_SPACE ) {
  6241. return ColorManagement.workingColorSpace;
  6242. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  6243. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  6244. }
  6245. return colorSpace;
  6246. }
  6247. setup( builder ) {
  6248. const { colorNode } = this;
  6249. const source = this.resolveColorSpace( builder, this.source );
  6250. const target = this.resolveColorSpace( builder, this.target );
  6251. let outputNode = colorNode;
  6252. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  6253. return outputNode;
  6254. }
  6255. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  6256. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  6257. }
  6258. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  6259. outputNode = vec4(
  6260. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  6261. outputNode.a
  6262. );
  6263. }
  6264. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  6265. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  6266. }
  6267. return outputNode;
  6268. }
  6269. }
  6270. /**
  6271. * TSL function for converting a given color node from the current working color space to the given color space.
  6272. *
  6273. * @tsl
  6274. * @function
  6275. * @param {Node} node - Represents the node to convert.
  6276. * @param {string} targetColorSpace - The target color space.
  6277. * @returns {ColorSpaceNode}
  6278. */
  6279. const workingToColorSpace = ( node, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace ) );
  6280. /**
  6281. * TSL function for converting a given color node from the given color space to the current working color space.
  6282. *
  6283. * @tsl
  6284. * @function
  6285. * @param {Node} node - Represents the node to convert.
  6286. * @param {string} sourceColorSpace - The source color space.
  6287. * @returns {ColorSpaceNode}
  6288. */
  6289. const colorSpaceToWorking = ( node, sourceColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE ) );
  6290. /**
  6291. * TSL function for converting a given color node from one color space to another one.
  6292. *
  6293. * @tsl
  6294. * @function
  6295. * @param {Node} node - Represents the node to convert.
  6296. * @param {string} sourceColorSpace - The source color space.
  6297. * @param {string} targetColorSpace - The target color space.
  6298. * @returns {ColorSpaceNode}
  6299. */
  6300. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  6301. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  6302. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  6303. // TODO: Avoid duplicated code and use only ReferenceBaseNode or ReferenceNode
  6304. /**
  6305. * This class is only relevant if the referenced property is array-like.
  6306. * In this case, `ReferenceElementNode` allows to refer to a specific
  6307. * element inside the data structure via an index.
  6308. *
  6309. * @augments ArrayElementNode
  6310. */
  6311. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  6312. static get type() {
  6313. return 'ReferenceElementNode';
  6314. }
  6315. /**
  6316. * Constructs a new reference element node.
  6317. *
  6318. * @param {ReferenceBaseNode} referenceNode - The reference node.
  6319. * @param {Node} indexNode - The index node that defines the element access.
  6320. */
  6321. constructor( referenceNode, indexNode ) {
  6322. super( referenceNode, indexNode );
  6323. /**
  6324. * Similar to {@link ReferenceBaseNode#reference}, an additional
  6325. * property references to the current node.
  6326. *
  6327. * @type {?ReferenceBaseNode}
  6328. * @default null
  6329. */
  6330. this.referenceNode = referenceNode;
  6331. /**
  6332. * This flag can be used for type testing.
  6333. *
  6334. * @type {boolean}
  6335. * @readonly
  6336. * @default true
  6337. */
  6338. this.isReferenceElementNode = true;
  6339. }
  6340. /**
  6341. * This method is overwritten since the node type is inferred from
  6342. * the uniform type of the reference node.
  6343. *
  6344. * @return {string} The node type.
  6345. */
  6346. getNodeType() {
  6347. return this.referenceNode.uniformType;
  6348. }
  6349. generate( builder ) {
  6350. const snippet = super.generate( builder );
  6351. const arrayType = this.referenceNode.getNodeType();
  6352. const elementType = this.getNodeType();
  6353. return builder.format( snippet, arrayType, elementType );
  6354. }
  6355. };
  6356. /**
  6357. * Base class for nodes which establishes a reference to a property of another object.
  6358. * In this way, the value of the node is automatically linked to the value of
  6359. * referenced object. Reference nodes internally represent the linked value
  6360. * as a uniform.
  6361. *
  6362. * @augments Node
  6363. */
  6364. class ReferenceBaseNode extends Node {
  6365. static get type() {
  6366. return 'ReferenceBaseNode';
  6367. }
  6368. /**
  6369. * Constructs a new reference base node.
  6370. *
  6371. * @param {string} property - The name of the property the node refers to.
  6372. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  6373. * @param {?Object} [object=null] - The object the property belongs to.
  6374. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  6375. */
  6376. constructor( property, uniformType, object = null, count = null ) {
  6377. super();
  6378. /**
  6379. * The name of the property the node refers to.
  6380. *
  6381. * @type {string}
  6382. */
  6383. this.property = property;
  6384. /**
  6385. * The uniform type that should be used to represent the property value.
  6386. *
  6387. * @type {string}
  6388. */
  6389. this.uniformType = uniformType;
  6390. /**
  6391. * The object the property belongs to.
  6392. *
  6393. * @type {?Object}
  6394. * @default null
  6395. */
  6396. this.object = object;
  6397. /**
  6398. * When the linked property is an array, this parameter defines its length.
  6399. *
  6400. * @type {?number}
  6401. * @default null
  6402. */
  6403. this.count = count;
  6404. /**
  6405. * The property name might have dots so nested properties can be referred.
  6406. * The hierarchy of the names is stored inside this array.
  6407. *
  6408. * @type {Array<string>}
  6409. */
  6410. this.properties = property.split( '.' );
  6411. /**
  6412. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  6413. * since the final reference might be updated from calling code.
  6414. *
  6415. * @type {?Object}
  6416. * @default null
  6417. */
  6418. this.reference = object;
  6419. /**
  6420. * The uniform node that holds the value of the reference node.
  6421. *
  6422. * @type {UniformNode}
  6423. * @default null
  6424. */
  6425. this.node = null;
  6426. /**
  6427. * The uniform group of the internal uniform.
  6428. *
  6429. * @type {UniformGroupNode}
  6430. * @default null
  6431. */
  6432. this.group = null;
  6433. /**
  6434. * Overwritten since reference nodes are updated per object.
  6435. *
  6436. * @type {string}
  6437. * @default 'object'
  6438. */
  6439. this.updateType = NodeUpdateType.OBJECT;
  6440. }
  6441. /**
  6442. * Sets the uniform group for this reference node.
  6443. *
  6444. * @param {UniformGroupNode} group - The uniform group to set.
  6445. * @return {ReferenceBaseNode} A reference to this node.
  6446. */
  6447. setGroup( group ) {
  6448. this.group = group;
  6449. return this;
  6450. }
  6451. /**
  6452. * When the referred property is array-like, this method can be used
  6453. * to access elements via an index node.
  6454. *
  6455. * @param {IndexNode} indexNode - indexNode.
  6456. * @return {ReferenceElementNode} A reference to an element.
  6457. */
  6458. element( indexNode ) {
  6459. return new ReferenceElementNode$1( this, nodeObject( indexNode ) );
  6460. }
  6461. /**
  6462. * Sets the node type which automatically defines the internal
  6463. * uniform type.
  6464. *
  6465. * @param {string} uniformType - The type to set.
  6466. */
  6467. setNodeType( uniformType ) {
  6468. const node = uniform( null, uniformType );
  6469. if ( this.group !== null ) {
  6470. node.setGroup( this.group );
  6471. }
  6472. this.node = node;
  6473. }
  6474. /**
  6475. * This method is overwritten since the node type is inferred from
  6476. * the type of the reference node.
  6477. *
  6478. * @param {NodeBuilder} builder - The current node builder.
  6479. * @return {string} The node type.
  6480. */
  6481. getNodeType( builder ) {
  6482. if ( this.node === null ) {
  6483. this.updateReference( builder );
  6484. this.updateValue();
  6485. }
  6486. return this.node.getNodeType( builder );
  6487. }
  6488. /**
  6489. * Returns the property value from the given referred object.
  6490. *
  6491. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  6492. * @return {any} The value.
  6493. */
  6494. getValueFromReference( object = this.reference ) {
  6495. const { properties } = this;
  6496. let value = object[ properties[ 0 ] ];
  6497. for ( let i = 1; i < properties.length; i ++ ) {
  6498. value = value[ properties[ i ] ];
  6499. }
  6500. return value;
  6501. }
  6502. /**
  6503. * Allows to update the reference based on the given state. The state is only
  6504. * evaluated {@link ReferenceBaseNode#object} is not set.
  6505. *
  6506. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6507. * @return {Object} The updated reference.
  6508. */
  6509. updateReference( state ) {
  6510. this.reference = this.object !== null ? this.object : state.object;
  6511. return this.reference;
  6512. }
  6513. /**
  6514. * The output of the reference node is the internal uniform node.
  6515. *
  6516. * @return {UniformNode} The output node.
  6517. */
  6518. setup() {
  6519. this.updateValue();
  6520. return this.node;
  6521. }
  6522. /**
  6523. * Overwritten to update the internal uniform value.
  6524. *
  6525. * @param {NodeFrame} frame - A reference to the current node frame.
  6526. */
  6527. update( /*frame*/ ) {
  6528. this.updateValue();
  6529. }
  6530. /**
  6531. * Retrieves the value from the referred object property and uses it
  6532. * to updated the internal uniform.
  6533. */
  6534. updateValue() {
  6535. if ( this.node === null ) this.setNodeType( this.uniformType );
  6536. const value = this.getValueFromReference();
  6537. if ( Array.isArray( value ) ) {
  6538. this.node.array = value;
  6539. } else {
  6540. this.node.value = value;
  6541. }
  6542. }
  6543. }
  6544. /**
  6545. * TSL function for creating a reference base node.
  6546. *
  6547. * @tsl
  6548. * @function
  6549. * @param {string} name - The name of the property the node refers to.
  6550. * @param {string} type - The uniform type that should be used to represent the property value.
  6551. * @param {Object} object - The object the property belongs to.
  6552. * @returns {ReferenceBaseNode}
  6553. */
  6554. const reference$1 = ( name, type, object ) => new ReferenceBaseNode( name, type, object );
  6555. /**
  6556. * This node is a special type of reference node which is intended
  6557. * for linking renderer properties with node values.
  6558. * ```js
  6559. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  6560. * ```
  6561. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  6562. * automatically be updated.
  6563. *
  6564. * @augments ReferenceBaseNode
  6565. */
  6566. class RendererReferenceNode extends ReferenceBaseNode {
  6567. static get type() {
  6568. return 'RendererReferenceNode';
  6569. }
  6570. /**
  6571. * Constructs a new renderer reference node.
  6572. *
  6573. * @param {string} property - The name of the property the node refers to.
  6574. * @param {string} inputType - The uniform type that should be used to represent the property value.
  6575. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6576. * the node refers to the renderer of the current state.
  6577. */
  6578. constructor( property, inputType, renderer = null ) {
  6579. super( property, inputType, renderer );
  6580. /**
  6581. * The renderer the property belongs to. When no renderer is set,
  6582. * the node refers to the renderer of the current state.
  6583. *
  6584. * @type {?Renderer}
  6585. * @default null
  6586. */
  6587. this.renderer = renderer;
  6588. this.setGroup( renderGroup );
  6589. }
  6590. /**
  6591. * Updates the reference based on the given state. The state is only evaluated
  6592. * {@link RendererReferenceNode#renderer} is not set.
  6593. *
  6594. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6595. * @return {Object} The updated reference.
  6596. */
  6597. updateReference( state ) {
  6598. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  6599. return this.reference;
  6600. }
  6601. }
  6602. /**
  6603. * TSL function for creating a renderer reference node.
  6604. *
  6605. * @tsl
  6606. * @function
  6607. * @param {string} name - The name of the property the node refers to.
  6608. * @param {string} type - The uniform type that should be used to represent the property value.
  6609. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6610. * the node refers to the renderer of the current state.
  6611. * @returns {RendererReferenceNode}
  6612. */
  6613. const rendererReference = ( name, type, renderer = null ) => new RendererReferenceNode( name, type, renderer );
  6614. /**
  6615. * This node represents a tone mapping operation.
  6616. *
  6617. * @augments TempNode
  6618. */
  6619. class ToneMappingNode extends TempNode {
  6620. static get type() {
  6621. return 'ToneMappingNode';
  6622. }
  6623. /**
  6624. * Constructs a new tone mapping node.
  6625. *
  6626. * @param {number} toneMapping - The tone mapping type.
  6627. * @param {Node} exposureNode - The tone mapping exposure.
  6628. * @param {Node} [colorNode=null] - The color node to process.
  6629. */
  6630. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  6631. super( 'vec3' );
  6632. /**
  6633. * The tone mapping type.
  6634. *
  6635. * @private
  6636. * @type {number}
  6637. */
  6638. this._toneMapping = toneMapping;
  6639. /**
  6640. * The tone mapping exposure.
  6641. *
  6642. * @type {Node}
  6643. * @default null
  6644. */
  6645. this.exposureNode = exposureNode;
  6646. /**
  6647. * Represents the color to process.
  6648. *
  6649. * @type {?Node}
  6650. * @default null
  6651. */
  6652. this.colorNode = colorNode;
  6653. }
  6654. /**
  6655. * Overwrites the default `customCacheKey()` implementation by including the tone
  6656. * mapping type into the cache key.
  6657. *
  6658. * @return {number} The hash.
  6659. */
  6660. customCacheKey() {
  6661. return hash$1( this._toneMapping );
  6662. }
  6663. /**
  6664. * Sets the tone mapping type.
  6665. *
  6666. * @param {number} value - The tone mapping type.
  6667. * @return {ToneMappingNode} A reference to this node.
  6668. */
  6669. setToneMapping( value ) {
  6670. this._toneMapping = value;
  6671. return this;
  6672. }
  6673. /**
  6674. * Gets the tone mapping type.
  6675. *
  6676. * @returns {number} The tone mapping type.
  6677. */
  6678. getToneMapping() {
  6679. return this._toneMapping;
  6680. }
  6681. setup( builder ) {
  6682. const colorNode = this.colorNode || builder.context.color;
  6683. const toneMapping = this._toneMapping;
  6684. if ( toneMapping === NoToneMapping ) return colorNode;
  6685. let outputNode = null;
  6686. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  6687. if ( toneMappingFn !== null ) {
  6688. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  6689. } else {
  6690. error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  6691. outputNode = colorNode;
  6692. }
  6693. return outputNode;
  6694. }
  6695. }
  6696. /**
  6697. * TSL function for creating a tone mapping node.
  6698. *
  6699. * @tsl
  6700. * @function
  6701. * @param {number} mapping - The tone mapping type.
  6702. * @param {Node<float> | number} exposure - The tone mapping exposure.
  6703. * @param {Node<vec3> | Color} color - The color node to process.
  6704. * @returns {ToneMappingNode<vec3>}
  6705. */
  6706. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  6707. /**
  6708. * TSL object that represents the global tone mapping exposure of the renderer.
  6709. *
  6710. * @tsl
  6711. * @type {RendererReferenceNode<vec3>}
  6712. */
  6713. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  6714. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  6715. /**
  6716. * Internal buffer attribute library.
  6717. *
  6718. * @private
  6719. * @type {WeakMap<TypedArray, InterleavedBuffer>}
  6720. */
  6721. const _bufferLib = new WeakMap();
  6722. /**
  6723. * Internal method for retrieving or creating interleaved buffers.
  6724. *
  6725. * @private
  6726. * @param {TypedArray} value - The attribute data.
  6727. * @param {number} itemSize - The attribute item size.
  6728. * @returns {InterleavedBuffer} The interleaved buffer.
  6729. */
  6730. function _getBufferAttribute( value, itemSize ) {
  6731. let buffer = _bufferLib.get( value );
  6732. if ( buffer === undefined ) {
  6733. buffer = new InterleavedBuffer( value, itemSize );
  6734. _bufferLib.set( value, buffer );
  6735. }
  6736. return buffer;
  6737. }
  6738. /**
  6739. * In earlier `three.js` versions it was only possible to define attribute data
  6740. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  6741. * on the node level.
  6742. * ```js
  6743. * const geometry = new THREE.PlaneGeometry();
  6744. * const positionAttribute = geometry.getAttribute( 'position' );
  6745. *
  6746. * const colors = [];
  6747. * for ( let i = 0; i < position.count; i ++ ) {
  6748. * colors.push( 1, 0, 0 );
  6749. * }
  6750. *
  6751. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  6752. * ```
  6753. * This new approach is especially interesting when geometry data are generated via
  6754. * compute shaders. The below line converts a storage buffer into an attribute node.
  6755. * ```js
  6756. * material.positionNode = positionBuffer.toAttribute();
  6757. * ```
  6758. * @augments InputNode
  6759. */
  6760. class BufferAttributeNode extends InputNode {
  6761. static get type() {
  6762. return 'BufferAttributeNode';
  6763. }
  6764. /**
  6765. * Constructs a new buffer attribute node.
  6766. *
  6767. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  6768. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  6769. * @param {number} [bufferStride=0] - The buffer stride.
  6770. * @param {number} [bufferOffset=0] - The buffer offset.
  6771. */
  6772. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  6773. super( value, bufferType );
  6774. /**
  6775. * This flag can be used for type testing.
  6776. *
  6777. * @type {boolean}
  6778. * @readonly
  6779. * @default true
  6780. */
  6781. this.isBufferNode = true;
  6782. /**
  6783. * The buffer type (e.g. `'vec3'`).
  6784. *
  6785. * @type {?string}
  6786. * @default null
  6787. */
  6788. this.bufferType = bufferType;
  6789. /**
  6790. * The buffer stride.
  6791. *
  6792. * @type {number}
  6793. * @default 0
  6794. */
  6795. this.bufferStride = bufferStride;
  6796. /**
  6797. * The buffer offset.
  6798. *
  6799. * @type {number}
  6800. * @default 0
  6801. */
  6802. this.bufferOffset = bufferOffset;
  6803. /**
  6804. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  6805. * if you are planning to update the attribute data per frame.
  6806. *
  6807. * @type {number}
  6808. * @default StaticDrawUsage
  6809. */
  6810. this.usage = StaticDrawUsage;
  6811. /**
  6812. * Whether the attribute is instanced or not.
  6813. *
  6814. * @type {boolean}
  6815. * @default false
  6816. */
  6817. this.instanced = false;
  6818. /**
  6819. * A reference to the buffer attribute.
  6820. *
  6821. * @type {?BufferAttribute}
  6822. * @default null
  6823. */
  6824. this.attribute = null;
  6825. /**
  6826. * `BufferAttributeNode` sets this property to `true` by default.
  6827. *
  6828. * @type {boolean}
  6829. * @default true
  6830. */
  6831. this.global = true;
  6832. if ( value && value.isBufferAttribute === true && value.itemSize <= 4 ) {
  6833. this.attribute = value;
  6834. this.usage = value.usage;
  6835. this.instanced = value.isInstancedBufferAttribute;
  6836. }
  6837. }
  6838. /**
  6839. * This method is overwritten since the attribute data might be shared
  6840. * and thus the hash should be shared as well.
  6841. *
  6842. * @param {NodeBuilder} builder - The current node builder.
  6843. * @return {string} The hash.
  6844. */
  6845. getHash( builder ) {
  6846. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6847. let bufferData = builder.globalCache.getData( this.value );
  6848. if ( bufferData === undefined ) {
  6849. bufferData = {
  6850. node: this
  6851. };
  6852. builder.globalCache.setData( this.value, bufferData );
  6853. }
  6854. return bufferData.node.uuid;
  6855. }
  6856. return this.uuid;
  6857. }
  6858. /**
  6859. * This method is overwritten since the node type is inferred from
  6860. * the buffer attribute.
  6861. *
  6862. * @param {NodeBuilder} builder - The current node builder.
  6863. * @return {string} The node type.
  6864. */
  6865. getNodeType( builder ) {
  6866. if ( this.bufferType === null ) {
  6867. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6868. }
  6869. return this.bufferType;
  6870. }
  6871. /**
  6872. * Depending on which value was passed to the node, `setup()` behaves
  6873. * differently. If no instance of `BufferAttribute` was passed, the method
  6874. * creates an internal attribute and configures it respectively.
  6875. *
  6876. * @param {NodeBuilder} builder - The current node builder.
  6877. */
  6878. setup( builder ) {
  6879. if ( this.attribute !== null ) return;
  6880. //
  6881. const type = this.getNodeType( builder );
  6882. const itemSize = builder.getTypeLength( type );
  6883. const value = this.value;
  6884. const stride = this.bufferStride || itemSize;
  6885. const offset = this.bufferOffset;
  6886. let buffer;
  6887. if ( value.isInterleavedBuffer === true ) {
  6888. buffer = value;
  6889. } else if ( value.isBufferAttribute === true ) {
  6890. buffer = _getBufferAttribute( value.array, stride );
  6891. } else {
  6892. buffer = _getBufferAttribute( value, stride );
  6893. }
  6894. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6895. buffer.setUsage( this.usage );
  6896. this.attribute = bufferAttribute;
  6897. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6898. }
  6899. /**
  6900. * Generates the code snippet of the buffer attribute node.
  6901. *
  6902. * @param {NodeBuilder} builder - The current node builder.
  6903. * @return {string} The generated code snippet.
  6904. */
  6905. generate( builder ) {
  6906. const nodeType = this.getNodeType( builder );
  6907. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6908. const propertyName = builder.getPropertyName( nodeAttribute );
  6909. let output = null;
  6910. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6911. this.name = propertyName;
  6912. output = propertyName;
  6913. } else {
  6914. const nodeVarying = varying( this );
  6915. output = nodeVarying.build( builder, nodeType );
  6916. }
  6917. return output;
  6918. }
  6919. /**
  6920. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  6921. *
  6922. * @param {NodeBuilder} builder - The current node builder.
  6923. * @return {string} The input type.
  6924. */
  6925. getInputType( /*builder*/ ) {
  6926. return 'bufferAttribute';
  6927. }
  6928. /**
  6929. * Sets the `usage` property to the given value.
  6930. *
  6931. * @param {number} value - The usage to set.
  6932. * @return {BufferAttributeNode} A reference to this node.
  6933. */
  6934. setUsage( value ) {
  6935. this.usage = value;
  6936. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  6937. this.attribute.usage = value;
  6938. }
  6939. return this;
  6940. }
  6941. /**
  6942. * Sets the `instanced` property to the given value.
  6943. *
  6944. * @param {boolean} value - The value to set.
  6945. * @return {BufferAttributeNode} A reference to this node.
  6946. */
  6947. setInstanced( value ) {
  6948. this.instanced = value;
  6949. return this;
  6950. }
  6951. }
  6952. /**
  6953. * Internal method for creating buffer attribute nodes.
  6954. *
  6955. * @private
  6956. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6957. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6958. * @param {number} [stride=0] - The buffer stride.
  6959. * @param {number} [offset=0] - The buffer offset.
  6960. * @param {number} [usage=StaticDrawUsage] - The buffer usage.
  6961. * @param {boolean} [instanced=false] - Whether the buffer is instanced.
  6962. * @returns {BufferAttributeNode|Node} The buffer attribute node.
  6963. */
  6964. function createBufferAttribute( array, type = null, stride = 0, offset = 0, usage = StaticDrawUsage, instanced = false ) {
  6965. if ( type === 'mat3' || ( type === null && array.itemSize === 9 ) ) {
  6966. return mat3(
  6967. new BufferAttributeNode( array, 'vec3', 9, 0 ).setUsage( usage ).setInstanced( instanced ),
  6968. new BufferAttributeNode( array, 'vec3', 9, 3 ).setUsage( usage ).setInstanced( instanced ),
  6969. new BufferAttributeNode( array, 'vec3', 9, 6 ).setUsage( usage ).setInstanced( instanced )
  6970. );
  6971. } else if ( type === 'mat4' || ( type === null && array.itemSize === 16 ) ) {
  6972. return mat4(
  6973. new BufferAttributeNode( array, 'vec4', 16, 0 ).setUsage( usage ).setInstanced( instanced ),
  6974. new BufferAttributeNode( array, 'vec4', 16, 4 ).setUsage( usage ).setInstanced( instanced ),
  6975. new BufferAttributeNode( array, 'vec4', 16, 8 ).setUsage( usage ).setInstanced( instanced ),
  6976. new BufferAttributeNode( array, 'vec4', 16, 12 ).setUsage( usage ).setInstanced( instanced )
  6977. );
  6978. }
  6979. return new BufferAttributeNode( array, type, stride, offset );
  6980. }
  6981. /**
  6982. * TSL function for creating a buffer attribute node.
  6983. *
  6984. * @tsl
  6985. * @function
  6986. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6987. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6988. * @param {number} [stride=0] - The buffer stride.
  6989. * @param {number} [offset=0] - The buffer offset.
  6990. * @returns {BufferAttributeNode|Node}
  6991. */
  6992. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset );
  6993. /**
  6994. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  6995. * Use this function if attribute data are updated per frame.
  6996. *
  6997. * @tsl
  6998. * @function
  6999. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7000. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7001. * @param {number} [stride=0] - The buffer stride.
  7002. * @param {number} [offset=0] - The buffer offset.
  7003. * @returns {BufferAttributeNode|Node}
  7004. */
  7005. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, DynamicDrawUsage );
  7006. /**
  7007. * TSL function for creating a buffer attribute node but with enabled instancing
  7008. *
  7009. * @tsl
  7010. * @function
  7011. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7012. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7013. * @param {number} [stride=0] - The buffer stride.
  7014. * @param {number} [offset=0] - The buffer offset.
  7015. * @returns {BufferAttributeNode|Node}
  7016. */
  7017. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, StaticDrawUsage, true );
  7018. /**
  7019. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  7020. *
  7021. * @tsl
  7022. * @function
  7023. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7024. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7025. * @param {number} [stride=0] - The buffer stride.
  7026. * @param {number} [offset=0] - The buffer offset.
  7027. * @returns {BufferAttributeNode|Node}
  7028. */
  7029. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, DynamicDrawUsage, true );
  7030. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  7031. /**
  7032. * TODO
  7033. *
  7034. * @augments Node
  7035. */
  7036. class ComputeNode extends Node {
  7037. static get type() {
  7038. return 'ComputeNode';
  7039. }
  7040. /**
  7041. * Constructs a new compute node.
  7042. *
  7043. * @param {Node} computeNode - TODO
  7044. * @param {Array<number>} workgroupSize - TODO.
  7045. */
  7046. constructor( computeNode, workgroupSize ) {
  7047. super( 'void' );
  7048. /**
  7049. * This flag can be used for type testing.
  7050. *
  7051. * @type {boolean}
  7052. * @readonly
  7053. * @default true
  7054. */
  7055. this.isComputeNode = true;
  7056. /**
  7057. * TODO
  7058. *
  7059. * @type {Node}
  7060. */
  7061. this.computeNode = computeNode;
  7062. /**
  7063. * TODO
  7064. *
  7065. * @type {Array<number>}
  7066. * @default [ 64 ]
  7067. */
  7068. this.workgroupSize = workgroupSize;
  7069. /**
  7070. * TODO
  7071. *
  7072. * @type {number|Array<number>}
  7073. */
  7074. this.count = null;
  7075. /**
  7076. * TODO
  7077. *
  7078. * @type {number}
  7079. */
  7080. this.version = 1;
  7081. /**
  7082. * The name or label of the uniform.
  7083. *
  7084. * @type {string}
  7085. * @default ''
  7086. */
  7087. this.name = '';
  7088. /**
  7089. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  7090. * is executed once per object by default.
  7091. *
  7092. * @type {string}
  7093. * @default 'object'
  7094. */
  7095. this.updateBeforeType = NodeUpdateType.OBJECT;
  7096. /**
  7097. * TODO
  7098. *
  7099. * @type {?Function}
  7100. */
  7101. this.onInitFunction = null;
  7102. }
  7103. /**
  7104. * TODO
  7105. *
  7106. * @param {number|Array<number>} count - Array with [ x, y, z ] values for dispatch or a single number for the count
  7107. * @return {ComputeNode}
  7108. */
  7109. setCount( count ) {
  7110. this.count = count;
  7111. return this;
  7112. }
  7113. /**
  7114. * TODO
  7115. *
  7116. * @return {number|Array<number>}
  7117. */
  7118. getCount() {
  7119. return this.count;
  7120. }
  7121. /**
  7122. * Executes the `dispose` event for this node.
  7123. */
  7124. dispose() {
  7125. this.dispatchEvent( { type: 'dispose' } );
  7126. }
  7127. /**
  7128. * Sets the {@link ComputeNode#name} property.
  7129. *
  7130. * @param {string} name - The name of the uniform.
  7131. * @return {ComputeNode} A reference to this node.
  7132. */
  7133. setName( name ) {
  7134. this.name = name;
  7135. return this;
  7136. }
  7137. /**
  7138. * Sets the {@link ComputeNode#name} property.
  7139. *
  7140. * @deprecated
  7141. * @param {string} name - The name of the uniform.
  7142. * @return {ComputeNode} A reference to this node.
  7143. */
  7144. label( name ) {
  7145. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  7146. return this.setName( name );
  7147. }
  7148. /**
  7149. * TODO
  7150. *
  7151. * @param {Function} callback - TODO.
  7152. * @return {ComputeNode} A reference to this node.
  7153. */
  7154. onInit( callback ) {
  7155. this.onInitFunction = callback;
  7156. return this;
  7157. }
  7158. /**
  7159. * The method execute the compute for this node.
  7160. *
  7161. * @param {NodeFrame} frame - A reference to the current node frame.
  7162. */
  7163. updateBefore( { renderer } ) {
  7164. renderer.compute( this );
  7165. }
  7166. setup( builder ) {
  7167. const result = this.computeNode.build( builder );
  7168. if ( result ) {
  7169. const properties = builder.getNodeProperties( this );
  7170. properties.outputComputeNode = result.outputNode;
  7171. result.outputNode = null;
  7172. }
  7173. return result;
  7174. }
  7175. generate( builder, output ) {
  7176. const { shaderStage } = builder;
  7177. if ( shaderStage === 'compute' ) {
  7178. const snippet = this.computeNode.build( builder, 'void' );
  7179. if ( snippet !== '' ) {
  7180. builder.addLineFlowCode( snippet, this );
  7181. }
  7182. } else {
  7183. const properties = builder.getNodeProperties( this );
  7184. const outputComputeNode = properties.outputComputeNode;
  7185. if ( outputComputeNode ) {
  7186. return outputComputeNode.build( builder, output );
  7187. }
  7188. }
  7189. }
  7190. }
  7191. /**
  7192. * TSL function for creating a compute kernel node.
  7193. *
  7194. * @tsl
  7195. * @function
  7196. * @param {Node} node - TODO
  7197. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  7198. * @returns {AtomicFunctionNode}
  7199. */
  7200. const computeKernel = ( node, workgroupSize = [ 64 ] ) => {
  7201. if ( workgroupSize.length === 0 || workgroupSize.length > 3 ) {
  7202. error( 'TSL: compute() workgroupSize must have 1, 2, or 3 elements' );
  7203. }
  7204. for ( let i = 0; i < workgroupSize.length; i ++ ) {
  7205. const val = workgroupSize[ i ];
  7206. if ( typeof val !== 'number' || val <= 0 || ! Number.isInteger( val ) ) {
  7207. error( `TSL: compute() workgroupSize element at index [ ${ i } ] must be a positive integer` );
  7208. }
  7209. }
  7210. // Implicit fill-up to [ x, y, z ] with 1s, just like WGSL treats @workgroup_size when fewer dimensions are specified
  7211. while ( workgroupSize.length < 3 ) workgroupSize.push( 1 );
  7212. //
  7213. return nodeObject( new ComputeNode( nodeObject( node ), workgroupSize ) );
  7214. };
  7215. /**
  7216. * TSL function for creating a compute node.
  7217. *
  7218. * @tsl
  7219. * @function
  7220. * @param {Node} node - TODO
  7221. * @param {number|Array<number>} count - TODO.
  7222. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  7223. * @returns {AtomicFunctionNode}
  7224. */
  7225. const compute = ( node, count, workgroupSize ) => computeKernel( node, workgroupSize ).setCount( count );
  7226. addMethodChaining( 'compute', compute );
  7227. addMethodChaining( 'computeKernel', computeKernel );
  7228. /**
  7229. * This node can be used as a cache management component for another node.
  7230. * Caching is in general used by default in {@link NodeBuilder} but this node
  7231. * allows the usage of a shared parent cache during the build process.
  7232. *
  7233. * @augments Node
  7234. */
  7235. class IsolateNode extends Node {
  7236. static get type() {
  7237. return 'IsolateNode';
  7238. }
  7239. /**
  7240. * Constructs a new cache node.
  7241. *
  7242. * @param {Node} node - The node that should be cached.
  7243. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7244. */
  7245. constructor( node, parent = true ) {
  7246. super();
  7247. /**
  7248. * The node that should be cached.
  7249. *
  7250. * @type {Node}
  7251. */
  7252. this.node = node;
  7253. /**
  7254. * Whether this node refers to a shared parent cache or not.
  7255. *
  7256. * @type {boolean}
  7257. * @default true
  7258. */
  7259. this.parent = parent;
  7260. /**
  7261. * This flag can be used for type testing.
  7262. *
  7263. * @type {boolean}
  7264. * @readonly
  7265. * @default true
  7266. */
  7267. this.isIsolateNode = true;
  7268. }
  7269. getNodeType( builder ) {
  7270. const previousCache = builder.getCache();
  7271. const cache = builder.getCacheFromNode( this, this.parent );
  7272. builder.setCache( cache );
  7273. const nodeType = this.node.getNodeType( builder );
  7274. builder.setCache( previousCache );
  7275. return nodeType;
  7276. }
  7277. build( builder, ...params ) {
  7278. const previousCache = builder.getCache();
  7279. const cache = builder.getCacheFromNode( this, this.parent );
  7280. builder.setCache( cache );
  7281. const data = this.node.build( builder, ...params );
  7282. builder.setCache( previousCache );
  7283. return data;
  7284. }
  7285. setParent( parent ) {
  7286. this.parent = parent;
  7287. return this;
  7288. }
  7289. getParent() {
  7290. return this.parent;
  7291. }
  7292. }
  7293. /**
  7294. * TSL function for creating a cache node.
  7295. *
  7296. * @tsl
  7297. * @function
  7298. * @param {Node} node - The node that should be cached.
  7299. * @returns {IsolateNode}
  7300. */
  7301. const isolate = ( node ) => new IsolateNode( nodeObject( node ) );
  7302. /**
  7303. * TSL function for creating a cache node.
  7304. *
  7305. * @tsl
  7306. * @function
  7307. * @deprecated
  7308. * @param {Node} node - The node that should be cached.
  7309. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7310. * @returns {IsolateNode}
  7311. */
  7312. function cache( node, parent = true ) {
  7313. warn( 'TSL: "cache()" has been deprecated. Use "isolate()" instead.' ); // @deprecated r181
  7314. return isolate( node ).setParent( parent );
  7315. }
  7316. addMethodChaining( 'cache', cache );
  7317. addMethodChaining( 'isolate', isolate );
  7318. /**
  7319. * The class generates the code of a given node but returns another node in the output.
  7320. * This can be used to call a method or node that does not return a value, i.e.
  7321. * type `void` on an input where returning a value is required. Example:
  7322. *
  7323. * ```js
  7324. * material.colorNode = myColor.bypass( runVoidFn() )
  7325. *```
  7326. *
  7327. * @augments Node
  7328. */
  7329. class BypassNode extends Node {
  7330. static get type() {
  7331. return 'BypassNode';
  7332. }
  7333. /**
  7334. * Constructs a new bypass node.
  7335. *
  7336. * @param {Node} outputNode - The output node.
  7337. * @param {Node} callNode - The call node.
  7338. */
  7339. constructor( outputNode, callNode ) {
  7340. super();
  7341. /**
  7342. * This flag can be used for type testing.
  7343. *
  7344. * @type {boolean}
  7345. * @readonly
  7346. * @default true
  7347. */
  7348. this.isBypassNode = true;
  7349. /**
  7350. * The output node.
  7351. *
  7352. * @type {Node}
  7353. */
  7354. this.outputNode = outputNode;
  7355. /**
  7356. * The call node.
  7357. *
  7358. * @type {Node}
  7359. */
  7360. this.callNode = callNode;
  7361. }
  7362. getNodeType( builder ) {
  7363. return this.outputNode.getNodeType( builder );
  7364. }
  7365. generate( builder ) {
  7366. const snippet = this.callNode.build( builder, 'void' );
  7367. if ( snippet !== '' ) {
  7368. builder.addLineFlowCode( snippet, this );
  7369. }
  7370. return this.outputNode.build( builder );
  7371. }
  7372. }
  7373. /**
  7374. * TSL function for creating a bypass node.
  7375. *
  7376. * @tsl
  7377. * @function
  7378. * @param {Node} outputNode - The output node.
  7379. * @param {Node} callNode - The call node.
  7380. * @returns {BypassNode}
  7381. */
  7382. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  7383. addMethodChaining( 'bypass', bypass );
  7384. /**
  7385. * This node allows to remap a node value from one range into another. E.g a value of
  7386. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  7387. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  7388. *
  7389. * @augments Node
  7390. */
  7391. class RemapNode extends Node {
  7392. static get type() {
  7393. return 'RemapNode';
  7394. }
  7395. /**
  7396. * Constructs a new remap node.
  7397. *
  7398. * @param {Node} node - The node that should be remapped.
  7399. * @param {Node} inLowNode - The source or current lower bound of the range.
  7400. * @param {Node} inHighNode - The source or current upper bound of the range.
  7401. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  7402. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  7403. */
  7404. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  7405. super();
  7406. /**
  7407. * The node that should be remapped.
  7408. *
  7409. * @type {Node}
  7410. */
  7411. this.node = node;
  7412. /**
  7413. * The source or current lower bound of the range.
  7414. *
  7415. * @type {Node}
  7416. */
  7417. this.inLowNode = inLowNode;
  7418. /**
  7419. * The source or current upper bound of the range.
  7420. *
  7421. * @type {Node}
  7422. */
  7423. this.inHighNode = inHighNode;
  7424. /**
  7425. * The target lower bound of the range.
  7426. *
  7427. * @type {Node}
  7428. * @default float(0)
  7429. */
  7430. this.outLowNode = outLowNode;
  7431. /**
  7432. * The target upper bound of the range.
  7433. *
  7434. * @type {Node}
  7435. * @default float(1)
  7436. */
  7437. this.outHighNode = outHighNode;
  7438. /**
  7439. * Whether the node value should be clamped before
  7440. * remapping it to the target range.
  7441. *
  7442. * @type {boolean}
  7443. * @default true
  7444. */
  7445. this.doClamp = true;
  7446. }
  7447. setup() {
  7448. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  7449. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  7450. if ( doClamp === true ) t = t.clamp();
  7451. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  7452. }
  7453. }
  7454. /**
  7455. * TSL function for creating a remap node.
  7456. *
  7457. * @tsl
  7458. * @function
  7459. * @param {Node} node - The node that should be remapped.
  7460. * @param {Node} inLowNode - The source or current lower bound of the range.
  7461. * @param {Node} inHighNode - The source or current upper bound of the range.
  7462. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7463. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7464. * @returns {RemapNode}
  7465. */
  7466. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  7467. /**
  7468. * TSL function for creating a remap node, but with enabled clamping.
  7469. *
  7470. * @tsl
  7471. * @function
  7472. * @param {Node} node - The node that should be remapped.
  7473. * @param {Node} inLowNode - The source or current lower bound of the range.
  7474. * @param {Node} inHighNode - The source or current upper bound of the range.
  7475. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7476. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7477. * @returns {RemapNode}
  7478. */
  7479. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  7480. addMethodChaining( 'remap', remap );
  7481. addMethodChaining( 'remapClamp', remapClamp );
  7482. /**
  7483. * This class can be used to implement basic expressions in shader code.
  7484. * Basic examples for that are `return`, `continue` or `discard` statements.
  7485. *
  7486. * @augments Node
  7487. */
  7488. class ExpressionNode extends Node {
  7489. static get type() {
  7490. return 'ExpressionNode';
  7491. }
  7492. /**
  7493. * Constructs a new expression node.
  7494. *
  7495. * @param {string} [snippet=''] - The native code snippet.
  7496. * @param {string} [nodeType='void'] - The node type.
  7497. */
  7498. constructor( snippet = '', nodeType = 'void' ) {
  7499. super( nodeType );
  7500. /**
  7501. * The native code snippet.
  7502. *
  7503. * @type {string}
  7504. * @default ''
  7505. */
  7506. this.snippet = snippet;
  7507. }
  7508. generate( builder, output ) {
  7509. const type = this.getNodeType( builder );
  7510. const snippet = this.snippet;
  7511. if ( type === 'void' ) {
  7512. builder.addLineFlowCode( snippet, this );
  7513. } else {
  7514. return builder.format( snippet, type, output );
  7515. }
  7516. }
  7517. }
  7518. /**
  7519. * TSL function for creating an expression node.
  7520. *
  7521. * @tsl
  7522. * @function
  7523. * @param {string} [snippet] - The native code snippet.
  7524. * @param {?string} [nodeType='void'] - The node type.
  7525. * @returns {ExpressionNode}
  7526. */
  7527. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  7528. /**
  7529. * Represents a `discard` shader operation in TSL.
  7530. *
  7531. * @tsl
  7532. * @function
  7533. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  7534. * @return {Node} The `discard` expression.
  7535. */
  7536. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  7537. /**
  7538. * Represents a `return` shader operation in TSL.
  7539. *
  7540. * @tsl
  7541. * @function
  7542. * @return {ExpressionNode} The `return` expression.
  7543. */
  7544. const Return = () => expression( 'return' ).toStack();
  7545. addMethodChaining( 'discard', Discard );
  7546. /**
  7547. * Normally, tone mapping and color conversion happens automatically
  7548. * before outputting pixel too the default (screen) framebuffer. In certain
  7549. * post processing setups this happens to late because certain effects
  7550. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  7551. * to apply tone mapping and color space conversion at an arbitrary point
  7552. * in the effect chain.
  7553. *
  7554. * When applying tone mapping and color space conversion manually with this node,
  7555. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  7556. *
  7557. * ```js
  7558. * const postProcessing = new PostProcessing( renderer );
  7559. * postProcessing.outputColorTransform = false;
  7560. *
  7561. * const scenePass = pass( scene, camera );
  7562. * const outputPass = renderOutput( scenePass );
  7563. *
  7564. * postProcessing.outputNode = outputPass;
  7565. * ```
  7566. *
  7567. * @augments TempNode
  7568. */
  7569. class RenderOutputNode extends TempNode {
  7570. static get type() {
  7571. return 'RenderOutputNode';
  7572. }
  7573. /**
  7574. * Constructs a new render output node.
  7575. *
  7576. * @param {Node} colorNode - The color node to process.
  7577. * @param {?number} toneMapping - The tone mapping type.
  7578. * @param {?string} outputColorSpace - The output color space.
  7579. */
  7580. constructor( colorNode, toneMapping, outputColorSpace ) {
  7581. super( 'vec4' );
  7582. /**
  7583. * The color node to process.
  7584. *
  7585. * @type {Node}
  7586. */
  7587. this.colorNode = colorNode;
  7588. /**
  7589. * The tone mapping type.
  7590. *
  7591. * @private
  7592. * @type {?number}
  7593. */
  7594. this._toneMapping = toneMapping;
  7595. /**
  7596. * The output color space.
  7597. *
  7598. * @type {?string}
  7599. */
  7600. this.outputColorSpace = outputColorSpace;
  7601. /**
  7602. * This flag can be used for type testing.
  7603. *
  7604. * @type {boolean}
  7605. * @readonly
  7606. * @default true
  7607. */
  7608. this.isRenderOutputNode = true;
  7609. }
  7610. /**
  7611. * Sets the tone mapping type.
  7612. *
  7613. * @param {number} value - The tone mapping type.
  7614. * @return {ToneMappingNode} A reference to this node.
  7615. */
  7616. setToneMapping( value ) {
  7617. this._toneMapping = value;
  7618. return this;
  7619. }
  7620. /**
  7621. * Gets the tone mapping type.
  7622. *
  7623. * @returns {number} The tone mapping type.
  7624. */
  7625. getToneMapping() {
  7626. return this._toneMapping;
  7627. }
  7628. setup( { context } ) {
  7629. let outputNode = this.colorNode || context.color;
  7630. // tone mapping
  7631. const toneMapping = ( this._toneMapping !== null ? this._toneMapping : context.toneMapping ) || NoToneMapping;
  7632. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  7633. if ( toneMapping !== NoToneMapping ) {
  7634. outputNode = outputNode.toneMapping( toneMapping );
  7635. }
  7636. // working to output color space
  7637. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  7638. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  7639. }
  7640. return outputNode;
  7641. }
  7642. }
  7643. /**
  7644. * TSL function for creating a posterize node.
  7645. *
  7646. * @tsl
  7647. * @function
  7648. * @param {Node} color - The color node to process.
  7649. * @param {?number} [toneMapping=null] - The tone mapping type.
  7650. * @param {?string} [outputColorSpace=null] - The output color space.
  7651. * @returns {RenderOutputNode}
  7652. */
  7653. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  7654. addMethodChaining( 'renderOutput', renderOutput );
  7655. class DebugNode extends TempNode {
  7656. static get type() {
  7657. return 'DebugNode';
  7658. }
  7659. constructor( node, callback = null ) {
  7660. super();
  7661. this.node = node;
  7662. this.callback = callback;
  7663. }
  7664. getNodeType( builder ) {
  7665. return this.node.getNodeType( builder );
  7666. }
  7667. setup( builder ) {
  7668. return this.node.build( builder );
  7669. }
  7670. analyze( builder ) {
  7671. return this.node.build( builder );
  7672. }
  7673. generate( builder ) {
  7674. const callback = this.callback;
  7675. const snippet = this.node.build( builder );
  7676. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  7677. const border = '-'.repeat( title.length );
  7678. let code = '';
  7679. code += '// #' + title + '#\n';
  7680. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  7681. code += '/* ... */ ' + snippet + ' /* ... */\n';
  7682. code += '// #' + border + '#\n';
  7683. if ( callback !== null ) {
  7684. callback( builder, code );
  7685. } else {
  7686. log$1( code );
  7687. }
  7688. return snippet;
  7689. }
  7690. }
  7691. /**
  7692. * TSL function for creating a debug node.
  7693. *
  7694. * @tsl
  7695. * @function
  7696. * @param {Node} node - The node to debug.
  7697. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  7698. * @returns {DebugNode}
  7699. */
  7700. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) ).toStack();
  7701. addMethodChaining( 'debug', debug );
  7702. /**
  7703. * InspectorBase is the base class for all inspectors.
  7704. *
  7705. * @class InspectorBase
  7706. */
  7707. class InspectorBase {
  7708. /**
  7709. * Creates a new InspectorBase.
  7710. */
  7711. constructor() {
  7712. /**
  7713. * The renderer associated with this inspector.
  7714. *
  7715. * @type {WebGLRenderer}
  7716. * @private
  7717. */
  7718. this._renderer = null;
  7719. /**
  7720. * The current frame being processed.
  7721. *
  7722. * @type {Object}
  7723. */
  7724. this.currentFrame = null;
  7725. }
  7726. /**
  7727. * Returns the node frame for the current renderer.
  7728. *
  7729. * @return {Object} The node frame.
  7730. */
  7731. get nodeFrame() {
  7732. return this._renderer._nodes.nodeFrame;
  7733. }
  7734. /**
  7735. * Sets the renderer for this inspector.
  7736. *
  7737. * @param {WebGLRenderer} renderer - The renderer to associate with this inspector.
  7738. * @return {InspectorBase} This inspector instance.
  7739. */
  7740. setRenderer( renderer ) {
  7741. this._renderer = renderer;
  7742. return this;
  7743. }
  7744. /**
  7745. * Returns the renderer associated with this inspector.
  7746. *
  7747. * @return {WebGLRenderer} The associated renderer.
  7748. */
  7749. getRenderer() {
  7750. return this._renderer;
  7751. }
  7752. /**
  7753. * Initializes the inspector.
  7754. */
  7755. init() { }
  7756. /**
  7757. * Called when a frame begins.
  7758. */
  7759. begin() { }
  7760. /**
  7761. * Called when a frame ends.
  7762. */
  7763. finish() { }
  7764. /**
  7765. * Inspects a node.
  7766. *
  7767. * @param {Node} node - The node to inspect.
  7768. */
  7769. inspect( /*node*/ ) { }
  7770. /**
  7771. * When a compute operation is performed.
  7772. *
  7773. * @param {ComputeNode} computeNode - The compute node being executed.
  7774. * @param {number|Array<number>} dispatchSizeOrCount - The dispatch size or count.
  7775. */
  7776. computeAsync( /*computeNode, dispatchSizeOrCount*/ ) { }
  7777. /**
  7778. * Called when a compute operation begins.
  7779. *
  7780. * @param {string} uid - A unique identifier for the render context.
  7781. * @param {ComputeNode} computeNode - The compute node being executed.
  7782. */
  7783. beginCompute( /*uid, computeNode*/ ) { }
  7784. /**
  7785. * Called when a compute operation ends.
  7786. *
  7787. * @param {string} uid - A unique identifier for the render context.
  7788. * @param {ComputeNode} computeNode - The compute node being executed.
  7789. */
  7790. finishCompute( /*uid*/ ) { }
  7791. /**
  7792. * Called when a render operation begins.
  7793. *
  7794. * @param {string} uid - A unique identifier for the render context.
  7795. * @param {Scene} scene - The scene being rendered.
  7796. * @param {Camera} camera - The camera being used for rendering.
  7797. * @param {?WebGLRenderTarget} renderTarget - The render target, if any.
  7798. */
  7799. beginRender( /*uid, scene, camera, renderTarget*/ ) { }
  7800. /**
  7801. * Called when an animation loop ends.
  7802. *
  7803. * @param {string} uid - A unique identifier for the render context.
  7804. */
  7805. finishRender( /*uid*/ ) { }
  7806. /**
  7807. * Called when a texture copy operation is performed.
  7808. *
  7809. * @param {Texture} srcTexture - The source texture.
  7810. * @param {Texture} dstTexture - The destination texture.
  7811. */
  7812. copyTextureToTexture( /*srcTexture, dstTexture*/ ) { }
  7813. /**
  7814. * Called when a framebuffer copy operation is performed.
  7815. *
  7816. * @param {Texture} framebufferTexture - The texture associated with the framebuffer.
  7817. */
  7818. copyFramebufferToTexture( /*framebufferTexture*/ ) { }
  7819. }
  7820. /**
  7821. * InspectorNode is a wrapper node that allows inspection of node values during rendering.
  7822. * It can be used to debug or analyze node outputs in the rendering pipeline.
  7823. *
  7824. * @augments Node
  7825. */
  7826. class InspectorNode extends Node {
  7827. /**
  7828. * Returns the type of the node.
  7829. *
  7830. * @returns {string}
  7831. */
  7832. static get type() {
  7833. return 'InspectorNode';
  7834. }
  7835. /**
  7836. * Creates an InspectorNode.
  7837. *
  7838. * @param {Node} node - The node to inspect.
  7839. * @param {string} [name=''] - Optional name for the inspector node.
  7840. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7841. */
  7842. constructor( node, name = '', callback = null ) {
  7843. super();
  7844. this.node = node;
  7845. this.name = name;
  7846. this.callback = callback;
  7847. this.updateType = NodeUpdateType.FRAME;
  7848. this.isInspectorNode = true;
  7849. }
  7850. /**
  7851. * Returns the name of the inspector node.
  7852. *
  7853. * @returns {string}
  7854. */
  7855. getName() {
  7856. return this.name || this.node.name;
  7857. }
  7858. /**
  7859. * Updates the inspector node, allowing inspection of the wrapped node.
  7860. *
  7861. * @param {NodeFrame} frame - A reference to the current node frame.
  7862. */
  7863. update( frame ) {
  7864. frame.renderer.inspector.inspect( this );
  7865. }
  7866. /**
  7867. * Returns the type of the wrapped node.
  7868. *
  7869. * @param {NodeBuilder} builder - The node builder.
  7870. * @returns {string}
  7871. */
  7872. getNodeType( builder ) {
  7873. return this.node.getNodeType( builder );
  7874. }
  7875. /**
  7876. * Sets up the inspector node.
  7877. *
  7878. * @param {NodeBuilder} builder - The node builder.
  7879. * @returns {Node} The setup node.
  7880. */
  7881. setup( builder ) {
  7882. let node = this.node;
  7883. if ( builder.context.inspector === true && this.callback !== null ) {
  7884. node = this.callback( node );
  7885. }
  7886. if ( builder.renderer.backend.isWebGPUBackend !== true && builder.renderer.inspector.constructor !== InspectorBase ) {
  7887. warnOnce( 'TSL: ".toInspector()" is only available with WebGPU.' );
  7888. }
  7889. return node;
  7890. }
  7891. }
  7892. /**
  7893. * Creates an inspector node to wrap around a given node for inspection purposes.
  7894. *
  7895. * @tsl
  7896. * @param {Node} node - The node to inspect.
  7897. * @param {string} [name=''] - Optional name for the inspector node.
  7898. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7899. * @returns {Node} The inspector node.
  7900. */
  7901. function inspector( node, name = '', callback = null ) {
  7902. node = nodeObject( node );
  7903. return node.before( new InspectorNode( node, name, callback ) );
  7904. }
  7905. addMethodChaining( 'toInspector', inspector );
  7906. function addNodeElement( name/*, nodeElement*/ ) {
  7907. warn( 'TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  7908. }
  7909. /**
  7910. * Base class for representing shader attributes as nodes.
  7911. *
  7912. * @augments Node
  7913. */
  7914. class AttributeNode extends Node {
  7915. static get type() {
  7916. return 'AttributeNode';
  7917. }
  7918. /**
  7919. * Constructs a new attribute node.
  7920. *
  7921. * @param {string} attributeName - The name of the attribute.
  7922. * @param {?string} nodeType - The node type.
  7923. */
  7924. constructor( attributeName, nodeType = null ) {
  7925. super( nodeType );
  7926. /**
  7927. * `AttributeNode` sets this property to `true` by default.
  7928. *
  7929. * @type {boolean}
  7930. * @default true
  7931. */
  7932. this.global = true;
  7933. this._attributeName = attributeName;
  7934. }
  7935. getHash( builder ) {
  7936. return this.getAttributeName( builder );
  7937. }
  7938. getNodeType( builder ) {
  7939. let nodeType = this.nodeType;
  7940. if ( nodeType === null ) {
  7941. const attributeName = this.getAttributeName( builder );
  7942. if ( builder.hasGeometryAttribute( attributeName ) ) {
  7943. const attribute = builder.geometry.getAttribute( attributeName );
  7944. nodeType = builder.getTypeFromAttribute( attribute );
  7945. } else {
  7946. nodeType = 'float';
  7947. }
  7948. }
  7949. return nodeType;
  7950. }
  7951. /**
  7952. * Sets the attribute name to the given value. The method can be
  7953. * overwritten in derived classes if the final name must be computed
  7954. * analytically.
  7955. *
  7956. * @param {string} attributeName - The name of the attribute.
  7957. * @return {AttributeNode} A reference to this node.
  7958. */
  7959. setAttributeName( attributeName ) {
  7960. this._attributeName = attributeName;
  7961. return this;
  7962. }
  7963. /**
  7964. * Returns the attribute name of this node. The method can be
  7965. * overwritten in derived classes if the final name must be computed
  7966. * analytically.
  7967. *
  7968. * @param {NodeBuilder} builder - The current node builder.
  7969. * @return {string} The attribute name.
  7970. */
  7971. getAttributeName( /*builder*/ ) {
  7972. return this._attributeName;
  7973. }
  7974. generate( builder ) {
  7975. const attributeName = this.getAttributeName( builder );
  7976. const nodeType = this.getNodeType( builder );
  7977. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  7978. if ( geometryAttribute === true ) {
  7979. const attribute = builder.geometry.getAttribute( attributeName );
  7980. const attributeType = builder.getTypeFromAttribute( attribute );
  7981. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  7982. if ( builder.shaderStage === 'vertex' ) {
  7983. return builder.format( nodeAttribute.name, attributeType, nodeType );
  7984. } else {
  7985. const nodeVarying = varying( this );
  7986. return nodeVarying.build( builder, nodeType );
  7987. }
  7988. } else {
  7989. warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  7990. return builder.generateConst( nodeType );
  7991. }
  7992. }
  7993. serialize( data ) {
  7994. super.serialize( data );
  7995. data.global = this.global;
  7996. data._attributeName = this._attributeName;
  7997. }
  7998. deserialize( data ) {
  7999. super.deserialize( data );
  8000. this.global = data.global;
  8001. this._attributeName = data._attributeName;
  8002. }
  8003. }
  8004. /**
  8005. * TSL function for creating an attribute node.
  8006. *
  8007. * @tsl
  8008. * @function
  8009. * @param {string} name - The name of the attribute.
  8010. * @param {?string} [nodeType=null] - The node type.
  8011. * @returns {AttributeNode}
  8012. */
  8013. const attribute = ( name, nodeType = null ) => new AttributeNode( name, nodeType );
  8014. /**
  8015. * TSL function for creating an uv attribute node with the given index.
  8016. *
  8017. * @tsl
  8018. * @function
  8019. * @param {number} [index=0] - The uv index.
  8020. * @return {AttributeNode<vec2>} The uv attribute node.
  8021. */
  8022. const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  8023. /**
  8024. * A node that represents the dimensions of a texture. The texture size is
  8025. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  8026. * or `textureSize()`.
  8027. *
  8028. * @augments Node
  8029. */
  8030. class TextureSizeNode extends Node {
  8031. static get type() {
  8032. return 'TextureSizeNode';
  8033. }
  8034. /**
  8035. * Constructs a new texture size node.
  8036. *
  8037. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  8038. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  8039. */
  8040. constructor( textureNode, levelNode = null ) {
  8041. super( 'uvec2' );
  8042. /**
  8043. * This flag can be used for type testing.
  8044. *
  8045. * @type {boolean}
  8046. * @readonly
  8047. * @default true
  8048. */
  8049. this.isTextureSizeNode = true;
  8050. /**
  8051. * A texture node which size should be retrieved.
  8052. *
  8053. * @type {TextureNode}
  8054. */
  8055. this.textureNode = textureNode;
  8056. /**
  8057. * A level node which defines the requested mip.
  8058. *
  8059. * @type {Node<int>}
  8060. * @default null
  8061. */
  8062. this.levelNode = levelNode;
  8063. }
  8064. generate( builder, output ) {
  8065. const textureProperty = this.textureNode.build( builder, 'property' );
  8066. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  8067. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  8068. }
  8069. }
  8070. /**
  8071. * TSL function for creating a texture size node.
  8072. *
  8073. * @tsl
  8074. * @function
  8075. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  8076. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  8077. * @returns {TextureSizeNode}
  8078. */
  8079. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  8080. /**
  8081. * A special type of uniform node that computes the
  8082. * maximum mipmap level for a given texture node.
  8083. *
  8084. * ```js
  8085. * const level = maxMipLevel( textureNode );
  8086. * ```
  8087. *
  8088. * @augments UniformNode
  8089. */
  8090. class MaxMipLevelNode extends UniformNode {
  8091. static get type() {
  8092. return 'MaxMipLevelNode';
  8093. }
  8094. /**
  8095. * Constructs a new max mip level node.
  8096. *
  8097. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  8098. */
  8099. constructor( textureNode ) {
  8100. super( 0 );
  8101. /**
  8102. * The texture node to compute the max mip level for.
  8103. *
  8104. * @private
  8105. * @type {TextureNode}
  8106. */
  8107. this._textureNode = textureNode;
  8108. /**
  8109. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  8110. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  8111. *
  8112. * @type {string}
  8113. * @default 'frame'
  8114. */
  8115. this.updateType = NodeUpdateType.FRAME;
  8116. }
  8117. /**
  8118. * The texture node to compute the max mip level for.
  8119. *
  8120. * @readonly
  8121. * @type {TextureNode}
  8122. */
  8123. get textureNode() {
  8124. return this._textureNode;
  8125. }
  8126. /**
  8127. * The texture.
  8128. *
  8129. * @readonly
  8130. * @type {Texture}
  8131. */
  8132. get texture() {
  8133. return this._textureNode.value;
  8134. }
  8135. update() {
  8136. const texture = this.texture;
  8137. const images = texture.images;
  8138. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  8139. if ( image && image.width !== undefined ) {
  8140. const { width, height } = image;
  8141. this.value = Math.log2( Math.max( width, height ) );
  8142. }
  8143. }
  8144. }
  8145. /**
  8146. * TSL function for creating a max mip level node.
  8147. *
  8148. * @tsl
  8149. * @function
  8150. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  8151. * @returns {MaxMipLevelNode}
  8152. */
  8153. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  8154. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  8155. /**
  8156. * This type of uniform node represents a 2D texture.
  8157. *
  8158. * @augments UniformNode
  8159. */
  8160. class TextureNode extends UniformNode {
  8161. static get type() {
  8162. return 'TextureNode';
  8163. }
  8164. /**
  8165. * Constructs a new texture node.
  8166. *
  8167. * @param {Texture} [value=EmptyTexture] - The texture.
  8168. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8169. * @param {?Node<int>} [levelNode=null] - The level node.
  8170. * @param {?Node<float>} [biasNode=null] - The bias node.
  8171. */
  8172. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  8173. super( value );
  8174. /**
  8175. * This flag can be used for type testing.
  8176. *
  8177. * @type {boolean}
  8178. * @readonly
  8179. * @default true
  8180. */
  8181. this.isTextureNode = true;
  8182. /**
  8183. * Represents the texture coordinates.
  8184. *
  8185. * @type {?Node<vec2|vec3>}
  8186. * @default null
  8187. */
  8188. this.uvNode = uvNode;
  8189. /**
  8190. * Represents the mip level that should be selected.
  8191. *
  8192. * @type {?Node<int>}
  8193. * @default null
  8194. */
  8195. this.levelNode = levelNode;
  8196. /**
  8197. * Represents the bias to be applied during level-of-detail computation.
  8198. *
  8199. * @type {?Node<float>}
  8200. * @default null
  8201. */
  8202. this.biasNode = biasNode;
  8203. /**
  8204. * Represents a reference value a texture sample is compared to.
  8205. *
  8206. * @type {?Node<float>}
  8207. * @default null
  8208. */
  8209. this.compareNode = null;
  8210. /**
  8211. * When using texture arrays, the depth node defines the layer to select.
  8212. *
  8213. * @type {?Node<int>}
  8214. * @default null
  8215. */
  8216. this.depthNode = null;
  8217. /**
  8218. * When defined, a texture is sampled using explicit gradients.
  8219. *
  8220. * @type {?Array<Node<vec2>>}
  8221. * @default null
  8222. */
  8223. this.gradNode = null;
  8224. /**
  8225. * Represents the optional texel offset applied to the unnormalized texture
  8226. * coordinate before sampling the texture.
  8227. *
  8228. * @type {?Node<ivec2|ivec3>}
  8229. * @default null
  8230. */
  8231. this.offsetNode = null;
  8232. /**
  8233. * Whether texture values should be sampled or fetched.
  8234. *
  8235. * @type {boolean}
  8236. * @default true
  8237. */
  8238. this.sampler = true;
  8239. /**
  8240. * Whether the uv transformation matrix should be
  8241. * automatically updated or not. Use `setUpdateMatrix()`
  8242. * if you want to change the value of the property.
  8243. *
  8244. * @type {boolean}
  8245. * @default false
  8246. */
  8247. this.updateMatrix = false;
  8248. /**
  8249. * By default the `update()` method is not executed. Depending on
  8250. * whether a uv transformation matrix and/or flipY is applied, `update()`
  8251. * is executed per object.
  8252. *
  8253. * @type {string}
  8254. * @default 'none'
  8255. */
  8256. this.updateType = NodeUpdateType.NONE;
  8257. /**
  8258. * The reference node.
  8259. *
  8260. * @type {?Node}
  8261. * @default null
  8262. */
  8263. this.referenceNode = null;
  8264. /**
  8265. * The texture value is stored in a private property.
  8266. *
  8267. * @private
  8268. * @type {Texture}
  8269. */
  8270. this._value = value;
  8271. /**
  8272. * The uniform node that represents the uv transformation matrix.
  8273. *
  8274. * @private
  8275. * @type {?UniformNode<mat3>}
  8276. * @default null
  8277. */
  8278. this._matrixUniform = null;
  8279. /**
  8280. * The uniform node that represents the y-flip. Only required for WebGL.
  8281. *
  8282. * @private
  8283. * @type {?UniformNode<bool>}
  8284. * @default null
  8285. */
  8286. this._flipYUniform = null;
  8287. this.setUpdateMatrix( uvNode === null );
  8288. }
  8289. set value( value ) {
  8290. if ( this.referenceNode ) {
  8291. this.referenceNode.value = value;
  8292. } else {
  8293. this._value = value;
  8294. }
  8295. }
  8296. /**
  8297. * The texture value.
  8298. *
  8299. * @type {Texture}
  8300. */
  8301. get value() {
  8302. return this.referenceNode ? this.referenceNode.value : this._value;
  8303. }
  8304. /**
  8305. * Overwritten since the uniform hash is defined by the texture's UUID.
  8306. *
  8307. * @param {NodeBuilder} builder - The current node builder.
  8308. * @return {string} The uniform hash.
  8309. */
  8310. getUniformHash( /*builder*/ ) {
  8311. return this.value.uuid;
  8312. }
  8313. /**
  8314. * Overwritten since the node type is inferred from the texture type.
  8315. *
  8316. * @param {NodeBuilder} builder - The current node builder.
  8317. * @return {string} The node type.
  8318. */
  8319. getNodeType( /*builder*/ ) {
  8320. if ( this.value.isDepthTexture === true ) return 'float';
  8321. if ( this.value.type === UnsignedIntType ) {
  8322. return 'uvec4';
  8323. } else if ( this.value.type === IntType ) {
  8324. return 'ivec4';
  8325. }
  8326. return 'vec4';
  8327. }
  8328. /**
  8329. * Overwrites the default implementation to return a fixed value `'texture'`.
  8330. *
  8331. * @param {NodeBuilder} builder - The current node builder.
  8332. * @return {string} The input type.
  8333. */
  8334. getInputType( /*builder*/ ) {
  8335. return 'texture';
  8336. }
  8337. /**
  8338. * Returns a default uvs based on the current texture's channel.
  8339. *
  8340. * @return {AttributeNode<vec2>} The default uvs.
  8341. */
  8342. getDefaultUV() {
  8343. return uv$1( this.value.channel );
  8344. }
  8345. /**
  8346. * Overwritten to always return the texture reference of the node.
  8347. *
  8348. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  8349. * @return {Texture} The texture reference.
  8350. */
  8351. updateReference( /*state*/ ) {
  8352. return this.value;
  8353. }
  8354. /**
  8355. * Transforms the given uv node with the texture transformation matrix.
  8356. *
  8357. * @param {Node} uvNode - The uv node to transform.
  8358. * @return {Node} The transformed uv node.
  8359. */
  8360. getTransformedUV( uvNode ) {
  8361. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  8362. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  8363. }
  8364. /**
  8365. * Defines whether the uv transformation matrix should automatically be updated or not.
  8366. *
  8367. * @param {boolean} value - The update toggle.
  8368. * @return {TextureNode} A reference to this node.
  8369. */
  8370. setUpdateMatrix( value ) {
  8371. this.updateMatrix = value;
  8372. return this;
  8373. }
  8374. /**
  8375. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  8376. * to modify the uv node for correct sampling.
  8377. *
  8378. * @param {NodeBuilder} builder - The current node builder.
  8379. * @param {Node} uvNode - The uv node to setup.
  8380. * @return {Node} The updated uv node.
  8381. */
  8382. setupUV( builder, uvNode ) {
  8383. if ( builder.isFlipY() ) {
  8384. if ( this._flipYUniform === null ) this._flipYUniform = uniform( false );
  8385. uvNode = uvNode.toVar();
  8386. if ( this.sampler ) {
  8387. uvNode = this._flipYUniform.select( uvNode.flipY(), uvNode );
  8388. } else {
  8389. uvNode = this._flipYUniform.select( uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) ), uvNode );
  8390. }
  8391. }
  8392. return uvNode;
  8393. }
  8394. /**
  8395. * Setups texture node by preparing the internal nodes for code generation.
  8396. *
  8397. * @param {NodeBuilder} builder - The current node builder.
  8398. */
  8399. setup( builder ) {
  8400. const properties = builder.getNodeProperties( this );
  8401. properties.referenceNode = this.referenceNode;
  8402. //
  8403. const texture = this.value;
  8404. if ( ! texture || texture.isTexture !== true ) {
  8405. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  8406. }
  8407. //
  8408. const uvNode = Fn( () => {
  8409. let uvNode = this.uvNode;
  8410. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  8411. uvNode = builder.context.getUV( this, builder );
  8412. }
  8413. if ( ! uvNode ) uvNode = this.getDefaultUV();
  8414. if ( this.updateMatrix === true ) {
  8415. uvNode = this.getTransformedUV( uvNode );
  8416. }
  8417. uvNode = this.setupUV( builder, uvNode );
  8418. //
  8419. this.updateType = ( this._matrixUniform !== null || this._flipYUniform !== null ) ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  8420. //
  8421. return uvNode;
  8422. } )();
  8423. //
  8424. let levelNode = this.levelNode;
  8425. if ( levelNode === null && builder.context.getTextureLevel ) {
  8426. levelNode = builder.context.getTextureLevel( this );
  8427. }
  8428. //
  8429. properties.uvNode = uvNode;
  8430. properties.levelNode = levelNode;
  8431. properties.biasNode = this.biasNode;
  8432. properties.compareNode = this.compareNode;
  8433. properties.gradNode = this.gradNode;
  8434. properties.depthNode = this.depthNode;
  8435. properties.offsetNode = this.offsetNode;
  8436. }
  8437. /**
  8438. * Generates the uv code snippet.
  8439. *
  8440. * @param {NodeBuilder} builder - The current node builder.
  8441. * @param {Node} uvNode - The uv node to generate code for.
  8442. * @return {string} The generated code snippet.
  8443. */
  8444. generateUV( builder, uvNode ) {
  8445. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  8446. }
  8447. /**
  8448. * Generates the offset code snippet.
  8449. *
  8450. * @param {NodeBuilder} builder - The current node builder.
  8451. * @param {Node} offsetNode - The offset node to generate code for.
  8452. * @return {string} The generated code snippet.
  8453. */
  8454. generateOffset( builder, offsetNode ) {
  8455. return offsetNode.build( builder, 'ivec2' );
  8456. }
  8457. /**
  8458. * Generates the snippet for the texture sampling.
  8459. *
  8460. * @param {NodeBuilder} builder - The current node builder.
  8461. * @param {string} textureProperty - The texture property.
  8462. * @param {string} uvSnippet - The uv snippet.
  8463. * @param {?string} levelSnippet - The level snippet.
  8464. * @param {?string} biasSnippet - The bias snippet.
  8465. * @param {?string} depthSnippet - The depth snippet.
  8466. * @param {?string} compareSnippet - The compare snippet.
  8467. * @param {?Array<string>} gradSnippet - The grad snippet.
  8468. * @param {?string} offsetSnippet - The offset snippet.
  8469. * @return {string} The generated code snippet.
  8470. */
  8471. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet ) {
  8472. const texture = this.value;
  8473. let snippet;
  8474. if ( biasSnippet ) {
  8475. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet );
  8476. } else if ( gradSnippet ) {
  8477. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet );
  8478. } else if ( compareSnippet ) {
  8479. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet );
  8480. } else if ( this.sampler === false ) {
  8481. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8482. } else if ( levelSnippet ) {
  8483. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8484. } else {
  8485. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet );
  8486. }
  8487. return snippet;
  8488. }
  8489. /**
  8490. * Generates the code snippet of the texture node.
  8491. *
  8492. * @param {NodeBuilder} builder - The current node builder.
  8493. * @param {string} output - The current output.
  8494. * @return {string} The generated code snippet.
  8495. */
  8496. generate( builder, output ) {
  8497. const texture = this.value;
  8498. const properties = builder.getNodeProperties( this );
  8499. const textureProperty = super.generate( builder, 'property' );
  8500. if ( /^sampler/.test( output ) ) {
  8501. return textureProperty + '_sampler';
  8502. } else if ( builder.isReference( output ) ) {
  8503. return textureProperty;
  8504. } else {
  8505. const nodeData = builder.getDataFromNode( this );
  8506. let propertyName = nodeData.propertyName;
  8507. if ( propertyName === undefined ) {
  8508. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode, offsetNode } = properties;
  8509. const uvSnippet = this.generateUV( builder, uvNode );
  8510. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  8511. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  8512. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  8513. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  8514. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  8515. const offsetSnippet = offsetNode ? this.generateOffset( builder, offsetNode ) : null;
  8516. const nodeVar = builder.getVarFromNode( this );
  8517. propertyName = builder.getPropertyName( nodeVar );
  8518. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet );
  8519. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  8520. nodeData.snippet = snippet;
  8521. nodeData.propertyName = propertyName;
  8522. }
  8523. let snippet = propertyName;
  8524. const nodeType = this.getNodeType( builder );
  8525. if ( builder.needsToWorkingColorSpace( texture ) ) {
  8526. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  8527. }
  8528. return builder.format( snippet, nodeType, output );
  8529. }
  8530. }
  8531. /**
  8532. * Sets the sampler value.
  8533. *
  8534. * @param {boolean} value - The sampler value to set.
  8535. * @return {TextureNode} A reference to this texture node.
  8536. */
  8537. setSampler( value ) {
  8538. this.sampler = value;
  8539. return this;
  8540. }
  8541. /**
  8542. * Returns the sampler value.
  8543. *
  8544. * @return {boolean} The sampler value.
  8545. */
  8546. getSampler() {
  8547. return this.sampler;
  8548. }
  8549. // @TODO: Move to TSL
  8550. /**
  8551. * @function
  8552. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  8553. *
  8554. * @param {Node} uvNode - The uv node.
  8555. * @return {TextureNode} A texture node representing the texture sample.
  8556. */
  8557. uv( uvNode ) { // @deprecated, r172
  8558. warn( 'TextureNode: .uv() has been renamed. Use .sample() instead.' );
  8559. return this.sample( uvNode );
  8560. }
  8561. /**
  8562. * Samples the texture with the given uv node.
  8563. *
  8564. * @param {Node} uvNode - The uv node.
  8565. * @return {TextureNode} A texture node representing the texture sample.
  8566. */
  8567. sample( uvNode ) {
  8568. const textureNode = this.clone();
  8569. textureNode.uvNode = nodeObject( uvNode );
  8570. textureNode.referenceNode = this.getBase();
  8571. return nodeObject( textureNode );
  8572. }
  8573. /**
  8574. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8575. *
  8576. * @param {Node<uvec2>} uvNode - The uv node.
  8577. * @returns {TextureNode} A texture node representing the texture load.
  8578. */
  8579. load( uvNode ) {
  8580. return this.sample( uvNode ).setSampler( false );
  8581. }
  8582. /**
  8583. * Samples a blurred version of the texture by defining an internal bias.
  8584. *
  8585. * @param {Node<float>} amountNode - How blurred the texture should be.
  8586. * @return {TextureNode} A texture node representing the texture sample.
  8587. */
  8588. blur( amountNode ) {
  8589. const textureNode = this.clone();
  8590. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  8591. textureNode.referenceNode = this.getBase();
  8592. const map = textureNode.value;
  8593. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  8594. warn( 'TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  8595. textureNode.biasNode = null;
  8596. }
  8597. return nodeObject( textureNode );
  8598. }
  8599. /**
  8600. * Samples a specific mip of the texture.
  8601. *
  8602. * @param {Node<int>} levelNode - The mip level to sample.
  8603. * @return {TextureNode} A texture node representing the texture sample.
  8604. */
  8605. level( levelNode ) {
  8606. const textureNode = this.clone();
  8607. textureNode.levelNode = nodeObject( levelNode );
  8608. textureNode.referenceNode = this.getBase();
  8609. return nodeObject( textureNode );
  8610. }
  8611. /**
  8612. * Returns the texture size of the requested level.
  8613. *
  8614. * @param {Node<int>} levelNode - The level to compute the size for.
  8615. * @return {TextureSizeNode} The texture size.
  8616. */
  8617. size( levelNode ) {
  8618. return textureSize( this, levelNode );
  8619. }
  8620. /**
  8621. * Samples the texture with the given bias.
  8622. *
  8623. * @param {Node<float>} biasNode - The bias node.
  8624. * @return {TextureNode} A texture node representing the texture sample.
  8625. */
  8626. bias( biasNode ) {
  8627. const textureNode = this.clone();
  8628. textureNode.biasNode = nodeObject( biasNode );
  8629. textureNode.referenceNode = this.getBase();
  8630. return nodeObject( textureNode );
  8631. }
  8632. /**
  8633. * Returns the base texture of this node.
  8634. * @return {TextureNode} The base texture node.
  8635. */
  8636. getBase() {
  8637. return this.referenceNode ? this.referenceNode.getBase() : this;
  8638. }
  8639. /**
  8640. * Samples the texture by executing a compare operation.
  8641. *
  8642. * @param {Node<float>} compareNode - The node that defines the compare value.
  8643. * @return {TextureNode} A texture node representing the texture sample.
  8644. */
  8645. compare( compareNode ) {
  8646. const textureNode = this.clone();
  8647. textureNode.compareNode = nodeObject( compareNode );
  8648. textureNode.referenceNode = this.getBase();
  8649. return nodeObject( textureNode );
  8650. }
  8651. /**
  8652. * Samples the texture using an explicit gradient.
  8653. *
  8654. * @param {Node<vec2>} gradNodeX - The gradX node.
  8655. * @param {Node<vec2>} gradNodeY - The gradY node.
  8656. * @return {TextureNode} A texture node representing the texture sample.
  8657. */
  8658. grad( gradNodeX, gradNodeY ) {
  8659. const textureNode = this.clone();
  8660. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  8661. textureNode.referenceNode = this.getBase();
  8662. return nodeObject( textureNode );
  8663. }
  8664. /**
  8665. * Samples the texture by defining a depth node.
  8666. *
  8667. * @param {Node<int>} depthNode - The depth node.
  8668. * @return {TextureNode} A texture node representing the texture sample.
  8669. */
  8670. depth( depthNode ) {
  8671. const textureNode = this.clone();
  8672. textureNode.depthNode = nodeObject( depthNode );
  8673. textureNode.referenceNode = this.getBase();
  8674. return nodeObject( textureNode );
  8675. }
  8676. /**
  8677. * Samples the texture by defining an offset node.
  8678. *
  8679. * @param {Node<ivec2>} offsetNode - The offset node.
  8680. * @return {TextureNode} A texture node representing the texture sample.
  8681. */
  8682. offset( offsetNode ) {
  8683. const textureNode = this.clone();
  8684. textureNode.offsetNode = nodeObject( offsetNode );
  8685. textureNode.referenceNode = this.getBase();
  8686. return nodeObject( textureNode );
  8687. }
  8688. // --
  8689. serialize( data ) {
  8690. super.serialize( data );
  8691. data.value = this.value.toJSON( data.meta ).uuid;
  8692. data.sampler = this.sampler;
  8693. data.updateMatrix = this.updateMatrix;
  8694. data.updateType = this.updateType;
  8695. }
  8696. deserialize( data ) {
  8697. super.deserialize( data );
  8698. this.value = data.meta.textures[ data.value ];
  8699. this.sampler = data.sampler;
  8700. this.updateMatrix = data.updateMatrix;
  8701. this.updateType = data.updateType;
  8702. }
  8703. /**
  8704. * The update is used to implement the update of the uv transformation matrix.
  8705. */
  8706. update() {
  8707. const texture = this.value;
  8708. const matrixUniform = this._matrixUniform;
  8709. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  8710. if ( texture.matrixAutoUpdate === true ) {
  8711. texture.updateMatrix();
  8712. }
  8713. //
  8714. const flipYUniform = this._flipYUniform;
  8715. if ( flipYUniform !== null ) {
  8716. flipYUniform.value = ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true );
  8717. }
  8718. }
  8719. /**
  8720. * Clones the texture node.
  8721. *
  8722. * @return {TextureNode} The cloned texture node.
  8723. */
  8724. clone() {
  8725. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  8726. newNode.sampler = this.sampler;
  8727. newNode.depthNode = this.depthNode;
  8728. newNode.compareNode = this.compareNode;
  8729. newNode.gradNode = this.gradNode;
  8730. newNode.offsetNode = this.offsetNode;
  8731. return newNode;
  8732. }
  8733. }
  8734. /**
  8735. * TSL function for creating a texture node.
  8736. *
  8737. * @tsl
  8738. * @function
  8739. * @param {?Texture} value - The texture.
  8740. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8741. * @param {?Node<int>} [levelNode=null] - The level node.
  8742. * @param {?Node<float>} [biasNode=null] - The bias node.
  8743. * @returns {TextureNode}
  8744. */
  8745. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  8746. /**
  8747. * TSL function for creating a texture node or sample a texture node already existing.
  8748. *
  8749. * @tsl
  8750. * @function
  8751. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8752. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8753. * @param {?Node<int>} [levelNode=null] - The level node.
  8754. * @param {?Node<float>} [biasNode=null] - The bias node.
  8755. * @returns {TextureNode}
  8756. */
  8757. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  8758. let textureNode;
  8759. if ( value && value.isTextureNode === true ) {
  8760. textureNode = nodeObject( value.clone() );
  8761. textureNode.referenceNode = value.getBase(); // Ensure the reference is set to the original node
  8762. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  8763. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  8764. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  8765. } else {
  8766. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  8767. }
  8768. return textureNode;
  8769. };
  8770. /**
  8771. * TSL function for creating a uniform texture node.
  8772. *
  8773. * @tsl
  8774. * @function
  8775. * @param {?Texture} value - The texture.
  8776. * @returns {TextureNode}
  8777. */
  8778. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  8779. /**
  8780. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8781. *
  8782. * @tsl
  8783. * @function
  8784. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8785. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8786. * @param {?Node<int>} [levelNode=null] - The level node.
  8787. * @param {?Node<float>} [biasNode=null] - The bias node.
  8788. * @returns {TextureNode}
  8789. */
  8790. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  8791. const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  8792. /**
  8793. * Converts a texture or texture node to a sampler.
  8794. *
  8795. * @tsl
  8796. * @function
  8797. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8798. * @returns {Node}
  8799. */
  8800. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  8801. /**
  8802. * Converts a texture or texture node to a sampler comparison.
  8803. *
  8804. * @tsl
  8805. * @function
  8806. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8807. * @returns {Node}
  8808. */
  8809. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  8810. /**
  8811. * A special type of uniform node which represents array-like data
  8812. * as uniform buffers. The access usually happens via `element()`
  8813. * which returns an instance of {@link ArrayElementNode}. For example:
  8814. *
  8815. * ```js
  8816. * const bufferNode = buffer( array, 'mat4', count );
  8817. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  8818. * ```
  8819. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  8820. * since it handles more input types and automatically cares about buffer paddings.
  8821. *
  8822. * @augments UniformNode
  8823. */
  8824. class BufferNode extends UniformNode {
  8825. static get type() {
  8826. return 'BufferNode';
  8827. }
  8828. /**
  8829. * Constructs a new buffer node.
  8830. *
  8831. * @param {Array<number>} value - Array-like buffer data.
  8832. * @param {string} bufferType - The data type of the buffer.
  8833. * @param {number} [bufferCount=0] - The count of buffer elements.
  8834. */
  8835. constructor( value, bufferType, bufferCount = 0 ) {
  8836. super( value, bufferType );
  8837. /**
  8838. * This flag can be used for type testing.
  8839. *
  8840. * @type {boolean}
  8841. * @readonly
  8842. * @default true
  8843. */
  8844. this.isBufferNode = true;
  8845. /**
  8846. * The data type of the buffer.
  8847. *
  8848. * @type {string}
  8849. */
  8850. this.bufferType = bufferType;
  8851. /**
  8852. * The uniform node that holds the value of the reference node.
  8853. *
  8854. * @type {number}
  8855. * @default 0
  8856. */
  8857. this.bufferCount = bufferCount;
  8858. /**
  8859. * An array of update ranges.
  8860. *
  8861. * @type {Array<{start: number, count: number}>}
  8862. */
  8863. this.updateRanges = [];
  8864. }
  8865. /**
  8866. * Adds a range of data in the data array to be updated on the GPU.
  8867. *
  8868. * @param {number} start - Position at which to start update.
  8869. * @param {number} count - The number of components to update.
  8870. */
  8871. addUpdateRange( start, count ) {
  8872. this.updateRanges.push( { start, count } );
  8873. }
  8874. /**
  8875. * Clears the update ranges.
  8876. */
  8877. clearUpdateRanges() {
  8878. this.updateRanges.length = 0;
  8879. }
  8880. /**
  8881. * The data type of the buffer elements.
  8882. *
  8883. * @param {NodeBuilder} builder - The current node builder.
  8884. * @return {string} The element type.
  8885. */
  8886. getElementType( builder ) {
  8887. return this.getNodeType( builder );
  8888. }
  8889. /**
  8890. * Overwrites the default implementation to return a fixed value `'buffer'`.
  8891. *
  8892. * @param {NodeBuilder} builder - The current node builder.
  8893. * @return {string} The input type.
  8894. */
  8895. getInputType( /*builder*/ ) {
  8896. return 'buffer';
  8897. }
  8898. }
  8899. /**
  8900. * TSL function for creating a buffer node.
  8901. *
  8902. * @tsl
  8903. * @function
  8904. * @param {Array<number>} value - Array-like buffer data.
  8905. * @param {string} type - The data type of a buffer element.
  8906. * @param {number} count - The count of buffer elements.
  8907. * @returns {BufferNode}
  8908. */
  8909. const buffer = ( value, type, count ) => new BufferNode( value, type, count );
  8910. /**
  8911. * Represents the element access on uniform array nodes.
  8912. *
  8913. * @augments ArrayElementNode
  8914. */
  8915. class UniformArrayElementNode extends ArrayElementNode {
  8916. static get type() {
  8917. return 'UniformArrayElementNode';
  8918. }
  8919. /**
  8920. * Constructs a new buffer node.
  8921. *
  8922. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  8923. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  8924. */
  8925. constructor( uniformArrayNode, indexNode ) {
  8926. super( uniformArrayNode, indexNode );
  8927. /**
  8928. * This flag can be used for type testing.
  8929. *
  8930. * @type {boolean}
  8931. * @readonly
  8932. * @default true
  8933. */
  8934. this.isArrayBufferElementNode = true;
  8935. }
  8936. generate( builder ) {
  8937. const snippet = super.generate( builder );
  8938. const type = this.getNodeType();
  8939. const paddedType = this.node.getPaddedType();
  8940. return builder.format( snippet, paddedType, type );
  8941. }
  8942. }
  8943. /**
  8944. * Similar to {@link BufferNode} this module represents array-like data as
  8945. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  8946. * data types in the array (e.g `three.js` primitives) and automatically
  8947. * manage buffer padding. It should be the first choice when working with
  8948. * uniforms buffers.
  8949. * ```js
  8950. * const tintColors = uniformArray( [
  8951. * new Color( 1, 0, 0 ),
  8952. * new Color( 0, 1, 0 ),
  8953. * new Color( 0, 0, 1 )
  8954. * ], 'color' );
  8955. *
  8956. * const redColor = tintColors.element( 0 );
  8957. *
  8958. * @augments BufferNode
  8959. */
  8960. class UniformArrayNode extends BufferNode {
  8961. static get type() {
  8962. return 'UniformArrayNode';
  8963. }
  8964. /**
  8965. * Constructs a new uniform array node.
  8966. *
  8967. * @param {Array<any>} value - Array holding the buffer data.
  8968. * @param {?string} [elementType=null] - The data type of a buffer element.
  8969. */
  8970. constructor( value, elementType = null ) {
  8971. super( null );
  8972. /**
  8973. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  8974. * hold number primitives as well as three.js objects like vectors, matrices
  8975. * or colors.
  8976. *
  8977. * @type {Array<any>}
  8978. */
  8979. this.array = value;
  8980. /**
  8981. * The data type of an array element.
  8982. *
  8983. * @type {string}
  8984. */
  8985. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  8986. /**
  8987. * The padded type. Uniform buffers must conform to a certain buffer layout
  8988. * so a separate type is computed to ensure correct buffer size.
  8989. *
  8990. * @type {string}
  8991. */
  8992. this.paddedType = this.getPaddedType();
  8993. /**
  8994. * Overwritten since uniform array nodes are updated per render.
  8995. *
  8996. * @type {string}
  8997. * @default 'render'
  8998. */
  8999. this.updateType = NodeUpdateType.RENDER;
  9000. /**
  9001. * This flag can be used for type testing.
  9002. *
  9003. * @type {boolean}
  9004. * @readonly
  9005. * @default true
  9006. */
  9007. this.isArrayBufferNode = true;
  9008. }
  9009. /**
  9010. * This method is overwritten since the node type is inferred from the
  9011. * {@link UniformArrayNode#paddedType}.
  9012. *
  9013. * @param {NodeBuilder} builder - The current node builder.
  9014. * @return {string} The node type.
  9015. */
  9016. getNodeType( /*builder*/ ) {
  9017. return this.paddedType;
  9018. }
  9019. /**
  9020. * The data type of the array elements.
  9021. *
  9022. * @param {NodeBuilder} builder - The current node builder.
  9023. * @return {string} The element type.
  9024. */
  9025. getElementType() {
  9026. return this.elementType;
  9027. }
  9028. /**
  9029. * Returns the padded type based on the element type.
  9030. *
  9031. * @return {string} The padded type.
  9032. */
  9033. getPaddedType() {
  9034. const elementType = this.elementType;
  9035. let paddedType = 'vec4';
  9036. if ( elementType === 'mat2' ) {
  9037. paddedType = 'mat2';
  9038. } else if ( /mat/.test( elementType ) === true ) {
  9039. paddedType = 'mat4';
  9040. } else if ( elementType.charAt( 0 ) === 'i' ) {
  9041. paddedType = 'ivec4';
  9042. } else if ( elementType.charAt( 0 ) === 'u' ) {
  9043. paddedType = 'uvec4';
  9044. }
  9045. return paddedType;
  9046. }
  9047. /**
  9048. * The update makes sure to correctly transfer the data from the (complex) objects
  9049. * in the array to the internal, correctly padded value buffer.
  9050. *
  9051. * @param {NodeFrame} frame - A reference to the current node frame.
  9052. */
  9053. update( /*frame*/ ) {
  9054. const { array, value } = this;
  9055. const elementType = this.elementType;
  9056. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  9057. for ( let i = 0; i < array.length; i ++ ) {
  9058. const index = i * 4;
  9059. value[ index ] = array[ i ];
  9060. }
  9061. } else if ( elementType === 'color' ) {
  9062. for ( let i = 0; i < array.length; i ++ ) {
  9063. const index = i * 4;
  9064. const vector = array[ i ];
  9065. value[ index ] = vector.r;
  9066. value[ index + 1 ] = vector.g;
  9067. value[ index + 2 ] = vector.b || 0;
  9068. //value[ index + 3 ] = vector.a || 0;
  9069. }
  9070. } else if ( elementType === 'mat2' ) {
  9071. for ( let i = 0; i < array.length; i ++ ) {
  9072. const index = i * 4;
  9073. const matrix = array[ i ];
  9074. value[ index ] = matrix.elements[ 0 ];
  9075. value[ index + 1 ] = matrix.elements[ 1 ];
  9076. value[ index + 2 ] = matrix.elements[ 2 ];
  9077. value[ index + 3 ] = matrix.elements[ 3 ];
  9078. }
  9079. } else if ( elementType === 'mat3' ) {
  9080. for ( let i = 0; i < array.length; i ++ ) {
  9081. const index = i * 16;
  9082. const matrix = array[ i ];
  9083. value[ index ] = matrix.elements[ 0 ];
  9084. value[ index + 1 ] = matrix.elements[ 1 ];
  9085. value[ index + 2 ] = matrix.elements[ 2 ];
  9086. value[ index + 4 ] = matrix.elements[ 3 ];
  9087. value[ index + 5 ] = matrix.elements[ 4 ];
  9088. value[ index + 6 ] = matrix.elements[ 5 ];
  9089. value[ index + 8 ] = matrix.elements[ 6 ];
  9090. value[ index + 9 ] = matrix.elements[ 7 ];
  9091. value[ index + 10 ] = matrix.elements[ 8 ];
  9092. value[ index + 15 ] = 1;
  9093. }
  9094. } else if ( elementType === 'mat4' ) {
  9095. for ( let i = 0; i < array.length; i ++ ) {
  9096. const index = i * 16;
  9097. const matrix = array[ i ];
  9098. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  9099. value[ index + i ] = matrix.elements[ i ];
  9100. }
  9101. }
  9102. } else {
  9103. for ( let i = 0; i < array.length; i ++ ) {
  9104. const index = i * 4;
  9105. const vector = array[ i ];
  9106. value[ index ] = vector.x;
  9107. value[ index + 1 ] = vector.y;
  9108. value[ index + 2 ] = vector.z || 0;
  9109. value[ index + 3 ] = vector.w || 0;
  9110. }
  9111. }
  9112. }
  9113. /**
  9114. * Implement the value buffer creation based on the array data.
  9115. *
  9116. * @param {NodeBuilder} builder - A reference to the current node builder.
  9117. * @return {null}
  9118. */
  9119. setup( builder ) {
  9120. const length = this.array.length;
  9121. const elementType = this.elementType;
  9122. let arrayType = Float32Array;
  9123. const paddedType = this.paddedType;
  9124. const paddedElementLength = builder.getTypeLength( paddedType );
  9125. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  9126. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  9127. this.value = new arrayType( length * paddedElementLength );
  9128. this.bufferCount = length;
  9129. this.bufferType = paddedType;
  9130. return super.setup( builder );
  9131. }
  9132. /**
  9133. * Overwrites the default `element()` method to provide element access
  9134. * based on {@link UniformArrayNode}.
  9135. *
  9136. * @param {IndexNode} indexNode - The index node.
  9137. * @return {UniformArrayElementNode}
  9138. */
  9139. element( indexNode ) {
  9140. return new UniformArrayElementNode( this, nodeObject( indexNode ) );
  9141. }
  9142. }
  9143. /**
  9144. * TSL function for creating an uniform array node.
  9145. *
  9146. * @tsl
  9147. * @function
  9148. * @param {Array<any>} values - Array-like data.
  9149. * @param {?string} [nodeType] - The data type of the array elements.
  9150. * @returns {UniformArrayNode}
  9151. */
  9152. const uniformArray = ( values, nodeType ) => new UniformArrayNode( values, nodeType );
  9153. /**
  9154. * The node allows to set values for built-in shader variables. That is
  9155. * required for features like hardware-accelerated vertex clipping.
  9156. *
  9157. * @augments Node
  9158. */
  9159. class BuiltinNode extends Node {
  9160. /**
  9161. * Constructs a new builtin node.
  9162. *
  9163. * @param {string} name - The name of the built-in shader variable.
  9164. */
  9165. constructor( name ) {
  9166. super( 'float' );
  9167. /**
  9168. * The name of the built-in shader variable.
  9169. *
  9170. * @type {string}
  9171. */
  9172. this.name = name;
  9173. /**
  9174. * This flag can be used for type testing.
  9175. *
  9176. * @type {boolean}
  9177. * @readonly
  9178. * @default true
  9179. */
  9180. this.isBuiltinNode = true;
  9181. }
  9182. /**
  9183. * Generates the code snippet of the builtin node.
  9184. *
  9185. * @param {NodeBuilder} builder - The current node builder.
  9186. * @return {string} The generated code snippet.
  9187. */
  9188. generate( /* builder */ ) {
  9189. return this.name;
  9190. }
  9191. }
  9192. /**
  9193. * TSL function for creating a builtin node.
  9194. *
  9195. * @tsl
  9196. * @function
  9197. * @param {string} name - The name of the built-in shader variable.
  9198. * @returns {BuiltinNode}
  9199. */
  9200. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  9201. let _screenSizeVec, _viewportVec;
  9202. /**
  9203. * This node provides a collection of screen related metrics.
  9204. * Depending on {@link ScreenNode#scope}, the nodes can represent
  9205. * resolution or viewport data as well as fragment or uv coordinates.
  9206. *
  9207. * @augments Node
  9208. */
  9209. class ScreenNode extends Node {
  9210. static get type() {
  9211. return 'ScreenNode';
  9212. }
  9213. /**
  9214. * Constructs a new screen node.
  9215. *
  9216. * @param {('coordinate'|'viewport'|'size'|'uv'|'dpr')} scope - The node's scope.
  9217. */
  9218. constructor( scope ) {
  9219. super();
  9220. /**
  9221. * The node represents different metric depending on which scope is selected.
  9222. *
  9223. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  9224. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  9225. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  9226. * - `ScreenNode.UV`: Normalized coordinates.
  9227. * - `ScreenNode.DPR`: Device pixel ratio.
  9228. *
  9229. * @type {('coordinate'|'viewport'|'size'|'uv'|'dpr')}
  9230. */
  9231. this.scope = scope;
  9232. /**
  9233. * This output node.
  9234. *
  9235. * @private
  9236. * @type {?Node}
  9237. * @default null
  9238. */
  9239. this._output = null;
  9240. /**
  9241. * This flag can be used for type testing.
  9242. *
  9243. * @type {boolean}
  9244. * @readonly
  9245. * @default true
  9246. */
  9247. this.isViewportNode = true;
  9248. }
  9249. /**
  9250. * This method is overwritten since the node type depends on the selected scope.
  9251. *
  9252. * @return {('float'|'vec2'|'vec4')} The node type.
  9253. */
  9254. getNodeType() {
  9255. if ( this.scope === ScreenNode.DPR ) return 'float';
  9256. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  9257. else return 'vec2';
  9258. }
  9259. /**
  9260. * This method is overwritten since the node's update type depends on the selected scope.
  9261. *
  9262. * @return {NodeUpdateType} The update type.
  9263. */
  9264. getUpdateType() {
  9265. let updateType = NodeUpdateType.NONE;
  9266. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT || this.scope === ScreenNode.DPR ) {
  9267. updateType = NodeUpdateType.RENDER;
  9268. }
  9269. this.updateType = updateType;
  9270. return updateType;
  9271. }
  9272. /**
  9273. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  9274. * from the current renderer.
  9275. *
  9276. * @param {NodeFrame} frame - A reference to the current node frame.
  9277. */
  9278. update( { renderer } ) {
  9279. const renderTarget = renderer.getRenderTarget();
  9280. if ( this.scope === ScreenNode.VIEWPORT ) {
  9281. if ( renderTarget !== null ) {
  9282. _viewportVec.copy( renderTarget.viewport );
  9283. } else {
  9284. renderer.getViewport( _viewportVec );
  9285. _viewportVec.multiplyScalar( renderer.getPixelRatio() );
  9286. }
  9287. } else if ( this.scope === ScreenNode.DPR ) {
  9288. this._output.value = renderer.getPixelRatio();
  9289. } else {
  9290. if ( renderTarget !== null ) {
  9291. _screenSizeVec.width = renderTarget.width;
  9292. _screenSizeVec.height = renderTarget.height;
  9293. } else {
  9294. renderer.getDrawingBufferSize( _screenSizeVec );
  9295. }
  9296. }
  9297. }
  9298. setup( /*builder*/ ) {
  9299. const scope = this.scope;
  9300. let output = null;
  9301. if ( scope === ScreenNode.SIZE ) {
  9302. output = uniform( _screenSizeVec || ( _screenSizeVec = new Vector2() ) );
  9303. } else if ( scope === ScreenNode.VIEWPORT ) {
  9304. output = uniform( _viewportVec || ( _viewportVec = new Vector4() ) );
  9305. } else if ( scope === ScreenNode.DPR ) {
  9306. output = uniform( 1 );
  9307. } else {
  9308. output = vec2( screenCoordinate.div( screenSize ) );
  9309. }
  9310. this._output = output;
  9311. return output;
  9312. }
  9313. generate( builder ) {
  9314. if ( this.scope === ScreenNode.COORDINATE ) {
  9315. let coord = builder.getFragCoord();
  9316. if ( builder.isFlipY() ) {
  9317. // follow webgpu standards
  9318. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  9319. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  9320. }
  9321. return coord;
  9322. }
  9323. return super.generate( builder );
  9324. }
  9325. }
  9326. ScreenNode.COORDINATE = 'coordinate';
  9327. ScreenNode.VIEWPORT = 'viewport';
  9328. ScreenNode.SIZE = 'size';
  9329. ScreenNode.UV = 'uv';
  9330. ScreenNode.DPR = 'dpr';
  9331. // Screen
  9332. /**
  9333. * TSL object that represents the current DPR.
  9334. *
  9335. * @tsl
  9336. * @type {ScreenNode<float>}
  9337. */
  9338. const screenDPR = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.DPR );
  9339. /**
  9340. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  9341. *
  9342. * @tsl
  9343. * @type {ScreenNode<vec2>}
  9344. */
  9345. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  9346. /**
  9347. * TSL object that represents the screen resolution in physical pixel units.
  9348. *
  9349. * @tsl
  9350. * @type {ScreenNode<vec2>}
  9351. */
  9352. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  9353. /**
  9354. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  9355. *
  9356. * @tsl
  9357. * @type {ScreenNode<vec2>}
  9358. */
  9359. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  9360. // Viewport
  9361. /**
  9362. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  9363. *
  9364. * @tsl
  9365. * @type {ScreenNode<vec4>}
  9366. */
  9367. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  9368. /**
  9369. * TSL object that represents the viewport resolution in physical pixel units.
  9370. *
  9371. * @tsl
  9372. * @type {ScreenNode<vec2>}
  9373. */
  9374. const viewportSize = viewport.zw;
  9375. /**
  9376. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  9377. *
  9378. * @tsl
  9379. * @type {ScreenNode<vec2>}
  9380. */
  9381. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  9382. /**
  9383. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  9384. *
  9385. * @tsl
  9386. * @type {ScreenNode<vec2>}
  9387. */
  9388. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  9389. // Deprecated
  9390. /**
  9391. * @deprecated since r169. Use {@link screenSize} instead.
  9392. */
  9393. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  9394. warn( 'TSL: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  9395. return screenSize;
  9396. }, 'vec2' ).once() )();
  9397. /**
  9398. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  9399. *
  9400. * @tsl
  9401. * @type {UniformNode<uint>}
  9402. */
  9403. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setName( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  9404. /**
  9405. * TSL object that represents the `near` value of the camera used for the current render.
  9406. *
  9407. * @tsl
  9408. * @type {UniformNode<float>}
  9409. */
  9410. const cameraNear = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  9411. /**
  9412. * TSL object that represents the `far` value of the camera used for the current render.
  9413. *
  9414. * @tsl
  9415. * @type {UniformNode<float>}
  9416. */
  9417. const cameraFar = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  9418. /**
  9419. * TSL object that represents the projection matrix of the camera used for the current render.
  9420. *
  9421. * @tsl
  9422. * @type {UniformNode<mat4>}
  9423. */
  9424. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9425. let cameraProjectionMatrix;
  9426. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9427. const matrices = [];
  9428. for ( const subCamera of camera.cameras ) {
  9429. matrices.push( subCamera.projectionMatrix );
  9430. }
  9431. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatrices' );
  9432. cameraProjectionMatrix = cameraProjectionMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrix' );
  9433. } else {
  9434. cameraProjectionMatrix = uniform( 'mat4' ).setName( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  9435. }
  9436. return cameraProjectionMatrix;
  9437. } ).once() )();
  9438. /**
  9439. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  9440. *
  9441. * @tsl
  9442. * @type {UniformNode<mat4>}
  9443. */
  9444. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9445. let cameraProjectionMatrixInverse;
  9446. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9447. const matrices = [];
  9448. for ( const subCamera of camera.cameras ) {
  9449. matrices.push( subCamera.projectionMatrixInverse );
  9450. }
  9451. const cameraProjectionMatricesInverse = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatricesInverse' );
  9452. cameraProjectionMatrixInverse = cameraProjectionMatricesInverse.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrixInverse' );
  9453. } else {
  9454. cameraProjectionMatrixInverse = uniform( 'mat4' ).setName( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  9455. }
  9456. return cameraProjectionMatrixInverse;
  9457. } ).once() )();
  9458. /**
  9459. * TSL object that represents the view matrix of the camera used for the current render.
  9460. *
  9461. * @tsl
  9462. * @type {UniformNode<mat4>}
  9463. */
  9464. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9465. let cameraViewMatrix;
  9466. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9467. const matrices = [];
  9468. for ( const subCamera of camera.cameras ) {
  9469. matrices.push( subCamera.matrixWorldInverse );
  9470. }
  9471. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraViewMatrices' );
  9472. cameraViewMatrix = cameraViewMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraViewMatrix' );
  9473. } else {
  9474. cameraViewMatrix = uniform( 'mat4' ).setName( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  9475. }
  9476. return cameraViewMatrix;
  9477. } ).once() )();
  9478. /**
  9479. * TSL object that represents the world matrix of the camera used for the current render.
  9480. *
  9481. * @tsl
  9482. * @type {UniformNode<mat4>}
  9483. */
  9484. const cameraWorldMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9485. let cameraWorldMatrix;
  9486. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9487. const matrices = [];
  9488. for ( const subCamera of camera.cameras ) {
  9489. matrices.push( subCamera.matrixWorld );
  9490. }
  9491. const cameraWorldMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraWorldMatrices' );
  9492. cameraWorldMatrix = cameraWorldMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraWorldMatrix' );
  9493. } else {
  9494. cameraWorldMatrix = uniform( 'mat4' ).setName( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  9495. }
  9496. return cameraWorldMatrix;
  9497. } ).once() )();
  9498. /**
  9499. * TSL object that represents the normal matrix of the camera used for the current render.
  9500. *
  9501. * @tsl
  9502. * @type {UniformNode<mat3>}
  9503. */
  9504. const cameraNormalMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9505. let cameraNormalMatrix;
  9506. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9507. const matrices = [];
  9508. for ( const subCamera of camera.cameras ) {
  9509. matrices.push( subCamera.normalMatrix );
  9510. }
  9511. const cameraNormalMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraNormalMatrices' );
  9512. cameraNormalMatrix = cameraNormalMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraNormalMatrix' );
  9513. } else {
  9514. cameraNormalMatrix = uniform( 'mat3' ).setName( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  9515. }
  9516. return cameraNormalMatrix;
  9517. } ).once() )();
  9518. /**
  9519. * TSL object that represents the position in world space of the camera used for the current render.
  9520. *
  9521. * @tsl
  9522. * @type {UniformNode<vec3>}
  9523. */
  9524. const cameraPosition = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9525. let cameraPosition;
  9526. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9527. const positions = [];
  9528. for ( let i = 0, l = camera.cameras.length; i < l; i ++ ) {
  9529. positions.push( new Vector3() );
  9530. }
  9531. const cameraPositions = uniformArray( positions ).setGroup( renderGroup ).setName( 'cameraPositions' ).onRenderUpdate( ( { camera }, self ) => {
  9532. const subCameras = camera.cameras;
  9533. const array = self.array;
  9534. for ( let i = 0, l = subCameras.length; i < l; i ++ ) {
  9535. array[ i ].setFromMatrixPosition( subCameras[ i ].matrixWorld );
  9536. }
  9537. } );
  9538. cameraPosition = cameraPositions.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraPosition' );
  9539. } else {
  9540. cameraPosition = uniform( new Vector3() ).setName( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  9541. }
  9542. return cameraPosition;
  9543. } ).once() )();
  9544. /**
  9545. * TSL object that represents the viewport of the camera used for the current render.
  9546. *
  9547. * @tsl
  9548. * @type {UniformNode<vec4>}
  9549. */
  9550. const cameraViewport = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9551. let cameraViewport;
  9552. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9553. const viewports = [];
  9554. for ( const subCamera of camera.cameras ) {
  9555. viewports.push( subCamera.viewport );
  9556. }
  9557. const cameraViewports = uniformArray( viewports, 'vec4' ).setGroup( renderGroup ).setName( 'cameraViewports' );
  9558. cameraViewport = cameraViewports.element( cameraIndex ).toConst( 'cameraViewport' );
  9559. } else {
  9560. // Fallback for single camera
  9561. cameraViewport = vec4( 0, 0, screenSize.x, screenSize.y ).toConst( 'cameraViewport' );
  9562. }
  9563. return cameraViewport;
  9564. } ).once() )();
  9565. const _sphere = /*@__PURE__*/ new Sphere();
  9566. /**
  9567. * This node can be used to access transformation related metrics of 3D objects.
  9568. * Depending on the selected scope, a different metric is represented as a uniform
  9569. * in the shader. The following scopes are supported:
  9570. *
  9571. * - `POSITION`: The object's position in world space.
  9572. * - `VIEW_POSITION`: The object's position in view/camera space.
  9573. * - `DIRECTION`: The object's direction in world space.
  9574. * - `SCALE`: The object's scale in world space.
  9575. * - `WORLD_MATRIX`: The object's matrix in world space.
  9576. *
  9577. * @augments Node
  9578. */
  9579. class Object3DNode extends Node {
  9580. static get type() {
  9581. return 'Object3DNode';
  9582. }
  9583. /**
  9584. * Constructs a new object 3D node.
  9585. *
  9586. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9587. * @param {?Object3D} [object3d=null] - The 3D object.
  9588. */
  9589. constructor( scope, object3d = null ) {
  9590. super();
  9591. /**
  9592. * The node reports a different type of transformation depending on the scope.
  9593. *
  9594. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  9595. */
  9596. this.scope = scope;
  9597. /**
  9598. * The 3D object.
  9599. *
  9600. * @type {?Object3D}
  9601. * @default null
  9602. */
  9603. this.object3d = object3d;
  9604. /**
  9605. * Overwritten since this type of node is updated per object.
  9606. *
  9607. * @type {string}
  9608. * @default 'object'
  9609. */
  9610. this.updateType = NodeUpdateType.OBJECT;
  9611. /**
  9612. * Holds the value of the node as a uniform.
  9613. *
  9614. * @type {UniformNode}
  9615. */
  9616. this.uniformNode = new UniformNode( null );
  9617. }
  9618. /**
  9619. * Overwritten since the node type is inferred from the scope.
  9620. *
  9621. * @return {('mat4'|'vec3'|'float')} The node type.
  9622. */
  9623. getNodeType() {
  9624. const scope = this.scope;
  9625. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9626. return 'mat4';
  9627. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9628. return 'vec3';
  9629. } else if ( scope === Object3DNode.RADIUS ) {
  9630. return 'float';
  9631. }
  9632. }
  9633. /**
  9634. * Updates the uniform value depending on the scope.
  9635. *
  9636. * @param {NodeFrame} frame - The current node frame.
  9637. */
  9638. update( frame ) {
  9639. const object = this.object3d;
  9640. const uniformNode = this.uniformNode;
  9641. const scope = this.scope;
  9642. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9643. uniformNode.value = object.matrixWorld;
  9644. } else if ( scope === Object3DNode.POSITION ) {
  9645. uniformNode.value = uniformNode.value || new Vector3();
  9646. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9647. } else if ( scope === Object3DNode.SCALE ) {
  9648. uniformNode.value = uniformNode.value || new Vector3();
  9649. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  9650. } else if ( scope === Object3DNode.DIRECTION ) {
  9651. uniformNode.value = uniformNode.value || new Vector3();
  9652. object.getWorldDirection( uniformNode.value );
  9653. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  9654. const camera = frame.camera;
  9655. uniformNode.value = uniformNode.value || new Vector3();
  9656. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9657. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  9658. } else if ( scope === Object3DNode.RADIUS ) {
  9659. const geometry = frame.object.geometry;
  9660. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9661. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  9662. uniformNode.value = _sphere.radius;
  9663. }
  9664. }
  9665. /**
  9666. * Generates the code snippet of the uniform node. The node type of the uniform
  9667. * node also depends on the selected scope.
  9668. *
  9669. * @param {NodeBuilder} builder - The current node builder.
  9670. * @return {string} The generated code snippet.
  9671. */
  9672. generate( builder ) {
  9673. const scope = this.scope;
  9674. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9675. this.uniformNode.nodeType = 'mat4';
  9676. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9677. this.uniformNode.nodeType = 'vec3';
  9678. } else if ( scope === Object3DNode.RADIUS ) {
  9679. this.uniformNode.nodeType = 'float';
  9680. }
  9681. return this.uniformNode.build( builder );
  9682. }
  9683. serialize( data ) {
  9684. super.serialize( data );
  9685. data.scope = this.scope;
  9686. }
  9687. deserialize( data ) {
  9688. super.deserialize( data );
  9689. this.scope = data.scope;
  9690. }
  9691. }
  9692. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  9693. Object3DNode.POSITION = 'position';
  9694. Object3DNode.SCALE = 'scale';
  9695. Object3DNode.VIEW_POSITION = 'viewPosition';
  9696. Object3DNode.DIRECTION = 'direction';
  9697. Object3DNode.RADIUS = 'radius';
  9698. /**
  9699. * TSL function for creating an object 3D node that represents the object's direction in world space.
  9700. *
  9701. * @tsl
  9702. * @function
  9703. * @param {?Object3D} [object3d] - The 3D object.
  9704. * @returns {Object3DNode<vec3>}
  9705. */
  9706. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  9707. /**
  9708. * TSL function for creating an object 3D node that represents the object's world matrix.
  9709. *
  9710. * @tsl
  9711. * @function
  9712. * @param {?Object3D} [object3d] - The 3D object.
  9713. * @returns {Object3DNode<mat4>}
  9714. */
  9715. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  9716. /**
  9717. * TSL function for creating an object 3D node that represents the object's position in world space.
  9718. *
  9719. * @tsl
  9720. * @function
  9721. * @param {?Object3D} [object3d] - The 3D object.
  9722. * @returns {Object3DNode<vec3>}
  9723. */
  9724. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  9725. /**
  9726. * TSL function for creating an object 3D node that represents the object's scale in world space.
  9727. *
  9728. * @tsl
  9729. * @function
  9730. * @param {?Object3D} [object3d] - The 3D object.
  9731. * @returns {Object3DNode<vec3>}
  9732. */
  9733. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  9734. /**
  9735. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  9736. *
  9737. * @tsl
  9738. * @function
  9739. * @param {?Object3D} [object3d] - The 3D object.
  9740. * @returns {Object3DNode<vec3>}
  9741. */
  9742. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  9743. /**
  9744. * TSL function for creating an object 3D node that represents the object's radius.
  9745. *
  9746. * @tsl
  9747. * @function
  9748. * @param {?Object3D} [object3d] - The 3D object.
  9749. * @returns {Object3DNode<float>}
  9750. */
  9751. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  9752. /**
  9753. * This type of node is a specialized version of `Object3DNode`
  9754. * with larger set of model related metrics. Unlike `Object3DNode`,
  9755. * `ModelNode` extracts the reference to the 3D object from the
  9756. * current node frame state.
  9757. *
  9758. * @augments Object3DNode
  9759. */
  9760. class ModelNode extends Object3DNode {
  9761. static get type() {
  9762. return 'ModelNode';
  9763. }
  9764. /**
  9765. * Constructs a new object model node.
  9766. *
  9767. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9768. */
  9769. constructor( scope ) {
  9770. super( scope );
  9771. }
  9772. /**
  9773. * Extracts the model reference from the frame state and then
  9774. * updates the uniform value depending on the scope.
  9775. *
  9776. * @param {NodeFrame} frame - The current node frame.
  9777. */
  9778. update( frame ) {
  9779. this.object3d = frame.object;
  9780. super.update( frame );
  9781. }
  9782. }
  9783. /**
  9784. * TSL object that represents the object's direction in world space.
  9785. *
  9786. * @tsl
  9787. * @type {ModelNode<vec3>}
  9788. */
  9789. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  9790. /**
  9791. * TSL object that represents the object's world matrix.
  9792. *
  9793. * @tsl
  9794. * @type {ModelNode<mat4>}
  9795. */
  9796. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  9797. /**
  9798. * TSL object that represents the object's position in world space.
  9799. *
  9800. * @tsl
  9801. * @type {ModelNode<vec3>}
  9802. */
  9803. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  9804. /**
  9805. * TSL object that represents the object's scale in world space.
  9806. *
  9807. * @tsl
  9808. * @type {ModelNode<vec3>}
  9809. */
  9810. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  9811. /**
  9812. * TSL object that represents the object's position in view/camera space.
  9813. *
  9814. * @tsl
  9815. * @type {ModelNode<vec3>}
  9816. */
  9817. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  9818. /**
  9819. * TSL object that represents the object's radius.
  9820. *
  9821. * @tsl
  9822. * @type {ModelNode<float>}
  9823. */
  9824. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  9825. /**
  9826. * TSL object that represents the object's normal matrix.
  9827. *
  9828. * @tsl
  9829. * @type {UniformNode<mat3>}
  9830. */
  9831. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  9832. /**
  9833. * TSL object that represents the object's inverse world matrix.
  9834. *
  9835. * @tsl
  9836. * @type {UniformNode<mat4>}
  9837. */
  9838. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  9839. /**
  9840. * TSL object that represents the object's model view matrix.
  9841. *
  9842. * @tsl
  9843. * @type {Node<mat4>}
  9844. */
  9845. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9846. return builder.context.modelViewMatrix || mediumpModelViewMatrix;
  9847. } ).once() )().toVar( 'modelViewMatrix' );
  9848. // GPU Precision
  9849. /**
  9850. * TSL object that represents the object's model view in `mediump` precision.
  9851. *
  9852. * @tsl
  9853. * @type {Node<mat4>}
  9854. */
  9855. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  9856. // CPU Precision
  9857. /**
  9858. * TSL object that represents the object's model view in `highp` precision
  9859. * which is achieved by computing the matrix in JS and not in the shader.
  9860. *
  9861. * @tsl
  9862. * @type {Node<mat4>}
  9863. */
  9864. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9865. builder.context.isHighPrecisionModelViewMatrix = true;
  9866. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  9867. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9868. } );
  9869. } ).once() )().toVar( 'highpModelViewMatrix' );
  9870. /**
  9871. * TSL object that represents the object's model normal view in `highp` precision
  9872. * which is achieved by computing the matrix in JS and not in the shader.
  9873. *
  9874. * @tsl
  9875. * @type {Node<mat3>}
  9876. */
  9877. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9878. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  9879. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  9880. if ( isHighPrecisionModelViewMatrix !== true ) {
  9881. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9882. }
  9883. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  9884. } );
  9885. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  9886. /**
  9887. * TSL object that represents the position attribute of the current rendered object.
  9888. *
  9889. * @tsl
  9890. * @type {AttributeNode<vec3>}
  9891. */
  9892. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  9893. /**
  9894. * TSL object that represents the vertex position in local space of the current rendered object.
  9895. *
  9896. * @tsl
  9897. * @type {AttributeNode<vec3>}
  9898. */
  9899. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  9900. /**
  9901. * TSL object that represents the previous vertex position in local space of the current rendered object.
  9902. * Used in context of {@link VelocityNode} for rendering motion vectors.
  9903. *
  9904. * @tsl
  9905. * @type {AttributeNode<vec3>}
  9906. */
  9907. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  9908. /**
  9909. * TSL object that represents the vertex position in world space of the current rendered object.
  9910. *
  9911. * @tsl
  9912. * @type {VaryingNode<vec3>}
  9913. */
  9914. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  9915. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getSubBuildProperty( 'v_positionWorld' ) );
  9916. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9917. /**
  9918. * TSL object that represents the position world direction of the current rendered object.
  9919. *
  9920. * @tsl
  9921. * @type {Node<vec3>}
  9922. */
  9923. const positionWorldDirection = /*@__PURE__*/ ( Fn( () => {
  9924. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' );
  9925. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  9926. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9927. /**
  9928. * TSL object that represents the vertex position in view space of the current rendered object.
  9929. *
  9930. * @tsl
  9931. * @type {VaryingNode<vec3>}
  9932. */
  9933. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  9934. return builder.context.setupPositionView().toVarying( 'v_positionView' );
  9935. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9936. /**
  9937. * TSL object that represents the position view direction of the current rendered object.
  9938. *
  9939. * @tsl
  9940. * @type {VaryingNode<vec3>}
  9941. */
  9942. const positionViewDirection = /*@__PURE__*/ ( Fn( ( builder ) => {
  9943. let output;
  9944. if ( builder.camera.isOrthographicCamera ) {
  9945. output = vec3( 0, 0, 1 );
  9946. } else {
  9947. output = positionView.negate().toVarying( 'v_positionViewDirection' ).normalize();
  9948. }
  9949. return output.toVar( 'positionViewDirection' );
  9950. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9951. /**
  9952. * This node can be used to evaluate whether a primitive is front or back facing.
  9953. *
  9954. * @augments Node
  9955. */
  9956. class FrontFacingNode extends Node {
  9957. static get type() {
  9958. return 'FrontFacingNode';
  9959. }
  9960. /**
  9961. * Constructs a new front facing node.
  9962. */
  9963. constructor() {
  9964. super( 'bool' );
  9965. /**
  9966. * This flag can be used for type testing.
  9967. *
  9968. * @type {boolean}
  9969. * @readonly
  9970. * @default true
  9971. */
  9972. this.isFrontFacingNode = true;
  9973. }
  9974. generate( builder ) {
  9975. if ( builder.shaderStage !== 'fragment' ) return 'true';
  9976. //
  9977. const { material } = builder;
  9978. if ( material.side === BackSide ) {
  9979. return 'false';
  9980. }
  9981. return builder.getFrontFacing();
  9982. }
  9983. }
  9984. /**
  9985. * TSL object that represents whether a primitive is front or back facing
  9986. *
  9987. * @tsl
  9988. * @type {FrontFacingNode<bool>}
  9989. */
  9990. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  9991. /**
  9992. * TSL object that represents the front facing status as a number instead of a bool.
  9993. * `1` means front facing, `-1` means back facing.
  9994. *
  9995. * @tsl
  9996. * @type {Node<float>}
  9997. */
  9998. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  9999. /**
  10000. * Converts a direction vector to a face direction vector based on the material's side.
  10001. *
  10002. * If the material is set to `BackSide`, the direction is inverted.
  10003. * If the material is set to `DoubleSide`, the direction is multiplied by `faceDirection`.
  10004. *
  10005. * @tsl
  10006. * @param {Node<vec3>} direction - The direction vector to convert.
  10007. * @returns {Node<vec3>} The converted direction vector.
  10008. */
  10009. const directionToFaceDirection = /*@__PURE__*/ Fn( ( [ direction ], { material } ) => {
  10010. const side = material.side;
  10011. if ( side === BackSide ) {
  10012. direction = direction.mul( -1 );
  10013. } else if ( side === DoubleSide ) {
  10014. direction = direction.mul( faceDirection );
  10015. }
  10016. return direction;
  10017. } );
  10018. /**
  10019. * TSL object that represents the normal attribute of the current rendered object in local space.
  10020. *
  10021. * @tsl
  10022. * @type {Node<vec3>}
  10023. */
  10024. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  10025. /**
  10026. * TSL object that represents the vertex normal of the current rendered object in local space.
  10027. *
  10028. * @tsl
  10029. * @type {Node<vec3>}
  10030. */
  10031. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  10032. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  10033. warn( 'TSL: Vertex attribute "normal" not found on geometry.' );
  10034. return vec3( 0, 1, 0 );
  10035. }
  10036. return normalGeometry;
  10037. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  10038. /**
  10039. * TSL object that represents the flat vertex normal of the current rendered object in view space.
  10040. *
  10041. * @tsl
  10042. * @type {Node<vec3>}
  10043. */
  10044. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  10045. /**
  10046. * TSL object that represents the vertex normal of the current rendered object in view space.
  10047. *
  10048. * @tsl
  10049. * @type {Node<vec3>}
  10050. */
  10051. const normalViewGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  10052. let node;
  10053. if ( builder.material.flatShading === true ) {
  10054. node = normalFlat;
  10055. } else {
  10056. node = transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry' ).normalize();
  10057. }
  10058. return node;
  10059. }, 'vec3' ).once() )().toVar( 'normalViewGeometry' );
  10060. /**
  10061. * TSL object that represents the vertex normal of the current rendered object in world space.
  10062. *
  10063. * @tsl
  10064. * @type {Node<vec3>}
  10065. */
  10066. const normalWorldGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  10067. let normal = normalViewGeometry.transformDirection( cameraViewMatrix );
  10068. if ( builder.material.flatShading !== true ) {
  10069. normal = normal.toVarying( 'v_normalWorldGeometry' );
  10070. }
  10071. return normal.normalize().toVar( 'normalWorldGeometry' );
  10072. }, 'vec3' ).once() )();
  10073. /**
  10074. * TSL object that represents the vertex normal of the current rendered object in view space.
  10075. *
  10076. * @tsl
  10077. * @type {Node<vec3>}
  10078. */
  10079. const normalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, material, context } ) => {
  10080. let node;
  10081. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  10082. node = normalViewGeometry;
  10083. if ( material.flatShading !== true ) {
  10084. node = directionToFaceDirection( node );
  10085. }
  10086. } else {
  10087. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  10088. node = context.setupNormal().context( { getUV: null } );
  10089. }
  10090. return node;
  10091. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'normalView' );
  10092. /**
  10093. * TSL object that represents the vertex normal of the current rendered object in world space.
  10094. *
  10095. * @tsl
  10096. * @type {Node<vec3>}
  10097. */
  10098. const normalWorld = /*@__PURE__*/ normalView.transformDirection( cameraViewMatrix ).toVar( 'normalWorld' );
  10099. /**
  10100. * TSL object that represents the clearcoat vertex normal of the current rendered object in view space.
  10101. *
  10102. * @tsl
  10103. * @type {Node<vec3>}
  10104. */
  10105. const clearcoatNormalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, context } ) => {
  10106. let node;
  10107. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  10108. node = normalView;
  10109. } else {
  10110. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  10111. node = context.setupClearcoatNormal().context( { getUV: null } );
  10112. }
  10113. return node;
  10114. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'clearcoatNormalView' );
  10115. /**
  10116. * Transforms the normal with the given matrix.
  10117. *
  10118. * @tsl
  10119. * @function
  10120. * @param {Node<vec3>} normal - The normal.
  10121. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  10122. * @return {Node<vec3>} The transformed normal.
  10123. */
  10124. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  10125. const m = mat3( matrix );
  10126. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  10127. return m.mul( transformedNormal ).xyz;
  10128. } );
  10129. /**
  10130. * Transforms the given normal from local to view space.
  10131. *
  10132. * @tsl
  10133. * @function
  10134. * @param {Node<vec3>} normal - The normal.
  10135. * @param {NodeBuilder} builder - The current node builder.
  10136. * @return {Node<vec3>} The transformed normal.
  10137. */
  10138. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  10139. const modelNormalViewMatrix = builder.context.modelNormalViewMatrix;
  10140. if ( modelNormalViewMatrix ) {
  10141. return modelNormalViewMatrix.transformDirection( normal );
  10142. }
  10143. //
  10144. const transformedNormal = modelNormalMatrix.mul( normal );
  10145. return cameraViewMatrix.transformDirection( transformedNormal );
  10146. } );
  10147. // Deprecated
  10148. /**
  10149. * TSL object that represents the transformed vertex normal of the current rendered object in view space.
  10150. *
  10151. * @tsl
  10152. * @type {Node<vec3>}
  10153. * @deprecated since r178. Use `normalView` instead.
  10154. */
  10155. const transformedNormalView = ( Fn( () => { // @deprecated, r177
  10156. warn( 'TSL: "transformedNormalView" is deprecated. Use "normalView" instead.' );
  10157. return normalView;
  10158. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10159. /**
  10160. * TSL object that represents the transformed vertex normal of the current rendered object in world space.
  10161. *
  10162. * @tsl
  10163. * @type {Node<vec3>}
  10164. * @deprecated since r178. Use `normalWorld` instead.
  10165. */
  10166. const transformedNormalWorld = ( Fn( () => { // @deprecated, r177
  10167. warn( 'TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.' );
  10168. return normalWorld;
  10169. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10170. /**
  10171. * TSL object that represents the transformed clearcoat vertex normal of the current rendered object in view space.
  10172. *
  10173. * @tsl
  10174. * @type {Node<vec3>}
  10175. * @deprecated since r178. Use `clearcoatNormalView` instead.
  10176. */
  10177. const transformedClearcoatNormalView = ( Fn( () => { // @deprecated, r177
  10178. warn( 'TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.' );
  10179. return clearcoatNormalView;
  10180. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10181. const _e1$1 = /*@__PURE__*/ new Euler();
  10182. const _m1$1 = /*@__PURE__*/ new Matrix4();
  10183. /**
  10184. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  10185. *
  10186. * @tsl
  10187. * @type {UniformNode<float>}
  10188. */
  10189. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  10190. /**
  10191. * TSL object that represents the intensity of environment maps of PBR materials.
  10192. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  10193. *
  10194. * @tsl
  10195. * @type {Node<float>}
  10196. */
  10197. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  10198. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  10199. } );
  10200. /**
  10201. * TSL object that represents the rotation of environment maps.
  10202. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  10203. * rotation of `scene.environment` instead.
  10204. *
  10205. * @tsl
  10206. * @type {Node<mat4>}
  10207. */
  10208. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  10209. return frame.material;
  10210. } ).onObjectUpdate( function ( { material, scene } ) {
  10211. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  10212. if ( rotation ) {
  10213. _e1$1.copy( rotation );
  10214. _m1$1.makeRotationFromEuler( _e1$1 );
  10215. } else {
  10216. _m1$1.identity();
  10217. }
  10218. return _m1$1;
  10219. } );
  10220. /**
  10221. * The reflect vector in view space.
  10222. *
  10223. * @tsl
  10224. * @type {Node<vec3>}
  10225. */
  10226. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( normalView );
  10227. /**
  10228. * The refract vector in view space.
  10229. *
  10230. * @tsl
  10231. * @type {Node<vec3>}
  10232. */
  10233. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( normalView, materialRefractionRatio );
  10234. /**
  10235. * Used for sampling cube maps when using cube reflection mapping.
  10236. *
  10237. * @tsl
  10238. * @type {Node<vec3>}
  10239. */
  10240. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  10241. /**
  10242. * Used for sampling cube maps when using cube refraction mapping.
  10243. *
  10244. * @tsl
  10245. * @type {Node<vec3>}
  10246. */
  10247. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  10248. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  10249. /**
  10250. * This type of uniform node represents a cube texture.
  10251. *
  10252. * @augments TextureNode
  10253. */
  10254. class CubeTextureNode extends TextureNode {
  10255. static get type() {
  10256. return 'CubeTextureNode';
  10257. }
  10258. /**
  10259. * Constructs a new cube texture node.
  10260. *
  10261. * @param {CubeTexture} value - The cube texture.
  10262. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10263. * @param {?Node<int>} [levelNode=null] - The level node.
  10264. * @param {?Node<float>} [biasNode=null] - The bias node.
  10265. */
  10266. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  10267. super( value, uvNode, levelNode, biasNode );
  10268. /**
  10269. * This flag can be used for type testing.
  10270. *
  10271. * @type {boolean}
  10272. * @readonly
  10273. * @default true
  10274. */
  10275. this.isCubeTextureNode = true;
  10276. }
  10277. /**
  10278. * Overwrites the default implementation to return the appropriate cube texture type.
  10279. *
  10280. * @param {NodeBuilder} builder - The current node builder.
  10281. * @return {string} The input type.
  10282. */
  10283. getInputType( /*builder*/ ) {
  10284. if ( this.value.isDepthTexture === true ) {
  10285. return 'cubeDepthTexture';
  10286. }
  10287. return 'cubeTexture';
  10288. }
  10289. /**
  10290. * Returns a default uvs based on the mapping type of the cube texture.
  10291. *
  10292. * @return {Node<vec3>} The default uv attribute.
  10293. */
  10294. getDefaultUV() {
  10295. const texture = this.value;
  10296. if ( texture.mapping === CubeReflectionMapping ) {
  10297. return reflectVector;
  10298. } else if ( texture.mapping === CubeRefractionMapping ) {
  10299. return refractVector;
  10300. } else {
  10301. error( 'CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  10302. return vec3( 0, 0, 0 );
  10303. }
  10304. }
  10305. /**
  10306. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  10307. * for cube textures. The uv transformation matrix is not applied to cube textures.
  10308. *
  10309. * @param {boolean} value - The update toggle.
  10310. */
  10311. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  10312. /**
  10313. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  10314. * to modify the uv node for correct sampling.
  10315. *
  10316. * @param {NodeBuilder} builder - The current node builder.
  10317. * @param {Node} uvNode - The uv node to setup.
  10318. * @return {Node} The updated uv node.
  10319. */
  10320. setupUV( builder, uvNode ) {
  10321. const texture = this.value;
  10322. // Depth textures (shadow maps) - no environment rotation, Y flip for WebGPU
  10323. if ( texture.isDepthTexture === true ) {
  10324. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  10325. return vec3( uvNode.x, uvNode.y.negate(), uvNode.z );
  10326. }
  10327. return uvNode;
  10328. }
  10329. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  10330. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  10331. }
  10332. return materialEnvRotation.mul( uvNode );
  10333. }
  10334. /**
  10335. * Generates the uv code snippet.
  10336. *
  10337. * @param {NodeBuilder} builder - The current node builder.
  10338. * @param {Node} cubeUV - The uv node to generate code for.
  10339. * @return {string} The generated code snippet.
  10340. */
  10341. generateUV( builder, cubeUV ) {
  10342. return cubeUV.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  10343. }
  10344. }
  10345. /**
  10346. * TSL function for creating a cube texture node.
  10347. *
  10348. * @tsl
  10349. * @function
  10350. * @param {CubeTexture} value - The cube texture.
  10351. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10352. * @param {?Node<int>} [levelNode=null] - The level node.
  10353. * @param {?Node<float>} [biasNode=null] - The bias node.
  10354. * @returns {CubeTextureNode}
  10355. */
  10356. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  10357. /**
  10358. * TSL function for creating a cube texture uniform node.
  10359. *
  10360. * @tsl
  10361. * @function
  10362. * @param {?(CubeTexture|CubeTextureNode)} [value=EmptyTexture] - The cube texture.
  10363. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10364. * @param {?Node<int>} [levelNode=null] - The level node.
  10365. * @param {?Node<float>} [biasNode=null] - The bias node.
  10366. * @returns {CubeTextureNode}
  10367. */
  10368. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  10369. let textureNode;
  10370. if ( value && value.isCubeTextureNode === true ) {
  10371. textureNode = nodeObject( value.clone() );
  10372. textureNode.referenceNode = value; // Ensure the reference is set to the original node
  10373. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  10374. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  10375. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  10376. } else {
  10377. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  10378. }
  10379. return textureNode;
  10380. };
  10381. /**
  10382. * TSL function for creating a uniform cube texture node.
  10383. *
  10384. * @tsl
  10385. * @function
  10386. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  10387. * @returns {CubeTextureNode}
  10388. */
  10389. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  10390. // TODO: Avoid duplicated code and use only ReferenceBaseNode or ReferenceNode
  10391. /**
  10392. * This class is only relevant if the referenced property is array-like.
  10393. * In this case, `ReferenceElementNode` allows to refer to a specific
  10394. * element inside the data structure via an index.
  10395. *
  10396. * @augments ArrayElementNode
  10397. */
  10398. class ReferenceElementNode extends ArrayElementNode {
  10399. static get type() {
  10400. return 'ReferenceElementNode';
  10401. }
  10402. /**
  10403. * Constructs a new reference element node.
  10404. *
  10405. * @param {?ReferenceNode} referenceNode - The reference node.
  10406. * @param {Node} indexNode - The index node that defines the element access.
  10407. */
  10408. constructor( referenceNode, indexNode ) {
  10409. super( referenceNode, indexNode );
  10410. /**
  10411. * Similar to {@link ReferenceNode#reference}, an additional
  10412. * property references to the current node.
  10413. *
  10414. * @type {?ReferenceNode}
  10415. * @default null
  10416. */
  10417. this.referenceNode = referenceNode;
  10418. /**
  10419. * This flag can be used for type testing.
  10420. *
  10421. * @type {boolean}
  10422. * @readonly
  10423. * @default true
  10424. */
  10425. this.isReferenceElementNode = true;
  10426. }
  10427. /**
  10428. * This method is overwritten since the node type is inferred from
  10429. * the uniform type of the reference node.
  10430. *
  10431. * @return {string} The node type.
  10432. */
  10433. getNodeType() {
  10434. return this.referenceNode.uniformType;
  10435. }
  10436. generate( builder ) {
  10437. const snippet = super.generate( builder );
  10438. const arrayType = this.referenceNode.getNodeType();
  10439. const elementType = this.getNodeType();
  10440. return builder.format( snippet, arrayType, elementType );
  10441. }
  10442. }
  10443. /**
  10444. * This type of node establishes a reference to a property of another object.
  10445. * In this way, the value of the node is automatically linked to the value of
  10446. * referenced object. Reference nodes internally represent the linked value
  10447. * as a uniform.
  10448. *
  10449. * @augments Node
  10450. */
  10451. class ReferenceNode extends Node {
  10452. static get type() {
  10453. return 'ReferenceNode';
  10454. }
  10455. /**
  10456. * Constructs a new reference node.
  10457. *
  10458. * @param {string} property - The name of the property the node refers to.
  10459. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  10460. * @param {?Object} [object=null] - The object the property belongs to.
  10461. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  10462. */
  10463. constructor( property, uniformType, object = null, count = null ) {
  10464. super();
  10465. /**
  10466. * The name of the property the node refers to.
  10467. *
  10468. * @type {string}
  10469. */
  10470. this.property = property;
  10471. /**
  10472. * The uniform type that should be used to represent the property value.
  10473. *
  10474. * @type {string}
  10475. */
  10476. this.uniformType = uniformType;
  10477. /**
  10478. * The object the property belongs to.
  10479. *
  10480. * @type {?Object}
  10481. * @default null
  10482. */
  10483. this.object = object;
  10484. /**
  10485. * When the linked property is an array, this parameter defines its length.
  10486. *
  10487. * @type {?number}
  10488. * @default null
  10489. */
  10490. this.count = count;
  10491. /**
  10492. * The property name might have dots so nested properties can be referred.
  10493. * The hierarchy of the names is stored inside this array.
  10494. *
  10495. * @type {Array<string>}
  10496. */
  10497. this.properties = property.split( '.' );
  10498. /**
  10499. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  10500. * since the final reference might be updated from calling code.
  10501. *
  10502. * @type {?Object}
  10503. * @default null
  10504. */
  10505. this.reference = object;
  10506. /**
  10507. * The uniform node that holds the value of the reference node.
  10508. *
  10509. * @type {UniformNode}
  10510. * @default null
  10511. */
  10512. this.node = null;
  10513. /**
  10514. * The uniform group of the internal uniform.
  10515. *
  10516. * @type {UniformGroupNode}
  10517. * @default null
  10518. */
  10519. this.group = null;
  10520. /**
  10521. * An optional label of the internal uniform node.
  10522. *
  10523. * @type {?string}
  10524. * @default null
  10525. */
  10526. this.name = null;
  10527. /**
  10528. * Overwritten since reference nodes are updated per object.
  10529. *
  10530. * @type {string}
  10531. * @default 'object'
  10532. */
  10533. this.updateType = NodeUpdateType.OBJECT;
  10534. }
  10535. /**
  10536. * When the referred property is array-like, this method can be used
  10537. * to access elements via an index node.
  10538. *
  10539. * @param {IndexNode} indexNode - indexNode.
  10540. * @return {ReferenceElementNode} A reference to an element.
  10541. */
  10542. element( indexNode ) {
  10543. return new ReferenceElementNode( this, nodeObject( indexNode ) );
  10544. }
  10545. /**
  10546. * Sets the uniform group for this reference node.
  10547. *
  10548. * @param {UniformGroupNode} group - The uniform group to set.
  10549. * @return {ReferenceNode} A reference to this node.
  10550. */
  10551. setGroup( group ) {
  10552. this.group = group;
  10553. return this;
  10554. }
  10555. /**
  10556. * Sets the name for the internal uniform.
  10557. *
  10558. * @param {string} name - The label to set.
  10559. * @return {ReferenceNode} A reference to this node.
  10560. */
  10561. setName( name ) {
  10562. this.name = name;
  10563. return this;
  10564. }
  10565. /**
  10566. * Sets the label for the internal uniform.
  10567. *
  10568. * @deprecated
  10569. * @param {string} name - The label to set.
  10570. * @return {ReferenceNode} A reference to this node.
  10571. */
  10572. label( name ) {
  10573. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  10574. return this.setName( name );
  10575. }
  10576. /**
  10577. * Sets the node type which automatically defines the internal
  10578. * uniform type.
  10579. *
  10580. * @param {string} uniformType - The type to set.
  10581. */
  10582. setNodeType( uniformType ) {
  10583. let node = null;
  10584. if ( this.count !== null ) {
  10585. node = buffer( null, uniformType, this.count );
  10586. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  10587. node = uniformArray( null, uniformType );
  10588. } else if ( uniformType === 'texture' ) {
  10589. node = texture( null );
  10590. } else if ( uniformType === 'cubeTexture' ) {
  10591. node = cubeTexture( null );
  10592. } else {
  10593. node = uniform( null, uniformType );
  10594. }
  10595. if ( this.group !== null ) {
  10596. node.setGroup( this.group );
  10597. }
  10598. if ( this.name !== null ) node.setName( this.name );
  10599. this.node = node;
  10600. }
  10601. /**
  10602. * This method is overwritten since the node type is inferred from
  10603. * the type of the reference node.
  10604. *
  10605. * @param {NodeBuilder} builder - The current node builder.
  10606. * @return {string} The node type.
  10607. */
  10608. getNodeType( builder ) {
  10609. if ( this.node === null ) {
  10610. this.updateReference( builder );
  10611. this.updateValue();
  10612. }
  10613. return this.node.getNodeType( builder );
  10614. }
  10615. /**
  10616. * Returns the property value from the given referred object.
  10617. *
  10618. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  10619. * @return {any} The value.
  10620. */
  10621. getValueFromReference( object = this.reference ) {
  10622. const { properties } = this;
  10623. let value = object[ properties[ 0 ] ];
  10624. for ( let i = 1; i < properties.length; i ++ ) {
  10625. value = value[ properties[ i ] ];
  10626. }
  10627. return value;
  10628. }
  10629. /**
  10630. * Allows to update the reference based on the given state. The state is only
  10631. * evaluated {@link ReferenceNode#object} is not set.
  10632. *
  10633. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10634. * @return {Object} The updated reference.
  10635. */
  10636. updateReference( state ) {
  10637. this.reference = this.object !== null ? this.object : state.object;
  10638. return this.reference;
  10639. }
  10640. /**
  10641. * The output of the reference node is the internal uniform node.
  10642. *
  10643. * @param {NodeBuilder} builder - The current node builder.
  10644. * @return {UniformNode} The output node.
  10645. */
  10646. setup( /* builder */ ) {
  10647. this.updateValue();
  10648. return this.node;
  10649. }
  10650. /**
  10651. * Overwritten to update the internal uniform value.
  10652. *
  10653. * @param {NodeFrame} frame - A reference to the current node frame.
  10654. */
  10655. update( /*frame*/ ) {
  10656. this.updateValue();
  10657. }
  10658. /**
  10659. * Retrieves the value from the referred object property and uses it
  10660. * to updated the internal uniform.
  10661. */
  10662. updateValue() {
  10663. if ( this.node === null ) this.setNodeType( this.uniformType );
  10664. const value = this.getValueFromReference();
  10665. if ( Array.isArray( value ) ) {
  10666. this.node.array = value;
  10667. } else {
  10668. this.node.value = value;
  10669. }
  10670. }
  10671. }
  10672. /**
  10673. * TSL function for creating a reference node.
  10674. *
  10675. * @tsl
  10676. * @function
  10677. * @param {string} name - The name of the property the node refers to.
  10678. * @param {string} type - The uniform type that should be used to represent the property value.
  10679. * @param {?Object} [object] - The object the property belongs to.
  10680. * @returns {ReferenceNode}
  10681. */
  10682. const reference = ( name, type, object ) => new ReferenceNode( name, type, object );
  10683. /**
  10684. * TSL function for creating a reference node. Use this function if you want need a reference
  10685. * to an array-like property that should be represented as a uniform buffer.
  10686. *
  10687. * @tsl
  10688. * @function
  10689. * @param {string} name - The name of the property the node refers to.
  10690. * @param {string} type - The uniform type that should be used to represent the property value.
  10691. * @param {number} count - The number of value inside the array-like object.
  10692. * @param {Object} object - An array-like object the property belongs to.
  10693. * @returns {ReferenceNode}
  10694. */
  10695. const referenceBuffer = ( name, type, count, object ) => new ReferenceNode( name, type, object, count );
  10696. /**
  10697. * This node is a special type of reference node which is intended
  10698. * for linking material properties with node values.
  10699. * ```js
  10700. * const opacityNode = materialReference( 'opacity', 'float', material );
  10701. * ```
  10702. * When changing `material.opacity`, the node value of `opacityNode` will
  10703. * automatically be updated.
  10704. *
  10705. * @augments ReferenceNode
  10706. */
  10707. class MaterialReferenceNode extends ReferenceNode {
  10708. static get type() {
  10709. return 'MaterialReferenceNode';
  10710. }
  10711. /**
  10712. * Constructs a new material reference node.
  10713. *
  10714. * @param {string} property - The name of the property the node refers to.
  10715. * @param {string} inputType - The uniform type that should be used to represent the property value.
  10716. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  10717. * the node refers to the material of the current rendered object.
  10718. */
  10719. constructor( property, inputType, material = null ) {
  10720. super( property, inputType, material );
  10721. /**
  10722. * The material the property belongs to. When no material is set,
  10723. * the node refers to the material of the current rendered object.
  10724. *
  10725. * @type {?Material}
  10726. * @default null
  10727. */
  10728. this.material = material;
  10729. /**
  10730. * This flag can be used for type testing.
  10731. *
  10732. * @type {boolean}
  10733. * @readonly
  10734. * @default true
  10735. */
  10736. this.isMaterialReferenceNode = true;
  10737. }
  10738. /**
  10739. * Updates the reference based on the given state. The state is only evaluated
  10740. * {@link MaterialReferenceNode#material} is not set.
  10741. *
  10742. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10743. * @return {Object} The updated reference.
  10744. */
  10745. updateReference( state ) {
  10746. this.reference = this.material !== null ? this.material : state.material;
  10747. return this.reference;
  10748. }
  10749. }
  10750. /**
  10751. * TSL function for creating a material reference node.
  10752. *
  10753. * @tsl
  10754. * @function
  10755. * @param {string} name - The name of the property the node refers to.
  10756. * @param {string} type - The uniform type that should be used to represent the property value.
  10757. * @param {?Material} [material=null] - The material the property belongs to.
  10758. * When no material is set, the node refers to the material of the current rendered object.
  10759. * @returns {MaterialReferenceNode}
  10760. */
  10761. const materialReference = ( name, type, material = null ) => new MaterialReferenceNode( name, type, material );
  10762. // Normal Mapping Without Precomputed Tangents
  10763. // http://www.thetenthplanet.de/archives/1180
  10764. const uv = uv$1();
  10765. const q0 = positionView.dFdx();
  10766. const q1 = positionView.dFdy();
  10767. const st0 = uv.dFdx();
  10768. const st1 = uv.dFdy();
  10769. const N = normalView;
  10770. const q1perp = q1.cross( N );
  10771. const q0perp = N.cross( q0 );
  10772. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  10773. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  10774. const det = T.dot( T ).max( B.dot( B ) );
  10775. const scale$1 = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() );
  10776. /**
  10777. * Tangent vector in view space, computed dynamically from geometry and UV derivatives.
  10778. * Useful for normal mapping without precomputed tangents.
  10779. *
  10780. * Reference: http://www.thetenthplanet.de/archives/1180
  10781. *
  10782. * @tsl
  10783. * @type {Node<vec3>}
  10784. */
  10785. const tangentViewFrame = /*@__PURE__*/ T.mul( scale$1 ).toVar( 'tangentViewFrame' );
  10786. /**
  10787. * Bitangent vector in view space, computed dynamically from geometry and UV derivatives.
  10788. * Complements the tangentViewFrame for constructing the tangent space basis.
  10789. *
  10790. * Reference: http://www.thetenthplanet.de/archives/1180
  10791. *
  10792. * @tsl
  10793. * @type {Node<vec3>}
  10794. */
  10795. const bitangentViewFrame = /*@__PURE__*/ B.mul( scale$1 ).toVar( 'bitangentViewFrame' );
  10796. /**
  10797. * TSL object that represents the tangent attribute of the current rendered object.
  10798. *
  10799. * @tsl
  10800. * @type {Node<vec4>}
  10801. */
  10802. const tangentGeometry = /*@__PURE__*/ attribute( 'tangent', 'vec4' );
  10803. /**
  10804. * TSL object that represents the vertex tangent in local space of the current rendered object.
  10805. *
  10806. * @tsl
  10807. * @type {Node<vec3>}
  10808. */
  10809. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  10810. /**
  10811. * TSL object that represents the vertex tangent in view space of the current rendered object.
  10812. *
  10813. * @tsl
  10814. * @type {Node<vec3>}
  10815. */
  10816. const tangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10817. let node;
  10818. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10819. node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize();
  10820. } else {
  10821. node = tangentViewFrame;
  10822. }
  10823. if ( material.flatShading !== true ) {
  10824. node = directionToFaceDirection( node );
  10825. }
  10826. return node;
  10827. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' );
  10828. /**
  10829. * TSL object that represents the vertex tangent in world space of the current rendered object.
  10830. *
  10831. * @tsl
  10832. * @type {Node<vec3>}
  10833. */
  10834. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  10835. /**
  10836. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  10837. *
  10838. * @tsl
  10839. * @private
  10840. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  10841. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  10842. * @returns {Node<vec3>} The bitangent node.
  10843. */
  10844. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], { subBuildFn, material } ) => {
  10845. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  10846. if ( subBuildFn === 'NORMAL' && material.flatShading !== true ) {
  10847. bitangent = bitangent.toVarying( varyingName );
  10848. }
  10849. return bitangent;
  10850. } ).once( [ 'NORMAL' ] );
  10851. /**
  10852. * TSL object that represents the bitangent attribute of the current rendered object.
  10853. *
  10854. * @tsl
  10855. * @type {Node<vec3>}
  10856. */
  10857. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  10858. /**
  10859. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  10860. *
  10861. * @tsl
  10862. * @type {Node<vec3>}
  10863. */
  10864. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  10865. /**
  10866. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  10867. *
  10868. * @tsl
  10869. * @type {Node<vec3>}
  10870. */
  10871. const bitangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10872. let node;
  10873. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10874. node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize();
  10875. } else {
  10876. node = bitangentViewFrame;
  10877. }
  10878. if ( material.flatShading !== true ) {
  10879. node = directionToFaceDirection( node );
  10880. }
  10881. return node;
  10882. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' );
  10883. /**
  10884. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  10885. *
  10886. * @tsl
  10887. * @type {Node<vec3>}
  10888. */
  10889. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  10890. /**
  10891. * TSL object that represents the TBN matrix in view space.
  10892. *
  10893. * @tsl
  10894. * @type {Node<mat3>}
  10895. */
  10896. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView ).toVar( 'TBNViewMatrix' );
  10897. /**
  10898. * TSL object that represents the parallax direction.
  10899. *
  10900. * @tsl
  10901. * @type {Node<mat3>}
  10902. */
  10903. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  10904. /**
  10905. * TSL function for computing parallax uv coordinates.
  10906. *
  10907. * @tsl
  10908. * @function
  10909. * @param {Node<vec2>} uv - A uv node.
  10910. * @param {Node<vec2>} scale - A scale node.
  10911. * @returns {Node<vec2>} Parallax uv coordinates.
  10912. */
  10913. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  10914. /**
  10915. * TSL function for computing bent normals.
  10916. *
  10917. * @tsl
  10918. * @function
  10919. * @returns {Node<vec3>} Bent normals.
  10920. */
  10921. const bentNormalView = /*@__PURE__*/ ( Fn( () => {
  10922. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  10923. let bentNormal = anisotropyB.cross( positionViewDirection );
  10924. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  10925. bentNormal = mix( bentNormal, normalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  10926. return bentNormal;
  10927. } ).once() )();
  10928. /**
  10929. * Packs a direction vector into a color value.
  10930. *
  10931. * @tsl
  10932. * @function
  10933. * @param {Node<vec3>} node - The direction to pack.
  10934. * @return {Node<vec3>} The color.
  10935. */
  10936. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  10937. /**
  10938. * Unpacks a color value into a direction vector.
  10939. *
  10940. * @tsl
  10941. * @function
  10942. * @param {Node<vec3>} node - The color to unpack.
  10943. * @return {Node<vec3>} The direction.
  10944. */
  10945. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  10946. /**
  10947. * Unpacks a tangent space normal, reconstructing the Z component by projecting the X,Y coordinates onto the hemisphere.
  10948. * The X,Y coordinates are expected to be in the [-1, 1] range.
  10949. *
  10950. * @tsl
  10951. * @function
  10952. * @param {Node<vec2>} xy - The X,Y coordinates of the normal.
  10953. * @return {Node<vec3>} The resulting normal.
  10954. */
  10955. const unpackNormal = ( xy ) => vec3( xy, sqrt( saturate( float( 1.0 ).sub( dot( xy, xy ) ) ) ) );
  10956. /**
  10957. * This class can be used for applying normals maps to materials.
  10958. *
  10959. * ```js
  10960. * material.normalNode = normalMap( texture( normalTex ) );
  10961. * ```
  10962. *
  10963. * @augments TempNode
  10964. */
  10965. class NormalMapNode extends TempNode {
  10966. static get type() {
  10967. return 'NormalMapNode';
  10968. }
  10969. /**
  10970. * Constructs a new normal map node.
  10971. *
  10972. * @param {Node<vec3>} node - Represents the normal map data.
  10973. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10974. */
  10975. constructor( node, scaleNode = null ) {
  10976. super( 'vec3' );
  10977. /**
  10978. * Represents the normal map data.
  10979. *
  10980. * @type {Node<vec3>}
  10981. */
  10982. this.node = node;
  10983. /**
  10984. * Controls the intensity of the effect.
  10985. *
  10986. * @type {?Node<vec2>}
  10987. * @default null
  10988. */
  10989. this.scaleNode = scaleNode;
  10990. /**
  10991. * The normal map type.
  10992. *
  10993. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  10994. * @default TangentSpaceNormalMap
  10995. */
  10996. this.normalMapType = TangentSpaceNormalMap;
  10997. /**
  10998. * Controls how to unpack the sampled normal map values.
  10999. *
  11000. * @type {string}
  11001. * @default NoNormalPacking
  11002. */
  11003. this.unpackNormalMode = NoNormalPacking;
  11004. }
  11005. setup( { material } ) {
  11006. const { normalMapType, scaleNode, unpackNormalMode } = this;
  11007. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  11008. if ( normalMapType === TangentSpaceNormalMap ) {
  11009. if ( unpackNormalMode === NormalRGPacking ) {
  11010. normalMap = unpackNormal( normalMap.xy );
  11011. } else if ( unpackNormalMode === NormalGAPacking ) {
  11012. normalMap = unpackNormal( normalMap.yw );
  11013. } else if ( unpackNormalMode !== NoNormalPacking ) {
  11014. console.error( `THREE.NodeMaterial: Unexpected unpack normal mode: ${ unpackNormalMode }` );
  11015. }
  11016. } else {
  11017. if ( unpackNormalMode !== NoNormalPacking ) {
  11018. console.error( `THREE.NodeMaterial: Normal map type '${ normalMapType }' is not compatible with unpack normal mode '${ unpackNormalMode }'` );
  11019. }
  11020. }
  11021. if ( scaleNode !== null ) {
  11022. let scale = scaleNode;
  11023. if ( material.flatShading === true ) {
  11024. scale = directionToFaceDirection( scale );
  11025. }
  11026. normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z );
  11027. }
  11028. let output = null;
  11029. if ( normalMapType === ObjectSpaceNormalMap ) {
  11030. output = transformNormalToView( normalMap );
  11031. } else if ( normalMapType === TangentSpaceNormalMap ) {
  11032. output = TBNViewMatrix.mul( normalMap ).normalize();
  11033. } else {
  11034. error( `NodeMaterial: Unsupported normal map type: ${ normalMapType }` );
  11035. output = normalView; // Fallback to default normal view
  11036. }
  11037. return output;
  11038. }
  11039. }
  11040. /**
  11041. * TSL function for creating a normal map node.
  11042. *
  11043. * @tsl
  11044. * @function
  11045. * @param {Node<vec3>} node - Represents the normal map data.
  11046. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  11047. * @returns {NormalMapNode}
  11048. */
  11049. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  11050. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  11051. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  11052. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  11053. // It's used to preserve the same TextureNode instance
  11054. const sampleTexture = ( callback ) => textureNode.isolate().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } );
  11055. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  11056. return vec2(
  11057. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  11058. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  11059. ).mul( bumpScale );
  11060. } );
  11061. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  11062. const perturbNormalArb = Fn( ( inputs ) => {
  11063. const { surf_pos, surf_norm, dHdxy } = inputs;
  11064. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  11065. const vSigmaX = surf_pos.dFdx().normalize();
  11066. const vSigmaY = surf_pos.dFdy().normalize();
  11067. const vN = surf_norm; // normalized
  11068. const R1 = vSigmaY.cross( vN );
  11069. const R2 = vN.cross( vSigmaX );
  11070. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  11071. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  11072. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  11073. } );
  11074. /**
  11075. * This class can be used for applying bump maps to materials.
  11076. *
  11077. * ```js
  11078. * material.normalNode = bumpMap( texture( bumpTex ) );
  11079. * ```
  11080. *
  11081. * @augments TempNode
  11082. */
  11083. class BumpMapNode extends TempNode {
  11084. static get type() {
  11085. return 'BumpMapNode';
  11086. }
  11087. /**
  11088. * Constructs a new bump map node.
  11089. *
  11090. * @param {Node<float>} textureNode - Represents the bump map data.
  11091. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  11092. */
  11093. constructor( textureNode, scaleNode = null ) {
  11094. super( 'vec3' );
  11095. /**
  11096. * Represents the bump map data.
  11097. *
  11098. * @type {Node<float>}
  11099. */
  11100. this.textureNode = textureNode;
  11101. /**
  11102. * Controls the intensity of the bump effect.
  11103. *
  11104. * @type {?Node<float>}
  11105. * @default null
  11106. */
  11107. this.scaleNode = scaleNode;
  11108. }
  11109. setup() {
  11110. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  11111. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  11112. return perturbNormalArb( {
  11113. surf_pos: positionView,
  11114. surf_norm: normalView,
  11115. dHdxy
  11116. } );
  11117. }
  11118. }
  11119. /**
  11120. * TSL function for creating a bump map node.
  11121. *
  11122. * @tsl
  11123. * @function
  11124. * @param {Node<float>} textureNode - Represents the bump map data.
  11125. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  11126. * @returns {BumpMapNode}
  11127. */
  11128. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  11129. const _propertyCache = new Map();
  11130. /**
  11131. * This class should simplify the node access to material properties.
  11132. * It internal uses reference nodes to make sure changes to material
  11133. * properties are automatically reflected to predefined TSL objects
  11134. * like e.g. `materialColor`.
  11135. *
  11136. * @augments Node
  11137. */
  11138. class MaterialNode extends Node {
  11139. static get type() {
  11140. return 'MaterialNode';
  11141. }
  11142. /**
  11143. * Constructs a new material node.
  11144. *
  11145. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  11146. */
  11147. constructor( scope ) {
  11148. super();
  11149. /**
  11150. * The scope defines what material property is referred by the node.
  11151. *
  11152. * @type {string}
  11153. */
  11154. this.scope = scope;
  11155. }
  11156. /**
  11157. * Returns a cached reference node for the given property and type.
  11158. *
  11159. * @param {string} property - The name of the material property.
  11160. * @param {string} type - The uniform type of the property.
  11161. * @return {MaterialReferenceNode} A material reference node representing the property access.
  11162. */
  11163. getCache( property, type ) {
  11164. let node = _propertyCache.get( property );
  11165. if ( node === undefined ) {
  11166. node = materialReference( property, type );
  11167. _propertyCache.set( property, node );
  11168. }
  11169. return node;
  11170. }
  11171. /**
  11172. * Returns a float-typed material reference node for the given property name.
  11173. *
  11174. * @param {string} property - The name of the material property.
  11175. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  11176. */
  11177. getFloat( property ) {
  11178. return this.getCache( property, 'float' );
  11179. }
  11180. /**
  11181. * Returns a color-typed material reference node for the given property name.
  11182. *
  11183. * @param {string} property - The name of the material property.
  11184. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  11185. */
  11186. getColor( property ) {
  11187. return this.getCache( property, 'color' );
  11188. }
  11189. /**
  11190. * Returns a texture-typed material reference node for the given property name.
  11191. *
  11192. * @param {string} property - The name of the material property.
  11193. * @return {MaterialReferenceNode} A material reference node representing the property access.
  11194. */
  11195. getTexture( property ) {
  11196. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  11197. }
  11198. /**
  11199. * The node setup is done depending on the selected scope. Multiple material properties
  11200. * might be grouped into a single node composition if they logically belong together.
  11201. *
  11202. * @param {NodeBuilder} builder - The current node builder.
  11203. * @return {Node} The node representing the selected scope.
  11204. */
  11205. setup( builder ) {
  11206. const material = builder.context.material;
  11207. const scope = this.scope;
  11208. let node = null;
  11209. if ( scope === MaterialNode.COLOR ) {
  11210. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  11211. if ( material.map && material.map.isTexture === true ) {
  11212. node = colorNode.mul( this.getTexture( 'map' ) );
  11213. } else {
  11214. node = colorNode;
  11215. }
  11216. } else if ( scope === MaterialNode.OPACITY ) {
  11217. const opacityNode = this.getFloat( scope );
  11218. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  11219. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  11220. } else {
  11221. node = opacityNode;
  11222. }
  11223. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  11224. if ( material.specularMap && material.specularMap.isTexture === true ) {
  11225. node = this.getTexture( 'specular' ).r;
  11226. } else {
  11227. node = float( 1 );
  11228. }
  11229. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  11230. const specularIntensityNode = this.getFloat( scope );
  11231. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  11232. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  11233. } else {
  11234. node = specularIntensityNode;
  11235. }
  11236. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  11237. const specularColorNode = this.getColor( scope );
  11238. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  11239. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  11240. } else {
  11241. node = specularColorNode;
  11242. }
  11243. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  11244. const roughnessNode = this.getFloat( scope );
  11245. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  11246. node = roughnessNode.mul( this.getTexture( scope ).g );
  11247. } else {
  11248. node = roughnessNode;
  11249. }
  11250. } else if ( scope === MaterialNode.METALNESS ) {
  11251. const metalnessNode = this.getFloat( scope );
  11252. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  11253. node = metalnessNode.mul( this.getTexture( scope ).b );
  11254. } else {
  11255. node = metalnessNode;
  11256. }
  11257. } else if ( scope === MaterialNode.EMISSIVE ) {
  11258. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  11259. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  11260. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  11261. node = emissiveNode.mul( this.getTexture( scope ) );
  11262. } else {
  11263. node = emissiveNode;
  11264. }
  11265. } else if ( scope === MaterialNode.NORMAL ) {
  11266. if ( material.normalMap ) {
  11267. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  11268. node.normalMapType = material.normalMapType;
  11269. if ( material.normalMap.format == RGFormat || material.normalMap.format == RED_GREEN_RGTC2_Format || material.normalMap.format == RG11_EAC_Format ) {
  11270. node.unpackNormalMode = NormalRGPacking;
  11271. }
  11272. } else if ( material.bumpMap ) {
  11273. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  11274. } else {
  11275. node = normalView;
  11276. }
  11277. } else if ( scope === MaterialNode.CLEARCOAT ) {
  11278. const clearcoatNode = this.getFloat( scope );
  11279. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  11280. node = clearcoatNode.mul( this.getTexture( scope ).r );
  11281. } else {
  11282. node = clearcoatNode;
  11283. }
  11284. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  11285. const clearcoatRoughnessNode = this.getFloat( scope );
  11286. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  11287. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  11288. } else {
  11289. node = clearcoatRoughnessNode;
  11290. }
  11291. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  11292. if ( material.clearcoatNormalMap ) {
  11293. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  11294. } else {
  11295. node = normalView;
  11296. }
  11297. } else if ( scope === MaterialNode.SHEEN ) {
  11298. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  11299. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  11300. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  11301. } else {
  11302. node = sheenNode;
  11303. }
  11304. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  11305. const sheenRoughnessNode = this.getFloat( scope );
  11306. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  11307. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  11308. } else {
  11309. node = sheenRoughnessNode;
  11310. }
  11311. node = node.clamp( 0.0001, 1.0 );
  11312. } else if ( scope === MaterialNode.ANISOTROPY ) {
  11313. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  11314. const anisotropyPolar = this.getTexture( scope );
  11315. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  11316. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  11317. } else {
  11318. node = materialAnisotropyVector;
  11319. }
  11320. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  11321. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  11322. if ( material.iridescenceThicknessMap ) {
  11323. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  11324. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  11325. } else {
  11326. node = iridescenceThicknessMaximum;
  11327. }
  11328. } else if ( scope === MaterialNode.TRANSMISSION ) {
  11329. const transmissionNode = this.getFloat( scope );
  11330. if ( material.transmissionMap ) {
  11331. node = transmissionNode.mul( this.getTexture( scope ).r );
  11332. } else {
  11333. node = transmissionNode;
  11334. }
  11335. } else if ( scope === MaterialNode.THICKNESS ) {
  11336. const thicknessNode = this.getFloat( scope );
  11337. if ( material.thicknessMap ) {
  11338. node = thicknessNode.mul( this.getTexture( scope ).g );
  11339. } else {
  11340. node = thicknessNode;
  11341. }
  11342. } else if ( scope === MaterialNode.IOR ) {
  11343. node = this.getFloat( scope );
  11344. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  11345. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  11346. } else if ( scope === MaterialNode.AO ) {
  11347. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  11348. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  11349. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  11350. } else {
  11351. const outputType = this.getNodeType( builder );
  11352. node = this.getCache( scope, outputType );
  11353. }
  11354. return node;
  11355. }
  11356. }
  11357. MaterialNode.ALPHA_TEST = 'alphaTest';
  11358. MaterialNode.COLOR = 'color';
  11359. MaterialNode.OPACITY = 'opacity';
  11360. MaterialNode.SHININESS = 'shininess';
  11361. MaterialNode.SPECULAR = 'specular';
  11362. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  11363. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  11364. MaterialNode.SPECULAR_COLOR = 'specularColor';
  11365. MaterialNode.REFLECTIVITY = 'reflectivity';
  11366. MaterialNode.ROUGHNESS = 'roughness';
  11367. MaterialNode.METALNESS = 'metalness';
  11368. MaterialNode.NORMAL = 'normal';
  11369. MaterialNode.CLEARCOAT = 'clearcoat';
  11370. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  11371. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  11372. MaterialNode.EMISSIVE = 'emissive';
  11373. MaterialNode.ROTATION = 'rotation';
  11374. MaterialNode.SHEEN = 'sheen';
  11375. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  11376. MaterialNode.ANISOTROPY = 'anisotropy';
  11377. MaterialNode.IRIDESCENCE = 'iridescence';
  11378. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  11379. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  11380. MaterialNode.IOR = 'ior';
  11381. MaterialNode.TRANSMISSION = 'transmission';
  11382. MaterialNode.THICKNESS = 'thickness';
  11383. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  11384. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  11385. MaterialNode.LINE_SCALE = 'scale';
  11386. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  11387. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  11388. MaterialNode.LINE_WIDTH = 'linewidth';
  11389. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  11390. MaterialNode.POINT_SIZE = 'size';
  11391. MaterialNode.DISPERSION = 'dispersion';
  11392. MaterialNode.LIGHT_MAP = 'light';
  11393. MaterialNode.AO = 'ao';
  11394. /**
  11395. * TSL object that represents alpha test of the current material.
  11396. *
  11397. * @tsl
  11398. * @type {Node<float>}
  11399. */
  11400. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  11401. /**
  11402. * TSL object that represents the diffuse color of the current material.
  11403. * The value is composed via `color` * `map`.
  11404. *
  11405. * @tsl
  11406. * @type {Node<vec3>}
  11407. */
  11408. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  11409. /**
  11410. * TSL object that represents the shininess of the current material.
  11411. *
  11412. * @tsl
  11413. * @type {Node<float>}
  11414. */
  11415. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  11416. /**
  11417. * TSL object that represents the emissive color of the current material.
  11418. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  11419. *
  11420. * @tsl
  11421. * @type {Node<vec3>}
  11422. */
  11423. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  11424. /**
  11425. * TSL object that represents the opacity of the current material.
  11426. * The value is composed via `opacity` * `alphaMap`.
  11427. *
  11428. * @tsl
  11429. * @type {Node<float>}
  11430. */
  11431. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  11432. /**
  11433. * TSL object that represents the specular of the current material.
  11434. *
  11435. * @tsl
  11436. * @type {Node<vec3>}
  11437. */
  11438. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  11439. /**
  11440. * TSL object that represents the specular intensity of the current material.
  11441. * The value is composed via `specularIntensity` * `specularMap.a`.
  11442. *
  11443. * @tsl
  11444. * @type {Node<float>}
  11445. */
  11446. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  11447. /**
  11448. * TSL object that represents the specular color of the current material.
  11449. * The value is composed via `specularColor` * `specularMap.rgb`.
  11450. *
  11451. * @tsl
  11452. * @type {Node<vec3>}
  11453. */
  11454. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  11455. /**
  11456. * TSL object that represents the specular strength of the current material.
  11457. * The value is composed via `specularMap.r`.
  11458. *
  11459. * @tsl
  11460. * @type {Node<float>}
  11461. */
  11462. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  11463. /**
  11464. * TSL object that represents the reflectivity of the current material.
  11465. *
  11466. * @tsl
  11467. * @type {Node<float>}
  11468. */
  11469. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  11470. /**
  11471. * TSL object that represents the roughness of the current material.
  11472. * The value is composed via `roughness` * `roughnessMap.g`.
  11473. *
  11474. * @tsl
  11475. * @type {Node<float>}
  11476. */
  11477. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  11478. /**
  11479. * TSL object that represents the metalness of the current material.
  11480. * The value is composed via `metalness` * `metalnessMap.b`.
  11481. *
  11482. * @tsl
  11483. * @type {Node<float>}
  11484. */
  11485. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  11486. /**
  11487. * TSL object that represents the normal of the current material.
  11488. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  11489. *
  11490. * @tsl
  11491. * @type {Node<vec3>}
  11492. */
  11493. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  11494. /**
  11495. * TSL object that represents the clearcoat of the current material.
  11496. * The value is composed via `clearcoat` * `clearcoatMap.r`
  11497. *
  11498. * @tsl
  11499. * @type {Node<float>}
  11500. */
  11501. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  11502. /**
  11503. * TSL object that represents the clearcoat roughness of the current material.
  11504. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  11505. *
  11506. * @tsl
  11507. * @type {Node<float>}
  11508. */
  11509. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  11510. /**
  11511. * TSL object that represents the clearcoat normal of the current material.
  11512. * The value will be either `clearcoatNormalMap` or `normalView`.
  11513. *
  11514. * @tsl
  11515. * @type {Node<vec3>}
  11516. */
  11517. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  11518. /**
  11519. * TSL object that represents the rotation of the current sprite material.
  11520. *
  11521. * @tsl
  11522. * @type {Node<float>}
  11523. */
  11524. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  11525. /**
  11526. * TSL object that represents the sheen color of the current material.
  11527. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  11528. *
  11529. * @tsl
  11530. * @type {Node<vec3>}
  11531. */
  11532. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  11533. /**
  11534. * TSL object that represents the sheen roughness of the current material.
  11535. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  11536. *
  11537. * @tsl
  11538. * @type {Node<float>}
  11539. */
  11540. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  11541. /**
  11542. * TSL object that represents the anisotropy of the current material.
  11543. *
  11544. * @tsl
  11545. * @type {Node<vec2>}
  11546. */
  11547. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  11548. /**
  11549. * TSL object that represents the iridescence of the current material.
  11550. *
  11551. * @tsl
  11552. * @type {Node<float>}
  11553. */
  11554. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  11555. /**
  11556. * TSL object that represents the iridescence IOR of the current material.
  11557. *
  11558. * @tsl
  11559. * @type {Node<float>}
  11560. */
  11561. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  11562. /**
  11563. * TSL object that represents the iridescence thickness of the current material.
  11564. *
  11565. * @tsl
  11566. * @type {Node<float>}
  11567. */
  11568. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  11569. /**
  11570. * TSL object that represents the transmission of the current material.
  11571. * The value is composed via `transmission` * `transmissionMap.r`.
  11572. *
  11573. * @tsl
  11574. * @type {Node<float>}
  11575. */
  11576. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  11577. /**
  11578. * TSL object that represents the thickness of the current material.
  11579. * The value is composed via `thickness` * `thicknessMap.g`.
  11580. *
  11581. * @tsl
  11582. * @type {Node<float>}
  11583. */
  11584. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  11585. /**
  11586. * TSL object that represents the IOR of the current material.
  11587. *
  11588. * @tsl
  11589. * @type {Node<float>}
  11590. */
  11591. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  11592. /**
  11593. * TSL object that represents the attenuation distance of the current material.
  11594. *
  11595. * @tsl
  11596. * @type {Node<float>}
  11597. */
  11598. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  11599. /**
  11600. * TSL object that represents the attenuation color of the current material.
  11601. *
  11602. * @tsl
  11603. * @type {Node<vec3>}
  11604. */
  11605. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  11606. /**
  11607. * TSL object that represents the scale of the current dashed line material.
  11608. *
  11609. * @tsl
  11610. * @type {Node<float>}
  11611. */
  11612. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  11613. /**
  11614. * TSL object that represents the dash size of the current dashed line material.
  11615. *
  11616. * @tsl
  11617. * @type {Node<float>}
  11618. */
  11619. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  11620. /**
  11621. * TSL object that represents the gap size of the current dashed line material.
  11622. *
  11623. * @tsl
  11624. * @type {Node<float>}
  11625. */
  11626. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  11627. /**
  11628. * TSL object that represents the line width of the current line material.
  11629. *
  11630. * @tsl
  11631. * @type {Node<float>}
  11632. */
  11633. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  11634. /**
  11635. * TSL object that represents the dash offset of the current line material.
  11636. *
  11637. * @tsl
  11638. * @type {Node<float>}
  11639. */
  11640. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  11641. /**
  11642. * TSL object that represents the point size of the current points material.
  11643. *
  11644. * @tsl
  11645. * @type {Node<float>}
  11646. */
  11647. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  11648. /**
  11649. * TSL object that represents the dispersion of the current material.
  11650. *
  11651. * @tsl
  11652. * @type {Node<float>}
  11653. */
  11654. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  11655. /**
  11656. * TSL object that represents the light map of the current material.
  11657. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  11658. *
  11659. * @tsl
  11660. * @type {Node<vec3>}
  11661. */
  11662. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  11663. /**
  11664. * TSL object that represents the ambient occlusion map of the current material.
  11665. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  11666. *
  11667. * @tsl
  11668. * @type {Node<float>}
  11669. */
  11670. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  11671. /**
  11672. * TSL object that represents the anisotropy vector of the current material.
  11673. *
  11674. * @tsl
  11675. * @type {Node<vec2>}
  11676. */
  11677. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  11678. return frame.material;
  11679. } ).onRenderUpdate( function ( { material } ) {
  11680. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  11681. } );
  11682. /**
  11683. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  11684. *
  11685. * @tsl
  11686. * @type {VaryingNode<vec4>}
  11687. */
  11688. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  11689. return builder.context.setupModelViewProjection();
  11690. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  11691. /**
  11692. * This class enables element access on instances of {@link StorageBufferNode}.
  11693. * In most cases, it is indirectly used when accessing elements with the
  11694. * {@link StorageBufferNode#element} method.
  11695. *
  11696. * ```js
  11697. * const position = positionStorage.element( instanceIndex );
  11698. * ```
  11699. *
  11700. * @augments ArrayElementNode
  11701. */
  11702. class StorageArrayElementNode extends ArrayElementNode {
  11703. static get type() {
  11704. return 'StorageArrayElementNode';
  11705. }
  11706. /**
  11707. * Constructs storage buffer element node.
  11708. *
  11709. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11710. * @param {Node} indexNode - The index node that defines the element access.
  11711. */
  11712. constructor( storageBufferNode, indexNode ) {
  11713. super( storageBufferNode, indexNode );
  11714. /**
  11715. * This flag can be used for type testing.
  11716. *
  11717. * @type {boolean}
  11718. * @readonly
  11719. * @default true
  11720. */
  11721. this.isStorageArrayElementNode = true;
  11722. }
  11723. /**
  11724. * The storage buffer node.
  11725. *
  11726. * @param {Node} value
  11727. * @type {StorageBufferNode}
  11728. */
  11729. set storageBufferNode( value ) {
  11730. this.node = value;
  11731. }
  11732. get storageBufferNode() {
  11733. return this.node;
  11734. }
  11735. getMemberType( builder, name ) {
  11736. const structTypeNode = this.storageBufferNode.structTypeNode;
  11737. if ( structTypeNode ) {
  11738. return structTypeNode.getMemberType( builder, name );
  11739. }
  11740. return 'void';
  11741. }
  11742. setup( builder ) {
  11743. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11744. if ( this.node.isPBO === true ) {
  11745. builder.setupPBO( this.node );
  11746. }
  11747. }
  11748. return super.setup( builder );
  11749. }
  11750. generate( builder, output ) {
  11751. let snippet;
  11752. const isAssignContext = builder.context.assign;
  11753. //
  11754. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11755. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  11756. snippet = builder.generatePBO( this );
  11757. } else {
  11758. snippet = this.node.build( builder );
  11759. }
  11760. } else {
  11761. snippet = super.generate( builder );
  11762. }
  11763. if ( isAssignContext !== true ) {
  11764. const type = this.getNodeType( builder );
  11765. snippet = builder.format( snippet, type, output );
  11766. }
  11767. return snippet;
  11768. }
  11769. }
  11770. /**
  11771. * TSL function for creating a storage element node.
  11772. *
  11773. * @tsl
  11774. * @function
  11775. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11776. * @param {Node} indexNode - The index node that defines the element access.
  11777. * @returns {StorageArrayElementNode}
  11778. */
  11779. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  11780. /**
  11781. * This node is used in context of compute shaders and allows to define a
  11782. * storage buffer for data. A typical workflow is to create instances of
  11783. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  11784. * setup up a compute shader that writes into the buffers and then convert
  11785. * the storage buffers to attribute nodes for rendering.
  11786. *
  11787. * ```js
  11788. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  11789. *
  11790. * const computeInit = Fn( () => { // the compute shader
  11791. *
  11792. * const position = positionBuffer.element( instanceIndex );
  11793. *
  11794. * // compute position data
  11795. *
  11796. * position.x = 1;
  11797. * position.y = 1;
  11798. * position.z = 1;
  11799. *
  11800. * } )().compute( particleCount );
  11801. *
  11802. * const particleMaterial = new THREE.SpriteNodeMaterial();
  11803. * particleMaterial.positionNode = positionBuffer.toAttribute();
  11804. *
  11805. * renderer.computeAsync( computeInit );
  11806. *
  11807. * ```
  11808. *
  11809. * @augments BufferNode
  11810. */
  11811. class StorageBufferNode extends BufferNode {
  11812. static get type() {
  11813. return 'StorageBufferNode';
  11814. }
  11815. /**
  11816. * Constructs a new storage buffer node.
  11817. *
  11818. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11819. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  11820. * @param {number} [bufferCount=0] - The buffer count.
  11821. */
  11822. constructor( value, bufferType = null, bufferCount = 0 ) {
  11823. let nodeType, structTypeNode = null;
  11824. if ( bufferType && bufferType.isStruct ) {
  11825. nodeType = 'struct';
  11826. structTypeNode = bufferType.layout;
  11827. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  11828. bufferCount = value.count;
  11829. }
  11830. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  11831. nodeType = getTypeFromLength( value.itemSize );
  11832. bufferCount = value.count;
  11833. } else {
  11834. nodeType = bufferType;
  11835. }
  11836. super( value, nodeType, bufferCount );
  11837. /**
  11838. * This flag can be used for type testing.
  11839. *
  11840. * @type {boolean}
  11841. * @readonly
  11842. * @default true
  11843. */
  11844. this.isStorageBufferNode = true;
  11845. /**
  11846. * The buffer struct type.
  11847. *
  11848. * @type {?StructTypeNode}
  11849. * @default null
  11850. */
  11851. this.structTypeNode = structTypeNode;
  11852. /**
  11853. * The access type of the texture node.
  11854. *
  11855. * @type {string}
  11856. * @default 'readWrite'
  11857. */
  11858. this.access = NodeAccess.READ_WRITE;
  11859. /**
  11860. * Whether the node is atomic or not.
  11861. *
  11862. * @type {boolean}
  11863. * @default false
  11864. */
  11865. this.isAtomic = false;
  11866. /**
  11867. * Whether the node represents a PBO or not.
  11868. * Only relevant for WebGL.
  11869. *
  11870. * @type {boolean}
  11871. * @default false
  11872. */
  11873. this.isPBO = false;
  11874. /**
  11875. * A reference to the internal buffer attribute node.
  11876. *
  11877. * @private
  11878. * @type {?BufferAttributeNode}
  11879. * @default null
  11880. */
  11881. this._attribute = null;
  11882. /**
  11883. * A reference to the internal varying node.
  11884. *
  11885. * @private
  11886. * @type {?VaryingNode}
  11887. * @default null
  11888. */
  11889. this._varying = null;
  11890. /**
  11891. * `StorageBufferNode` sets this property to `true` by default.
  11892. *
  11893. * @type {boolean}
  11894. * @default true
  11895. */
  11896. this.global = true;
  11897. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  11898. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  11899. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  11900. else value.isStorageBufferAttribute = true;
  11901. }
  11902. }
  11903. /**
  11904. * This method is overwritten since the buffer data might be shared
  11905. * and thus the hash should be shared as well.
  11906. *
  11907. * @param {NodeBuilder} builder - The current node builder.
  11908. * @return {string} The hash.
  11909. */
  11910. getHash( builder ) {
  11911. if ( this.bufferCount === 0 ) {
  11912. let bufferData = builder.globalCache.getData( this.value );
  11913. if ( bufferData === undefined ) {
  11914. bufferData = {
  11915. node: this
  11916. };
  11917. builder.globalCache.setData( this.value, bufferData );
  11918. }
  11919. return bufferData.node.uuid;
  11920. }
  11921. return this.uuid;
  11922. }
  11923. /**
  11924. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  11925. *
  11926. * @param {NodeBuilder} builder - The current node builder.
  11927. * @return {string} The input type.
  11928. */
  11929. getInputType( /*builder*/ ) {
  11930. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  11931. }
  11932. /**
  11933. * Enables element access with the given index node.
  11934. *
  11935. * @param {IndexNode} indexNode - The index node.
  11936. * @return {StorageArrayElementNode} A node representing the element access.
  11937. */
  11938. element( indexNode ) {
  11939. return storageElement( this, indexNode );
  11940. }
  11941. /**
  11942. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  11943. *
  11944. * @param {boolean} value - The value so set.
  11945. * @return {StorageBufferNode} A reference to this node.
  11946. */
  11947. setPBO( value ) {
  11948. this.isPBO = value;
  11949. return this;
  11950. }
  11951. /**
  11952. * Returns the `isPBO` value.
  11953. *
  11954. * @return {boolean} Whether the node represents a PBO or not.
  11955. */
  11956. getPBO() {
  11957. return this.isPBO;
  11958. }
  11959. /**
  11960. * Defines the node access.
  11961. *
  11962. * @param {string} value - The node access.
  11963. * @return {StorageBufferNode} A reference to this node.
  11964. */
  11965. setAccess( value ) {
  11966. this.access = value;
  11967. return this;
  11968. }
  11969. /**
  11970. * Convenience method for configuring a read-only node access.
  11971. *
  11972. * @return {StorageBufferNode} A reference to this node.
  11973. */
  11974. toReadOnly() {
  11975. return this.setAccess( NodeAccess.READ_ONLY );
  11976. }
  11977. /**
  11978. * Defines whether the node is atomic or not.
  11979. *
  11980. * @param {boolean} value - The atomic flag.
  11981. * @return {StorageBufferNode} A reference to this node.
  11982. */
  11983. setAtomic( value ) {
  11984. this.isAtomic = value;
  11985. return this;
  11986. }
  11987. /**
  11988. * Convenience method for making this node atomic.
  11989. *
  11990. * @return {StorageBufferNode} A reference to this node.
  11991. */
  11992. toAtomic() {
  11993. return this.setAtomic( true );
  11994. }
  11995. /**
  11996. * Returns attribute data for this storage buffer node.
  11997. *
  11998. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  11999. */
  12000. getAttributeData() {
  12001. if ( this._attribute === null ) {
  12002. this._attribute = bufferAttribute( this.value );
  12003. this._varying = varying( this._attribute );
  12004. }
  12005. return {
  12006. attribute: this._attribute,
  12007. varying: this._varying
  12008. };
  12009. }
  12010. /**
  12011. * This method is overwritten since the node type from the availability of storage buffers
  12012. * and the attribute data.
  12013. *
  12014. * @param {NodeBuilder} builder - The current node builder.
  12015. * @return {string} The node type.
  12016. */
  12017. getNodeType( builder ) {
  12018. if ( this.structTypeNode !== null ) {
  12019. return this.structTypeNode.getNodeType( builder );
  12020. }
  12021. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12022. return super.getNodeType( builder );
  12023. }
  12024. const { attribute } = this.getAttributeData();
  12025. return attribute.getNodeType( builder );
  12026. }
  12027. /**
  12028. * Returns the type of a member of the struct.
  12029. *
  12030. * @param {NodeBuilder} builder - The current node builder.
  12031. * @param {string} name - The name of the member.
  12032. * @return {string} The type of the member.
  12033. */
  12034. getMemberType( builder, name ) {
  12035. if ( this.structTypeNode !== null ) {
  12036. return this.structTypeNode.getMemberType( builder, name );
  12037. }
  12038. return 'void';
  12039. }
  12040. /**
  12041. * Generates the code snippet of the storage buffer node.
  12042. *
  12043. * @param {NodeBuilder} builder - The current node builder.
  12044. * @return {string} The generated code snippet.
  12045. */
  12046. generate( builder ) {
  12047. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  12048. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12049. return super.generate( builder );
  12050. }
  12051. const { attribute, varying } = this.getAttributeData();
  12052. const output = varying.build( builder );
  12053. builder.registerTransform( output, attribute );
  12054. return output;
  12055. }
  12056. }
  12057. /**
  12058. * TSL function for creating a storage buffer node.
  12059. *
  12060. * @tsl
  12061. * @function
  12062. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12063. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  12064. * @param {number} [count=0] - The buffer count.
  12065. * @returns {StorageBufferNode}
  12066. */
  12067. const storage = ( value, type = null, count = 0 ) => new StorageBufferNode( value, type, count );
  12068. /**
  12069. * @tsl
  12070. * @function
  12071. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  12072. *
  12073. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12074. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  12075. * @param {number} count - The buffer count.
  12076. * @returns {StorageBufferNode}
  12077. */
  12078. const storageObject = ( value, type, count ) => { // @deprecated, r171
  12079. warn( 'TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  12080. return storage( value, type, count ).setPBO( true );
  12081. };
  12082. /**
  12083. * This class represents shader indices of different types. The following predefined node
  12084. * objects cover frequent use cases:
  12085. *
  12086. * - `vertexIndex`: The index of a vertex within a mesh.
  12087. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  12088. * - `drawIndex`: The index of a draw call.
  12089. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  12090. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  12091. * - `subgroupIndex`: The index of a compute invocation's subgroup within its workgroup.
  12092. *
  12093. * @augments Node
  12094. */
  12095. class IndexNode extends Node {
  12096. static get type() {
  12097. return 'IndexNode';
  12098. }
  12099. /**
  12100. * Constructs a new index node.
  12101. *
  12102. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationGlobal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  12103. */
  12104. constructor( scope ) {
  12105. super( 'uint' );
  12106. /**
  12107. * The scope of the index node.
  12108. *
  12109. * @type {string}
  12110. */
  12111. this.scope = scope;
  12112. /**
  12113. * This flag can be used for type testing.
  12114. *
  12115. * @type {boolean}
  12116. * @readonly
  12117. * @default true
  12118. */
  12119. this.isIndexNode = true;
  12120. }
  12121. generate( builder ) {
  12122. const nodeType = this.getNodeType( builder );
  12123. const scope = this.scope;
  12124. let propertyName;
  12125. if ( scope === IndexNode.VERTEX ) {
  12126. propertyName = builder.getVertexIndex();
  12127. } else if ( scope === IndexNode.INSTANCE ) {
  12128. propertyName = builder.getInstanceIndex();
  12129. } else if ( scope === IndexNode.DRAW ) {
  12130. propertyName = builder.getDrawIndex();
  12131. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  12132. propertyName = builder.getInvocationLocalIndex();
  12133. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  12134. propertyName = builder.getInvocationSubgroupIndex();
  12135. } else if ( scope === IndexNode.SUBGROUP ) {
  12136. propertyName = builder.getSubgroupIndex();
  12137. } else {
  12138. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  12139. }
  12140. let output;
  12141. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  12142. output = propertyName;
  12143. } else {
  12144. const nodeVarying = varying( this );
  12145. output = nodeVarying.build( builder, nodeType );
  12146. }
  12147. return output;
  12148. }
  12149. }
  12150. IndexNode.VERTEX = 'vertex';
  12151. IndexNode.INSTANCE = 'instance';
  12152. IndexNode.SUBGROUP = 'subgroup';
  12153. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  12154. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  12155. IndexNode.DRAW = 'draw';
  12156. /**
  12157. * TSL object that represents the index of a vertex within a mesh.
  12158. *
  12159. * @tsl
  12160. * @type {IndexNode}
  12161. */
  12162. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  12163. /**
  12164. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  12165. *
  12166. * @tsl
  12167. * @type {IndexNode}
  12168. */
  12169. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  12170. /**
  12171. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  12172. *
  12173. * @tsl
  12174. * @type {IndexNode}
  12175. */
  12176. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  12177. /**
  12178. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  12179. *
  12180. * @tsl
  12181. * @type {IndexNode}
  12182. */
  12183. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  12184. /**
  12185. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  12186. *
  12187. * @tsl
  12188. * @type {IndexNode}
  12189. */
  12190. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  12191. /**
  12192. * TSL object that represents the index of a draw call.
  12193. *
  12194. * @tsl
  12195. * @type {IndexNode}
  12196. */
  12197. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  12198. /**
  12199. * This node implements the vertex shader logic which is required
  12200. * when rendering 3D objects via instancing. The code makes sure
  12201. * vertex positions, normals and colors can be modified via instanced
  12202. * data.
  12203. *
  12204. * @augments Node
  12205. */
  12206. class InstanceNode extends Node {
  12207. static get type() {
  12208. return 'InstanceNode';
  12209. }
  12210. /**
  12211. * Constructs a new instance node.
  12212. *
  12213. * @param {number} count - The number of instances.
  12214. * @param {InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  12215. * @param {?InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  12216. */
  12217. constructor( count, instanceMatrix, instanceColor = null ) {
  12218. super( 'void' );
  12219. /**
  12220. * The number of instances.
  12221. *
  12222. * @type {number}
  12223. */
  12224. this.count = count;
  12225. /**
  12226. * Instanced buffer attribute representing the transformation of instances.
  12227. *
  12228. * @type {InstancedBufferAttribute}
  12229. */
  12230. this.instanceMatrix = instanceMatrix;
  12231. /**
  12232. * Instanced buffer attribute representing the color of instances.
  12233. *
  12234. * @type {InstancedBufferAttribute}
  12235. */
  12236. this.instanceColor = instanceColor;
  12237. /**
  12238. * The node that represents the instance matrix data.
  12239. *
  12240. * @type {?Node}
  12241. */
  12242. this.instanceMatrixNode = null;
  12243. /**
  12244. * The node that represents the instance color data.
  12245. *
  12246. * @type {?Node}
  12247. * @default null
  12248. */
  12249. this.instanceColorNode = null;
  12250. /**
  12251. * The update type is set to `frame` since an update
  12252. * of instanced buffer data must be checked per frame.
  12253. *
  12254. * @type {string}
  12255. * @default 'frame'
  12256. */
  12257. this.updateType = NodeUpdateType.FRAME;
  12258. /**
  12259. * A reference to a buffer that is used by `instanceMatrixNode`.
  12260. *
  12261. * @type {?InstancedInterleavedBuffer}
  12262. */
  12263. this.buffer = null;
  12264. /**
  12265. * A reference to a buffer that is used by `instanceColorNode`.
  12266. *
  12267. * @type {?InstancedBufferAttribute}
  12268. */
  12269. this.bufferColor = null;
  12270. }
  12271. /**
  12272. * Tracks whether the matrix data is provided via a storage buffer.
  12273. *
  12274. * @type {boolean}
  12275. */
  12276. get isStorageMatrix() {
  12277. const { instanceMatrix } = this;
  12278. return instanceMatrix && instanceMatrix.isStorageInstancedBufferAttribute === true;
  12279. }
  12280. /**
  12281. * Tracks whether the color data is provided via a storage buffer.
  12282. *
  12283. * @type {boolean}
  12284. */
  12285. get isStorageColor() {
  12286. const { instanceColor } = this;
  12287. return instanceColor && instanceColor.isStorageInstancedBufferAttribute === true;
  12288. }
  12289. /**
  12290. * Setups the internal buffers and nodes and assigns the transformed vertex data
  12291. * to predefined node variables for accumulation. That follows the same patterns
  12292. * like with morph and skinning nodes.
  12293. *
  12294. * @param {NodeBuilder} builder - The current node builder.
  12295. */
  12296. setup( builder ) {
  12297. const { instanceMatrix, instanceColor, isStorageMatrix, isStorageColor } = this;
  12298. const { count } = instanceMatrix;
  12299. let { instanceMatrixNode, instanceColorNode } = this;
  12300. if ( instanceMatrixNode === null ) {
  12301. if ( isStorageMatrix ) {
  12302. instanceMatrixNode = storage( instanceMatrix, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  12303. } else {
  12304. // Both backends have ~64kb UBO limit; fallback to attributes above 1000 matrices.
  12305. if ( count <= 1000 ) {
  12306. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  12307. } else {
  12308. const interleaved = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  12309. this.buffer = interleaved;
  12310. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  12311. const instanceBuffers = [
  12312. bufferFn( interleaved, 'vec4', 16, 0 ),
  12313. bufferFn( interleaved, 'vec4', 16, 4 ),
  12314. bufferFn( interleaved, 'vec4', 16, 8 ),
  12315. bufferFn( interleaved, 'vec4', 16, 12 )
  12316. ];
  12317. instanceMatrixNode = mat4( ...instanceBuffers );
  12318. }
  12319. }
  12320. this.instanceMatrixNode = instanceMatrixNode;
  12321. }
  12322. if ( instanceColor && instanceColorNode === null ) {
  12323. if ( isStorageColor ) {
  12324. instanceColorNode = storage( instanceColor, 'vec3', Math.max( instanceColor.count, 1 ) ).element( instanceIndex );
  12325. } else {
  12326. const bufferAttribute = new InstancedBufferAttribute( instanceColor.array, 3 );
  12327. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  12328. this.bufferColor = bufferAttribute;
  12329. instanceColorNode = vec3( bufferFn( bufferAttribute, 'vec3', 3, 0 ) );
  12330. }
  12331. this.instanceColorNode = instanceColorNode;
  12332. }
  12333. // POSITION
  12334. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  12335. positionLocal.assign( instancePosition );
  12336. // NORMAL
  12337. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  12338. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  12339. // ASSIGNS
  12340. normalLocal.assign( instanceNormal );
  12341. }
  12342. // COLOR
  12343. if ( this.instanceColorNode !== null ) {
  12344. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  12345. }
  12346. }
  12347. /**
  12348. * Checks if the internal buffers require an update.
  12349. *
  12350. * @param {NodeFrame} frame - The current node frame.
  12351. */
  12352. update( /*frame*/ ) {
  12353. if ( this.buffer !== null && this.isStorageMatrix !== true ) {
  12354. this.buffer.clearUpdateRanges();
  12355. this.buffer.updateRanges.push( ... this.instanceMatrix.updateRanges );
  12356. // update version if necessary
  12357. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.instanceMatrix.version !== this.buffer.version ) {
  12358. this.buffer.version = this.instanceMatrix.version;
  12359. }
  12360. }
  12361. if ( this.instanceColor && this.bufferColor !== null && this.isStorageColor !== true ) {
  12362. this.bufferColor.clearUpdateRanges();
  12363. this.bufferColor.updateRanges.push( ... this.instanceColor.updateRanges );
  12364. if ( this.instanceColor.usage !== DynamicDrawUsage && this.instanceColor.version !== this.bufferColor.version ) {
  12365. this.bufferColor.version = this.instanceColor.version;
  12366. }
  12367. }
  12368. }
  12369. }
  12370. /**
  12371. * TSL function for creating an instance node.
  12372. *
  12373. * @tsl
  12374. * @function
  12375. * @param {number} count - The number of instances.
  12376. * @param {InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  12377. * @param {?InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  12378. * @returns {InstanceNode}
  12379. */
  12380. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  12381. /**
  12382. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  12383. * It allows an easier setup of the instance node.
  12384. *
  12385. * @augments InstanceNode
  12386. */
  12387. class InstancedMeshNode extends InstanceNode {
  12388. static get type() {
  12389. return 'InstancedMeshNode';
  12390. }
  12391. /**
  12392. * Constructs a new instanced mesh node.
  12393. *
  12394. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  12395. */
  12396. constructor( instancedMesh ) {
  12397. const { count, instanceMatrix, instanceColor } = instancedMesh;
  12398. super( count, instanceMatrix, instanceColor );
  12399. /**
  12400. * A reference to the instanced mesh.
  12401. *
  12402. * @type {InstancedMesh}
  12403. */
  12404. this.instancedMesh = instancedMesh;
  12405. }
  12406. }
  12407. /**
  12408. * TSL function for creating an instanced mesh node.
  12409. *
  12410. * @tsl
  12411. * @function
  12412. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  12413. * @returns {InstancedMeshNode}
  12414. */
  12415. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  12416. /**
  12417. * This node implements the vertex shader logic which is required
  12418. * when rendering 3D objects via batching. `BatchNode` must be used
  12419. * with instances of {@link BatchedMesh}.
  12420. *
  12421. * @augments Node
  12422. */
  12423. class BatchNode extends Node {
  12424. static get type() {
  12425. return 'BatchNode';
  12426. }
  12427. /**
  12428. * Constructs a new batch node.
  12429. *
  12430. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  12431. */
  12432. constructor( batchMesh ) {
  12433. super( 'void' );
  12434. /**
  12435. * A reference to batched mesh.
  12436. *
  12437. * @type {BatchedMesh}
  12438. */
  12439. this.batchMesh = batchMesh;
  12440. /**
  12441. * The batching index node.
  12442. *
  12443. * @type {?IndexNode}
  12444. * @default null
  12445. */
  12446. this.batchingIdNode = null;
  12447. }
  12448. /**
  12449. * Setups the internal buffers and nodes and assigns the transformed vertex data
  12450. * to predefined node variables for accumulation. That follows the same patterns
  12451. * like with morph and skinning nodes.
  12452. *
  12453. * @param {NodeBuilder} builder - The current node builder.
  12454. */
  12455. setup( builder ) {
  12456. if ( this.batchingIdNode === null ) {
  12457. if ( builder.getDrawIndex() === null ) {
  12458. this.batchingIdNode = instanceIndex;
  12459. } else {
  12460. this.batchingIdNode = drawIndex;
  12461. }
  12462. }
  12463. const getIndirectIndex = Fn( ( [ id ] ) => {
  12464. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x ).toConst();
  12465. const x = int( id ).mod( size ).toConst();
  12466. const y = int( id ).div( size ).toConst();
  12467. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  12468. } ).setLayout( {
  12469. name: 'getIndirectIndex',
  12470. type: 'uint',
  12471. inputs: [
  12472. { name: 'id', type: 'int' }
  12473. ]
  12474. } );
  12475. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  12476. const matricesTexture = this.batchMesh._matricesTexture;
  12477. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x ).toConst();
  12478. const j = float( indirectId ).mul( 4 ).toInt().toConst();
  12479. const x = j.mod( size ).toConst();
  12480. const y = j.div( size ).toConst();
  12481. const batchingMatrix = mat4(
  12482. textureLoad( matricesTexture, ivec2( x, y ) ),
  12483. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  12484. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  12485. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  12486. );
  12487. const colorsTexture = this.batchMesh._colorsTexture;
  12488. if ( colorsTexture !== null ) {
  12489. const getBatchingColor = Fn( ( [ id ] ) => {
  12490. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x ).toConst();
  12491. const j = id;
  12492. const x = j.mod( size ).toConst();
  12493. const y = j.div( size ).toConst();
  12494. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  12495. } ).setLayout( {
  12496. name: 'getBatchingColor',
  12497. type: 'vec3',
  12498. inputs: [
  12499. { name: 'id', type: 'int' }
  12500. ]
  12501. } );
  12502. const color = getBatchingColor( indirectId );
  12503. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  12504. }
  12505. const bm = mat3( batchingMatrix );
  12506. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  12507. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  12508. const batchingNormal = bm.mul( transformedNormal ).xyz;
  12509. normalLocal.assign( batchingNormal );
  12510. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  12511. tangentLocal.mulAssign( bm );
  12512. }
  12513. }
  12514. }
  12515. /**
  12516. * TSL function for creating a batch node.
  12517. *
  12518. * @tsl
  12519. * @function
  12520. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  12521. * @returns {BatchNode}
  12522. */
  12523. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  12524. const _frameId = new WeakMap();
  12525. /**
  12526. * This node implements the vertex transformation shader logic which is required
  12527. * for skinning/skeletal animation.
  12528. *
  12529. * @augments Node
  12530. */
  12531. class SkinningNode extends Node {
  12532. static get type() {
  12533. return 'SkinningNode';
  12534. }
  12535. /**
  12536. * Constructs a new skinning node.
  12537. *
  12538. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12539. */
  12540. constructor( skinnedMesh ) {
  12541. super( 'void' );
  12542. /**
  12543. * The skinned mesh.
  12544. *
  12545. * @type {SkinnedMesh}
  12546. */
  12547. this.skinnedMesh = skinnedMesh;
  12548. /**
  12549. * The update type overwritten since skinning nodes are updated per object.
  12550. *
  12551. * @type {string}
  12552. */
  12553. this.updateType = NodeUpdateType.OBJECT;
  12554. //
  12555. /**
  12556. * The skin index attribute.
  12557. *
  12558. * @type {AttributeNode}
  12559. */
  12560. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  12561. /**
  12562. * The skin weight attribute.
  12563. *
  12564. * @type {AttributeNode}
  12565. */
  12566. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  12567. /**
  12568. * The bind matrix node.
  12569. *
  12570. * @type {Node<mat4>}
  12571. */
  12572. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  12573. /**
  12574. * The bind matrix inverse node.
  12575. *
  12576. * @type {Node<mat4>}
  12577. */
  12578. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  12579. /**
  12580. * The bind matrices as a uniform buffer node.
  12581. *
  12582. * @type {Node}
  12583. */
  12584. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12585. /**
  12586. * The current vertex position in local space.
  12587. *
  12588. * @type {Node<vec3>}
  12589. */
  12590. this.positionNode = positionLocal;
  12591. /**
  12592. * The result of vertex position in local space.
  12593. *
  12594. * @type {Node<vec3>}
  12595. */
  12596. this.toPositionNode = positionLocal;
  12597. /**
  12598. * The previous bind matrices as a uniform buffer node.
  12599. * Required for computing motion vectors.
  12600. *
  12601. * @type {?Node}
  12602. * @default null
  12603. */
  12604. this.previousBoneMatricesNode = null;
  12605. }
  12606. /**
  12607. * Transforms the given vertex position via skinning.
  12608. *
  12609. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12610. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  12611. * @return {Node<vec3>} The transformed vertex position.
  12612. */
  12613. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  12614. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12615. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12616. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12617. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12618. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12619. // POSITION
  12620. const skinVertex = bindMatrixNode.mul( position );
  12621. const skinned = add(
  12622. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  12623. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  12624. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  12625. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  12626. );
  12627. return bindMatrixInverseNode.mul( skinned ).xyz;
  12628. }
  12629. /**
  12630. * Transforms the given vertex normal via skinning.
  12631. *
  12632. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12633. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  12634. * @return {Node<vec3>} The transformed vertex normal.
  12635. */
  12636. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  12637. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12638. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12639. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12640. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12641. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12642. // NORMAL
  12643. let skinMatrix = add(
  12644. skinWeightNode.x.mul( boneMatX ),
  12645. skinWeightNode.y.mul( boneMatY ),
  12646. skinWeightNode.z.mul( boneMatZ ),
  12647. skinWeightNode.w.mul( boneMatW )
  12648. );
  12649. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  12650. return skinMatrix.transformDirection( normal ).xyz;
  12651. }
  12652. /**
  12653. * Computes the transformed/skinned vertex position of the previous frame.
  12654. *
  12655. * @param {NodeBuilder} builder - The current node builder.
  12656. * @return {Node<vec3>} The skinned position from the previous frame.
  12657. */
  12658. getPreviousSkinnedPosition( builder ) {
  12659. const skinnedMesh = builder.object;
  12660. if ( this.previousBoneMatricesNode === null ) {
  12661. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  12662. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12663. }
  12664. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  12665. }
  12666. /**
  12667. * Returns `true` if bone matrices from the previous frame are required. Relevant
  12668. * when computing motion vectors with {@link VelocityNode}.
  12669. *
  12670. * @param {NodeBuilder} builder - The current node builder.
  12671. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  12672. */
  12673. needsPreviousBoneMatrices( builder ) {
  12674. const mrt = builder.renderer.getMRT();
  12675. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  12676. }
  12677. /**
  12678. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  12679. *
  12680. * @param {NodeBuilder} builder - The current node builder.
  12681. * @return {Node<vec3>} The transformed vertex position.
  12682. */
  12683. setup( builder ) {
  12684. if ( this.needsPreviousBoneMatrices( builder ) ) {
  12685. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  12686. }
  12687. const skinPosition = this.getSkinnedPosition();
  12688. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  12689. //
  12690. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  12691. const skinNormal = this.getSkinnedNormal();
  12692. normalLocal.assign( skinNormal );
  12693. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  12694. tangentLocal.assign( skinNormal );
  12695. }
  12696. }
  12697. return skinPosition;
  12698. }
  12699. /**
  12700. * Generates the code snippet of the skinning node.
  12701. *
  12702. * @param {NodeBuilder} builder - The current node builder.
  12703. * @param {string} output - The current output.
  12704. * @return {string} The generated code snippet.
  12705. */
  12706. generate( builder, output ) {
  12707. if ( output !== 'void' ) {
  12708. return super.generate( builder, output );
  12709. }
  12710. }
  12711. /**
  12712. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  12713. *
  12714. * @param {NodeFrame} frame - The current node frame.
  12715. */
  12716. update( frame ) {
  12717. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  12718. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  12719. _frameId.set( skeleton, frame.frameId );
  12720. if ( this.previousBoneMatricesNode !== null ) {
  12721. if ( skeleton.previousBoneMatrices === null ) {
  12722. // cloned skeletons miss "previousBoneMatrices" in their first updated
  12723. skeleton.previousBoneMatrices = new Float32Array( skeleton.boneMatrices );
  12724. }
  12725. skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  12726. }
  12727. skeleton.update();
  12728. }
  12729. }
  12730. /**
  12731. * TSL function for creating a skinning node.
  12732. *
  12733. * @tsl
  12734. * @function
  12735. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12736. * @returns {SkinningNode}
  12737. */
  12738. const skinning = ( skinnedMesh ) => new SkinningNode( skinnedMesh );
  12739. /**
  12740. * TSL function for computing skinning.
  12741. *
  12742. * @tsl
  12743. * @function
  12744. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12745. * @param {Node<vec3>} [toPosition=null] - The target position.
  12746. * @returns {SkinningNode}
  12747. */
  12748. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  12749. const node = new SkinningNode( skinnedMesh );
  12750. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12751. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12752. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12753. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  12754. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  12755. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  12756. node.toPositionNode = toPosition;
  12757. return nodeObject( node );
  12758. };
  12759. /**
  12760. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  12761. * ```js
  12762. * Loop( count, ( { i } ) => {
  12763. *
  12764. * } );
  12765. * ```
  12766. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  12767. * ```js
  12768. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  12769. *
  12770. * } );
  12771. *```
  12772. * Nested loops can be defined in a compacted form:
  12773. * ```js
  12774. * Loop( 10, 5, ( { i, j } ) => {
  12775. *
  12776. * } );
  12777. * ```
  12778. * Loops that should run backwards can be defined like so:
  12779. * ```js
  12780. * Loop( { start: 10 }, () => {} );
  12781. * ```
  12782. * It is possible to execute with boolean values, similar to the `while` syntax.
  12783. * ```js
  12784. * const value = float( 0 ).toVar();
  12785. *
  12786. * Loop( value.lessThan( 10 ), () => {
  12787. *
  12788. * value.addAssign( 1 );
  12789. *
  12790. * } );
  12791. * ```
  12792. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  12793. * @augments Node
  12794. */
  12795. class LoopNode extends Node {
  12796. static get type() {
  12797. return 'LoopNode';
  12798. }
  12799. /**
  12800. * Constructs a new loop node.
  12801. *
  12802. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  12803. */
  12804. constructor( params = [] ) {
  12805. super( 'void' );
  12806. this.params = params;
  12807. }
  12808. /**
  12809. * Returns a loop variable name based on an index. The pattern is
  12810. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  12811. *
  12812. * @param {number} index - The index.
  12813. * @return {string} The loop variable name.
  12814. */
  12815. getVarName( index ) {
  12816. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  12817. }
  12818. /**
  12819. * Returns properties about this node.
  12820. *
  12821. * @param {NodeBuilder} builder - The current node builder.
  12822. * @return {Object} The node properties.
  12823. */
  12824. getProperties( builder ) {
  12825. const properties = builder.getNodeProperties( this );
  12826. if ( properties.stackNode !== undefined ) return properties;
  12827. //
  12828. const inputs = {};
  12829. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12830. const param = this.params[ i ];
  12831. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  12832. const type = ( param.isNode !== true && param.type ) || 'int';
  12833. inputs[ name ] = expression( name, type );
  12834. }
  12835. const stack = builder.addStack();
  12836. const fnCall = this.params[ this.params.length - 1 ]( inputs );
  12837. properties.returnsNode = fnCall.context( { nodeLoop: fnCall } );
  12838. properties.stackNode = stack;
  12839. const baseParam = this.params[ 0 ];
  12840. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  12841. const fnUpdateCall = Fn( this.params[ 0 ].update )( inputs );
  12842. properties.updateNode = fnUpdateCall.context( { nodeLoop: fnUpdateCall } );
  12843. }
  12844. builder.removeStack();
  12845. return properties;
  12846. }
  12847. setup( builder ) {
  12848. // setup properties
  12849. this.getProperties( builder );
  12850. if ( builder.fnCall ) {
  12851. const shaderNodeData = builder.getDataFromNode( builder.fnCall.shaderNode );
  12852. shaderNodeData.hasLoop = true;
  12853. }
  12854. }
  12855. generate( builder ) {
  12856. const properties = this.getProperties( builder );
  12857. const params = this.params;
  12858. const stackNode = properties.stackNode;
  12859. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  12860. const param = params[ i ];
  12861. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  12862. if ( param.isNode ) {
  12863. if ( param.getNodeType( builder ) === 'bool' ) {
  12864. isWhile = true;
  12865. type = 'bool';
  12866. end = param.build( builder, type );
  12867. } else {
  12868. type = 'int';
  12869. name = this.getVarName( i );
  12870. start = '0';
  12871. end = param.build( builder, type );
  12872. condition = '<';
  12873. }
  12874. } else {
  12875. type = param.type || 'int';
  12876. name = param.name || this.getVarName( i );
  12877. start = param.start;
  12878. end = param.end;
  12879. condition = param.condition;
  12880. update = param.update;
  12881. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  12882. else if ( start && start.isNode ) start = start.build( builder, type );
  12883. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  12884. else if ( end && end.isNode ) end = end.build( builder, type );
  12885. if ( start !== undefined && end === undefined ) {
  12886. start = start + ' - 1';
  12887. end = '0';
  12888. condition = '>=';
  12889. } else if ( end !== undefined && start === undefined ) {
  12890. start = '0';
  12891. condition = '<';
  12892. }
  12893. if ( condition === undefined ) {
  12894. if ( Number( start ) > Number( end ) ) {
  12895. condition = '>=';
  12896. } else {
  12897. condition = '<';
  12898. }
  12899. }
  12900. }
  12901. let loopSnippet;
  12902. if ( isWhile ) {
  12903. loopSnippet = `while ( ${ end } )`;
  12904. } else {
  12905. const internalParam = { start, end};
  12906. //
  12907. const startSnippet = internalParam.start;
  12908. const endSnippet = internalParam.end;
  12909. let updateSnippet;
  12910. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  12911. if ( update !== undefined && update !== null ) {
  12912. switch ( typeof update ) {
  12913. case 'function':
  12914. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  12915. const snippet = flow.code.replace( /\t|;/g, '' );
  12916. updateSnippet = snippet;
  12917. break;
  12918. case 'number':
  12919. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  12920. break;
  12921. case 'string':
  12922. updateSnippet = name + ' ' + update;
  12923. break;
  12924. default:
  12925. if ( update.isNode ) {
  12926. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  12927. } else {
  12928. error( 'TSL: \'Loop( { update: ... } )\' is not a function, string or number.' );
  12929. updateSnippet = 'break /* invalid update */';
  12930. }
  12931. }
  12932. } else {
  12933. if ( type === 'int' || type === 'uint' ) {
  12934. update = condition.includes( '<' ) ? '++' : '--';
  12935. } else {
  12936. update = deltaOperator() + ' 1.';
  12937. }
  12938. updateSnippet = name + ' ' + update;
  12939. }
  12940. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  12941. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  12942. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  12943. }
  12944. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  12945. }
  12946. const stackSnippet = stackNode.build( builder, 'void' );
  12947. properties.returnsNode.build( builder, 'void' );
  12948. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  12949. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12950. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  12951. }
  12952. builder.addFlowTab();
  12953. }
  12954. }
  12955. /**
  12956. * TSL function for creating a loop node.
  12957. *
  12958. * @tsl
  12959. * @function
  12960. * @param {...any} params - A list of parameters.
  12961. * @returns {LoopNode}
  12962. */
  12963. const Loop = ( ...params ) => new LoopNode( nodeArray( params, 'int' ) ).toStack();
  12964. /**
  12965. * TSL function for creating a `Continue()` expression.
  12966. *
  12967. * @tsl
  12968. * @function
  12969. * @returns {ExpressionNode}
  12970. */
  12971. const Continue = () => expression( 'continue' ).toStack();
  12972. /**
  12973. * TSL function for creating a `Break()` expression.
  12974. *
  12975. * @tsl
  12976. * @function
  12977. * @returns {ExpressionNode}
  12978. */
  12979. const Break = () => expression( 'break' ).toStack();
  12980. const _morphTextures = /*@__PURE__*/ new WeakMap();
  12981. const _morphVec4 = /*@__PURE__*/ new Vector4();
  12982. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  12983. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  12984. const y = texelIndex.div( width );
  12985. const x = texelIndex.sub( y.mul( width ) );
  12986. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  12987. return bufferAttrib.mul( influence );
  12988. } );
  12989. function getEntry( geometry ) {
  12990. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12991. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  12992. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  12993. // instead of using attributes, the WebGL 2 code path encodes morph targets
  12994. // into an array of data textures. Each layer represents a single morph target.
  12995. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12996. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12997. let entry = _morphTextures.get( geometry );
  12998. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  12999. if ( entry !== undefined ) entry.texture.dispose();
  13000. const morphTargets = geometry.morphAttributes.position || [];
  13001. const morphNormals = geometry.morphAttributes.normal || [];
  13002. const morphColors = geometry.morphAttributes.color || [];
  13003. let vertexDataCount = 0;
  13004. if ( hasMorphPosition === true ) vertexDataCount = 1;
  13005. if ( hasMorphNormals === true ) vertexDataCount = 2;
  13006. if ( hasMorphColors === true ) vertexDataCount = 3;
  13007. let width = geometry.attributes.position.count * vertexDataCount;
  13008. let height = 1;
  13009. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  13010. if ( width > maxTextureSize ) {
  13011. height = Math.ceil( width / maxTextureSize );
  13012. width = maxTextureSize;
  13013. }
  13014. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  13015. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  13016. bufferTexture.type = FloatType;
  13017. bufferTexture.needsUpdate = true;
  13018. // fill buffer
  13019. const vertexDataStride = vertexDataCount * 4;
  13020. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  13021. const morphTarget = morphTargets[ i ];
  13022. const morphNormal = morphNormals[ i ];
  13023. const morphColor = morphColors[ i ];
  13024. const offset = width * height * 4 * i;
  13025. for ( let j = 0; j < morphTarget.count; j ++ ) {
  13026. const stride = j * vertexDataStride;
  13027. if ( hasMorphPosition === true ) {
  13028. _morphVec4.fromBufferAttribute( morphTarget, j );
  13029. buffer[ offset + stride + 0 ] = _morphVec4.x;
  13030. buffer[ offset + stride + 1 ] = _morphVec4.y;
  13031. buffer[ offset + stride + 2 ] = _morphVec4.z;
  13032. buffer[ offset + stride + 3 ] = 0;
  13033. }
  13034. if ( hasMorphNormals === true ) {
  13035. _morphVec4.fromBufferAttribute( morphNormal, j );
  13036. buffer[ offset + stride + 4 ] = _morphVec4.x;
  13037. buffer[ offset + stride + 5 ] = _morphVec4.y;
  13038. buffer[ offset + stride + 6 ] = _morphVec4.z;
  13039. buffer[ offset + stride + 7 ] = 0;
  13040. }
  13041. if ( hasMorphColors === true ) {
  13042. _morphVec4.fromBufferAttribute( morphColor, j );
  13043. buffer[ offset + stride + 8 ] = _morphVec4.x;
  13044. buffer[ offset + stride + 9 ] = _morphVec4.y;
  13045. buffer[ offset + stride + 10 ] = _morphVec4.z;
  13046. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  13047. }
  13048. }
  13049. }
  13050. entry = {
  13051. count: morphTargetsCount,
  13052. texture: bufferTexture,
  13053. stride: vertexDataCount,
  13054. size: new Vector2( width, height )
  13055. };
  13056. _morphTextures.set( geometry, entry );
  13057. function disposeTexture() {
  13058. bufferTexture.dispose();
  13059. _morphTextures.delete( geometry );
  13060. geometry.removeEventListener( 'dispose', disposeTexture );
  13061. }
  13062. geometry.addEventListener( 'dispose', disposeTexture );
  13063. }
  13064. return entry;
  13065. }
  13066. /**
  13067. * This node implements the vertex transformation shader logic which is required
  13068. * for morph target animation.
  13069. *
  13070. * @augments Node
  13071. */
  13072. class MorphNode extends Node {
  13073. static get type() {
  13074. return 'MorphNode';
  13075. }
  13076. /**
  13077. * Constructs a new morph node.
  13078. *
  13079. * @param {Mesh} mesh - The mesh holding the morph targets.
  13080. */
  13081. constructor( mesh ) {
  13082. super( 'void' );
  13083. /**
  13084. * The mesh holding the morph targets.
  13085. *
  13086. * @type {Mesh}
  13087. */
  13088. this.mesh = mesh;
  13089. /**
  13090. * A uniform node which represents the morph base influence value.
  13091. *
  13092. * @type {UniformNode<float>}
  13093. */
  13094. this.morphBaseInfluence = uniform( 1 );
  13095. /**
  13096. * The update type overwritten since morph nodes are updated per object.
  13097. *
  13098. * @type {string}
  13099. */
  13100. this.updateType = NodeUpdateType.OBJECT;
  13101. }
  13102. /**
  13103. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  13104. *
  13105. * @param {NodeBuilder} builder - The current node builder.
  13106. */
  13107. setup( builder ) {
  13108. const { geometry } = builder;
  13109. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  13110. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  13111. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  13112. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  13113. // nodes
  13114. const { texture: bufferMap, stride, size } = getEntry( geometry );
  13115. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  13116. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  13117. const width = int( size.width );
  13118. Loop( morphTargetsCount, ( { i } ) => {
  13119. const influence = float( 0 ).toVar();
  13120. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  13121. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  13122. } else {
  13123. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  13124. }
  13125. If( influence.notEqual( 0 ), () => {
  13126. if ( hasMorphPosition === true ) {
  13127. positionLocal.addAssign( getMorph( {
  13128. bufferMap,
  13129. influence,
  13130. stride,
  13131. width,
  13132. depth: i,
  13133. offset: int( 0 )
  13134. } ) );
  13135. }
  13136. if ( hasMorphNormals === true ) {
  13137. normalLocal.addAssign( getMorph( {
  13138. bufferMap,
  13139. influence,
  13140. stride,
  13141. width,
  13142. depth: i,
  13143. offset: int( 1 )
  13144. } ) );
  13145. }
  13146. } );
  13147. } );
  13148. }
  13149. /**
  13150. * Updates the state of the morphed mesh by updating the base influence.
  13151. *
  13152. * @param {NodeFrame} frame - The current node frame.
  13153. */
  13154. update( /*frame*/ ) {
  13155. const morphBaseInfluence = this.morphBaseInfluence;
  13156. if ( this.mesh.geometry.morphTargetsRelative ) {
  13157. morphBaseInfluence.value = 1;
  13158. } else {
  13159. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  13160. }
  13161. }
  13162. }
  13163. /**
  13164. * TSL function for creating a morph node.
  13165. *
  13166. * @tsl
  13167. * @function
  13168. * @param {Mesh} mesh - The mesh holding the morph targets.
  13169. * @returns {MorphNode}
  13170. */
  13171. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  13172. /**
  13173. * Base class for lighting nodes.
  13174. *
  13175. * @augments Node
  13176. */
  13177. class LightingNode extends Node {
  13178. static get type() {
  13179. return 'LightingNode';
  13180. }
  13181. /**
  13182. * Constructs a new lighting node.
  13183. */
  13184. constructor() {
  13185. super( 'vec3' );
  13186. /**
  13187. * This flag can be used for type testing.
  13188. *
  13189. * @type {boolean}
  13190. * @readonly
  13191. * @default true
  13192. */
  13193. this.isLightingNode = true;
  13194. }
  13195. }
  13196. /**
  13197. * A generic class that can be used by nodes which contribute
  13198. * ambient occlusion to the scene. E.g. an ambient occlusion map
  13199. * node can be used as input for this module. Used in {@link NodeMaterial}.
  13200. *
  13201. * @augments LightingNode
  13202. */
  13203. class AONode extends LightingNode {
  13204. static get type() {
  13205. return 'AONode';
  13206. }
  13207. /**
  13208. * Constructs a new AO node.
  13209. *
  13210. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  13211. */
  13212. constructor( aoNode = null ) {
  13213. super();
  13214. /**
  13215. * The ambient occlusion node.
  13216. *
  13217. * @type {?Node<float>}
  13218. * @default null
  13219. */
  13220. this.aoNode = aoNode;
  13221. }
  13222. setup( builder ) {
  13223. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  13224. }
  13225. }
  13226. /**
  13227. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  13228. * by adding lighting specific context data. It represents the runtime context of
  13229. * {@link LightsNode}.
  13230. *
  13231. * @augments ContextNode
  13232. */
  13233. class LightingContextNode extends ContextNode {
  13234. static get type() {
  13235. return 'LightingContextNode';
  13236. }
  13237. /**
  13238. * Constructs a new lighting context node.
  13239. *
  13240. * @param {LightsNode} lightsNode - The lights node.
  13241. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  13242. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  13243. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  13244. */
  13245. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  13246. super( lightsNode );
  13247. /**
  13248. * The current lighting model.
  13249. *
  13250. * @type {?LightingModel}
  13251. * @default null
  13252. */
  13253. this.lightingModel = lightingModel;
  13254. /**
  13255. * A backdrop node.
  13256. *
  13257. * @type {?Node<vec3>}
  13258. * @default null
  13259. */
  13260. this.backdropNode = backdropNode;
  13261. /**
  13262. * A backdrop alpha node.
  13263. *
  13264. * @type {?Node<float>}
  13265. * @default null
  13266. */
  13267. this.backdropAlphaNode = backdropAlphaNode;
  13268. this._value = null;
  13269. }
  13270. /**
  13271. * Returns a lighting context object.
  13272. *
  13273. * @return {{
  13274. * radiance: Node<vec3>,
  13275. * irradiance: Node<vec3>,
  13276. * iblIrradiance: Node<vec3>,
  13277. * ambientOcclusion: Node<float>,
  13278. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  13279. * backdrop: Node<vec3>,
  13280. * backdropAlpha: Node<float>
  13281. * }} The lighting context object.
  13282. */
  13283. getContext() {
  13284. const { backdropNode, backdropAlphaNode } = this;
  13285. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  13286. directSpecular = vec3().toVar( 'directSpecular' ),
  13287. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  13288. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  13289. const reflectedLight = {
  13290. directDiffuse,
  13291. directSpecular,
  13292. indirectDiffuse,
  13293. indirectSpecular
  13294. };
  13295. const context = {
  13296. radiance: vec3().toVar( 'radiance' ),
  13297. irradiance: vec3().toVar( 'irradiance' ),
  13298. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  13299. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  13300. reflectedLight,
  13301. backdrop: backdropNode,
  13302. backdropAlpha: backdropAlphaNode
  13303. };
  13304. return context;
  13305. }
  13306. setup( builder ) {
  13307. this.value = this._value || ( this._value = this.getContext() );
  13308. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  13309. return super.setup( builder );
  13310. }
  13311. }
  13312. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  13313. /**
  13314. * A generic class that can be used by nodes which contribute
  13315. * irradiance to the scene. E.g. a light map node can be used
  13316. * as input for this module. Used in {@link NodeMaterial}.
  13317. *
  13318. * @augments LightingNode
  13319. */
  13320. class IrradianceNode extends LightingNode {
  13321. static get type() {
  13322. return 'IrradianceNode';
  13323. }
  13324. /**
  13325. * Constructs a new irradiance node.
  13326. *
  13327. * @param {Node<vec3>} node - A node contributing irradiance.
  13328. */
  13329. constructor( node ) {
  13330. super();
  13331. /**
  13332. * A node contributing irradiance.
  13333. *
  13334. * @type {Node<vec3>}
  13335. */
  13336. this.node = node;
  13337. }
  13338. setup( builder ) {
  13339. builder.context.irradiance.addAssign( this.node );
  13340. }
  13341. }
  13342. const _size$5 = /*@__PURE__*/ new Vector2();
  13343. /**
  13344. * A special type of texture node which represents the data of the current viewport
  13345. * as a texture. The module extracts data from the current bound framebuffer with
  13346. * a copy operation so no extra render pass is required to produce the texture data
  13347. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  13348. * variety of effects like refractive or transmissive materials.
  13349. *
  13350. * @augments TextureNode
  13351. */
  13352. class ViewportTextureNode extends TextureNode {
  13353. static get type() {
  13354. return 'ViewportTextureNode';
  13355. }
  13356. /**
  13357. * Constructs a new viewport texture node.
  13358. *
  13359. * @param {Node} [uvNode=screenUV] - The uv node.
  13360. * @param {?Node} [levelNode=null] - The level node.
  13361. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13362. */
  13363. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  13364. let defaultFramebuffer = null;
  13365. if ( framebufferTexture === null ) {
  13366. defaultFramebuffer = new FramebufferTexture();
  13367. defaultFramebuffer.minFilter = LinearMipmapLinearFilter;
  13368. framebufferTexture = defaultFramebuffer;
  13369. } else {
  13370. defaultFramebuffer = framebufferTexture;
  13371. }
  13372. super( framebufferTexture, uvNode, levelNode );
  13373. /**
  13374. * Whether to generate mipmaps or not.
  13375. *
  13376. * @type {boolean}
  13377. * @default false
  13378. */
  13379. this.generateMipmaps = false;
  13380. /**
  13381. * The reference framebuffer texture. This is used to store the framebuffer texture
  13382. * for the current render target. If the render target changes, a new framebuffer texture
  13383. * is created automatically.
  13384. *
  13385. * @type {FramebufferTexture}
  13386. * @default null
  13387. */
  13388. this.defaultFramebuffer = defaultFramebuffer;
  13389. /**
  13390. * This flag can be used for type testing.
  13391. *
  13392. * @type {boolean}
  13393. * @readonly
  13394. * @default true
  13395. */
  13396. this.isOutputTextureNode = true;
  13397. /**
  13398. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  13399. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  13400. *
  13401. * @type {string}
  13402. * @default 'frame'
  13403. */
  13404. this.updateBeforeType = NodeUpdateType.FRAME;
  13405. /**
  13406. * The framebuffer texture for the current renderer context.
  13407. *
  13408. * @type {WeakMap<RenderTarget, FramebufferTexture>}
  13409. * @private
  13410. */
  13411. this._cacheTextures = new WeakMap();
  13412. }
  13413. /**
  13414. * This methods returns a texture for the given render target reference.
  13415. *
  13416. * To avoid rendering errors, `ViewportTextureNode` must use unique framebuffer textures
  13417. * for different render contexts.
  13418. *
  13419. * @param {?RenderTarget} [reference=null] - The render target reference.
  13420. * @return {Texture} The framebuffer texture.
  13421. */
  13422. getTextureForReference( reference = null ) {
  13423. let defaultFramebuffer;
  13424. let cacheTextures;
  13425. if ( this.referenceNode ) {
  13426. defaultFramebuffer = this.referenceNode.defaultFramebuffer;
  13427. cacheTextures = this.referenceNode._cacheTextures;
  13428. } else {
  13429. defaultFramebuffer = this.defaultFramebuffer;
  13430. cacheTextures = this._cacheTextures;
  13431. }
  13432. if ( reference === null ) {
  13433. return defaultFramebuffer;
  13434. }
  13435. if ( cacheTextures.has( reference ) === false ) {
  13436. const framebufferTexture = defaultFramebuffer.clone();
  13437. cacheTextures.set( reference, framebufferTexture );
  13438. }
  13439. return cacheTextures.get( reference );
  13440. }
  13441. updateReference( frame ) {
  13442. const renderTarget = frame.renderer.getRenderTarget();
  13443. this.value = this.getTextureForReference( renderTarget );
  13444. return this.value;
  13445. }
  13446. updateBefore( frame ) {
  13447. const renderer = frame.renderer;
  13448. const renderTarget = renderer.getRenderTarget();
  13449. if ( renderTarget === null ) {
  13450. renderer.getDrawingBufferSize( _size$5 );
  13451. } else {
  13452. _size$5.set( renderTarget.width, renderTarget.height );
  13453. }
  13454. //
  13455. const framebufferTexture = this.getTextureForReference( renderTarget );
  13456. if ( framebufferTexture.image.width !== _size$5.width || framebufferTexture.image.height !== _size$5.height ) {
  13457. framebufferTexture.image.width = _size$5.width;
  13458. framebufferTexture.image.height = _size$5.height;
  13459. framebufferTexture.needsUpdate = true;
  13460. }
  13461. //
  13462. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  13463. framebufferTexture.generateMipmaps = this.generateMipmaps;
  13464. renderer.copyFramebufferToTexture( framebufferTexture );
  13465. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  13466. }
  13467. clone() {
  13468. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  13469. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  13470. return viewportTextureNode;
  13471. }
  13472. }
  13473. /**
  13474. * TSL function for creating a viewport texture node.
  13475. *
  13476. * @tsl
  13477. * @function
  13478. * @param {?Node} [uvNode=screenUV] - The uv node.
  13479. * @param {?Node} [levelNode=null] - The level node.
  13480. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13481. * @returns {ViewportTextureNode}
  13482. */
  13483. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  13484. /**
  13485. * TSL function for creating a viewport texture node with enabled mipmap generation.
  13486. *
  13487. * @tsl
  13488. * @function
  13489. * @param {?Node} [uvNode=screenUV] - The uv node.
  13490. * @param {?Node} [levelNode=null] - The level node.
  13491. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13492. * @returns {ViewportTextureNode}
  13493. */
  13494. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  13495. let _sharedDepthbuffer = null;
  13496. /**
  13497. * Represents the depth of the current viewport as a texture. This module
  13498. * can be used in combination with viewport texture to achieve effects
  13499. * that require depth evaluation.
  13500. *
  13501. * @augments ViewportTextureNode
  13502. */
  13503. class ViewportDepthTextureNode extends ViewportTextureNode {
  13504. static get type() {
  13505. return 'ViewportDepthTextureNode';
  13506. }
  13507. /**
  13508. * Constructs a new viewport depth texture node.
  13509. *
  13510. * @param {Node} [uvNode=screenUV] - The uv node.
  13511. * @param {?Node} [levelNode=null] - The level node.
  13512. */
  13513. constructor( uvNode = screenUV, levelNode = null ) {
  13514. if ( _sharedDepthbuffer === null ) {
  13515. _sharedDepthbuffer = new DepthTexture();
  13516. }
  13517. super( uvNode, levelNode, _sharedDepthbuffer );
  13518. }
  13519. /**
  13520. * Overwritten so the method always returns the unique shared
  13521. * depth texture.
  13522. *
  13523. * @return {DepthTexture} The shared depth texture.
  13524. */
  13525. getTextureForReference() {
  13526. return _sharedDepthbuffer;
  13527. }
  13528. }
  13529. /**
  13530. * TSL function for a viewport depth texture node.
  13531. *
  13532. * @tsl
  13533. * @function
  13534. * @param {?Node} [uvNode=screenUV] - The uv node.
  13535. * @param {?Node} [levelNode=null] - The level node.
  13536. * @returns {ViewportDepthTextureNode}
  13537. */
  13538. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  13539. /**
  13540. * This node offers a collection of features in context of the depth logic in the fragment shader.
  13541. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  13542. * fragment or for depth evaluation purposes.
  13543. *
  13544. * @augments Node
  13545. */
  13546. class ViewportDepthNode extends Node {
  13547. static get type() {
  13548. return 'ViewportDepthNode';
  13549. }
  13550. /**
  13551. * Constructs a new viewport depth node.
  13552. *
  13553. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  13554. * @param {?Node} [valueNode=null] - The value node.
  13555. */
  13556. constructor( scope, valueNode = null ) {
  13557. super( 'float' );
  13558. /**
  13559. * The node behaves differently depending on which scope is selected.
  13560. *
  13561. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  13562. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  13563. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  13564. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  13565. *
  13566. * @type {('depth'|'depthBase'|'linearDepth')}
  13567. */
  13568. this.scope = scope;
  13569. /**
  13570. * Can be used to define a custom depth value.
  13571. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  13572. *
  13573. * @type {?Node}
  13574. * @default null
  13575. */
  13576. this.valueNode = valueNode;
  13577. /**
  13578. * This flag can be used for type testing.
  13579. *
  13580. * @type {boolean}
  13581. * @readonly
  13582. * @default true
  13583. */
  13584. this.isViewportDepthNode = true;
  13585. }
  13586. generate( builder ) {
  13587. const { scope } = this;
  13588. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13589. return builder.getFragDepth();
  13590. }
  13591. return super.generate( builder );
  13592. }
  13593. setup( { camera } ) {
  13594. const { scope } = this;
  13595. const value = this.valueNode;
  13596. let node = null;
  13597. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13598. if ( value !== null ) {
  13599. node = depthBase().assign( value );
  13600. }
  13601. } else if ( scope === ViewportDepthNode.DEPTH ) {
  13602. if ( camera.isPerspectiveCamera ) {
  13603. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  13604. } else {
  13605. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13606. }
  13607. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  13608. if ( value !== null ) {
  13609. if ( camera.isPerspectiveCamera ) {
  13610. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  13611. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  13612. } else {
  13613. node = value;
  13614. }
  13615. } else {
  13616. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13617. }
  13618. }
  13619. return node;
  13620. }
  13621. }
  13622. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  13623. ViewportDepthNode.DEPTH = 'depth';
  13624. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  13625. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  13626. /**
  13627. * TSL function for converting a viewZ value to an orthographic depth value.
  13628. *
  13629. * @tsl
  13630. * @function
  13631. * @param {Node<float>} viewZ - The viewZ node.
  13632. * @param {Node<float>} near - The camera's near value.
  13633. * @param {Node<float>} far - The camera's far value.
  13634. * @returns {Node<float>}
  13635. */
  13636. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  13637. /**
  13638. * TSL function for converting an orthographic depth value to a viewZ value.
  13639. *
  13640. * @tsl
  13641. * @function
  13642. * @param {Node<float>} depth - The orthographic depth.
  13643. * @param {Node<float>} near - The camera's near value.
  13644. * @param {Node<float>} far - The camera's far value.
  13645. * @returns {Node<float>}
  13646. */
  13647. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  13648. /**
  13649. * TSL function for converting a viewZ value to a perspective depth value.
  13650. *
  13651. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  13652. *
  13653. * @tsl
  13654. * @function
  13655. * @param {Node<float>} viewZ - The viewZ node.
  13656. * @param {Node<float>} near - The camera's near value.
  13657. * @param {Node<float>} far - The camera's far value.
  13658. * @returns {Node<float>}
  13659. */
  13660. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  13661. /**
  13662. * TSL function for converting a perspective depth value to a viewZ value.
  13663. *
  13664. * @tsl
  13665. * @function
  13666. * @param {Node<float>} depth - The perspective depth.
  13667. * @param {Node<float>} near - The camera's near value.
  13668. * @param {Node<float>} far - The camera's far value.
  13669. * @returns {Node<float>}
  13670. */
  13671. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  13672. /**
  13673. * TSL function for converting a viewZ value to a logarithmic depth value.
  13674. *
  13675. * @tsl
  13676. * @function
  13677. * @param {Node<float>} viewZ - The viewZ node.
  13678. * @param {Node<float>} near - The camera's near value.
  13679. * @param {Node<float>} far - The camera's far value.
  13680. * @returns {Node<float>}
  13681. */
  13682. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  13683. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  13684. // The final logarithmic depth formula used here is adapted from one described in an
  13685. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  13686. // which was an improvement upon an earlier formula one described in an
  13687. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  13688. // Ulrich's formula is the following:
  13689. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  13690. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  13691. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  13692. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  13693. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  13694. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  13695. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  13696. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  13697. // be used, and ultimately Ulrich's "near plane" version was chosen.
  13698. // Outerra eventually made another improvement to their original "C-constant" variant,
  13699. // but it still does not incorporate the camera near plane (for this version,
  13700. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  13701. // Here we make 4 changes to Ulrich's formula:
  13702. // 1. Clamp the camera near plane so we don't divide by 0.
  13703. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  13704. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  13705. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  13706. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  13707. // so we do the same here, hence the 'viewZ.negate()' call.
  13708. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  13709. near = near.max( 1e-6 ).toVar();
  13710. const numerator = log2( viewZ.negate().div( near ) );
  13711. const denominator = log2( far.div( near ) );
  13712. return numerator.div( denominator );
  13713. };
  13714. /**
  13715. * TSL function for converting a logarithmic depth value to a viewZ value.
  13716. *
  13717. * @tsl
  13718. * @function
  13719. * @param {Node<float>} depth - The logarithmic depth.
  13720. * @param {Node<float>} near - The camera's near value.
  13721. * @param {Node<float>} far - The camera's far value.
  13722. * @returns {Node<float>}
  13723. */
  13724. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  13725. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  13726. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  13727. // a negative viewZ).
  13728. const exponent = depth.mul( log( far.div( near ) ) );
  13729. return float( Math.E ).pow( exponent ).mul( near ).negate();
  13730. };
  13731. /**
  13732. * TSL function for defining a value for the current fragment's depth.
  13733. *
  13734. * @tsl
  13735. * @function
  13736. * @param {Node<float>} value - The depth value to set.
  13737. * @returns {ViewportDepthNode<float>}
  13738. */
  13739. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  13740. /**
  13741. * TSL object that represents the depth value for the current fragment.
  13742. *
  13743. * @tsl
  13744. * @type {ViewportDepthNode}
  13745. */
  13746. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  13747. /**
  13748. * TSL function for converting a perspective depth value to linear depth.
  13749. *
  13750. * @tsl
  13751. * @function
  13752. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  13753. * @returns {ViewportDepthNode<float>}
  13754. */
  13755. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  13756. /**
  13757. * TSL object that represents the linear (orthographic) depth value of the current fragment
  13758. *
  13759. * @tsl
  13760. * @type {ViewportDepthNode}
  13761. */
  13762. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  13763. depth.assign = ( value ) => depthBase( value );
  13764. /**
  13765. * This node is used in {@link NodeMaterial} to setup the clipping
  13766. * which can happen hardware-accelerated (if supported) and optionally
  13767. * use alpha-to-coverage for anti-aliasing clipped edges.
  13768. *
  13769. * @augments Node
  13770. */
  13771. class ClippingNode extends Node {
  13772. static get type() {
  13773. return 'ClippingNode';
  13774. }
  13775. /**
  13776. * Constructs a new clipping node.
  13777. *
  13778. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  13779. * the selected scope influences the behavior of the node and what type of code is generated.
  13780. */
  13781. constructor( scope = ClippingNode.DEFAULT ) {
  13782. super();
  13783. /**
  13784. * The node's scope. Similar to other nodes, the selected scope influences
  13785. * the behavior of the node and what type of code is generated.
  13786. *
  13787. * @type {('default'|'hardware'|'alphaToCoverage')}
  13788. */
  13789. this.scope = scope;
  13790. }
  13791. /**
  13792. * Setups the node depending on the selected scope.
  13793. *
  13794. * @param {NodeBuilder} builder - The current node builder.
  13795. * @return {Node} The result node.
  13796. */
  13797. setup( builder ) {
  13798. super.setup( builder );
  13799. const clippingContext = builder.clippingContext;
  13800. const { intersectionPlanes, unionPlanes } = clippingContext;
  13801. this.hardwareClipping = builder.material.hardwareClipping;
  13802. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  13803. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  13804. } else if ( this.scope === ClippingNode.HARDWARE ) {
  13805. return this.setupHardwareClipping( unionPlanes, builder );
  13806. } else {
  13807. return this.setupDefault( intersectionPlanes, unionPlanes );
  13808. }
  13809. }
  13810. /**
  13811. * Setups alpha to coverage.
  13812. *
  13813. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13814. * @param {Array<Vector4>} unionPlanes - The union planes.
  13815. * @return {Node} The result node.
  13816. */
  13817. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  13818. return Fn( () => {
  13819. const distanceToPlane = float().toVar( 'distanceToPlane' );
  13820. const distanceGradient = float().toVar( 'distanceToGradient' );
  13821. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  13822. const numUnionPlanes = unionPlanes.length;
  13823. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13824. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13825. Loop( numUnionPlanes, ( { i } ) => {
  13826. const plane = clippingPlanes.element( i );
  13827. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13828. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13829. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  13830. } );
  13831. }
  13832. const numIntersectionPlanes = intersectionPlanes.length;
  13833. if ( numIntersectionPlanes > 0 ) {
  13834. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13835. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  13836. Loop( numIntersectionPlanes, ( { i } ) => {
  13837. const plane = clippingPlanes.element( i );
  13838. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13839. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13840. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  13841. } );
  13842. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  13843. }
  13844. diffuseColor.a.mulAssign( clipOpacity );
  13845. diffuseColor.a.equal( 0.0 ).discard();
  13846. } )();
  13847. }
  13848. /**
  13849. * Setups the default clipping.
  13850. *
  13851. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13852. * @param {Array<Vector4>} unionPlanes - The union planes.
  13853. * @return {Node} The result node.
  13854. */
  13855. setupDefault( intersectionPlanes, unionPlanes ) {
  13856. return Fn( () => {
  13857. const numUnionPlanes = unionPlanes.length;
  13858. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13859. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13860. Loop( numUnionPlanes, ( { i } ) => {
  13861. const plane = clippingPlanes.element( i );
  13862. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  13863. } );
  13864. }
  13865. const numIntersectionPlanes = intersectionPlanes.length;
  13866. if ( numIntersectionPlanes > 0 ) {
  13867. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13868. const clipped = bool( true ).toVar( 'clipped' );
  13869. Loop( numIntersectionPlanes, ( { i } ) => {
  13870. const plane = clippingPlanes.element( i );
  13871. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  13872. } );
  13873. clipped.discard();
  13874. }
  13875. } )();
  13876. }
  13877. /**
  13878. * Setups hardware clipping.
  13879. *
  13880. * @param {Array<Vector4>} unionPlanes - The union planes.
  13881. * @param {NodeBuilder} builder - The current node builder.
  13882. * @return {Node} The result node.
  13883. */
  13884. setupHardwareClipping( unionPlanes, builder ) {
  13885. const numUnionPlanes = unionPlanes.length;
  13886. builder.enableHardwareClipping( numUnionPlanes );
  13887. return Fn( () => {
  13888. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13889. const hw_clip_distances = builtin( builder.getClipDistance() );
  13890. Loop( numUnionPlanes, ( { i } ) => {
  13891. const plane = clippingPlanes.element( i );
  13892. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  13893. hw_clip_distances.element( i ).assign( distance );
  13894. } );
  13895. } )();
  13896. }
  13897. }
  13898. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  13899. ClippingNode.DEFAULT = 'default';
  13900. ClippingNode.HARDWARE = 'hardware';
  13901. /**
  13902. * TSL function for setting up the default clipping logic.
  13903. *
  13904. * @tsl
  13905. * @function
  13906. * @returns {ClippingNode}
  13907. */
  13908. const clipping = () => new ClippingNode();
  13909. /**
  13910. * TSL function for setting up alpha to coverage.
  13911. *
  13912. * @tsl
  13913. * @function
  13914. * @returns {ClippingNode}
  13915. */
  13916. const clippingAlpha = () => new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE );
  13917. /**
  13918. * TSL function for setting up hardware-based clipping.
  13919. *
  13920. * @tsl
  13921. * @function
  13922. * @returns {ClippingNode}
  13923. */
  13924. const hardwareClipping = () => new ClippingNode( ClippingNode.HARDWARE );
  13925. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  13926. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  13927. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13928. 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 ) ) ) ) ) );
  13929. } );
  13930. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13931. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  13932. } );
  13933. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  13934. // Find the discretized derivatives of our coordinates
  13935. const maxDeriv = max$1(
  13936. length( dFdx( position.xyz ) ),
  13937. length( dFdy( position.xyz ) )
  13938. );
  13939. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  13940. // Find two nearest log-discretized noise scales
  13941. const pixScales = vec2(
  13942. exp2( floor( log2( pixScale ) ) ),
  13943. exp2( ceil( log2( pixScale ) ) )
  13944. );
  13945. // Compute alpha thresholds at our two noise scales
  13946. const alpha = vec2(
  13947. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  13948. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  13949. );
  13950. // Factor to interpolate lerp with
  13951. const lerpFactor = fract( log2( pixScale ) );
  13952. // Interpolate alpha threshold from noise at two scales
  13953. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  13954. // Pass into CDF to compute uniformly distrib threshold
  13955. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  13956. const cases = vec3(
  13957. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  13958. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  13959. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  13960. // Find our final, uniformly distributed alpha threshold (ατ)
  13961. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  13962. // Avoids ατ == 0. Could also do ατ =1-ατ
  13963. return clamp( threshold, 1.0e-6, 1.0 );
  13964. } ).setLayout( {
  13965. name: 'getAlphaHashThreshold',
  13966. type: 'float',
  13967. inputs: [
  13968. { name: 'position', type: 'vec3' }
  13969. ]
  13970. } );
  13971. /**
  13972. * An attribute node for representing vertex colors.
  13973. *
  13974. * @augments AttributeNode
  13975. */
  13976. class VertexColorNode extends AttributeNode {
  13977. static get type() {
  13978. return 'VertexColorNode';
  13979. }
  13980. /**
  13981. * Constructs a new vertex color node.
  13982. *
  13983. * @param {number} index - The attribute index.
  13984. */
  13985. constructor( index ) {
  13986. super( null, 'vec4' );
  13987. /**
  13988. * This flag can be used for type testing.
  13989. *
  13990. * @type {boolean}
  13991. * @readonly
  13992. * @default true
  13993. */
  13994. this.isVertexColorNode = true;
  13995. /**
  13996. * The attribute index to enable more than one sets of vertex colors.
  13997. *
  13998. * @type {number}
  13999. * @default 0
  14000. */
  14001. this.index = index;
  14002. }
  14003. /**
  14004. * Overwrites the default implementation by honoring the attribute index.
  14005. *
  14006. * @param {NodeBuilder} builder - The current node builder.
  14007. * @return {string} The attribute name.
  14008. */
  14009. getAttributeName( /*builder*/ ) {
  14010. const index = this.index;
  14011. return 'color' + ( index > 0 ? index : '' );
  14012. }
  14013. generate( builder ) {
  14014. const attributeName = this.getAttributeName( builder );
  14015. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  14016. let result;
  14017. if ( geometryAttribute === true ) {
  14018. result = super.generate( builder );
  14019. } else {
  14020. // Vertex color fallback should be white
  14021. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  14022. }
  14023. return result;
  14024. }
  14025. serialize( data ) {
  14026. super.serialize( data );
  14027. data.index = this.index;
  14028. }
  14029. deserialize( data ) {
  14030. super.deserialize( data );
  14031. this.index = data.index;
  14032. }
  14033. }
  14034. /**
  14035. * TSL function for creating a reference node.
  14036. *
  14037. * @tsl
  14038. * @function
  14039. * @param {number} [index=0] - The attribute index.
  14040. * @returns {VertexColorNode}
  14041. */
  14042. const vertexColor = ( index = 0 ) => new VertexColorNode( index );
  14043. /**
  14044. * Represents a "Color Burn" blend mode.
  14045. *
  14046. * It's designed to darken the base layer's colors based on the color of the blend layer.
  14047. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  14048. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  14049. *
  14050. * @tsl
  14051. * @function
  14052. * @param {Node<vec3>} base - The base color.
  14053. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  14054. * @return {Node<vec3>} The result.
  14055. */
  14056. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14057. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  14058. } ).setLayout( {
  14059. name: 'blendBurn',
  14060. type: 'vec3',
  14061. inputs: [
  14062. { name: 'base', type: 'vec3' },
  14063. { name: 'blend', type: 'vec3' }
  14064. ]
  14065. } );
  14066. /**
  14067. * Represents a "Color Dodge" blend mode.
  14068. *
  14069. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  14070. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  14071. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  14072. *
  14073. * @tsl
  14074. * @function
  14075. * @param {Node<vec3>} base - The base color.
  14076. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  14077. * @return {Node<vec3>} The result.
  14078. */
  14079. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14080. return min$1( base.div( blend.oneMinus() ), 1.0 );
  14081. } ).setLayout( {
  14082. name: 'blendDodge',
  14083. type: 'vec3',
  14084. inputs: [
  14085. { name: 'base', type: 'vec3' },
  14086. { name: 'blend', type: 'vec3' }
  14087. ]
  14088. } );
  14089. /**
  14090. * Represents a "Screen" blend mode.
  14091. *
  14092. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  14093. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  14094. * effects.
  14095. *
  14096. * @tsl
  14097. * @function
  14098. * @param {Node<vec3>} base - The base color.
  14099. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  14100. * @return {Node<vec3>} The result.
  14101. */
  14102. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14103. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  14104. } ).setLayout( {
  14105. name: 'blendScreen',
  14106. type: 'vec3',
  14107. inputs: [
  14108. { name: 'base', type: 'vec3' },
  14109. { name: 'blend', type: 'vec3' }
  14110. ]
  14111. } );
  14112. /**
  14113. * Represents a "Overlay" blend mode.
  14114. *
  14115. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  14116. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  14117. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  14118. *
  14119. * @tsl
  14120. * @function
  14121. * @param {Node<vec3>} base - The base color.
  14122. * @param {Node<vec3>} blend - The blend color
  14123. * @return {Node<vec3>} The result.
  14124. */
  14125. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14126. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  14127. } ).setLayout( {
  14128. name: 'blendOverlay',
  14129. type: 'vec3',
  14130. inputs: [
  14131. { name: 'base', type: 'vec3' },
  14132. { name: 'blend', type: 'vec3' }
  14133. ]
  14134. } );
  14135. /**
  14136. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  14137. * It assumes both input colors have non-premultiplied alpha.
  14138. *
  14139. * @tsl
  14140. * @function
  14141. * @param {Node<vec4>} base - The base color.
  14142. * @param {Node<vec4>} blend - The blend color
  14143. * @return {Node<vec4>} The result.
  14144. */
  14145. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14146. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  14147. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  14148. } ).setLayout( {
  14149. name: 'blendColor',
  14150. type: 'vec4',
  14151. inputs: [
  14152. { name: 'base', type: 'vec4' },
  14153. { name: 'blend', type: 'vec4' }
  14154. ]
  14155. } );
  14156. /**
  14157. * Premultiplies the RGB channels of a color by its alpha channel.
  14158. *
  14159. * This function is useful for converting a non-premultiplied alpha color
  14160. * into a premultiplied alpha format, where the RGB values are scaled
  14161. * by the alpha value. Premultiplied alpha is often used in graphics
  14162. * rendering for certain operations, such as compositing and image processing.
  14163. *
  14164. * @tsl
  14165. * @function
  14166. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  14167. * @return {Node<vec4>} The color with premultiplied alpha.
  14168. */
  14169. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  14170. return vec4( color.rgb.mul( color.a ), color.a );
  14171. }, { color: 'vec4', return: 'vec4' } );
  14172. /**
  14173. * Unpremultiplies the RGB channels of a color by its alpha channel.
  14174. *
  14175. * This function is useful for converting a premultiplied alpha color
  14176. * back into a non-premultiplied alpha format, where the RGB values are
  14177. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  14178. * rendering for certain operations, such as compositing and image processing.
  14179. *
  14180. * @tsl
  14181. * @function
  14182. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  14183. * @return {Node<vec4>} The color with non-premultiplied alpha.
  14184. */
  14185. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  14186. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  14187. return vec4( color.rgb.div( color.a ), color.a );
  14188. }, { color: 'vec4', return: 'vec4' } );
  14189. // Deprecated
  14190. /**
  14191. * @tsl
  14192. * @function
  14193. * @deprecated since r171. Use {@link blendBurn} instead.
  14194. *
  14195. * @param {...any} params
  14196. * @returns {Function}
  14197. */
  14198. const burn = ( ...params ) => { // @deprecated, r171
  14199. warn( 'TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  14200. return blendBurn( params );
  14201. };
  14202. /**
  14203. * @tsl
  14204. * @function
  14205. * @deprecated since r171. Use {@link blendDodge} instead.
  14206. *
  14207. * @param {...any} params
  14208. * @returns {Function}
  14209. */
  14210. const dodge = ( ...params ) => { // @deprecated, r171
  14211. warn( 'TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  14212. return blendDodge( params );
  14213. };
  14214. /**
  14215. * @tsl
  14216. * @function
  14217. * @deprecated since r171. Use {@link blendScreen} instead.
  14218. *
  14219. * @param {...any} params
  14220. * @returns {Function}
  14221. */
  14222. const screen = ( ...params ) => { // @deprecated, r171
  14223. warn( 'TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  14224. return blendScreen( params );
  14225. };
  14226. /**
  14227. * @tsl
  14228. * @function
  14229. * @deprecated since r171. Use {@link blendOverlay} instead.
  14230. *
  14231. * @param {...any} params
  14232. * @returns {Function}
  14233. */
  14234. const overlay = ( ...params ) => { // @deprecated, r171
  14235. warn( 'TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  14236. return blendOverlay( params );
  14237. };
  14238. /**
  14239. * Base class for all node materials.
  14240. *
  14241. * @augments Material
  14242. */
  14243. class NodeMaterial extends Material {
  14244. static get type() {
  14245. return 'NodeMaterial';
  14246. }
  14247. /**
  14248. * Represents the type of the node material.
  14249. *
  14250. * @type {string}
  14251. */
  14252. get type() {
  14253. return this.constructor.type;
  14254. }
  14255. set type( _value ) { /* */ }
  14256. /**
  14257. * Constructs a new node material.
  14258. */
  14259. constructor() {
  14260. super();
  14261. /**
  14262. * This flag can be used for type testing.
  14263. *
  14264. * @type {boolean}
  14265. * @readonly
  14266. * @default true
  14267. */
  14268. this.isNodeMaterial = true;
  14269. /**
  14270. * Whether this material is affected by fog or not.
  14271. *
  14272. * @type {boolean}
  14273. * @default true
  14274. */
  14275. this.fog = true;
  14276. /**
  14277. * Whether this material is affected by lights or not.
  14278. *
  14279. * @type {boolean}
  14280. * @default false
  14281. */
  14282. this.lights = false;
  14283. /**
  14284. * Whether this material uses hardware clipping or not.
  14285. * This property is managed by the engine and should not be
  14286. * modified by apps.
  14287. *
  14288. * @type {boolean}
  14289. * @default false
  14290. */
  14291. this.hardwareClipping = false;
  14292. /**
  14293. * Node materials which set their `lights` property to `true`
  14294. * are affected by all lights of the scene. Sometimes selective
  14295. * lighting is wanted which means only _some_ lights in the scene
  14296. * affect a material. This can be achieved by creating an instance
  14297. * of {@link LightsNode} with a list of selective
  14298. * lights and assign the node to this property.
  14299. *
  14300. * ```js
  14301. * const customLightsNode = lights( [ light1, light2 ] );
  14302. * material.lightsNode = customLightsNode;
  14303. * ```
  14304. *
  14305. * @type {?LightsNode}
  14306. * @default null
  14307. */
  14308. this.lightsNode = null;
  14309. /**
  14310. * The environment of node materials can be defined by an environment
  14311. * map assigned to the `envMap` property or by `Scene.environment`
  14312. * if the node material is a PBR material. This node property allows to overwrite
  14313. * the default behavior and define the environment with a custom node.
  14314. *
  14315. * ```js
  14316. * material.envNode = pmremTexture( renderTarget.texture );
  14317. * ```
  14318. *
  14319. * @type {?Node<vec3>}
  14320. * @default null
  14321. */
  14322. this.envNode = null;
  14323. /**
  14324. * The lighting of node materials might be influenced by ambient occlusion.
  14325. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  14326. * and the respective `aoMapIntensity`. This node property allows to overwrite
  14327. * the default and define the ambient occlusion with a custom node instead.
  14328. *
  14329. * If you don't want to overwrite the diffuse color but modify the existing
  14330. * values instead, use {@link materialAO}.
  14331. *
  14332. * @type {?Node<float>}
  14333. * @default null
  14334. */
  14335. this.aoNode = null;
  14336. /**
  14337. * The diffuse color of node materials is by default inferred from the
  14338. * `color` and `map` properties. This node property allows to overwrite the default
  14339. * and define the diffuse color with a node instead.
  14340. *
  14341. * ```js
  14342. * material.colorNode = color( 0xff0000 ); // define red color
  14343. * ```
  14344. *
  14345. * If you don't want to overwrite the diffuse color but modify the existing
  14346. * values instead, use {@link materialColor}.
  14347. *
  14348. * ```js
  14349. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  14350. * ```
  14351. *
  14352. * @type {?Node<vec3>}
  14353. * @default null
  14354. */
  14355. this.colorNode = null;
  14356. /**
  14357. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  14358. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  14359. * and define the normals with a node instead.
  14360. *
  14361. * If you don't want to overwrite the normals but modify the existing values instead,
  14362. * use {@link materialNormal}.
  14363. *
  14364. * @type {?Node<vec3>}
  14365. * @default null
  14366. */
  14367. this.normalNode = null;
  14368. /**
  14369. * The opacity of node materials is by default inferred from the `opacity`
  14370. * and `alphaMap` properties. This node property allows to overwrite the default
  14371. * and define the opacity with a node instead.
  14372. *
  14373. * If you don't want to overwrite the opacity but modify the existing
  14374. * value instead, use {@link materialOpacity}.
  14375. *
  14376. * @type {?Node<float>}
  14377. * @default null
  14378. */
  14379. this.opacityNode = null;
  14380. /**
  14381. * This node can be used to implement a variety of filter-like effects. The idea is
  14382. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  14383. * to create an arbitrary effect and then assign the node composition to this property.
  14384. * Everything behind the object using this material will now be affected by a filter.
  14385. *
  14386. * ```js
  14387. * const material = new NodeMaterial()
  14388. * material.transparent = true;
  14389. *
  14390. * // everything behind the object will be monochromatic
  14391. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  14392. * ```
  14393. *
  14394. * Backdrop computations are part of the lighting so only lit materials can use this property.
  14395. *
  14396. * @type {?Node<vec3>}
  14397. * @default null
  14398. */
  14399. this.backdropNode = null;
  14400. /**
  14401. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  14402. *
  14403. * @type {?Node<float>}
  14404. * @default null
  14405. */
  14406. this.backdropAlphaNode = null;
  14407. /**
  14408. * The alpha test of node materials is by default inferred from the `alphaTest`
  14409. * property. This node property allows to overwrite the default and define the
  14410. * alpha test with a node instead.
  14411. *
  14412. * If you don't want to overwrite the alpha test but modify the existing
  14413. * value instead, use {@link materialAlphaTest}.
  14414. *
  14415. * @type {?Node<float>}
  14416. * @default null
  14417. */
  14418. this.alphaTestNode = null;
  14419. /**
  14420. * Discards the fragment if the mask value is `false`.
  14421. *
  14422. * @type {?Node<bool>}
  14423. * @default null
  14424. */
  14425. this.maskNode = null;
  14426. /**
  14427. * The local vertex positions are computed based on multiple factors like the
  14428. * attribute data, morphing or skinning. This node property allows to overwrite
  14429. * the default and define local vertex positions with nodes instead.
  14430. *
  14431. * If you don't want to overwrite the vertex positions but modify the existing
  14432. * values instead, use {@link positionLocal}.
  14433. *
  14434. *```js
  14435. * material.positionNode = positionLocal.add( displace );
  14436. * ```
  14437. *
  14438. * @type {?Node<vec3>}
  14439. * @default null
  14440. */
  14441. this.positionNode = null;
  14442. /**
  14443. * This node property is intended for logic which modifies geometry data once or per animation step.
  14444. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  14445. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  14446. * can be implemented.
  14447. *
  14448. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  14449. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  14450. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  14451. * eventually assigned to `geometryNode`.
  14452. *
  14453. * @type {?Function}
  14454. * @default null
  14455. */
  14456. this.geometryNode = null;
  14457. /**
  14458. * Allows to overwrite depth values in the fragment shader.
  14459. *
  14460. * @type {?Node<float>}
  14461. * @default null
  14462. */
  14463. this.depthNode = null;
  14464. /**
  14465. * Allows to overwrite the position used for shadow map rendering which
  14466. * is by default {@link positionWorld}, the vertex position
  14467. * in world space.
  14468. *
  14469. * @type {?Node<float>}
  14470. * @default null
  14471. */
  14472. this.receivedShadowPositionNode = null;
  14473. /**
  14474. * Allows to overwrite the geometry position used for shadow map projection which
  14475. * is by default {@link positionLocal}, the vertex position in local space.
  14476. *
  14477. * @type {?Node<float>}
  14478. * @default null
  14479. */
  14480. this.castShadowPositionNode = null;
  14481. /**
  14482. * This node can be used to influence how an object using this node material
  14483. * receive shadows.
  14484. *
  14485. * ```js
  14486. * const totalShadows = float( 1 ).toVar();
  14487. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  14488. * totalShadows.mulAssign( shadow );
  14489. * //return float( 1 ); // bypass received shadows
  14490. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  14491. * } );
  14492. *
  14493. * @type {?(Function|FunctionNode<vec4>)}
  14494. * @default null
  14495. */
  14496. this.receivedShadowNode = null;
  14497. /**
  14498. * This node can be used to influence how an object using this node material
  14499. * casts shadows. To apply a color to shadows, you can simply do:
  14500. *
  14501. * ```js
  14502. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  14503. * ```
  14504. *
  14505. * Which can be nice to fake colored shadows of semi-transparent objects. It
  14506. * is also common to use the property with `Fn` function so checks are performed
  14507. * per fragment.
  14508. *
  14509. * ```js
  14510. * materialCustomShadow.castShadowNode = Fn( () => {
  14511. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  14512. * return materialColor;
  14513. * } )();
  14514. * ```
  14515. *
  14516. * @type {?Node<vec4>}
  14517. * @default null
  14518. */
  14519. this.castShadowNode = null;
  14520. /**
  14521. * This node can be used to define the final output of the material.
  14522. *
  14523. * TODO: Explain the differences to `fragmentNode`.
  14524. *
  14525. * @type {?Node<vec4>}
  14526. * @default null
  14527. */
  14528. this.outputNode = null;
  14529. /**
  14530. * MRT configuration is done on renderer or pass level. This node allows to
  14531. * overwrite what values are written into MRT targets on material level. This
  14532. * can be useful for implementing selective FX features that should only affect
  14533. * specific objects.
  14534. *
  14535. * @type {?MRTNode}
  14536. * @default null
  14537. */
  14538. this.mrtNode = null;
  14539. /**
  14540. * This node property can be used if you need complete freedom in implementing
  14541. * the fragment shader. Assigning a node will replace the built-in material
  14542. * logic used in the fragment stage.
  14543. *
  14544. * @type {?Node<vec4>}
  14545. * @default null
  14546. */
  14547. this.fragmentNode = null;
  14548. /**
  14549. * This node property can be used if you need complete freedom in implementing
  14550. * the vertex shader. Assigning a node will replace the built-in material logic
  14551. * used in the vertex stage.
  14552. *
  14553. * @type {?Node<vec4>}
  14554. * @default null
  14555. */
  14556. this.vertexNode = null;
  14557. /**
  14558. * This node can be used as a global context management component for this material.
  14559. *
  14560. * @type {?ContextNode}
  14561. * @default null
  14562. */
  14563. this.contextNode = null;
  14564. // Deprecated properties
  14565. Object.defineProperty( this, 'shadowPositionNode', { // @deprecated, r176
  14566. get: () => {
  14567. return this.receivedShadowPositionNode;
  14568. },
  14569. set: ( value ) => {
  14570. warn( 'NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".' );
  14571. this.receivedShadowPositionNode = value;
  14572. }
  14573. } );
  14574. }
  14575. /**
  14576. * Returns an array of child nodes for this material.
  14577. *
  14578. * @private
  14579. * @returns {Array<{property: string, childNode: Node}>}
  14580. */
  14581. _getNodeChildren() {
  14582. const children = [];
  14583. for ( const property of Object.getOwnPropertyNames( this ) ) {
  14584. if ( property.startsWith( '_' ) === true ) continue;
  14585. const object = this[ property ];
  14586. if ( object && object.isNode === true ) {
  14587. children.push( { property, childNode: object } );
  14588. }
  14589. }
  14590. return children;
  14591. }
  14592. /**
  14593. * Allows to define a custom cache key that influence the material key computation
  14594. * for render objects.
  14595. *
  14596. * @return {string} The custom cache key.
  14597. */
  14598. customProgramCacheKey() {
  14599. const values = [];
  14600. for ( const { property, childNode } of this._getNodeChildren() ) {
  14601. values.push( hashString( property.slice( 0, -4 ) ), childNode.getCacheKey() );
  14602. }
  14603. return this.type + hashArray( values );
  14604. }
  14605. /**
  14606. * Builds this material with the given node builder.
  14607. *
  14608. * @param {NodeBuilder} builder - The current node builder.
  14609. */
  14610. build( builder ) {
  14611. this.setup( builder );
  14612. }
  14613. /**
  14614. * Setups a node material observer with the given builder.
  14615. *
  14616. * @param {NodeBuilder} builder - The current node builder.
  14617. * @return {NodeMaterialObserver} The node material observer.
  14618. */
  14619. setupObserver( builder ) {
  14620. return new NodeMaterialObserver( builder );
  14621. }
  14622. /**
  14623. * Setups the vertex and fragment stage of this node material.
  14624. *
  14625. * @param {NodeBuilder} builder - The current node builder.
  14626. */
  14627. setup( builder ) {
  14628. builder.context.setupNormal = () => subBuild( this.setupNormal( builder ), 'NORMAL', 'vec3' );
  14629. builder.context.setupPositionView = () => this.setupPositionView( builder );
  14630. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  14631. const renderer = builder.renderer;
  14632. const renderTarget = renderer.getRenderTarget();
  14633. // < CONTEXT >
  14634. if ( renderer.contextNode.isContextNode === true ) {
  14635. builder.context = { ...builder.context, ...renderer.contextNode.getFlowContextData() };
  14636. } else {
  14637. error( 'NodeMaterial: "renderer.contextNode" must be an instance of `context()`.' );
  14638. }
  14639. if ( this.contextNode !== null ) {
  14640. if ( this.contextNode.isContextNode === true ) {
  14641. builder.context = { ...builder.context, ...this.contextNode.getFlowContextData() };
  14642. } else {
  14643. error( 'NodeMaterial: "material.contextNode" must be an instance of `context()`.' );
  14644. }
  14645. }
  14646. // < VERTEX STAGE >
  14647. builder.addStack();
  14648. const mvp = subBuild( this.setupVertex( builder ), 'VERTEX' );
  14649. const vertexNode = this.vertexNode || mvp;
  14650. builder.stack.outputNode = vertexNode;
  14651. this.setupHardwareClipping( builder );
  14652. if ( this.geometryNode !== null ) {
  14653. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  14654. }
  14655. builder.addFlow( 'vertex', builder.removeStack() );
  14656. // < FRAGMENT STAGE >
  14657. builder.addStack();
  14658. let resultNode;
  14659. const clippingNode = this.setupClipping( builder );
  14660. if ( this.depthWrite === true || this.depthTest === true ) {
  14661. // only write depth if depth buffer is configured
  14662. if ( renderTarget !== null ) {
  14663. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  14664. } else {
  14665. if ( renderer.depth === true ) this.setupDepth( builder );
  14666. }
  14667. }
  14668. if ( this.fragmentNode === null ) {
  14669. this.setupDiffuseColor( builder );
  14670. this.setupVariants( builder );
  14671. const outgoingLightNode = this.setupLighting( builder );
  14672. if ( clippingNode !== null ) builder.stack.addToStack( clippingNode );
  14673. // force unsigned floats - useful for RenderTargets
  14674. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  14675. resultNode = this.setupOutput( builder, basicOutput );
  14676. // OUTPUT NODE
  14677. output.assign( resultNode );
  14678. //
  14679. const isCustomOutput = this.outputNode !== null;
  14680. if ( isCustomOutput ) resultNode = this.outputNode;
  14681. //
  14682. if ( builder.context.getOutput ) {
  14683. resultNode = builder.context.getOutput( resultNode, builder );
  14684. }
  14685. // MRT
  14686. if ( renderTarget !== null ) {
  14687. const mrt = renderer.getMRT();
  14688. const materialMRT = this.mrtNode;
  14689. if ( mrt !== null ) {
  14690. if ( isCustomOutput ) output.assign( resultNode );
  14691. resultNode = mrt;
  14692. if ( materialMRT !== null ) {
  14693. resultNode = mrt.merge( materialMRT );
  14694. }
  14695. } else if ( materialMRT !== null ) {
  14696. resultNode = materialMRT;
  14697. }
  14698. }
  14699. } else {
  14700. let fragmentNode = this.fragmentNode;
  14701. if ( fragmentNode.isOutputStructNode !== true ) {
  14702. fragmentNode = vec4( fragmentNode );
  14703. }
  14704. resultNode = this.setupOutput( builder, fragmentNode );
  14705. }
  14706. builder.stack.outputNode = resultNode;
  14707. builder.addFlow( 'fragment', builder.removeStack() );
  14708. // < OBSERVER >
  14709. builder.observer = this.setupObserver( builder );
  14710. }
  14711. /**
  14712. * Setups the clipping node.
  14713. *
  14714. * @param {NodeBuilder} builder - The current node builder.
  14715. * @return {ClippingNode} The clipping node.
  14716. */
  14717. setupClipping( builder ) {
  14718. if ( builder.clippingContext === null ) return null;
  14719. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  14720. let result = null;
  14721. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  14722. const samples = builder.renderer.currentSamples;
  14723. if ( this.alphaToCoverage && samples > 1 ) {
  14724. // to be added to flow when the color/alpha value has been determined
  14725. result = clippingAlpha();
  14726. } else {
  14727. builder.stack.addToStack( clipping() );
  14728. }
  14729. }
  14730. return result;
  14731. }
  14732. /**
  14733. * Setups the hardware clipping if available on the current device.
  14734. *
  14735. * @param {NodeBuilder} builder - The current node builder.
  14736. */
  14737. setupHardwareClipping( builder ) {
  14738. this.hardwareClipping = false;
  14739. if ( builder.clippingContext === null ) return;
  14740. const candidateCount = builder.clippingContext.unionPlanes.length;
  14741. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  14742. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  14743. builder.stack.addToStack( hardwareClipping() );
  14744. this.hardwareClipping = true;
  14745. }
  14746. return;
  14747. }
  14748. /**
  14749. * Setups the depth of this material.
  14750. *
  14751. * @param {NodeBuilder} builder - The current node builder.
  14752. */
  14753. setupDepth( builder ) {
  14754. const { renderer, camera } = builder;
  14755. // Depth
  14756. let depthNode = this.depthNode;
  14757. if ( depthNode === null ) {
  14758. const mrt = renderer.getMRT();
  14759. if ( mrt && mrt.has( 'depth' ) ) {
  14760. depthNode = mrt.get( 'depth' );
  14761. } else if ( renderer.logarithmicDepthBuffer === true ) {
  14762. if ( camera.isPerspectiveCamera ) {
  14763. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  14764. } else {
  14765. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  14766. }
  14767. }
  14768. }
  14769. if ( depthNode !== null ) {
  14770. depth.assign( depthNode ).toStack();
  14771. }
  14772. }
  14773. /**
  14774. * Setups the position node in view space. This method exists
  14775. * so derived node materials can modify the implementation e.g. sprite materials.
  14776. *
  14777. * @param {NodeBuilder} builder - The current node builder.
  14778. * @return {Node<vec3>} The position in view space.
  14779. */
  14780. setupPositionView( /*builder*/ ) {
  14781. return modelViewMatrix.mul( positionLocal ).xyz;
  14782. }
  14783. /**
  14784. * Setups the position in clip space.
  14785. *
  14786. * @param {NodeBuilder} builder - The current node builder.
  14787. * @return {Node<vec4>} The position in view space.
  14788. */
  14789. setupModelViewProjection( /*builder*/ ) {
  14790. return cameraProjectionMatrix.mul( positionView );
  14791. }
  14792. /**
  14793. * Setups the logic for the vertex stage.
  14794. *
  14795. * @param {NodeBuilder} builder - The current node builder.
  14796. * @return {Node<vec4>} The position in clip space.
  14797. */
  14798. setupVertex( builder ) {
  14799. builder.addStack();
  14800. this.setupPosition( builder );
  14801. builder.context.vertex = builder.removeStack();
  14802. return modelViewProjection;
  14803. }
  14804. /**
  14805. * Setups the computation of the position in local space.
  14806. *
  14807. * @param {NodeBuilder} builder - The current node builder.
  14808. * @return {Node<vec3>} The position in local space.
  14809. */
  14810. setupPosition( builder ) {
  14811. const { object, geometry } = builder;
  14812. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  14813. morphReference( object ).toStack();
  14814. }
  14815. if ( object.isSkinnedMesh === true ) {
  14816. skinning( object ).toStack();
  14817. }
  14818. if ( this.displacementMap ) {
  14819. const displacementMap = materialReference( 'displacementMap', 'texture' );
  14820. const displacementScale = materialReference( 'displacementScale', 'float' );
  14821. const displacementBias = materialReference( 'displacementBias', 'float' );
  14822. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  14823. }
  14824. if ( object.isBatchedMesh ) {
  14825. batch( object ).toStack();
  14826. }
  14827. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  14828. instancedMesh( object ).toStack();
  14829. }
  14830. if ( this.positionNode !== null ) {
  14831. positionLocal.assign( subBuild( this.positionNode, 'POSITION', 'vec3' ) );
  14832. }
  14833. return positionLocal;
  14834. }
  14835. /**
  14836. * Setups the computation of the material's diffuse color.
  14837. *
  14838. * @param {NodeBuilder} builder - The current node builder.
  14839. * @param {BufferGeometry} geometry - The geometry.
  14840. */
  14841. setupDiffuseColor( builder ) {
  14842. const { object, geometry } = builder;
  14843. // MASK
  14844. if ( this.maskNode !== null ) {
  14845. // Discard if the mask is `false`
  14846. bool( this.maskNode ).not().discard();
  14847. }
  14848. // COLOR
  14849. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  14850. // VERTEX COLORS
  14851. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  14852. colorNode = colorNode.mul( vertexColor() );
  14853. }
  14854. // INSTANCED COLORS
  14855. if ( object.instanceColor ) {
  14856. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  14857. colorNode = instanceColor.mul( colorNode );
  14858. }
  14859. if ( object.isBatchedMesh && object._colorsTexture ) {
  14860. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  14861. colorNode = batchColor.mul( colorNode );
  14862. }
  14863. // DIFFUSE COLOR
  14864. diffuseColor.assign( colorNode );
  14865. // OPACITY
  14866. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14867. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  14868. // ALPHA TEST
  14869. let alphaTestNode = null;
  14870. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  14871. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  14872. if ( this.alphaToCoverage === true ) {
  14873. diffuseColor.a = smoothstep( alphaTestNode, alphaTestNode.add( fwidth( diffuseColor.a ) ), diffuseColor.a );
  14874. diffuseColor.a.lessThanEqual( 0 ).discard();
  14875. } else {
  14876. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  14877. }
  14878. }
  14879. // ALPHA HASH
  14880. if ( this.alphaHash === true ) {
  14881. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  14882. }
  14883. // OPAQUE
  14884. if ( builder.isOpaque() ) {
  14885. diffuseColor.a.assign( 1.0 );
  14886. }
  14887. }
  14888. /**
  14889. * Abstract interface method that can be implemented by derived materials
  14890. * to setup material-specific node variables.
  14891. *
  14892. * @abstract
  14893. * @param {NodeBuilder} builder - The current node builder.
  14894. */
  14895. setupVariants( /*builder*/ ) {
  14896. // Interface function.
  14897. }
  14898. /**
  14899. * Setups the outgoing light node variable
  14900. *
  14901. * @return {Node<vec3>} The outgoing light node.
  14902. */
  14903. setupOutgoingLight() {
  14904. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  14905. }
  14906. /**
  14907. * Setups the normal node from the material.
  14908. *
  14909. * @return {Node<vec3>} The normal node.
  14910. */
  14911. setupNormal() {
  14912. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  14913. }
  14914. /**
  14915. * Setups the environment node from the material.
  14916. *
  14917. * @param {NodeBuilder} builder - The current node builder.
  14918. * @return {Node<vec4>} The environment node.
  14919. */
  14920. setupEnvironment( /*builder*/ ) {
  14921. let node = null;
  14922. if ( this.envNode ) {
  14923. node = this.envNode;
  14924. } else if ( this.envMap ) {
  14925. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  14926. }
  14927. return node;
  14928. }
  14929. /**
  14930. * Setups the light map node from the material.
  14931. *
  14932. * @param {NodeBuilder} builder - The current node builder.
  14933. * @return {Node<vec3>} The light map node.
  14934. */
  14935. setupLightMap( builder ) {
  14936. let node = null;
  14937. if ( builder.material.lightMap ) {
  14938. node = new IrradianceNode( materialLightMap );
  14939. }
  14940. return node;
  14941. }
  14942. /**
  14943. * Setups the lights node based on the scene, environment and material.
  14944. *
  14945. * @param {NodeBuilder} builder - The current node builder.
  14946. * @return {LightsNode} The lights node.
  14947. */
  14948. setupLights( builder ) {
  14949. const materialLightsNode = [];
  14950. //
  14951. const envNode = this.setupEnvironment( builder );
  14952. if ( envNode && envNode.isLightingNode ) {
  14953. materialLightsNode.push( envNode );
  14954. }
  14955. const lightMapNode = this.setupLightMap( builder );
  14956. if ( lightMapNode && lightMapNode.isLightingNode ) {
  14957. materialLightsNode.push( lightMapNode );
  14958. }
  14959. let aoNode = this.aoNode;
  14960. if ( aoNode === null && builder.material.aoMap ) {
  14961. aoNode = materialAO;
  14962. }
  14963. if ( builder.context.getAO ) {
  14964. aoNode = builder.context.getAO( aoNode, builder );
  14965. }
  14966. if ( aoNode ) {
  14967. materialLightsNode.push( new AONode( aoNode ) );
  14968. }
  14969. let lightsN = this.lightsNode || builder.lightsNode;
  14970. if ( materialLightsNode.length > 0 ) {
  14971. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  14972. }
  14973. return lightsN;
  14974. }
  14975. /**
  14976. * This method should be implemented by most derived materials
  14977. * since it defines the material's lighting model.
  14978. *
  14979. * @abstract
  14980. * @param {NodeBuilder} builder - The current node builder.
  14981. * @return {LightingModel} The lighting model.
  14982. */
  14983. setupLightingModel( /*builder*/ ) {
  14984. // Interface function.
  14985. }
  14986. /**
  14987. * Setups the outgoing light node.
  14988. *
  14989. * @param {NodeBuilder} builder - The current node builder.
  14990. * @return {Node<vec3>} The outgoing light node.
  14991. */
  14992. setupLighting( builder ) {
  14993. const { material } = builder;
  14994. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  14995. // OUTGOING LIGHT
  14996. const lights = this.lights === true || this.lightsNode !== null;
  14997. const lightsNode = lights ? this.setupLights( builder ) : null;
  14998. let outgoingLightNode = this.setupOutgoingLight( builder );
  14999. if ( lightsNode && lightsNode.getScope().hasLights ) {
  15000. const lightingModel = this.setupLightingModel( builder ) || null;
  15001. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  15002. } else if ( backdropNode !== null ) {
  15003. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  15004. }
  15005. // EMISSIVE
  15006. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  15007. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  15008. outgoingLightNode = outgoingLightNode.add( emissive );
  15009. }
  15010. return outgoingLightNode;
  15011. }
  15012. /**
  15013. * Setup the fog.
  15014. *
  15015. * @param {NodeBuilder} builder - The current node builder.
  15016. * @param {Node<vec4>} outputNode - The existing output node.
  15017. * @return {Node<vec4>} The output node.
  15018. */
  15019. setupFog( builder, outputNode ) {
  15020. const fogNode = builder.fogNode;
  15021. if ( fogNode ) {
  15022. output.assign( outputNode );
  15023. outputNode = vec4( fogNode.toVar() );
  15024. }
  15025. return outputNode;
  15026. }
  15027. /**
  15028. * Setups premultiplied alpha.
  15029. *
  15030. * @param {NodeBuilder} builder - The current node builder.
  15031. * @param {Node<vec4>} outputNode - The existing output node.
  15032. * @return {Node<vec4>} The output node.
  15033. */
  15034. setupPremultipliedAlpha( builder, outputNode ) {
  15035. return premultiplyAlpha( outputNode );
  15036. }
  15037. /**
  15038. * Setups the output node.
  15039. *
  15040. * @param {NodeBuilder} builder - The current node builder.
  15041. * @param {Node<vec4>} outputNode - The existing output node.
  15042. * @return {Node<vec4>} The output node.
  15043. */
  15044. setupOutput( builder, outputNode ) {
  15045. // FOG
  15046. if ( this.fog === true ) {
  15047. outputNode = this.setupFog( builder, outputNode );
  15048. }
  15049. // PREMULTIPLIED ALPHA
  15050. if ( this.premultipliedAlpha === true ) {
  15051. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  15052. }
  15053. return outputNode;
  15054. }
  15055. /**
  15056. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  15057. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  15058. * defining all material properties of the classic type in the node type.
  15059. *
  15060. * @param {Material} material - The material to copy properties with their values to this node material.
  15061. */
  15062. setDefaultValues( material ) {
  15063. // This approach is to reuse the native refreshUniforms*
  15064. // and turn available the use of features like transmission and environment in core
  15065. for ( const property in material ) {
  15066. const value = material[ property ];
  15067. if ( this[ property ] === undefined ) {
  15068. this[ property ] = value;
  15069. if ( value && value.clone ) this[ property ] = value.clone();
  15070. }
  15071. }
  15072. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  15073. for ( const key in descriptors ) {
  15074. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  15075. descriptors[ key ].get !== undefined ) {
  15076. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  15077. }
  15078. }
  15079. }
  15080. /**
  15081. * Serializes this material to JSON.
  15082. *
  15083. * @param {?(Object|string)} meta - The meta information for serialization.
  15084. * @return {Object} The serialized node.
  15085. */
  15086. toJSON( meta ) {
  15087. const isRoot = ( meta === undefined || typeof meta === 'string' );
  15088. if ( isRoot ) {
  15089. meta = {
  15090. textures: {},
  15091. images: {},
  15092. nodes: {}
  15093. };
  15094. }
  15095. const data = Material.prototype.toJSON.call( this, meta );
  15096. data.inputNodes = {};
  15097. for ( const { property, childNode } of this._getNodeChildren() ) {
  15098. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  15099. }
  15100. // TODO: Copied from Object3D.toJSON
  15101. function extractFromCache( cache ) {
  15102. const values = [];
  15103. for ( const key in cache ) {
  15104. const data = cache[ key ];
  15105. delete data.metadata;
  15106. values.push( data );
  15107. }
  15108. return values;
  15109. }
  15110. if ( isRoot ) {
  15111. const textures = extractFromCache( meta.textures );
  15112. const images = extractFromCache( meta.images );
  15113. const nodes = extractFromCache( meta.nodes );
  15114. if ( textures.length > 0 ) data.textures = textures;
  15115. if ( images.length > 0 ) data.images = images;
  15116. if ( nodes.length > 0 ) data.nodes = nodes;
  15117. }
  15118. return data;
  15119. }
  15120. /**
  15121. * Copies the properties of the given node material to this instance.
  15122. *
  15123. * @param {NodeMaterial} source - The material to copy.
  15124. * @return {NodeMaterial} A reference to this node material.
  15125. */
  15126. copy( source ) {
  15127. this.lightsNode = source.lightsNode;
  15128. this.envNode = source.envNode;
  15129. this.aoNode = source.aoNode;
  15130. this.colorNode = source.colorNode;
  15131. this.normalNode = source.normalNode;
  15132. this.opacityNode = source.opacityNode;
  15133. this.backdropNode = source.backdropNode;
  15134. this.backdropAlphaNode = source.backdropAlphaNode;
  15135. this.alphaTestNode = source.alphaTestNode;
  15136. this.maskNode = source.maskNode;
  15137. this.positionNode = source.positionNode;
  15138. this.geometryNode = source.geometryNode;
  15139. this.depthNode = source.depthNode;
  15140. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  15141. this.castShadowPositionNode = source.castShadowPositionNode;
  15142. this.receivedShadowNode = source.receivedShadowNode;
  15143. this.castShadowNode = source.castShadowNode;
  15144. this.outputNode = source.outputNode;
  15145. this.mrtNode = source.mrtNode;
  15146. this.fragmentNode = source.fragmentNode;
  15147. this.vertexNode = source.vertexNode;
  15148. this.contextNode = source.contextNode;
  15149. return super.copy( source );
  15150. }
  15151. }
  15152. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  15153. /**
  15154. * Node material version of {@link LineBasicMaterial}.
  15155. *
  15156. * @augments NodeMaterial
  15157. */
  15158. class LineBasicNodeMaterial extends NodeMaterial {
  15159. static get type() {
  15160. return 'LineBasicNodeMaterial';
  15161. }
  15162. /**
  15163. * Constructs a new line basic node material.
  15164. *
  15165. * @param {Object} [parameters] - The configuration parameter.
  15166. */
  15167. constructor( parameters ) {
  15168. super();
  15169. /**
  15170. * This flag can be used for type testing.
  15171. *
  15172. * @type {boolean}
  15173. * @readonly
  15174. * @default true
  15175. */
  15176. this.isLineBasicNodeMaterial = true;
  15177. this.setDefaultValues( _defaultValues$d );
  15178. this.setValues( parameters );
  15179. }
  15180. }
  15181. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  15182. /**
  15183. * Node material version of {@link LineDashedMaterial}.
  15184. *
  15185. * @augments NodeMaterial
  15186. */
  15187. class LineDashedNodeMaterial extends NodeMaterial {
  15188. static get type() {
  15189. return 'LineDashedNodeMaterial';
  15190. }
  15191. /**
  15192. * Constructs a new line dashed node material.
  15193. *
  15194. * @param {Object} [parameters] - The configuration parameter.
  15195. */
  15196. constructor( parameters ) {
  15197. super();
  15198. /**
  15199. * This flag can be used for type testing.
  15200. *
  15201. * @type {boolean}
  15202. * @readonly
  15203. * @default true
  15204. */
  15205. this.isLineDashedNodeMaterial = true;
  15206. this.setDefaultValues( _defaultValues$c );
  15207. /**
  15208. * The dash offset.
  15209. *
  15210. * @type {number}
  15211. * @default 0
  15212. */
  15213. this.dashOffset = 0;
  15214. /**
  15215. * The offset of dash materials is by default inferred from the `dashOffset`
  15216. * property. This node property allows to overwrite the default
  15217. * and define the offset with a node instead.
  15218. *
  15219. * If you don't want to overwrite the offset but modify the existing
  15220. * value instead, use {@link materialLineDashOffset}.
  15221. *
  15222. * @type {?Node<float>}
  15223. * @default null
  15224. */
  15225. this.offsetNode = null;
  15226. /**
  15227. * The scale of dash materials is by default inferred from the `scale`
  15228. * property. This node property allows to overwrite the default
  15229. * and define the scale with a node instead.
  15230. *
  15231. * If you don't want to overwrite the scale but modify the existing
  15232. * value instead, use {@link materialLineScale}.
  15233. *
  15234. * @type {?Node<float>}
  15235. * @default null
  15236. */
  15237. this.dashScaleNode = null;
  15238. /**
  15239. * The dash size of dash materials is by default inferred from the `dashSize`
  15240. * property. This node property allows to overwrite the default
  15241. * and define the dash size with a node instead.
  15242. *
  15243. * If you don't want to overwrite the dash size but modify the existing
  15244. * value instead, use {@link materialLineDashSize}.
  15245. *
  15246. * @type {?Node<float>}
  15247. * @default null
  15248. */
  15249. this.dashSizeNode = null;
  15250. /**
  15251. * The gap size of dash materials is by default inferred from the `gapSize`
  15252. * property. This node property allows to overwrite the default
  15253. * and define the gap size with a node instead.
  15254. *
  15255. * If you don't want to overwrite the gap size but modify the existing
  15256. * value instead, use {@link materialLineGapSize}.
  15257. *
  15258. * @type {?Node<float>}
  15259. * @default null
  15260. */
  15261. this.gapSizeNode = null;
  15262. this.setValues( parameters );
  15263. }
  15264. /**
  15265. * Setups the dash specific node variables.
  15266. *
  15267. * @param {NodeBuilder} builder - The current node builder.
  15268. */
  15269. setupVariants( /* builder */ ) {
  15270. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15271. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15272. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15273. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15274. dashSize.assign( dashSizeNode );
  15275. gapSize.assign( gapSizeNode );
  15276. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  15277. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  15278. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  15279. }
  15280. }
  15281. let _sharedFramebuffer = null;
  15282. /**
  15283. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  15284. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  15285. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  15286. *
  15287. * @augments ViewportTextureNode
  15288. */
  15289. class ViewportSharedTextureNode extends ViewportTextureNode {
  15290. static get type() {
  15291. return 'ViewportSharedTextureNode';
  15292. }
  15293. /**
  15294. * Constructs a new viewport shared texture node.
  15295. *
  15296. * @param {Node} [uvNode=screenUV] - The uv node.
  15297. * @param {?Node} [levelNode=null] - The level node.
  15298. */
  15299. constructor( uvNode = screenUV, levelNode = null ) {
  15300. if ( _sharedFramebuffer === null ) {
  15301. _sharedFramebuffer = new FramebufferTexture();
  15302. }
  15303. super( uvNode, levelNode, _sharedFramebuffer );
  15304. }
  15305. /**
  15306. * Overwritten so the method always returns the unique shared
  15307. * framebuffer texture.
  15308. *
  15309. * @return {FramebufferTexture} The shared framebuffer texture.
  15310. */
  15311. getTextureForReference() {
  15312. return _sharedFramebuffer;
  15313. }
  15314. updateReference() {
  15315. return this;
  15316. }
  15317. }
  15318. /**
  15319. * TSL function for creating a shared viewport texture node.
  15320. *
  15321. * @tsl
  15322. * @function
  15323. * @param {?Node} [uvNode=screenUV] - The uv node.
  15324. * @param {?Node} [levelNode=null] - The level node.
  15325. * @returns {ViewportSharedTextureNode}
  15326. */
  15327. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  15328. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  15329. /**
  15330. * This node material can be used to render lines with a size larger than one
  15331. * by representing them as instanced meshes.
  15332. *
  15333. * @augments NodeMaterial
  15334. */
  15335. class Line2NodeMaterial extends NodeMaterial {
  15336. static get type() {
  15337. return 'Line2NodeMaterial';
  15338. }
  15339. /**
  15340. * Constructs a new node material for wide line rendering.
  15341. *
  15342. * @param {Object} [parameters={}] - The configuration parameter.
  15343. */
  15344. constructor( parameters = {} ) {
  15345. super();
  15346. /**
  15347. * This flag can be used for type testing.
  15348. *
  15349. * @type {boolean}
  15350. * @readonly
  15351. * @default true
  15352. */
  15353. this.isLine2NodeMaterial = true;
  15354. this.setDefaultValues( _defaultValues$b );
  15355. /**
  15356. * Whether vertex colors should be used or not.
  15357. *
  15358. * @type {boolean}
  15359. * @default false
  15360. */
  15361. this.useColor = parameters.vertexColors;
  15362. /**
  15363. * The dash offset.
  15364. *
  15365. * @type {number}
  15366. * @default 0
  15367. */
  15368. this.dashOffset = 0;
  15369. /**
  15370. * Defines the lines color.
  15371. *
  15372. * @type {?Node<vec3>}
  15373. * @default null
  15374. */
  15375. this.lineColorNode = null;
  15376. /**
  15377. * Defines the offset.
  15378. *
  15379. * @type {?Node<float>}
  15380. * @default null
  15381. */
  15382. this.offsetNode = null;
  15383. /**
  15384. * Defines the dash scale.
  15385. *
  15386. * @type {?Node<float>}
  15387. * @default null
  15388. */
  15389. this.dashScaleNode = null;
  15390. /**
  15391. * Defines the dash size.
  15392. *
  15393. * @type {?Node<float>}
  15394. * @default null
  15395. */
  15396. this.dashSizeNode = null;
  15397. /**
  15398. * Defines the gap size.
  15399. *
  15400. * @type {?Node<float>}
  15401. * @default null
  15402. */
  15403. this.gapSizeNode = null;
  15404. /**
  15405. * Blending is set to `NoBlending` since transparency
  15406. * is not supported, yet.
  15407. *
  15408. * @type {number}
  15409. * @default 0
  15410. */
  15411. this.blending = NoBlending;
  15412. this._useDash = parameters.dashed;
  15413. this._useAlphaToCoverage = true;
  15414. this._useWorldUnits = false;
  15415. this.setValues( parameters );
  15416. }
  15417. /**
  15418. * Setups the vertex and fragment stage of this node material.
  15419. *
  15420. * @param {NodeBuilder} builder - The current node builder.
  15421. */
  15422. setup( builder ) {
  15423. const { renderer } = builder;
  15424. const useAlphaToCoverage = this._useAlphaToCoverage;
  15425. const useColor = this.useColor;
  15426. const useDash = this._useDash;
  15427. const useWorldUnits = this._useWorldUnits;
  15428. const trimSegment = Fn( ( { start, end } ) => {
  15429. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  15430. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  15431. const nearEstimate = b.mul( -0.5 ).div( a );
  15432. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  15433. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  15434. } ).setLayout( {
  15435. name: 'trimSegment',
  15436. type: 'vec4',
  15437. inputs: [
  15438. { name: 'start', type: 'vec4' },
  15439. { name: 'end', type: 'vec4' }
  15440. ]
  15441. } );
  15442. this.vertexNode = Fn( () => {
  15443. const instanceStart = attribute( 'instanceStart' );
  15444. const instanceEnd = attribute( 'instanceEnd' );
  15445. // camera space
  15446. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  15447. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  15448. if ( useDash ) {
  15449. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15450. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15451. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  15452. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  15453. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  15454. lineDistance = lineDistance.add( offsetNode );
  15455. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  15456. }
  15457. if ( useWorldUnits ) {
  15458. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  15459. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  15460. }
  15461. const aspect = viewport.z.div( viewport.w );
  15462. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  15463. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  15464. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  15465. // perhaps there is a more elegant solution -- WestLangley
  15466. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  15467. If( perspective, () => {
  15468. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  15469. end.assign( trimSegment( { start: start, end: end } ) );
  15470. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  15471. start.assign( trimSegment( { start: end, end: start } ) );
  15472. } );
  15473. } );
  15474. // clip space
  15475. const clipStart = cameraProjectionMatrix.mul( start );
  15476. const clipEnd = cameraProjectionMatrix.mul( end );
  15477. // ndc space
  15478. const ndcStart = clipStart.xyz.div( clipStart.w );
  15479. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  15480. // direction
  15481. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  15482. // account for clip-space aspect ratio
  15483. dir.x.assign( dir.x.mul( aspect ) );
  15484. dir.assign( dir.normalize() );
  15485. const clip = vec4().toVar();
  15486. if ( useWorldUnits ) {
  15487. // get the offset direction as perpendicular to the view vector
  15488. const worldDir = end.xyz.sub( start.xyz ).normalize();
  15489. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  15490. const worldUp = worldDir.cross( tmpFwd ).normalize();
  15491. const worldFwd = worldDir.cross( worldUp );
  15492. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  15493. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  15494. // height offset
  15495. const hw = materialLineWidth.mul( 0.5 );
  15496. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  15497. // don't extend the line if we're rendering dashes because we
  15498. // won't be rendering the endcaps
  15499. if ( ! useDash ) {
  15500. // cap extension
  15501. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  15502. // add width to the box
  15503. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  15504. // endcaps
  15505. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  15506. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  15507. } );
  15508. }
  15509. // project the worldpos
  15510. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  15511. // shift the depth of the projected points so the line
  15512. // segments overlap neatly
  15513. const clipPose = vec3().toVar();
  15514. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  15515. clip.z.assign( clipPose.z.mul( clip.w ) );
  15516. } else {
  15517. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  15518. // undo aspect ratio adjustment
  15519. dir.x.assign( dir.x.div( aspect ) );
  15520. offset.x.assign( offset.x.div( aspect ) );
  15521. // sign flip
  15522. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  15523. // endcaps
  15524. If( positionGeometry.y.lessThan( 0.0 ), () => {
  15525. offset.assign( offset.sub( dir ) );
  15526. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  15527. offset.assign( offset.add( dir ) );
  15528. } );
  15529. // adjust for linewidth
  15530. offset.assign( offset.mul( materialLineWidth ) );
  15531. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  15532. offset.assign( offset.div( viewport.w.div( screenDPR ) ) );
  15533. // select end
  15534. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  15535. // back to clip space
  15536. offset.assign( offset.mul( clip.w ) );
  15537. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  15538. }
  15539. return clip;
  15540. } )();
  15541. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  15542. const p13 = p1.sub( p3 );
  15543. const p43 = p4.sub( p3 );
  15544. const p21 = p2.sub( p1 );
  15545. const d1343 = p13.dot( p43 );
  15546. const d4321 = p43.dot( p21 );
  15547. const d1321 = p13.dot( p21 );
  15548. const d4343 = p43.dot( p43 );
  15549. const d2121 = p21.dot( p21 );
  15550. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  15551. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  15552. const mua = numer.div( denom ).clamp();
  15553. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  15554. return vec2( mua, mub );
  15555. } );
  15556. this.colorNode = Fn( () => {
  15557. const vUv = uv$1();
  15558. if ( useDash ) {
  15559. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15560. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15561. dashSize.assign( dashSizeNode );
  15562. gapSize.assign( gapSizeNode );
  15563. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  15564. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  15565. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  15566. }
  15567. const alpha = float( 1 ).toVar( 'alpha' );
  15568. if ( useWorldUnits ) {
  15569. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  15570. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  15571. // Find the closest points on the view ray and the line segment
  15572. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  15573. const lineDir = worldEnd.sub( worldStart );
  15574. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  15575. const p1 = worldStart.add( lineDir.mul( params.x ) );
  15576. const p2 = rayEnd.mul( params.y );
  15577. const delta = p1.sub( p2 );
  15578. const len = delta.length();
  15579. const norm = len.div( materialLineWidth );
  15580. if ( ! useDash ) {
  15581. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15582. const dnorm = norm.fwidth();
  15583. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  15584. } else {
  15585. norm.greaterThan( 0.5 ).discard();
  15586. }
  15587. }
  15588. } else {
  15589. // round endcaps
  15590. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15591. const a = vUv.x;
  15592. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15593. const len2 = a.mul( a ).add( b.mul( b ) );
  15594. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  15595. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15596. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  15597. } );
  15598. } else {
  15599. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15600. const a = vUv.x;
  15601. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15602. const len2 = a.mul( a ).add( b.mul( b ) );
  15603. len2.greaterThan( 1.0 ).discard();
  15604. } );
  15605. }
  15606. }
  15607. let lineColorNode;
  15608. if ( this.lineColorNode ) {
  15609. lineColorNode = this.lineColorNode;
  15610. } else {
  15611. if ( useColor ) {
  15612. const instanceColorStart = attribute( 'instanceColorStart' );
  15613. const instanceColorEnd = attribute( 'instanceColorEnd' );
  15614. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  15615. lineColorNode = instanceColor.mul( materialColor );
  15616. } else {
  15617. lineColorNode = materialColor;
  15618. }
  15619. }
  15620. return vec4( lineColorNode, alpha );
  15621. } )();
  15622. if ( this.transparent ) {
  15623. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15624. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  15625. }
  15626. super.setup( builder );
  15627. }
  15628. /**
  15629. * Whether the lines should sized in world units or not.
  15630. * When set to `false` the unit is pixel.
  15631. *
  15632. * @type {boolean}
  15633. * @default false
  15634. */
  15635. get worldUnits() {
  15636. return this._useWorldUnits;
  15637. }
  15638. set worldUnits( value ) {
  15639. if ( this._useWorldUnits !== value ) {
  15640. this._useWorldUnits = value;
  15641. this.needsUpdate = true;
  15642. }
  15643. }
  15644. /**
  15645. * Whether the lines should be dashed or not.
  15646. *
  15647. * @type {boolean}
  15648. * @default false
  15649. */
  15650. get dashed() {
  15651. return this._useDash;
  15652. }
  15653. set dashed( value ) {
  15654. if ( this._useDash !== value ) {
  15655. this._useDash = value;
  15656. this.needsUpdate = true;
  15657. }
  15658. }
  15659. /**
  15660. * Whether alpha to coverage should be used or not.
  15661. *
  15662. * @type {boolean}
  15663. * @default true
  15664. */
  15665. get alphaToCoverage() {
  15666. return this._useAlphaToCoverage;
  15667. }
  15668. set alphaToCoverage( value ) {
  15669. if ( this._useAlphaToCoverage !== value ) {
  15670. this._useAlphaToCoverage = value;
  15671. this.needsUpdate = true;
  15672. }
  15673. }
  15674. }
  15675. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  15676. /**
  15677. * Node material version of {@link MeshNormalMaterial}.
  15678. *
  15679. * @augments NodeMaterial
  15680. */
  15681. class MeshNormalNodeMaterial extends NodeMaterial {
  15682. static get type() {
  15683. return 'MeshNormalNodeMaterial';
  15684. }
  15685. /**
  15686. * Constructs a new mesh normal node material.
  15687. *
  15688. * @param {Object} [parameters] - The configuration parameter.
  15689. */
  15690. constructor( parameters ) {
  15691. super();
  15692. /**
  15693. * This flag can be used for type testing.
  15694. *
  15695. * @type {boolean}
  15696. * @readonly
  15697. * @default true
  15698. */
  15699. this.isMeshNormalNodeMaterial = true;
  15700. this.setDefaultValues( _defaultValues$a );
  15701. this.setValues( parameters );
  15702. }
  15703. /**
  15704. * Overwrites the default implementation by computing the diffuse color
  15705. * based on the normal data.
  15706. */
  15707. setupDiffuseColor() {
  15708. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15709. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  15710. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( normalView ), opacityNode ), SRGBColorSpace ) );
  15711. }
  15712. }
  15713. /**
  15714. * TSL function for creating an equirect uv node.
  15715. *
  15716. * Can be used to compute texture coordinates for projecting an
  15717. * equirectangular texture onto a mesh for using it as the scene's
  15718. * background.
  15719. *
  15720. * ```js
  15721. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  15722. * ```
  15723. *
  15724. * @tsl
  15725. * @function
  15726. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  15727. * @returns {Node<vec2>}
  15728. */
  15729. const equirectUV = /*@__PURE__*/ Fn( ( [ dir = positionWorldDirection ] ) => {
  15730. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  15731. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  15732. return vec2( u, v );
  15733. } );
  15734. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  15735. /**
  15736. * This class represents a cube render target. It is a special version
  15737. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  15738. *
  15739. * @augments WebGLCubeRenderTarget
  15740. */
  15741. class CubeRenderTarget extends WebGLCubeRenderTarget {
  15742. /**
  15743. * Constructs a new cube render target.
  15744. *
  15745. * @param {number} [size=1] - The size of the render target.
  15746. * @param {RenderTarget~Options} [options] - The configuration object.
  15747. */
  15748. constructor( size = 1, options = {} ) {
  15749. super( size, options );
  15750. /**
  15751. * This flag can be used for type testing.
  15752. *
  15753. * @type {boolean}
  15754. * @readonly
  15755. * @default true
  15756. */
  15757. this.isCubeRenderTarget = true;
  15758. }
  15759. /**
  15760. * Converts the given equirectangular texture to a cube map.
  15761. *
  15762. * @param {Renderer} renderer - The renderer.
  15763. * @param {Texture} texture - The equirectangular texture.
  15764. * @return {CubeRenderTarget} A reference to this cube render target.
  15765. */
  15766. fromEquirectangularTexture( renderer, texture$1 ) {
  15767. const currentMinFilter = texture$1.minFilter;
  15768. const currentGenerateMipmaps = texture$1.generateMipmaps;
  15769. texture$1.generateMipmaps = true;
  15770. this.texture.type = texture$1.type;
  15771. this.texture.colorSpace = texture$1.colorSpace;
  15772. this.texture.generateMipmaps = texture$1.generateMipmaps;
  15773. this.texture.minFilter = texture$1.minFilter;
  15774. this.texture.magFilter = texture$1.magFilter;
  15775. const geometry = new BoxGeometry( 5, 5, 5 );
  15776. const uvNode = equirectUV( positionWorldDirection );
  15777. const material = new NodeMaterial();
  15778. material.colorNode = texture( texture$1, uvNode, 0 );
  15779. material.side = BackSide;
  15780. material.blending = NoBlending;
  15781. const mesh = new Mesh( geometry, material );
  15782. const scene = new Scene();
  15783. scene.add( mesh );
  15784. // Avoid blurred poles
  15785. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  15786. const camera = new CubeCamera( 1, 10, this );
  15787. const currentMRT = renderer.getMRT();
  15788. renderer.setMRT( null );
  15789. camera.update( renderer, scene );
  15790. renderer.setMRT( currentMRT );
  15791. texture$1.minFilter = currentMinFilter;
  15792. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  15793. mesh.geometry.dispose();
  15794. mesh.material.dispose();
  15795. return this;
  15796. }
  15797. }
  15798. const _cache$1 = new WeakMap();
  15799. /**
  15800. * This node can be used to automatically convert environment maps in the
  15801. * equirectangular format into the cube map format.
  15802. *
  15803. * @augments TempNode
  15804. */
  15805. class CubeMapNode extends TempNode {
  15806. static get type() {
  15807. return 'CubeMapNode';
  15808. }
  15809. /**
  15810. * Constructs a new cube map node.
  15811. *
  15812. * @param {Node} envNode - The node representing the environment map.
  15813. */
  15814. constructor( envNode ) {
  15815. super( 'vec3' );
  15816. /**
  15817. * The node representing the environment map.
  15818. *
  15819. * @type {Node}
  15820. */
  15821. this.envNode = envNode;
  15822. /**
  15823. * A reference to the internal cube texture.
  15824. *
  15825. * @private
  15826. * @type {?CubeTexture}
  15827. * @default null
  15828. */
  15829. this._cubeTexture = null;
  15830. /**
  15831. * A reference to the internal cube texture node.
  15832. *
  15833. * @private
  15834. * @type {CubeTextureNode}
  15835. */
  15836. this._cubeTextureNode = cubeTexture( null );
  15837. const defaultTexture = new CubeTexture();
  15838. defaultTexture.isRenderTargetTexture = true;
  15839. /**
  15840. * A default cube texture that acts as a placeholder.
  15841. * It is used when the conversion from equirectangular to cube
  15842. * map has not finished yet for a given texture.
  15843. *
  15844. * @private
  15845. * @type {CubeTexture}
  15846. */
  15847. this._defaultTexture = defaultTexture;
  15848. /**
  15849. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  15850. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  15851. *
  15852. * @type {string}
  15853. * @default 'render'
  15854. */
  15855. this.updateBeforeType = NodeUpdateType.RENDER;
  15856. }
  15857. updateBefore( frame ) {
  15858. const { renderer, material } = frame;
  15859. const envNode = this.envNode;
  15860. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  15861. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  15862. if ( texture && texture.isTexture ) {
  15863. const mapping = texture.mapping;
  15864. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  15865. // check for converted cubemap map
  15866. if ( _cache$1.has( texture ) ) {
  15867. const cubeMap = _cache$1.get( texture );
  15868. mapTextureMapping( cubeMap, texture.mapping );
  15869. this._cubeTexture = cubeMap;
  15870. } else {
  15871. // create cube map from equirectangular map
  15872. const image = texture.image;
  15873. if ( isEquirectangularMapReady$1( image ) ) {
  15874. const renderTarget = new CubeRenderTarget( image.height );
  15875. renderTarget.fromEquirectangularTexture( renderer, texture );
  15876. mapTextureMapping( renderTarget.texture, texture.mapping );
  15877. this._cubeTexture = renderTarget.texture;
  15878. _cache$1.set( texture, renderTarget.texture );
  15879. texture.addEventListener( 'dispose', onTextureDispose );
  15880. } else {
  15881. // default cube texture as fallback when equirectangular texture is not yet loaded
  15882. this._cubeTexture = this._defaultTexture;
  15883. }
  15884. }
  15885. //
  15886. this._cubeTextureNode.value = this._cubeTexture;
  15887. } else {
  15888. // envNode already refers to a cube map
  15889. this._cubeTextureNode = this.envNode;
  15890. }
  15891. }
  15892. }
  15893. }
  15894. setup( builder ) {
  15895. this.updateBefore( builder );
  15896. return this._cubeTextureNode;
  15897. }
  15898. }
  15899. /**
  15900. * Returns true if the given equirectangular image has been fully loaded
  15901. * and is ready for further processing.
  15902. *
  15903. * @private
  15904. * @param {Image} image - The equirectangular image to check.
  15905. * @return {boolean} Whether the image is ready or not.
  15906. */
  15907. function isEquirectangularMapReady$1( image ) {
  15908. if ( image === null || image === undefined ) return false;
  15909. return image.height > 0;
  15910. }
  15911. /**
  15912. * This function is executed when `dispose()` is called on the equirectangular
  15913. * texture. In this case, the generated cube map with its render target
  15914. * is deleted as well.
  15915. *
  15916. * @private
  15917. * @param {Object} event - The event object.
  15918. */
  15919. function onTextureDispose( event ) {
  15920. const texture = event.target;
  15921. texture.removeEventListener( 'dispose', onTextureDispose );
  15922. const renderTarget = _cache$1.get( texture );
  15923. if ( renderTarget !== undefined ) {
  15924. _cache$1.delete( texture );
  15925. renderTarget.dispose();
  15926. }
  15927. }
  15928. /**
  15929. * This function makes sure the generated cube map uses the correct
  15930. * texture mapping that corresponds to the equirectangular original.
  15931. *
  15932. * @private
  15933. * @param {Texture} texture - The cube texture.
  15934. * @param {number} mapping - The original texture mapping.
  15935. */
  15936. function mapTextureMapping( texture, mapping ) {
  15937. if ( mapping === EquirectangularReflectionMapping ) {
  15938. texture.mapping = CubeReflectionMapping;
  15939. } else if ( mapping === EquirectangularRefractionMapping ) {
  15940. texture.mapping = CubeRefractionMapping;
  15941. }
  15942. }
  15943. /**
  15944. * TSL function for creating a cube map node.
  15945. *
  15946. * @tsl
  15947. * @function
  15948. * @param {Node} envNode - The node representing the environment map.
  15949. * @returns {CubeMapNode}
  15950. */
  15951. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  15952. /**
  15953. * Represents a basic model for Image-based lighting (IBL). The environment
  15954. * is defined via environment maps in the equirectangular or cube map format.
  15955. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  15956. * or {@link MeshPhongNodeMaterial}.
  15957. *
  15958. * @augments LightingNode
  15959. */
  15960. class BasicEnvironmentNode extends LightingNode {
  15961. static get type() {
  15962. return 'BasicEnvironmentNode';
  15963. }
  15964. /**
  15965. * Constructs a new basic environment node.
  15966. *
  15967. * @param {Node} [envNode=null] - A node representing the environment.
  15968. */
  15969. constructor( envNode = null ) {
  15970. super();
  15971. /**
  15972. * A node representing the environment.
  15973. *
  15974. * @type {Node}
  15975. * @default null
  15976. */
  15977. this.envNode = envNode;
  15978. }
  15979. setup( builder ) {
  15980. // environment property is used in the finish() method of BasicLightingModel
  15981. builder.context.environment = cubeMapNode( this.envNode );
  15982. }
  15983. }
  15984. /**
  15985. * A specific version of {@link IrradianceNode} that is only relevant
  15986. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  15987. * requires a special scaling factor for the light map.
  15988. *
  15989. * @augments LightingNode
  15990. */
  15991. class BasicLightMapNode extends LightingNode {
  15992. static get type() {
  15993. return 'BasicLightMapNode';
  15994. }
  15995. /**
  15996. * Constructs a new basic light map node.
  15997. *
  15998. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  15999. */
  16000. constructor( lightMapNode = null ) {
  16001. super();
  16002. /**
  16003. * The light map node.
  16004. *
  16005. * @type {?Node<vec3>}
  16006. */
  16007. this.lightMapNode = lightMapNode;
  16008. }
  16009. setup( builder ) {
  16010. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  16011. const RECIPROCAL_PI = float( 1 / Math.PI );
  16012. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  16013. }
  16014. }
  16015. /**
  16016. * Abstract class for implementing lighting models. The module defines
  16017. * multiple methods that concrete lighting models can implement. These
  16018. * methods are executed at different points during the light evaluation
  16019. * process.
  16020. */
  16021. class LightingModel {
  16022. /**
  16023. * This method is intended for setting up lighting model and context data
  16024. * which are later used in the evaluation process.
  16025. *
  16026. * @abstract
  16027. * @param {NodeBuilder} builder - The current node builder.
  16028. */
  16029. start( builder ) {
  16030. // lights ( direct )
  16031. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  16032. // indirect
  16033. this.indirect( builder );
  16034. }
  16035. /**
  16036. * This method is intended for executing final tasks like final updates
  16037. * to the outgoing light.
  16038. *
  16039. * @abstract
  16040. * @param {NodeBuilder} builder - The current node builder.
  16041. */
  16042. finish( /*builder*/ ) { }
  16043. /**
  16044. * This method is intended for implementing the direct light term and
  16045. * executed during the build process of directional, point and spot light nodes.
  16046. *
  16047. * @abstract
  16048. * @param {Object} lightData - The light data.
  16049. * @param {NodeBuilder} builder - The current node builder.
  16050. */
  16051. direct( /*lightData, builder*/ ) { }
  16052. /**
  16053. * This method is intended for implementing the direct light term for
  16054. * rect area light nodes.
  16055. *
  16056. * @abstract
  16057. * @param {Object} lightData - The light data.
  16058. * @param {NodeBuilder} builder - The current node builder.
  16059. */
  16060. directRectArea( /*lightData, builder*/ ) {}
  16061. /**
  16062. * This method is intended for implementing the indirect light term.
  16063. *
  16064. * @abstract
  16065. * @param {NodeBuilder} builder - The current node builder.
  16066. */
  16067. indirect( /*builder*/ ) { }
  16068. /**
  16069. * This method is intended for implementing the ambient occlusion term.
  16070. * Unlike other methods, this method must be called manually by the lighting
  16071. * model in its indirect term.
  16072. *
  16073. * @abstract
  16074. * @param {NodeBuilder} builder - The current node builder.
  16075. */
  16076. ambientOcclusion( /*input, stack, builder*/ ) { }
  16077. }
  16078. /**
  16079. * Represents the lighting model for unlit materials. The only light contribution
  16080. * is baked indirect lighting modulated with ambient occlusion and the material's
  16081. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  16082. *
  16083. * @augments LightingModel
  16084. */
  16085. class BasicLightingModel extends LightingModel {
  16086. /**
  16087. * Constructs a new basic lighting model.
  16088. */
  16089. constructor() {
  16090. super();
  16091. }
  16092. /**
  16093. * Implements the baked indirect lighting with its modulation.
  16094. *
  16095. * @param {NodeBuilder} builder - The current node builder.
  16096. */
  16097. indirect( { context } ) {
  16098. const ambientOcclusion = context.ambientOcclusion;
  16099. const reflectedLight = context.reflectedLight;
  16100. const irradianceLightMap = context.irradianceLightMap;
  16101. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  16102. // accumulation (baked indirect lighting only)
  16103. if ( irradianceLightMap ) {
  16104. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  16105. } else {
  16106. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  16107. }
  16108. // modulation
  16109. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16110. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  16111. }
  16112. /**
  16113. * Implements the environment mapping.
  16114. *
  16115. * @param {NodeBuilder} builder - The current node builder.
  16116. */
  16117. finish( builder ) {
  16118. const { material, context } = builder;
  16119. const outgoingLight = context.outgoingLight;
  16120. const envNode = builder.context.environment;
  16121. if ( envNode ) {
  16122. switch ( material.combine ) {
  16123. case MultiplyOperation:
  16124. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  16125. break;
  16126. case MixOperation:
  16127. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  16128. break;
  16129. case AddOperation:
  16130. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  16131. break;
  16132. default:
  16133. warn( 'BasicLightingModel: Unsupported .combine value:', material.combine );
  16134. break;
  16135. }
  16136. }
  16137. }
  16138. }
  16139. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  16140. /**
  16141. * Node material version of {@link MeshBasicMaterial}.
  16142. *
  16143. * @augments NodeMaterial
  16144. */
  16145. class MeshBasicNodeMaterial extends NodeMaterial {
  16146. static get type() {
  16147. return 'MeshBasicNodeMaterial';
  16148. }
  16149. /**
  16150. * Constructs a new mesh basic node material.
  16151. *
  16152. * @param {Object} [parameters] - The configuration parameter.
  16153. */
  16154. constructor( parameters ) {
  16155. super();
  16156. /**
  16157. * This flag can be used for type testing.
  16158. *
  16159. * @type {boolean}
  16160. * @readonly
  16161. * @default true
  16162. */
  16163. this.isMeshBasicNodeMaterial = true;
  16164. /**
  16165. * Although the basic material is by definition unlit, we set
  16166. * this property to `true` since we use a lighting model to compute
  16167. * the outgoing light of the fragment shader.
  16168. *
  16169. * @type {boolean}
  16170. * @default true
  16171. */
  16172. this.lights = true;
  16173. this.setDefaultValues( _defaultValues$9 );
  16174. this.setValues( parameters );
  16175. }
  16176. /**
  16177. * Basic materials are not affected by normal and bump maps so we
  16178. * return by default {@link normalViewGeometry}.
  16179. *
  16180. * @return {Node<vec3>} The normal node.
  16181. */
  16182. setupNormal() {
  16183. return directionToFaceDirection( normalViewGeometry ); // see #28839
  16184. }
  16185. /**
  16186. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16187. * to implement the default environment mapping.
  16188. *
  16189. * @param {NodeBuilder} builder - The current node builder.
  16190. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16191. */
  16192. setupEnvironment( builder ) {
  16193. const envNode = super.setupEnvironment( builder );
  16194. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16195. }
  16196. /**
  16197. * This method must be overwritten since light maps are evaluated
  16198. * with a special scaling factor for basic materials.
  16199. *
  16200. * @param {NodeBuilder} builder - The current node builder.
  16201. * @return {?BasicLightMapNode<vec3>} The light map node.
  16202. */
  16203. setupLightMap( builder ) {
  16204. let node = null;
  16205. if ( builder.material.lightMap ) {
  16206. node = new BasicLightMapNode( materialLightMap );
  16207. }
  16208. return node;
  16209. }
  16210. /**
  16211. * The material overwrites this method because `lights` is set to `true` but
  16212. * we still want to return the diffuse color as the outgoing light.
  16213. *
  16214. * @return {Node<vec3>} The outgoing light node.
  16215. */
  16216. setupOutgoingLight() {
  16217. return diffuseColor.rgb;
  16218. }
  16219. /**
  16220. * Setups the lighting model.
  16221. *
  16222. * @return {BasicLightingModel} The lighting model.
  16223. */
  16224. setupLightingModel() {
  16225. return new BasicLightingModel();
  16226. }
  16227. }
  16228. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  16229. // Original approximation by Christophe Schlick '94
  16230. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  16231. // Optimized variant (presented by Epic at SIGGRAPH '13)
  16232. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  16233. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  16234. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  16235. } ); // validated
  16236. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  16237. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  16238. } ); // validated
  16239. const G_BlinnPhong_Implicit = () => float( 0.25 );
  16240. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  16241. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  16242. } );
  16243. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16244. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16245. const dotNH = normalView.dot( halfDir ).clamp();
  16246. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16247. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  16248. const G = G_BlinnPhong_Implicit();
  16249. const D = D_BlinnPhong( { dotNH } );
  16250. return F.mul( G ).mul( D );
  16251. } );
  16252. /**
  16253. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  16254. *
  16255. * @augments BasicLightingModel
  16256. */
  16257. class PhongLightingModel extends BasicLightingModel {
  16258. /**
  16259. * Constructs a new phong lighting model.
  16260. *
  16261. * @param {boolean} [specular=true] - Whether specular is supported or not.
  16262. */
  16263. constructor( specular = true ) {
  16264. super();
  16265. /**
  16266. * Whether specular is supported or not. Set this to `false` if you are
  16267. * looking for a Lambert-like material meaning a material for non-shiny
  16268. * surfaces, without specular highlights.
  16269. *
  16270. * @type {boolean}
  16271. * @default true
  16272. */
  16273. this.specular = specular;
  16274. }
  16275. /**
  16276. * Implements the direct lighting. The specular portion is optional an can be controlled
  16277. * with the {@link PhongLightingModel#specular} flag.
  16278. *
  16279. * @param {Object} lightData - The light data.
  16280. */
  16281. direct( { lightDirection, lightColor, reflectedLight } ) {
  16282. const dotNL = normalView.dot( lightDirection ).clamp();
  16283. const irradiance = dotNL.mul( lightColor );
  16284. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  16285. if ( this.specular === true ) {
  16286. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  16287. }
  16288. }
  16289. /**
  16290. * Implements the indirect lighting.
  16291. *
  16292. * @param {NodeBuilder} builder - The current node builder.
  16293. */
  16294. indirect( builder ) {
  16295. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  16296. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16297. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16298. }
  16299. }
  16300. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  16301. /**
  16302. * Node material version of {@link MeshLambertMaterial}.
  16303. *
  16304. * @augments NodeMaterial
  16305. */
  16306. class MeshLambertNodeMaterial extends NodeMaterial {
  16307. static get type() {
  16308. return 'MeshLambertNodeMaterial';
  16309. }
  16310. /**
  16311. * Constructs a new mesh lambert node material.
  16312. *
  16313. * @param {Object} [parameters] - The configuration parameter.
  16314. */
  16315. constructor( parameters ) {
  16316. super();
  16317. /**
  16318. * This flag can be used for type testing.
  16319. *
  16320. * @type {boolean}
  16321. * @readonly
  16322. * @default true
  16323. */
  16324. this.isMeshLambertNodeMaterial = true;
  16325. /**
  16326. * Set to `true` because lambert materials react on lights.
  16327. *
  16328. * @type {boolean}
  16329. * @default true
  16330. */
  16331. this.lights = true;
  16332. this.setDefaultValues( _defaultValues$8 );
  16333. this.setValues( parameters );
  16334. }
  16335. /**
  16336. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16337. * to implement the default environment mapping.
  16338. *
  16339. * @param {NodeBuilder} builder - The current node builder.
  16340. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16341. */
  16342. setupEnvironment( builder ) {
  16343. const envNode = super.setupEnvironment( builder );
  16344. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16345. }
  16346. /**
  16347. * Setups the lighting model.
  16348. *
  16349. * @return {PhongLightingModel} The lighting model.
  16350. */
  16351. setupLightingModel( /*builder*/ ) {
  16352. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  16353. }
  16354. }
  16355. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  16356. /**
  16357. * Node material version of {@link MeshPhongMaterial}.
  16358. *
  16359. * @augments NodeMaterial
  16360. */
  16361. class MeshPhongNodeMaterial extends NodeMaterial {
  16362. static get type() {
  16363. return 'MeshPhongNodeMaterial';
  16364. }
  16365. /**
  16366. * Constructs a new mesh lambert node material.
  16367. *
  16368. * @param {Object} [parameters] - The configuration parameter.
  16369. */
  16370. constructor( parameters ) {
  16371. super();
  16372. /**
  16373. * This flag can be used for type testing.
  16374. *
  16375. * @type {boolean}
  16376. * @readonly
  16377. * @default true
  16378. */
  16379. this.isMeshPhongNodeMaterial = true;
  16380. /**
  16381. * Set to `true` because phong materials react on lights.
  16382. *
  16383. * @type {boolean}
  16384. * @default true
  16385. */
  16386. this.lights = true;
  16387. /**
  16388. * The shininess of phong materials is by default inferred from the `shininess`
  16389. * property. This node property allows to overwrite the default
  16390. * and define the shininess with a node instead.
  16391. *
  16392. * If you don't want to overwrite the shininess but modify the existing
  16393. * value instead, use {@link materialShininess}.
  16394. *
  16395. * @type {?Node<float>}
  16396. * @default null
  16397. */
  16398. this.shininessNode = null;
  16399. /**
  16400. * The specular color of phong materials is by default inferred from the
  16401. * `specular` property. This node property allows to overwrite the default
  16402. * and define the specular color with a node instead.
  16403. *
  16404. * If you don't want to overwrite the specular color but modify the existing
  16405. * value instead, use {@link materialSpecular}.
  16406. *
  16407. * @type {?Node<vec3>}
  16408. * @default null
  16409. */
  16410. this.specularNode = null;
  16411. this.setDefaultValues( _defaultValues$7 );
  16412. this.setValues( parameters );
  16413. }
  16414. /**
  16415. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16416. * to implement the default environment mapping.
  16417. *
  16418. * @param {NodeBuilder} builder - The current node builder.
  16419. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16420. */
  16421. setupEnvironment( builder ) {
  16422. const envNode = super.setupEnvironment( builder );
  16423. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16424. }
  16425. /**
  16426. * Setups the lighting model.
  16427. *
  16428. * @return {PhongLightingModel} The lighting model.
  16429. */
  16430. setupLightingModel( /*builder*/ ) {
  16431. return new PhongLightingModel();
  16432. }
  16433. /**
  16434. * Setups the phong specific node variables.
  16435. *
  16436. * @param {NodeBuilder} builder - The current node builder.
  16437. */
  16438. setupVariants( /*builder*/ ) {
  16439. // SHININESS
  16440. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16441. shininess.assign( shininessNode );
  16442. // SPECULAR COLOR
  16443. const specularNode = this.specularNode || materialSpecular;
  16444. specularColor.assign( specularNode );
  16445. }
  16446. copy( source ) {
  16447. this.shininessNode = source.shininessNode;
  16448. this.specularNode = source.specularNode;
  16449. return super.copy( source );
  16450. }
  16451. }
  16452. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  16453. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  16454. return float( 0 );
  16455. }
  16456. const dxy = normalViewGeometry.dFdx().abs().max( normalViewGeometry.dFdy().abs() );
  16457. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  16458. return geometryRoughness;
  16459. } );
  16460. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  16461. const { roughness } = inputs;
  16462. const geometryRoughness = getGeometryRoughness();
  16463. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  16464. roughnessFactor = roughnessFactor.add( geometryRoughness );
  16465. roughnessFactor = roughnessFactor.min( 1.0 );
  16466. return roughnessFactor;
  16467. } );
  16468. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  16469. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  16470. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  16471. const a2 = alpha.pow2();
  16472. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  16473. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  16474. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  16475. } ).setLayout( {
  16476. name: 'V_GGX_SmithCorrelated',
  16477. type: 'float',
  16478. inputs: [
  16479. { name: 'alpha', type: 'float' },
  16480. { name: 'dotNL', type: 'float' },
  16481. { name: 'dotNV', type: 'float' }
  16482. ]
  16483. } ); // validated
  16484. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16485. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  16486. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  16487. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  16488. const v = div( 0.5, gv.add( gl ) );
  16489. return v;
  16490. } ).setLayout( {
  16491. name: 'V_GGX_SmithCorrelated_Anisotropic',
  16492. type: 'float',
  16493. inputs: [
  16494. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16495. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16496. { name: 'dotTV', type: 'float', qualifier: 'in' },
  16497. { name: 'dotBV', type: 'float', qualifier: 'in' },
  16498. { name: 'dotTL', type: 'float', qualifier: 'in' },
  16499. { name: 'dotBL', type: 'float', qualifier: 'in' },
  16500. { name: 'dotNV', type: 'float', qualifier: 'in' },
  16501. { name: 'dotNL', type: 'float', qualifier: 'in' }
  16502. ]
  16503. } );
  16504. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  16505. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  16506. // alpha is "roughness squared" in Disney’s reparameterization
  16507. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  16508. const a2 = alpha.pow2();
  16509. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  16510. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  16511. } ).setLayout( {
  16512. name: 'D_GGX',
  16513. type: 'float',
  16514. inputs: [
  16515. { name: 'alpha', type: 'float' },
  16516. { name: 'dotNH', type: 'float' }
  16517. ]
  16518. } ); // validated
  16519. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  16520. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16521. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  16522. const a2 = alphaT.mul( alphaB );
  16523. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  16524. const v2 = v.dot( v );
  16525. const w2 = a2.div( v2 );
  16526. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  16527. } ).setLayout( {
  16528. name: 'D_GGX_Anisotropic',
  16529. type: 'float',
  16530. inputs: [
  16531. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16532. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16533. { name: 'dotNH', type: 'float', qualifier: 'in' },
  16534. { name: 'dotTH', type: 'float', qualifier: 'in' },
  16535. { name: 'dotBH', type: 'float', qualifier: 'in' }
  16536. ]
  16537. } );
  16538. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  16539. const BRDF_GGX = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness, f, normalView: normalView$1 = normalView, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16540. const alpha = roughness.pow2(); // UE4's roughness
  16541. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16542. const dotNL = normalView$1.dot( lightDirection ).clamp();
  16543. const dotNV = normalView$1.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16544. const dotNH = normalView$1.dot( halfDir ).clamp();
  16545. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16546. let F = F_Schlick( { f0, f90, dotVH } );
  16547. let V, D;
  16548. if ( defined( USE_IRIDESCENCE ) ) {
  16549. F = iridescence.mix( F, f );
  16550. }
  16551. if ( defined( USE_ANISOTROPY ) ) {
  16552. const dotTL = anisotropyT.dot( lightDirection );
  16553. const dotTV = anisotropyT.dot( positionViewDirection );
  16554. const dotTH = anisotropyT.dot( halfDir );
  16555. const dotBL = anisotropyB.dot( lightDirection );
  16556. const dotBV = anisotropyB.dot( positionViewDirection );
  16557. const dotBH = anisotropyB.dot( halfDir );
  16558. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  16559. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  16560. } else {
  16561. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  16562. D = D_GGX( { alpha, dotNH } );
  16563. }
  16564. return F.mul( V ).mul( D );
  16565. } ); // validated
  16566. /**
  16567. * Precomputed DFG LUT for Image-Based Lighting
  16568. * Resolution: 16x16
  16569. * Samples: 4096 per texel
  16570. * Format: RG16F (2 half floats per texel: scale, bias)
  16571. */
  16572. const DATA = new Uint16Array( [
  16573. 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,
  16574. 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,
  16575. 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,
  16576. 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,
  16577. 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,
  16578. 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,
  16579. 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,
  16580. 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,
  16581. 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,
  16582. 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,
  16583. 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,
  16584. 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,
  16585. 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,
  16586. 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,
  16587. 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,
  16588. 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
  16589. ] );
  16590. let lut = null;
  16591. const DFGLUT = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  16592. if ( lut === null ) {
  16593. lut = new DataTexture( DATA, 16, 16, RGFormat, HalfFloatType );
  16594. lut.name = 'DFG_LUT';
  16595. lut.minFilter = LinearFilter;
  16596. lut.magFilter = LinearFilter;
  16597. lut.wrapS = ClampToEdgeWrapping;
  16598. lut.wrapT = ClampToEdgeWrapping;
  16599. lut.generateMipmaps = false;
  16600. lut.needsUpdate = true;
  16601. }
  16602. const uv = vec2( roughness, dotNV );
  16603. return texture( lut, uv ).rg;
  16604. } );
  16605. // GGX BRDF with multi-scattering energy compensation for direct lighting
  16606. // This provides more accurate energy conservation, especially for rough materials
  16607. // Based on "Practical Multiple Scattering Compensation for Microfacet Models"
  16608. // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf
  16609. const BRDF_GGX_Multiscatter = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness: _roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16610. // Single-scattering BRDF (standard GGX)
  16611. const singleScatter = BRDF_GGX( { lightDirection, f0, f90, roughness: _roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } );
  16612. // Multi-scattering compensation
  16613. const dotNL = normalView.dot( lightDirection ).clamp();
  16614. const dotNV = normalView.dot( positionViewDirection ).clamp();
  16615. // Precomputed DFG values for view and light directions
  16616. const dfgV = DFGLUT( { roughness: _roughness, dotNV } );
  16617. const dfgL = DFGLUT( { roughness: _roughness, dotNV: dotNL } );
  16618. // Single-scattering energy for view and light
  16619. const FssEss_V = f0.mul( dfgV.x ).add( f90.mul( dfgV.y ) );
  16620. const FssEss_L = f0.mul( dfgL.x ).add( f90.mul( dfgL.y ) );
  16621. const Ess_V = dfgV.x.add( dfgV.y );
  16622. const Ess_L = dfgL.x.add( dfgL.y );
  16623. // Energy lost to multiple scattering
  16624. const Ems_V = float( 1.0 ).sub( Ess_V );
  16625. const Ems_L = float( 1.0 ).sub( Ess_L );
  16626. // Average Fresnel reflectance
  16627. const Favg = f0.add( f0.oneMinus().mul( 0.047619 ) ); // 1/21
  16628. // Multiple scattering contribution
  16629. // Uses geometric mean of view and light contributions for better energy distribution
  16630. 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 ) );
  16631. // Energy compensation factor
  16632. const compensationFactor = Ems_V.mul( Ems_L );
  16633. const multiScatter = Fms.mul( compensationFactor );
  16634. return singleScatter.add( multiScatter );
  16635. } );
  16636. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  16637. const { dotNV, specularColor, specularF90, roughness } = inputs;
  16638. const fab = DFGLUT( { dotNV, roughness } );
  16639. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16640. } );
  16641. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  16642. const x = dotVH.oneMinus().saturate();
  16643. const x2 = x.mul( x );
  16644. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  16645. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  16646. } ).setLayout( {
  16647. name: 'Schlick_to_F0',
  16648. type: 'vec3',
  16649. inputs: [
  16650. { name: 'f', type: 'vec3' },
  16651. { name: 'f90', type: 'float' },
  16652. { name: 'dotVH', type: 'float' }
  16653. ]
  16654. } );
  16655. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16656. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  16657. const alpha = roughness.pow2();
  16658. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  16659. const invAlpha = float( 1.0 ).div( alpha );
  16660. const cos2h = dotNH.pow2();
  16661. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  16662. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  16663. } ).setLayout( {
  16664. name: 'D_Charlie',
  16665. type: 'float',
  16666. inputs: [
  16667. { name: 'roughness', type: 'float' },
  16668. { name: 'dotNH', type: 'float' }
  16669. ]
  16670. } );
  16671. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16672. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  16673. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  16674. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  16675. } ).setLayout( {
  16676. name: 'V_Neubelt',
  16677. type: 'float',
  16678. inputs: [
  16679. { name: 'dotNV', type: 'float' },
  16680. { name: 'dotNL', type: 'float' }
  16681. ]
  16682. } );
  16683. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16684. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16685. const dotNL = normalView.dot( lightDirection ).clamp();
  16686. const dotNV = normalView.dot( positionViewDirection ).clamp();
  16687. const dotNH = normalView.dot( halfDir ).clamp();
  16688. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  16689. const V = V_Neubelt( { dotNV, dotNL } );
  16690. return sheen.mul( D ).mul( V );
  16691. } );
  16692. // Rect Area Light
  16693. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  16694. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  16695. // code: https://github.com/selfshadow/ltc_code/
  16696. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  16697. const LUT_SIZE = 64.0;
  16698. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  16699. const LUT_BIAS = 0.5 / LUT_SIZE;
  16700. const dotNV = N.dot( V ).saturate();
  16701. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  16702. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  16703. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  16704. return uv;
  16705. } ).setLayout( {
  16706. name: 'LTC_Uv',
  16707. type: 'vec2',
  16708. inputs: [
  16709. { name: 'N', type: 'vec3' },
  16710. { name: 'V', type: 'vec3' },
  16711. { name: 'roughness', type: 'float' }
  16712. ]
  16713. } );
  16714. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  16715. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  16716. // An approximation of the form factor of a horizon-clipped rectangle.
  16717. const l = f.length();
  16718. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  16719. } ).setLayout( {
  16720. name: 'LTC_ClippedSphereFormFactor',
  16721. type: 'float',
  16722. inputs: [
  16723. { name: 'f', type: 'vec3' }
  16724. ]
  16725. } );
  16726. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  16727. const x = v1.dot( v2 );
  16728. const y = x.abs().toVar();
  16729. // rational polynomial approximation to theta / sin( theta ) / 2PI
  16730. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  16731. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  16732. const v = a.div( b );
  16733. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  16734. return v1.cross( v2 ).mul( theta_sintheta );
  16735. } ).setLayout( {
  16736. name: 'LTC_EdgeVectorFormFactor',
  16737. type: 'vec3',
  16738. inputs: [
  16739. { name: 'v1', type: 'vec3' },
  16740. { name: 'v2', type: 'vec3' }
  16741. ]
  16742. } );
  16743. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  16744. // bail if point is on back side of plane of light
  16745. // assumes ccw winding order of light vertices
  16746. const v1 = p1.sub( p0 ).toVar();
  16747. const v2 = p3.sub( p0 ).toVar();
  16748. const lightNormal = v1.cross( v2 );
  16749. const result = vec3().toVar();
  16750. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16751. // construct orthonormal basis around N
  16752. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  16753. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  16754. // compute transform
  16755. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  16756. // transform rect
  16757. // & project rect onto sphere
  16758. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  16759. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  16760. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  16761. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  16762. // calculate vector form factor
  16763. const vectorFormFactor = vec3( 0 ).toVar();
  16764. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16765. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16766. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16767. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16768. // adjust for horizon clipping
  16769. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  16770. } );
  16771. return result;
  16772. } ).setLayout( {
  16773. name: 'LTC_Evaluate',
  16774. type: 'vec3',
  16775. inputs: [
  16776. { name: 'N', type: 'vec3' },
  16777. { name: 'V', type: 'vec3' },
  16778. { name: 'P', type: 'vec3' },
  16779. { name: 'mInv', type: 'mat3' },
  16780. { name: 'p0', type: 'vec3' },
  16781. { name: 'p1', type: 'vec3' },
  16782. { name: 'p2', type: 'vec3' },
  16783. { name: 'p3', type: 'vec3' }
  16784. ]
  16785. } );
  16786. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  16787. // bail if point is on back side of plane of light
  16788. // assumes ccw winding order of light vertices
  16789. const v1 = p1.sub( p0 ).toVar();
  16790. const v2 = p3.sub( p0 ).toVar();
  16791. const lightNormal = v1.cross( v2 );
  16792. const result = vec3().toVar();
  16793. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16794. // transform rect
  16795. // & project rect onto sphere
  16796. const coords0 = p0.sub( P ).normalize().toVar();
  16797. const coords1 = p1.sub( P ).normalize().toVar();
  16798. const coords2 = p2.sub( P ).normalize().toVar();
  16799. const coords3 = p3.sub( P ).normalize().toVar();
  16800. // calculate vector form factor
  16801. const vectorFormFactor = vec3( 0 ).toVar();
  16802. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16803. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16804. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16805. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16806. // adjust for horizon clipping
  16807. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  16808. } );
  16809. return result;
  16810. } ).setLayout( {
  16811. name: 'LTC_Evaluate',
  16812. type: 'vec3',
  16813. inputs: [
  16814. { name: 'P', type: 'vec3' },
  16815. { name: 'p0', type: 'vec3' },
  16816. { name: 'p1', type: 'vec3' },
  16817. { name: 'p2', type: 'vec3' },
  16818. { name: 'p3', type: 'vec3' }
  16819. ]
  16820. } );
  16821. // Mipped Bicubic Texture Filtering by N8
  16822. // https://www.shadertoy.com/view/Dl2SDW
  16823. const bC = 1.0 / 6.0;
  16824. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  16825. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  16826. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  16827. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  16828. const g0 = ( a ) => w0( a ).add( w1( a ) );
  16829. const g1 = ( a ) => w2( a ).add( w3( a ) );
  16830. // h0 and h1 are the two offset functions
  16831. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  16832. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  16833. const bicubic = ( textureNode, texelSize, lod ) => {
  16834. const uv = textureNode.uvNode;
  16835. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  16836. const iuv = floor( uvScaled );
  16837. const fuv = fract( uvScaled );
  16838. const g0x = g0( fuv.x );
  16839. const g1x = g1( fuv.x );
  16840. const h0x = h0( fuv.x );
  16841. const h1x = h1( fuv.x );
  16842. const h0y = h0( fuv.y );
  16843. const h1y = h1( fuv.y );
  16844. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16845. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16846. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16847. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16848. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  16849. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  16850. return a.add( b );
  16851. };
  16852. /**
  16853. * Applies mipped bicubic texture filtering to the given texture node.
  16854. *
  16855. * @tsl
  16856. * @function
  16857. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16858. * @param {Node<float>} lodNode - Defines the LOD to sample from.
  16859. * @return {Node} The filtered texture sample.
  16860. */
  16861. const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => {
  16862. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  16863. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  16864. const fLodSizeInv = div( 1.0, fLodSize );
  16865. const cLodSizeInv = div( 1.0, cLodSize );
  16866. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  16867. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  16868. return fract( lodNode ).mix( fSample, cSample );
  16869. } );
  16870. /**
  16871. * Applies mipped bicubic texture filtering to the given texture node.
  16872. *
  16873. * @tsl
  16874. * @function
  16875. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16876. * @param {Node<float>} [strength] - Defines the strength of the bicubic filtering.
  16877. * @return {Node} The filtered texture sample.
  16878. */
  16879. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => {
  16880. const lod = strength.mul( maxMipLevel( textureNode ) );
  16881. return textureBicubicLevel( textureNode, lod );
  16882. } );
  16883. //
  16884. // Transmission
  16885. //
  16886. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  16887. // Direction of refracted light.
  16888. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  16889. // Compute rotation-independent scaling of the model matrix.
  16890. const modelScale = vec3(
  16891. length( modelMatrix[ 0 ].xyz ),
  16892. length( modelMatrix[ 1 ].xyz ),
  16893. length( modelMatrix[ 2 ].xyz )
  16894. );
  16895. // The thickness is specified in local space.
  16896. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  16897. } ).setLayout( {
  16898. name: 'getVolumeTransmissionRay',
  16899. type: 'vec3',
  16900. inputs: [
  16901. { name: 'n', type: 'vec3' },
  16902. { name: 'v', type: 'vec3' },
  16903. { name: 'thickness', type: 'float' },
  16904. { name: 'ior', type: 'float' },
  16905. { name: 'modelMatrix', type: 'mat4' }
  16906. ]
  16907. } );
  16908. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  16909. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  16910. // an IOR of 1.5 results in the default amount of microfacet refraction.
  16911. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  16912. } ).setLayout( {
  16913. name: 'applyIorToRoughness',
  16914. type: 'float',
  16915. inputs: [
  16916. { name: 'roughness', type: 'float' },
  16917. { name: 'ior', type: 'float' }
  16918. ]
  16919. } );
  16920. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  16921. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  16922. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  16923. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  16924. const transmissionSample = vTexture.sample( fragCoord );
  16925. //const transmissionSample = viewportMipTexture( fragCoord );
  16926. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  16927. return textureBicubicLevel( transmissionSample, lod );
  16928. } );
  16929. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  16930. If( attenuationDistance.notEqual( 0 ), () => {
  16931. // Compute light attenuation using Beer's law.
  16932. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  16933. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  16934. return transmittance;
  16935. } );
  16936. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  16937. return vec3( 1.0 );
  16938. } ).setLayout( {
  16939. name: 'volumeAttenuation',
  16940. type: 'vec3',
  16941. inputs: [
  16942. { name: 'transmissionDistance', type: 'float' },
  16943. { name: 'attenuationColor', type: 'vec3' },
  16944. { name: 'attenuationDistance', type: 'float' }
  16945. ]
  16946. } );
  16947. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  16948. let transmittedLight, transmittance;
  16949. if ( dispersion ) {
  16950. transmittedLight = vec4().toVar();
  16951. transmittance = vec3().toVar();
  16952. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  16953. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  16954. Loop( { start: 0, end: 3 }, ( { i } ) => {
  16955. const ior = iors.element( i );
  16956. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16957. const refractedRayExit = position.add( transmissionRay );
  16958. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16959. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16960. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16961. refractionCoords.addAssign( 1.0 );
  16962. refractionCoords.divAssign( 2.0 );
  16963. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16964. // Sample framebuffer to get pixel the refracted ray hits.
  16965. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  16966. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  16967. transmittedLight.a.addAssign( transmissionSample.a );
  16968. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  16969. } );
  16970. transmittedLight.a.divAssign( 3.0 );
  16971. } else {
  16972. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16973. const refractedRayExit = position.add( transmissionRay );
  16974. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16975. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16976. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16977. refractionCoords.addAssign( 1.0 );
  16978. refractionCoords.divAssign( 2.0 );
  16979. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16980. // Sample framebuffer to get pixel the refracted ray hits.
  16981. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  16982. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  16983. }
  16984. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  16985. const dotNV = n.dot( v ).clamp();
  16986. // Get the specular component.
  16987. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  16988. dotNV,
  16989. specularColor,
  16990. specularF90,
  16991. roughness
  16992. } ) );
  16993. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  16994. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  16995. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  16996. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  16997. } );
  16998. //
  16999. // Iridescence
  17000. //
  17001. // XYZ to linear-sRGB color space
  17002. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  17003. 3.2404542, -0.969266, 0.0556434,
  17004. -1.5371385, 1.8760108, -0.2040259,
  17005. -0.4985314, 0.0415560, 1.0572252
  17006. );
  17007. // Assume air interface for top
  17008. // Note: We don't handle the case fresnel0 == 1
  17009. const Fresnel0ToIor = ( fresnel0 ) => {
  17010. const sqrtF0 = fresnel0.sqrt();
  17011. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  17012. };
  17013. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  17014. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  17015. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  17016. };
  17017. // Fresnel equations for dielectric/dielectric interfaces.
  17018. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  17019. // Evaluation XYZ sensitivity curves in Fourier space
  17020. const evalSensitivity = ( OPD, shift ) => {
  17021. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  17022. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  17023. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  17024. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  17025. 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() );
  17026. 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() );
  17027. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  17028. const rgb = XYZ_TO_REC709.mul( xyz );
  17029. return rgb;
  17030. };
  17031. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  17032. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  17033. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  17034. // Evaluate the cosTheta on the base layer (Snell law)
  17035. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  17036. // Handle TIR:
  17037. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  17038. If( cosTheta2Sq.lessThan( 0 ), () => {
  17039. return vec3( 1.0 );
  17040. } );
  17041. const cosTheta2 = cosTheta2Sq.sqrt();
  17042. // First interface
  17043. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  17044. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  17045. //const R21 = R12;
  17046. const T121 = R12.oneMinus();
  17047. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  17048. const phi21 = float( Math.PI ).sub( phi12 );
  17049. // Second interface
  17050. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  17051. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  17052. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  17053. const phi23 = vec3(
  17054. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  17055. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  17056. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  17057. );
  17058. // Phase shift
  17059. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  17060. const phi = vec3( phi21 ).add( phi23 );
  17061. // Compound terms
  17062. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  17063. const r123 = R123.sqrt();
  17064. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  17065. // Reflectance term for m = 0 (DC term amplitude)
  17066. const C0 = R12.add( Rs );
  17067. const I = C0.toVar();
  17068. // Reflectance term for m > 0 (pairs of diracs)
  17069. const Cm = Rs.sub( T121 ).toVar();
  17070. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  17071. Cm.mulAssign( r123 );
  17072. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  17073. I.addAssign( Cm.mul( Sm ) );
  17074. } );
  17075. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  17076. return I.max( vec3( 0.0 ) );
  17077. } ).setLayout( {
  17078. name: 'evalIridescence',
  17079. type: 'vec3',
  17080. inputs: [
  17081. { name: 'outsideIOR', type: 'float' },
  17082. { name: 'eta2', type: 'float' },
  17083. { name: 'cosTheta1', type: 'float' },
  17084. { name: 'thinFilmThickness', type: 'float' },
  17085. { name: 'baseF0', type: 'vec3' }
  17086. ]
  17087. } );
  17088. //
  17089. // Sheen
  17090. //
  17091. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  17092. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF".
  17093. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  17094. const dotNV = normal.dot( viewDir ).saturate();
  17095. const r2 = roughness.mul( roughness );
  17096. const rInv = roughness.add( 0.1 ).reciprocal();
  17097. const a = float( -1.9362 ).add( roughness.mul( 1.0678 ) ).add( r2.mul( 0.4573 ) ).sub( rInv.mul( 0.8469 ) );
  17098. const b = float( -0.6014 ).add( roughness.mul( 0.5538 ) ).sub( r2.mul( 0.4670 ) ).sub( rInv.mul( 0.1255 ) );
  17099. const DG = a.mul( dotNV ).add( b ).exp();
  17100. return DG.saturate();
  17101. } );
  17102. const clearcoatF0 = vec3( 0.04 );
  17103. const clearcoatF90 = float( 1 );
  17104. /**
  17105. * Represents the lighting model for a PBR material.
  17106. *
  17107. * @augments LightingModel
  17108. */
  17109. class PhysicalLightingModel extends LightingModel {
  17110. /**
  17111. * Constructs a new physical lighting model.
  17112. *
  17113. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  17114. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  17115. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  17116. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  17117. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  17118. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  17119. */
  17120. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  17121. super();
  17122. /**
  17123. * Whether clearcoat is supported or not.
  17124. *
  17125. * @type {boolean}
  17126. * @default false
  17127. */
  17128. this.clearcoat = clearcoat;
  17129. /**
  17130. * Whether sheen is supported or not.
  17131. *
  17132. * @type {boolean}
  17133. * @default false
  17134. */
  17135. this.sheen = sheen;
  17136. /**
  17137. * Whether iridescence is supported or not.
  17138. *
  17139. * @type {boolean}
  17140. * @default false
  17141. */
  17142. this.iridescence = iridescence;
  17143. /**
  17144. * Whether anisotropy is supported or not.
  17145. *
  17146. * @type {boolean}
  17147. * @default false
  17148. */
  17149. this.anisotropy = anisotropy;
  17150. /**
  17151. * Whether transmission is supported or not.
  17152. *
  17153. * @type {boolean}
  17154. * @default false
  17155. */
  17156. this.transmission = transmission;
  17157. /**
  17158. * Whether dispersion is supported or not.
  17159. *
  17160. * @type {boolean}
  17161. * @default false
  17162. */
  17163. this.dispersion = dispersion;
  17164. /**
  17165. * The clear coat radiance.
  17166. *
  17167. * @type {?Node}
  17168. * @default null
  17169. */
  17170. this.clearcoatRadiance = null;
  17171. /**
  17172. * The clear coat specular direct.
  17173. *
  17174. * @type {?Node}
  17175. * @default null
  17176. */
  17177. this.clearcoatSpecularDirect = null;
  17178. /**
  17179. * The clear coat specular indirect.
  17180. *
  17181. * @type {?Node}
  17182. * @default null
  17183. */
  17184. this.clearcoatSpecularIndirect = null;
  17185. /**
  17186. * The sheen specular direct.
  17187. *
  17188. * @type {?Node}
  17189. * @default null
  17190. */
  17191. this.sheenSpecularDirect = null;
  17192. /**
  17193. * The sheen specular indirect.
  17194. *
  17195. * @type {?Node}
  17196. * @default null
  17197. */
  17198. this.sheenSpecularIndirect = null;
  17199. /**
  17200. * The iridescence Fresnel.
  17201. *
  17202. * @type {?Node}
  17203. * @default null
  17204. */
  17205. this.iridescenceFresnel = null;
  17206. /**
  17207. * The iridescence F0.
  17208. *
  17209. * @type {?Node}
  17210. * @default null
  17211. */
  17212. this.iridescenceF0 = null;
  17213. /**
  17214. * The iridescence F0 dielectric.
  17215. *
  17216. * @type {?Node}
  17217. * @default null
  17218. */
  17219. this.iridescenceF0Dielectric = null;
  17220. /**
  17221. * The iridescence F0 metallic.
  17222. *
  17223. * @type {?Node}
  17224. * @default null
  17225. */
  17226. this.iridescenceF0Metallic = null;
  17227. }
  17228. /**
  17229. * Depending on what features are requested, the method prepares certain node variables
  17230. * which are later used for lighting computations.
  17231. *
  17232. * @param {NodeBuilder} builder - The current node builder.
  17233. */
  17234. start( builder ) {
  17235. if ( this.clearcoat === true ) {
  17236. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  17237. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  17238. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  17239. }
  17240. if ( this.sheen === true ) {
  17241. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  17242. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  17243. }
  17244. if ( this.iridescence === true ) {
  17245. const dotNVi = normalView.dot( positionViewDirection ).clamp();
  17246. const iridescenceFresnelDielectric = evalIridescence( {
  17247. outsideIOR: float( 1.0 ),
  17248. eta2: iridescenceIOR,
  17249. cosTheta1: dotNVi,
  17250. thinFilmThickness: iridescenceThickness,
  17251. baseF0: specularColor
  17252. } );
  17253. const iridescenceFresnelMetallic = evalIridescence( {
  17254. outsideIOR: float( 1.0 ),
  17255. eta2: iridescenceIOR,
  17256. cosTheta1: dotNVi,
  17257. thinFilmThickness: iridescenceThickness,
  17258. baseF0: diffuseColor.rgb
  17259. } );
  17260. this.iridescenceFresnel = mix( iridescenceFresnelDielectric, iridescenceFresnelMetallic, metalness );
  17261. this.iridescenceF0Dielectric = Schlick_to_F0( { f: iridescenceFresnelDielectric, f90: 1.0, dotVH: dotNVi } );
  17262. this.iridescenceF0Metallic = Schlick_to_F0( { f: iridescenceFresnelMetallic, f90: 1.0, dotVH: dotNVi } );
  17263. this.iridescenceF0 = mix( this.iridescenceF0Dielectric, this.iridescenceF0Metallic, metalness );
  17264. }
  17265. if ( this.transmission === true ) {
  17266. const position = positionWorld;
  17267. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  17268. const n = normalWorld;
  17269. const context = builder.context;
  17270. context.backdrop = getIBLVolumeRefraction(
  17271. n,
  17272. v,
  17273. roughness,
  17274. diffuseContribution,
  17275. specularColorBlended,
  17276. specularF90, // specularF90
  17277. position, // positionWorld
  17278. modelWorldMatrix, // modelMatrix
  17279. cameraViewMatrix, // viewMatrix
  17280. cameraProjectionMatrix, // projMatrix
  17281. ior,
  17282. thickness,
  17283. attenuationColor,
  17284. attenuationDistance,
  17285. this.dispersion ? dispersion : null
  17286. );
  17287. context.backdropAlpha = transmission;
  17288. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  17289. }
  17290. super.start( builder );
  17291. }
  17292. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  17293. // Approximates multi-scattering in order to preserve energy.
  17294. // http://www.jcgt.org/published/0008/01/03/
  17295. computeMultiscattering( singleScatter, multiScatter, specularF90, f0, iridescenceF0 = null ) {
  17296. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17297. const fab = DFGLUT( { roughness, dotNV } );
  17298. const Fr = iridescenceF0 ? iridescence.mix( f0, iridescenceF0 ) : f0;
  17299. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  17300. const Ess = fab.x.add( fab.y );
  17301. const Ems = Ess.oneMinus();
  17302. const Favg = Fr.add( Fr.oneMinus().mul( 0.047619 ) ); // 1/21
  17303. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  17304. singleScatter.addAssign( FssEss );
  17305. multiScatter.addAssign( Fms.mul( Ems ) );
  17306. }
  17307. /**
  17308. * Implements the direct light.
  17309. *
  17310. * @param {Object} lightData - The light data.
  17311. * @param {NodeBuilder} builder - The current node builder.
  17312. */
  17313. direct( { lightDirection, lightColor, reflectedLight }, /* builder */ ) {
  17314. const dotNL = normalView.dot( lightDirection ).clamp();
  17315. const irradiance = dotNL.mul( lightColor ).toVar();
  17316. if ( this.sheen === true ) {
  17317. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  17318. const sheenAlbedoV = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17319. const sheenAlbedoL = IBLSheenBRDF( { normal: normalView, viewDir: lightDirection, roughness: sheenRoughness } );
  17320. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedoV.max( sheenAlbedoL ) ).oneMinus();
  17321. irradiance.mulAssign( sheenEnergyComp );
  17322. }
  17323. if ( this.clearcoat === true ) {
  17324. const dotNLcc = clearcoatNormalView.dot( lightDirection ).clamp();
  17325. const ccIrradiance = dotNLcc.mul( lightColor );
  17326. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: clearcoatNormalView } ) ) );
  17327. }
  17328. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseContribution } ) ) );
  17329. 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 } ) ) );
  17330. }
  17331. /**
  17332. * This method is intended for implementing the direct light term for
  17333. * rect area light nodes.
  17334. *
  17335. * @param {Object} input - The input data.
  17336. * @param {NodeBuilder} builder - The current node builder.
  17337. */
  17338. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 }, /* builder */ ) {
  17339. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  17340. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  17341. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  17342. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  17343. const N = normalView;
  17344. const V = positionViewDirection;
  17345. const P = positionView.toVar();
  17346. const uv = LTC_Uv( { N, V, roughness } );
  17347. const t1 = ltc_1.sample( uv ).toVar();
  17348. const t2 = ltc_2.sample( uv ).toVar();
  17349. const mInv = mat3(
  17350. vec3( t1.x, 0, t1.y ),
  17351. vec3( 0, 1, 0 ),
  17352. vec3( t1.z, 0, t1.w )
  17353. ).toVar();
  17354. // LTC Fresnel Approximation by Stephen Hill
  17355. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  17356. const fresnel = specularColorBlended.mul( t2.x ).add( specularColorBlended.oneMinus().mul( t2.y ) ).toVar();
  17357. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  17358. 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 } ) ) );
  17359. }
  17360. /**
  17361. * Implements the indirect lighting.
  17362. *
  17363. * @param {NodeBuilder} builder - The current node builder.
  17364. */
  17365. indirect( builder ) {
  17366. this.indirectDiffuse( builder );
  17367. this.indirectSpecular( builder );
  17368. this.ambientOcclusion( builder );
  17369. }
  17370. /**
  17371. * Implements the indirect diffuse term.
  17372. *
  17373. * @param {NodeBuilder} builder - The current node builder.
  17374. */
  17375. indirectDiffuse( builder ) {
  17376. const { irradiance, reflectedLight } = builder.context;
  17377. const diffuse = irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseContribution } ) ).toVar();
  17378. if ( this.sheen === true ) {
  17379. const sheenAlbedo = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17380. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedo ).oneMinus();
  17381. diffuse.mulAssign( sheenEnergyComp );
  17382. }
  17383. reflectedLight.indirectDiffuse.addAssign( diffuse );
  17384. }
  17385. /**
  17386. * Implements the indirect specular term.
  17387. *
  17388. * @param {NodeBuilder} builder - The current node builder.
  17389. */
  17390. indirectSpecular( builder ) {
  17391. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  17392. if ( this.sheen === true ) {
  17393. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  17394. sheen,
  17395. IBLSheenBRDF( {
  17396. normal: normalView,
  17397. viewDir: positionViewDirection,
  17398. roughness: sheenRoughness
  17399. } )
  17400. ) );
  17401. }
  17402. if ( this.clearcoat === true ) {
  17403. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17404. const clearcoatEnv = EnvironmentBRDF( {
  17405. dotNV: dotNVcc,
  17406. specularColor: clearcoatF0,
  17407. specularF90: clearcoatF90,
  17408. roughness: clearcoatRoughness
  17409. } );
  17410. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  17411. }
  17412. // Both indirect specular and indirect diffuse light accumulate here
  17413. // Compute multiscattering separately for dielectric and metallic, then mix
  17414. const singleScatteringDielectric = vec3().toVar( 'singleScatteringDielectric' );
  17415. const multiScatteringDielectric = vec3().toVar( 'multiScatteringDielectric' );
  17416. const singleScatteringMetallic = vec3().toVar( 'singleScatteringMetallic' );
  17417. const multiScatteringMetallic = vec3().toVar( 'multiScatteringMetallic' );
  17418. this.computeMultiscattering( singleScatteringDielectric, multiScatteringDielectric, specularF90, specularColor, this.iridescenceF0Dielectric );
  17419. this.computeMultiscattering( singleScatteringMetallic, multiScatteringMetallic, specularF90, diffuseColor.rgb, this.iridescenceF0Metallic );
  17420. // Mix based on metalness
  17421. const singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, metalness );
  17422. const multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, metalness );
  17423. // Diffuse energy conservation uses dielectric path
  17424. const totalScatteringDielectric = singleScatteringDielectric.add( multiScatteringDielectric );
  17425. const diffuse = diffuseContribution.mul( totalScatteringDielectric.oneMinus() );
  17426. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  17427. const indirectSpecular = radiance.mul( singleScattering ).add( multiScattering.mul( cosineWeightedIrradiance ) ).toVar();
  17428. const indirectDiffuse = diffuse.mul( cosineWeightedIrradiance ).toVar();
  17429. if ( this.sheen === true ) {
  17430. const sheenAlbedo = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17431. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedo ).oneMinus();
  17432. indirectSpecular.mulAssign( sheenEnergyComp );
  17433. indirectDiffuse.mulAssign( sheenEnergyComp );
  17434. }
  17435. reflectedLight.indirectSpecular.addAssign( indirectSpecular );
  17436. reflectedLight.indirectDiffuse.addAssign( indirectDiffuse );
  17437. }
  17438. /**
  17439. * Implements the ambient occlusion term.
  17440. *
  17441. * @param {NodeBuilder} builder - The current node builder.
  17442. */
  17443. ambientOcclusion( builder ) {
  17444. const { ambientOcclusion, reflectedLight } = builder.context;
  17445. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17446. const aoNV = dotNV.add( ambientOcclusion );
  17447. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  17448. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  17449. if ( this.clearcoat === true ) {
  17450. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  17451. }
  17452. if ( this.sheen === true ) {
  17453. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  17454. }
  17455. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  17456. reflectedLight.indirectSpecular.mulAssign( aoNode );
  17457. }
  17458. /**
  17459. * Used for final lighting accumulations depending on the requested features.
  17460. *
  17461. * @param {NodeBuilder} builder - The current node builder.
  17462. */
  17463. finish( { context } ) {
  17464. const { outgoingLight } = context;
  17465. if ( this.clearcoat === true ) {
  17466. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17467. const Fcc = F_Schlick( {
  17468. dotVH: dotNVcc,
  17469. f0: clearcoatF0,
  17470. f90: clearcoatF90
  17471. } );
  17472. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  17473. outgoingLight.assign( clearcoatLight );
  17474. }
  17475. if ( this.sheen === true ) {
  17476. const sheenLight = outgoingLight.add( this.sheenSpecularDirect, this.sheenSpecularIndirect.mul( 1.0 / Math.PI ) );
  17477. outgoingLight.assign( sheenLight );
  17478. }
  17479. }
  17480. }
  17481. // These defines must match with PMREMGenerator
  17482. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  17483. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  17484. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  17485. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  17486. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  17487. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  17488. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  17489. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  17490. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  17491. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  17492. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  17493. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  17494. // These shader functions convert between the UV coordinates of a single face of
  17495. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  17496. // sampling a textureCube (not generally normalized ).
  17497. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  17498. const absDirection = vec3( abs( direction ) ).toVar();
  17499. const face = float( -1 ).toVar();
  17500. If( absDirection.x.greaterThan( absDirection.z ), () => {
  17501. If( absDirection.x.greaterThan( absDirection.y ), () => {
  17502. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  17503. } ).Else( () => {
  17504. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17505. } );
  17506. } ).Else( () => {
  17507. If( absDirection.z.greaterThan( absDirection.y ), () => {
  17508. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  17509. } ).Else( () => {
  17510. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17511. } );
  17512. } );
  17513. return face;
  17514. } ).setLayout( {
  17515. name: 'getFace',
  17516. type: 'float',
  17517. inputs: [
  17518. { name: 'direction', type: 'vec3' }
  17519. ]
  17520. } );
  17521. // RH coordinate system; PMREM face-indexing convention
  17522. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  17523. const uv = vec2().toVar();
  17524. If( face.equal( 0.0 ), () => {
  17525. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  17526. } ).ElseIf( face.equal( 1.0 ), () => {
  17527. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  17528. } ).ElseIf( face.equal( 2.0 ), () => {
  17529. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  17530. } ).ElseIf( face.equal( 3.0 ), () => {
  17531. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  17532. } ).ElseIf( face.equal( 4.0 ), () => {
  17533. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  17534. } ).Else( () => {
  17535. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  17536. } );
  17537. return mul( 0.5, uv.add( 1.0 ) );
  17538. } ).setLayout( {
  17539. name: 'getUV',
  17540. type: 'vec2',
  17541. inputs: [
  17542. { name: 'direction', type: 'vec3' },
  17543. { name: 'face', type: 'float' }
  17544. ]
  17545. } );
  17546. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  17547. const mip = float( 0.0 ).toVar();
  17548. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  17549. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  17550. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  17551. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  17552. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  17553. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  17554. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  17555. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  17556. } ).Else( () => {
  17557. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  17558. } );
  17559. return mip;
  17560. } ).setLayout( {
  17561. name: 'roughnessToMip',
  17562. type: 'float',
  17563. inputs: [
  17564. { name: 'roughness', type: 'float' }
  17565. ]
  17566. } );
  17567. // RH coordinate system; PMREM face-indexing convention
  17568. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  17569. const uv = uv_immutable.toVar();
  17570. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  17571. const direction = vec3( uv, 1.0 ).toVar();
  17572. If( face.equal( 0.0 ), () => {
  17573. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  17574. } ).ElseIf( face.equal( 1.0 ), () => {
  17575. direction.assign( direction.xzy );
  17576. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  17577. } ).ElseIf( face.equal( 2.0 ), () => {
  17578. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  17579. } ).ElseIf( face.equal( 3.0 ), () => {
  17580. direction.assign( direction.zyx );
  17581. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  17582. } ).ElseIf( face.equal( 4.0 ), () => {
  17583. direction.assign( direction.xzy );
  17584. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  17585. } ).ElseIf( face.equal( 5.0 ), () => {
  17586. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  17587. } );
  17588. return direction;
  17589. } ).setLayout( {
  17590. name: 'getDirection',
  17591. type: 'vec3',
  17592. inputs: [
  17593. { name: 'uv', type: 'vec2' },
  17594. { name: 'face', type: 'float' }
  17595. ]
  17596. } );
  17597. //
  17598. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17599. const roughness = float( roughness_immutable );
  17600. const sampleDir = vec3( sampleDir_immutable );
  17601. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  17602. const mipF = fract( mip );
  17603. const mipInt = floor( mip );
  17604. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17605. If( mipF.notEqual( 0.0 ), () => {
  17606. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17607. color0.assign( mix( color0, color1, mipF ) );
  17608. } );
  17609. return color0;
  17610. } );
  17611. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17612. const mipInt = float( mipInt_immutable ).toVar();
  17613. const direction = vec3( direction_immutable );
  17614. const face = float( getFace( direction ) ).toVar();
  17615. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  17616. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  17617. const faceSize = float( exp2( mipInt ) ).toVar();
  17618. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  17619. If( face.greaterThan( 2.0 ), () => {
  17620. uv.y.addAssign( faceSize );
  17621. face.subAssign( 3.0 );
  17622. } );
  17623. uv.x.addAssign( face.mul( faceSize ) );
  17624. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  17625. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  17626. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  17627. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  17628. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  17629. } );
  17630. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17631. const cosTheta = cos( theta );
  17632. // Rodrigues' axis-angle rotation
  17633. const sampleDirection = outputDirection.mul( cosTheta )
  17634. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  17635. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  17636. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  17637. } );
  17638. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17639. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  17640. If( axis.equal( vec3( 0.0 ) ), () => {
  17641. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  17642. } );
  17643. axis.assign( normalize( axis ) );
  17644. const gl_FragColor = vec3().toVar();
  17645. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17646. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  17647. If( i.greaterThanEqual( samples ), () => {
  17648. Break();
  17649. } );
  17650. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  17651. 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 } ) ) );
  17652. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17653. } );
  17654. return vec4( gl_FragColor, 1 );
  17655. } );
  17656. // GGX VNDF importance sampling functions
  17657. // Van der Corput radical inverse for generating quasi-random sequences
  17658. const radicalInverse_VdC = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  17659. const bits = uint( bits_immutable ).toVar();
  17660. bits.assign( bits.shiftLeft( uint( 16 ) ).bitOr( bits.shiftRight( uint( 16 ) ) ) );
  17661. bits.assign( bits.bitAnd( uint( 0x55555555 ) ).shiftLeft( uint( 1 ) ).bitOr( bits.bitAnd( uint( 0xAAAAAAAA ) ).shiftRight( uint( 1 ) ) ) );
  17662. bits.assign( bits.bitAnd( uint( 0x33333333 ) ).shiftLeft( uint( 2 ) ).bitOr( bits.bitAnd( uint( 0xCCCCCCCC ) ).shiftRight( uint( 2 ) ) ) );
  17663. bits.assign( bits.bitAnd( uint( 0x0F0F0F0F ) ).shiftLeft( uint( 4 ) ).bitOr( bits.bitAnd( uint( 0xF0F0F0F0 ) ).shiftRight( uint( 4 ) ) ) );
  17664. bits.assign( bits.bitAnd( uint( 0x00FF00FF ) ).shiftLeft( uint( 8 ) ).bitOr( bits.bitAnd( uint( 0xFF00FF00 ) ).shiftRight( uint( 8 ) ) ) );
  17665. return float( bits ).mul( 2.3283064365386963e-10 ); // / 0x100000000
  17666. } );
  17667. // Hammersley sequence for quasi-Monte Carlo sampling
  17668. const hammersley = /*@__PURE__*/ Fn( ( [ i, N ] ) => {
  17669. return vec2( float( i ).div( float( N ) ), radicalInverse_VdC( i ) );
  17670. } );
  17671. // GGX VNDF importance sampling (Eric Heitz 2018)
  17672. // "Sampling the GGX Distribution of Visible Normals"
  17673. // https://jcgt.org/published/0007/04/01/
  17674. const importanceSampleGGX_VNDF = /*@__PURE__*/ Fn( ( [ Xi, V_immutable, roughness_immutable ] ) => {
  17675. const V = vec3( V_immutable ).toVar();
  17676. const roughness = float( roughness_immutable );
  17677. const alpha = roughness.mul( roughness ).toVar();
  17678. // Section 3.2: Transform view direction to hemisphere configuration
  17679. const Vh = normalize( vec3( alpha.mul( V.x ), alpha.mul( V.y ), V.z ) ).toVar();
  17680. // Section 4.1: Orthonormal basis
  17681. const lensq = Vh.x.mul( Vh.x ).add( Vh.y.mul( Vh.y ) );
  17682. const T1 = select( lensq.greaterThan( 0.0 ), vec3( Vh.y.negate(), Vh.x, 0.0 ).div( sqrt( lensq ) ), vec3( 1.0, 0.0, 0.0 ) ).toVar();
  17683. const T2 = cross( Vh, T1 ).toVar();
  17684. // Section 4.2: Parameterization of projected area
  17685. const r = sqrt( Xi.x );
  17686. const phi = mul( 2.0, 3.14159265359 ).mul( Xi.y );
  17687. const t1 = r.mul( cos( phi ) ).toVar();
  17688. const t2 = r.mul( sin( phi ) ).toVar();
  17689. const s = mul( 0.5, Vh.z.add( 1.0 ) );
  17690. t2.assign( s.oneMinus().mul( sqrt( t1.mul( t1 ).oneMinus() ) ).add( s.mul( t2 ) ) );
  17691. // Section 4.3: Reprojection onto hemisphere
  17692. const Nh = T1.mul( t1 ).add( T2.mul( t2 ) ).add( Vh.mul( sqrt( max$1( 0.0, t1.mul( t1 ).add( t2.mul( t2 ) ).oneMinus() ) ) ) );
  17693. // Section 3.4: Transform back to ellipsoid configuration
  17694. return normalize( vec3( alpha.mul( Nh.x ), alpha.mul( Nh.y ), max$1( 0.0, Nh.z ) ) );
  17695. } );
  17696. // GGX convolution using VNDF importance sampling
  17697. const ggxConvolution = /*@__PURE__*/ Fn( ( { roughness, mipInt, envMap, N_immutable, GGX_SAMPLES, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17698. const N = vec3( N_immutable ).toVar();
  17699. const prefilteredColor = vec3( 0.0 ).toVar();
  17700. const totalWeight = float( 0.0 ).toVar();
  17701. // For very low roughness, just sample the environment directly
  17702. If( roughness.lessThan( 0.001 ), () => {
  17703. prefilteredColor.assign( bilinearCubeUV( envMap, N, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) );
  17704. } ).Else( () => {
  17705. // Tangent space basis for VNDF sampling
  17706. const up = select( abs( N.z ).lessThan( 0.999 ), vec3( 0.0, 0.0, 1.0 ), vec3( 1.0, 0.0, 0.0 ) );
  17707. const tangent = normalize( cross( up, N ) ).toVar();
  17708. const bitangent = cross( N, tangent ).toVar();
  17709. Loop( { start: uint( 0 ), end: GGX_SAMPLES }, ( { i } ) => {
  17710. const Xi = hammersley( i, GGX_SAMPLES );
  17711. // For PMREM, V = N, so in tangent space V is always (0, 0, 1)
  17712. const H_tangent = importanceSampleGGX_VNDF( Xi, vec3( 0.0, 0.0, 1.0 ), roughness );
  17713. // Transform H back to world space
  17714. const H = normalize( tangent.mul( H_tangent.x ).add( bitangent.mul( H_tangent.y ) ).add( N.mul( H_tangent.z ) ) );
  17715. const L = normalize( H.mul( dot( N, H ).mul( 2.0 ) ).sub( N ) );
  17716. const NdotL = max$1( dot( N, L ), 0.0 );
  17717. If( NdotL.greaterThan( 0.0 ), () => {
  17718. // Sample environment at fixed mip level
  17719. // VNDF importance sampling handles the distribution filtering
  17720. const sampleColor = bilinearCubeUV( envMap, L, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  17721. // Weight by NdotL for the split-sum approximation
  17722. // VNDF PDF naturally accounts for the visible microfacet distribution
  17723. prefilteredColor.addAssign( sampleColor.mul( NdotL ) );
  17724. totalWeight.addAssign( NdotL );
  17725. } );
  17726. } );
  17727. If( totalWeight.greaterThan( 0.0 ), () => {
  17728. prefilteredColor.assign( prefilteredColor.div( totalWeight ) );
  17729. } );
  17730. } );
  17731. return vec4( prefilteredColor, 1.0 );
  17732. } );
  17733. const LOD_MIN = 4;
  17734. // The standard deviations (radians) associated with the extra mips.
  17735. // Used for scene blur in fromScene() method.
  17736. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  17737. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  17738. // samples and exit early, but not recompile the shader.
  17739. // Used for scene blur in fromScene() method.
  17740. const MAX_SAMPLES = 20;
  17741. // GGX VNDF importance sampling configuration
  17742. const GGX_SAMPLES = 512;
  17743. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  17744. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  17745. const _clearColor$2 = /*@__PURE__*/ new Color();
  17746. let _oldTarget = null;
  17747. let _oldActiveCubeFace = 0;
  17748. let _oldActiveMipmapLevel = 0;
  17749. const _origin = /*@__PURE__*/ new Vector3();
  17750. // maps blur materials to their uniforms dictionary
  17751. const _uniformsMap = new WeakMap();
  17752. // WebGPU Face indices
  17753. const _faceLib = [
  17754. 3, 1, 5,
  17755. 0, 4, 2
  17756. ];
  17757. const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize();
  17758. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  17759. /**
  17760. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  17761. * (PMREM) from a cubeMap environment texture. This allows different levels of
  17762. * blur to be quickly accessed based on material roughness. It is packed into a
  17763. * special CubeUV format that allows us to perform custom interpolation so that
  17764. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  17765. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  17766. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  17767. * higher roughness levels. In this way we maintain resolution to smoothly
  17768. * interpolate diffuse lighting while limiting sampling computation.
  17769. *
  17770. * The prefiltering uses GGX VNDF (Visible Normal Distribution Function)
  17771. * importance sampling based on "Sampling the GGX Distribution of Visible Normals"
  17772. * (Heitz, 2018) to generate environment maps that accurately match the GGX BRDF
  17773. * used in material rendering for physically-based image-based lighting.
  17774. */
  17775. class PMREMGenerator {
  17776. /**
  17777. * Constructs a new PMREM generator.
  17778. *
  17779. * @param {Renderer} renderer - The renderer.
  17780. */
  17781. constructor( renderer ) {
  17782. this._renderer = renderer;
  17783. this._pingPongRenderTarget = null;
  17784. this._lodMax = 0;
  17785. this._cubeSize = 0;
  17786. this._sizeLods = [];
  17787. this._sigmas = [];
  17788. this._lodMeshes = [];
  17789. this._blurMaterial = null;
  17790. this._ggxMaterial = null;
  17791. this._cubemapMaterial = null;
  17792. this._equirectMaterial = null;
  17793. this._backgroundBox = null;
  17794. }
  17795. get _hasInitialized() {
  17796. return this._renderer.hasInitialized();
  17797. }
  17798. /**
  17799. * Generates a PMREM from a supplied Scene, which can be faster than using an
  17800. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  17801. * in radians to be applied to the scene before PMREM generation. Optional near
  17802. * and far planes ensure the scene is rendered in its entirety.
  17803. *
  17804. * @param {Scene} scene - The scene to be captured.
  17805. * @param {number} [sigma=0] - The blur radius in radians.
  17806. * @param {number} [near=0.1] - The near plane distance.
  17807. * @param {number} [far=100] - The far plane distance.
  17808. * @param {Object} [options={}] - The configuration options.
  17809. * @param {number} [options.size=256] - The texture size of the PMREM.
  17810. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  17811. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17812. * @return {RenderTarget} The resulting PMREM.
  17813. * @see {@link PMREMGenerator#fromScene}
  17814. */
  17815. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17816. const {
  17817. size = 256,
  17818. position = _origin,
  17819. renderTarget = null,
  17820. } = options;
  17821. this._setSize( size );
  17822. if ( this._hasInitialized === false ) {
  17823. warn( 'PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.' );
  17824. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17825. options.renderTarget = cubeUVRenderTarget;
  17826. this.fromSceneAsync( scene, sigma, near, far, options );
  17827. return cubeUVRenderTarget;
  17828. }
  17829. _oldTarget = this._renderer.getRenderTarget();
  17830. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17831. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17832. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17833. cubeUVRenderTarget.depthBuffer = true;
  17834. this._init( cubeUVRenderTarget );
  17835. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  17836. if ( sigma > 0 ) {
  17837. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  17838. }
  17839. this._applyPMREM( cubeUVRenderTarget );
  17840. this._cleanup( cubeUVRenderTarget );
  17841. return cubeUVRenderTarget;
  17842. }
  17843. /**
  17844. * Generates a PMREM from a supplied Scene, which can be faster than using an
  17845. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  17846. * in radians to be applied to the scene before PMREM generation. Optional near
  17847. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  17848. * is placed at the origin).
  17849. *
  17850. * @deprecated
  17851. * @param {Scene} scene - The scene to be captured.
  17852. * @param {number} [sigma=0] - The blur radius in radians.
  17853. * @param {number} [near=0.1] - The near plane distance.
  17854. * @param {number} [far=100] - The far plane distance.
  17855. * @param {Object} [options={}] - The configuration options.
  17856. * @param {number} [options.size=256] - The texture size of the PMREM.
  17857. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  17858. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17859. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  17860. * @see {@link PMREMGenerator#fromScene}
  17861. */
  17862. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17863. warnOnce( 'PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  17864. await this._renderer.init();
  17865. return this.fromScene( scene, sigma, near, far, options );
  17866. }
  17867. /**
  17868. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17869. * or HDR. The ideal input image size is 1k (1024 x 512),
  17870. * as this matches best with the 256 x 256 cubemap output.
  17871. *
  17872. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17873. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17874. * @return {RenderTarget} The resulting PMREM.
  17875. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  17876. */
  17877. fromEquirectangular( equirectangular, renderTarget = null ) {
  17878. if ( this._hasInitialized === false ) {
  17879. warn( 'PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" instead.' );
  17880. this._setSizeFromTexture( equirectangular );
  17881. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17882. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  17883. return cubeUVRenderTarget;
  17884. }
  17885. return this._fromTexture( equirectangular, renderTarget );
  17886. }
  17887. /**
  17888. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17889. * or HDR. The ideal input image size is 1k (1024 x 512),
  17890. * as this matches best with the 256 x 256 cubemap output.
  17891. *
  17892. * @deprecated
  17893. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17894. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17895. * @return {Promise<RenderTarget>} The resulting PMREM.
  17896. * @see {@link PMREMGenerator#fromEquirectangular}
  17897. */
  17898. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  17899. warnOnce( 'PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  17900. await this._renderer.init();
  17901. return this._fromTexture( equirectangular, renderTarget );
  17902. }
  17903. /**
  17904. * Generates a PMREM from an cubemap texture, which can be either LDR
  17905. * or HDR. The ideal input cube size is 256 x 256,
  17906. * as this matches best with the 256 x 256 cubemap output.
  17907. *
  17908. * @param {Texture} cubemap - The cubemap texture to be converted.
  17909. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17910. * @return {RenderTarget} The resulting PMREM.
  17911. * @see {@link PMREMGenerator#fromCubemapAsync}
  17912. */
  17913. fromCubemap( cubemap, renderTarget = null ) {
  17914. if ( this._hasInitialized === false ) {
  17915. warn( 'PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  17916. this._setSizeFromTexture( cubemap );
  17917. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17918. this.fromCubemapAsync( cubemap, renderTarget );
  17919. return cubeUVRenderTarget;
  17920. }
  17921. return this._fromTexture( cubemap, renderTarget );
  17922. }
  17923. /**
  17924. * Generates a PMREM from an cubemap texture, which can be either LDR
  17925. * or HDR. The ideal input cube size is 256 x 256,
  17926. * with the 256 x 256 cubemap output.
  17927. *
  17928. * @deprecated
  17929. * @param {Texture} cubemap - The cubemap texture to be converted.
  17930. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17931. * @return {Promise<RenderTarget>} The resulting PMREM.
  17932. * @see {@link PMREMGenerator#fromCubemap}
  17933. */
  17934. async fromCubemapAsync( cubemap, renderTarget = null ) {
  17935. warnOnce( 'PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  17936. await this._renderer.init();
  17937. return this._fromTexture( cubemap, renderTarget );
  17938. }
  17939. /**
  17940. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  17941. * your texture's network fetch for increased concurrency.
  17942. *
  17943. * @returns {Promise}
  17944. */
  17945. async compileCubemapShader() {
  17946. if ( this._cubemapMaterial === null ) {
  17947. this._cubemapMaterial = _getCubemapMaterial();
  17948. await this._compileMaterial( this._cubemapMaterial );
  17949. }
  17950. }
  17951. /**
  17952. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  17953. * your texture's network fetch for increased concurrency.
  17954. *
  17955. * @returns {Promise}
  17956. */
  17957. async compileEquirectangularShader() {
  17958. if ( this._equirectMaterial === null ) {
  17959. this._equirectMaterial = _getEquirectMaterial();
  17960. await this._compileMaterial( this._equirectMaterial );
  17961. }
  17962. }
  17963. /**
  17964. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  17965. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  17966. * one of them will cause any others to also become unusable.
  17967. */
  17968. dispose() {
  17969. this._dispose();
  17970. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  17971. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  17972. if ( this._backgroundBox !== null ) {
  17973. this._backgroundBox.geometry.dispose();
  17974. this._backgroundBox.material.dispose();
  17975. }
  17976. }
  17977. // private interface
  17978. _setSizeFromTexture( texture ) {
  17979. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  17980. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  17981. } else { // Equirectangular
  17982. this._setSize( texture.image.width / 4 );
  17983. }
  17984. }
  17985. _setSize( cubeSize ) {
  17986. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  17987. this._cubeSize = Math.pow( 2, this._lodMax );
  17988. }
  17989. _dispose() {
  17990. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  17991. if ( this._ggxMaterial !== null ) this._ggxMaterial.dispose();
  17992. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  17993. for ( let i = 0; i < this._lodMeshes.length; i ++ ) {
  17994. this._lodMeshes[ i ].geometry.dispose();
  17995. }
  17996. }
  17997. _cleanup( outputTarget ) {
  17998. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  17999. outputTarget.scissorTest = false;
  18000. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  18001. }
  18002. _fromTexture( texture, renderTarget ) {
  18003. this._setSizeFromTexture( texture );
  18004. _oldTarget = this._renderer.getRenderTarget();
  18005. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  18006. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  18007. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  18008. this._init( cubeUVRenderTarget );
  18009. this._textureToCubeUV( texture, cubeUVRenderTarget );
  18010. this._applyPMREM( cubeUVRenderTarget );
  18011. this._cleanup( cubeUVRenderTarget );
  18012. return cubeUVRenderTarget;
  18013. }
  18014. _allocateTarget() {
  18015. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  18016. const height = 4 * this._cubeSize;
  18017. const cubeUVRenderTarget = _createRenderTarget( width, height );
  18018. return cubeUVRenderTarget;
  18019. }
  18020. _init( renderTarget ) {
  18021. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  18022. if ( this._pingPongRenderTarget !== null ) {
  18023. this._dispose();
  18024. }
  18025. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  18026. const { _lodMax } = this;
  18027. ( { lodMeshes: this._lodMeshes, sizeLods: this._sizeLods, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  18028. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  18029. this._ggxMaterial = _getGGXShader( _lodMax, renderTarget.width, renderTarget.height );
  18030. }
  18031. }
  18032. async _compileMaterial( material ) {
  18033. const mesh = new Mesh( new BufferGeometry(), material );
  18034. await this._renderer.compile( mesh, _flatCamera );
  18035. }
  18036. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  18037. const cubeCamera = _cubeCamera;
  18038. cubeCamera.near = near;
  18039. cubeCamera.far = far;
  18040. // px, py, pz, nx, ny, nz
  18041. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  18042. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  18043. const renderer = this._renderer;
  18044. const originalAutoClear = renderer.autoClear;
  18045. renderer.getClearColor( _clearColor$2 );
  18046. renderer.autoClear = false;
  18047. if ( this._backgroundBox === null ) {
  18048. this._backgroundBox = new Mesh(
  18049. new BoxGeometry(),
  18050. new MeshBasicMaterial( {
  18051. name: 'PMREM.Background',
  18052. side: BackSide,
  18053. depthWrite: false,
  18054. depthTest: false,
  18055. } )
  18056. );
  18057. }
  18058. const backgroundBox = this._backgroundBox;
  18059. const backgroundMaterial = backgroundBox.material;
  18060. let useSolidColor = false;
  18061. const background = scene.background;
  18062. if ( background ) {
  18063. if ( background.isColor ) {
  18064. backgroundMaterial.color.copy( background );
  18065. scene.background = null;
  18066. useSolidColor = true;
  18067. }
  18068. } else {
  18069. backgroundMaterial.color.copy( _clearColor$2 );
  18070. useSolidColor = true;
  18071. }
  18072. renderer.setRenderTarget( cubeUVRenderTarget );
  18073. renderer.clear();
  18074. if ( useSolidColor ) {
  18075. renderer.render( backgroundBox, cubeCamera );
  18076. }
  18077. for ( let i = 0; i < 6; i ++ ) {
  18078. const col = i % 3;
  18079. if ( col === 0 ) {
  18080. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18081. cubeCamera.position.set( position.x, position.y, position.z );
  18082. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  18083. } else if ( col === 1 ) {
  18084. cubeCamera.up.set( 0, 0, upSign[ i ] );
  18085. cubeCamera.position.set( position.x, position.y, position.z );
  18086. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  18087. } else {
  18088. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18089. cubeCamera.position.set( position.x, position.y, position.z );
  18090. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  18091. }
  18092. const size = this._cubeSize;
  18093. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  18094. renderer.render( scene, cubeCamera );
  18095. }
  18096. renderer.autoClear = originalAutoClear;
  18097. scene.background = background;
  18098. }
  18099. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  18100. const renderer = this._renderer;
  18101. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  18102. if ( isCubeTexture ) {
  18103. if ( this._cubemapMaterial === null ) {
  18104. this._cubemapMaterial = _getCubemapMaterial( texture );
  18105. }
  18106. } else {
  18107. if ( this._equirectMaterial === null ) {
  18108. this._equirectMaterial = _getEquirectMaterial( texture );
  18109. }
  18110. }
  18111. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  18112. material.fragmentNode.value = texture;
  18113. const mesh = this._lodMeshes[ 0 ];
  18114. mesh.material = material;
  18115. const size = this._cubeSize;
  18116. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  18117. renderer.setRenderTarget( cubeUVRenderTarget );
  18118. renderer.render( mesh, _flatCamera );
  18119. }
  18120. _applyPMREM( cubeUVRenderTarget ) {
  18121. const renderer = this._renderer;
  18122. const autoClear = renderer.autoClear;
  18123. renderer.autoClear = false;
  18124. const n = this._lodMeshes.length;
  18125. // Use GGX VNDF importance sampling
  18126. for ( let i = 1; i < n; i ++ ) {
  18127. this._applyGGXFilter( cubeUVRenderTarget, i - 1, i );
  18128. }
  18129. renderer.autoClear = autoClear;
  18130. }
  18131. /**
  18132. * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map.
  18133. * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the
  18134. * GGX BRDF for physically-based rendering. Reads from the previous LOD level and
  18135. * applies incremental roughness filtering to avoid over-blurring.
  18136. *
  18137. * @private
  18138. * @param {RenderTarget} cubeUVRenderTarget
  18139. * @param {number} lodIn - Source LOD level to read from
  18140. * @param {number} lodOut - Target LOD level to write to
  18141. */
  18142. _applyGGXFilter( cubeUVRenderTarget, lodIn, lodOut ) {
  18143. const renderer = this._renderer;
  18144. const pingPongRenderTarget = this._pingPongRenderTarget;
  18145. const ggxMaterial = this._ggxMaterial;
  18146. const ggxMesh = this._lodMeshes[ lodOut ];
  18147. ggxMesh.material = ggxMaterial;
  18148. const ggxUniforms = _uniformsMap.get( ggxMaterial );
  18149. // Calculate incremental roughness between LOD levels
  18150. const targetRoughness = lodOut / ( this._lodMeshes.length - 1 );
  18151. const sourceRoughness = lodIn / ( this._lodMeshes.length - 1 );
  18152. const incrementalRoughness = Math.sqrt( targetRoughness * targetRoughness - sourceRoughness * sourceRoughness );
  18153. // Apply blur strength mapping for better quality across the roughness range
  18154. const blurStrength = 0.0 + targetRoughness * 1.25;
  18155. const adjustedRoughness = incrementalRoughness * blurStrength;
  18156. // Calculate viewport position based on output LOD level
  18157. const { _lodMax } = this;
  18158. const outputSize = this._sizeLods[ lodOut ];
  18159. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  18160. const y = 4 * ( this._cubeSize - outputSize );
  18161. // Read from previous LOD with incremental roughness
  18162. cubeUVRenderTarget.texture.frame = ( cubeUVRenderTarget.texture.frame || 0 ) + 1;
  18163. ggxUniforms.envMap.value = cubeUVRenderTarget.texture;
  18164. ggxUniforms.roughness.value = adjustedRoughness;
  18165. ggxUniforms.mipInt.value = _lodMax - lodIn; // Sample from input LOD
  18166. _setViewport( pingPongRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  18167. renderer.setRenderTarget( pingPongRenderTarget );
  18168. renderer.render( ggxMesh, _flatCamera );
  18169. // Copy from pingPong back to cubeUV (simple direct copy)
  18170. pingPongRenderTarget.texture.frame = ( pingPongRenderTarget.texture.frame || 0 ) + 1;
  18171. ggxUniforms.envMap.value = pingPongRenderTarget.texture;
  18172. ggxUniforms.roughness.value = 0.0; // Direct copy
  18173. ggxUniforms.mipInt.value = _lodMax - lodOut; // Read from the level we just wrote
  18174. _setViewport( cubeUVRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  18175. renderer.setRenderTarget( cubeUVRenderTarget );
  18176. renderer.render( ggxMesh, _flatCamera );
  18177. }
  18178. /**
  18179. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  18180. * vertically and horizontally, but this breaks down on a cube. Here we apply
  18181. * the blur latitudinally (around the poles), and then longitudinally (towards
  18182. * the poles) to approximate the orthogonally-separable blur. It is least
  18183. * accurate at the poles, but still does a decent job.
  18184. *
  18185. * Used for initial scene blur in fromScene() method when sigma > 0.
  18186. *
  18187. * @private
  18188. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  18189. * @param {number} lodIn - The input level-of-detail.
  18190. * @param {number} lodOut - The output level-of-detail.
  18191. * @param {number} sigma - The blur radius in radians.
  18192. * @param {Vector3} [poleAxis] - The pole axis.
  18193. */
  18194. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  18195. const pingPongRenderTarget = this._pingPongRenderTarget;
  18196. this._halfBlur(
  18197. cubeUVRenderTarget,
  18198. pingPongRenderTarget,
  18199. lodIn,
  18200. lodOut,
  18201. sigma,
  18202. 'latitudinal',
  18203. poleAxis );
  18204. this._halfBlur(
  18205. pingPongRenderTarget,
  18206. cubeUVRenderTarget,
  18207. lodOut,
  18208. lodOut,
  18209. sigma,
  18210. 'longitudinal',
  18211. poleAxis );
  18212. }
  18213. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  18214. const renderer = this._renderer;
  18215. const blurMaterial = this._blurMaterial;
  18216. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  18217. error( 'blur direction must be either latitudinal or longitudinal!' );
  18218. }
  18219. // Number of standard deviations at which to cut off the discrete approximation.
  18220. const STANDARD_DEVIATIONS = 3;
  18221. const blurMesh = this._lodMeshes[ lodOut ];
  18222. blurMesh.material = blurMaterial;
  18223. const blurUniforms = _uniformsMap.get( blurMaterial );
  18224. const pixels = this._sizeLods[ lodIn ] - 1;
  18225. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  18226. const sigmaPixels = sigmaRadians / radiansPerPixel;
  18227. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  18228. if ( samples > MAX_SAMPLES ) {
  18229. warn( `sigmaRadians, ${
  18230. sigmaRadians}, is too large and will clip, as it requested ${
  18231. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  18232. }
  18233. const weights = [];
  18234. let sum = 0;
  18235. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  18236. const x = i / sigmaPixels;
  18237. const weight = Math.exp( - x * x / 2 );
  18238. weights.push( weight );
  18239. if ( i === 0 ) {
  18240. sum += weight;
  18241. } else if ( i < samples ) {
  18242. sum += 2 * weight;
  18243. }
  18244. }
  18245. for ( let i = 0; i < weights.length; i ++ ) {
  18246. weights[ i ] = weights[ i ] / sum;
  18247. }
  18248. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  18249. blurUniforms.envMap.value = targetIn.texture;
  18250. blurUniforms.samples.value = samples;
  18251. blurUniforms.weights.array = weights;
  18252. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  18253. if ( poleAxis ) {
  18254. blurUniforms.poleAxis.value = poleAxis;
  18255. }
  18256. const { _lodMax } = this;
  18257. blurUniforms.dTheta.value = radiansPerPixel;
  18258. blurUniforms.mipInt.value = _lodMax - lodIn;
  18259. const outputSize = this._sizeLods[ lodOut ];
  18260. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  18261. const y = 4 * ( this._cubeSize - outputSize );
  18262. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  18263. renderer.setRenderTarget( targetOut );
  18264. renderer.render( blurMesh, _flatCamera );
  18265. }
  18266. }
  18267. function _createPlanes( lodMax ) {
  18268. const sizeLods = [];
  18269. const sigmas = [];
  18270. const lodMeshes = [];
  18271. let lod = lodMax;
  18272. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  18273. for ( let i = 0; i < totalLods; i ++ ) {
  18274. const sizeLod = Math.pow( 2, lod );
  18275. sizeLods.push( sizeLod );
  18276. let sigma = 1.0 / sizeLod;
  18277. if ( i > lodMax - LOD_MIN ) {
  18278. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  18279. } else if ( i === 0 ) {
  18280. sigma = 0;
  18281. }
  18282. sigmas.push( sigma );
  18283. const texelSize = 1.0 / ( sizeLod - 2 );
  18284. const min = - texelSize;
  18285. const max = 1 + texelSize;
  18286. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  18287. const cubeFaces = 6;
  18288. const vertices = 6;
  18289. const positionSize = 3;
  18290. const uvSize = 2;
  18291. const faceIndexSize = 1;
  18292. const position = new Float32Array( positionSize * vertices * cubeFaces );
  18293. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  18294. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  18295. for ( let face = 0; face < cubeFaces; face ++ ) {
  18296. const x = ( face % 3 ) * 2 / 3 - 1;
  18297. const y = face > 2 ? 0 : -1;
  18298. const coordinates = [
  18299. x, y, 0,
  18300. x + 2 / 3, y, 0,
  18301. x + 2 / 3, y + 1, 0,
  18302. x, y, 0,
  18303. x + 2 / 3, y + 1, 0,
  18304. x, y + 1, 0
  18305. ];
  18306. const faceIdx = _faceLib[ face ];
  18307. position.set( coordinates, positionSize * vertices * faceIdx );
  18308. uv.set( uv1, uvSize * vertices * faceIdx );
  18309. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  18310. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  18311. }
  18312. const planes = new BufferGeometry();
  18313. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  18314. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  18315. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  18316. lodMeshes.push( new Mesh( planes, null ) );
  18317. if ( lod > LOD_MIN ) {
  18318. lod --;
  18319. }
  18320. }
  18321. return { lodMeshes, sizeLods, sigmas };
  18322. }
  18323. function _createRenderTarget( width, height ) {
  18324. const params = {
  18325. magFilter: LinearFilter,
  18326. minFilter: LinearFilter,
  18327. generateMipmaps: false,
  18328. type: HalfFloatType,
  18329. format: RGBAFormat,
  18330. colorSpace: LinearSRGBColorSpace,
  18331. //depthBuffer: false
  18332. };
  18333. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  18334. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  18335. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  18336. cubeUVRenderTarget.texture.isPMREMTexture = true;
  18337. cubeUVRenderTarget.scissorTest = true;
  18338. return cubeUVRenderTarget;
  18339. }
  18340. function _setViewport( target, x, y, width, height ) {
  18341. target.viewport.set( x, y, width, height );
  18342. target.scissor.set( x, y, width, height );
  18343. }
  18344. function _getMaterial( type ) {
  18345. const material = new NodeMaterial();
  18346. material.depthTest = false;
  18347. material.depthWrite = false;
  18348. material.blending = NoBlending;
  18349. material.name = `PMREM_${ type }`;
  18350. return material;
  18351. }
  18352. function _getBlurShader( lodMax, width, height ) {
  18353. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  18354. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  18355. const dTheta = uniform( 0 );
  18356. const n = float( MAX_SAMPLES );
  18357. const latitudinal = uniform( 0 ); // false, bool
  18358. const samples = uniform( 1 ); // int
  18359. const envMap = texture();
  18360. const mipInt = uniform( 0 ); // int
  18361. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18362. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18363. const CUBEUV_MAX_MIP = float( lodMax );
  18364. const materialUniforms = {
  18365. n,
  18366. latitudinal,
  18367. weights,
  18368. poleAxis,
  18369. outputDirection: _outputDirection,
  18370. dTheta,
  18371. samples,
  18372. envMap,
  18373. mipInt,
  18374. CUBEUV_TEXEL_WIDTH,
  18375. CUBEUV_TEXEL_HEIGHT,
  18376. CUBEUV_MAX_MIP
  18377. };
  18378. const material = _getMaterial( 'blur' );
  18379. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  18380. _uniformsMap.set( material, materialUniforms );
  18381. return material;
  18382. }
  18383. function _getGGXShader( lodMax, width, height ) {
  18384. const envMap = texture();
  18385. const roughness = uniform( 0 );
  18386. const mipInt = uniform( 0 );
  18387. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18388. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18389. const CUBEUV_MAX_MIP = float( lodMax );
  18390. const materialUniforms = {
  18391. envMap,
  18392. roughness,
  18393. mipInt,
  18394. CUBEUV_TEXEL_WIDTH,
  18395. CUBEUV_TEXEL_HEIGHT,
  18396. CUBEUV_MAX_MIP
  18397. };
  18398. const material = _getMaterial( 'ggx' );
  18399. material.fragmentNode = ggxConvolution( {
  18400. ...materialUniforms,
  18401. N_immutable: _outputDirection,
  18402. GGX_SAMPLES: uint( GGX_SAMPLES )
  18403. } );
  18404. _uniformsMap.set( material, materialUniforms );
  18405. return material;
  18406. }
  18407. function _getCubemapMaterial( envTexture ) {
  18408. const material = _getMaterial( 'cubemap' );
  18409. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  18410. return material;
  18411. }
  18412. function _getEquirectMaterial( envTexture ) {
  18413. const material = _getMaterial( 'equirect' );
  18414. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  18415. return material;
  18416. }
  18417. const _cache = new WeakMap();
  18418. /**
  18419. * Generates the cubeUV size based on the given image height.
  18420. *
  18421. * @private
  18422. * @param {number} imageHeight - The image height.
  18423. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  18424. */
  18425. function _generateCubeUVSize( imageHeight ) {
  18426. const maxMip = Math.log2( imageHeight ) - 2;
  18427. const texelHeight = 1.0 / imageHeight;
  18428. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  18429. return { texelWidth, texelHeight, maxMip };
  18430. }
  18431. /**
  18432. * Generates a PMREM from the given texture.
  18433. *
  18434. * @private
  18435. * @param {Texture} texture - The texture to create the PMREM for.
  18436. * @param {Renderer} renderer - The renderer.
  18437. * @param {PMREMGenerator} generator - The PMREM generator.
  18438. * @return {?Texture} The PMREM.
  18439. */
  18440. function _getPMREMFromTexture( texture, renderer, generator ) {
  18441. const cache = _getCache( renderer );
  18442. let cacheTexture = cache.get( texture );
  18443. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  18444. if ( pmremVersion !== texture.pmremVersion ) {
  18445. const image = texture.image;
  18446. if ( texture.isCubeTexture ) {
  18447. if ( isCubeMapReady( image ) ) {
  18448. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  18449. } else {
  18450. return null;
  18451. }
  18452. } else {
  18453. if ( isEquirectangularMapReady( image ) ) {
  18454. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  18455. } else {
  18456. return null;
  18457. }
  18458. }
  18459. cacheTexture.pmremVersion = texture.pmremVersion;
  18460. cache.set( texture, cacheTexture );
  18461. }
  18462. return cacheTexture.texture;
  18463. }
  18464. /**
  18465. * Returns a cache that stores generated PMREMs for the respective textures.
  18466. * A cache must be maintained per renderer since PMREMs are render target textures
  18467. * which can't be shared across render contexts.
  18468. *
  18469. * @private
  18470. * @param {Renderer} renderer - The renderer.
  18471. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  18472. */
  18473. function _getCache( renderer ) {
  18474. let rendererCache = _cache.get( renderer );
  18475. if ( rendererCache === undefined ) {
  18476. rendererCache = new WeakMap();
  18477. _cache.set( renderer, rendererCache );
  18478. }
  18479. return rendererCache;
  18480. }
  18481. /**
  18482. * This node represents a PMREM which is a special type of preprocessed
  18483. * environment map intended for PBR materials.
  18484. *
  18485. * ```js
  18486. * const material = new MeshStandardNodeMaterial();
  18487. * material.envNode = pmremTexture( envMap );
  18488. * ```
  18489. *
  18490. * @augments TempNode
  18491. */
  18492. class PMREMNode extends TempNode {
  18493. static get type() {
  18494. return 'PMREMNode';
  18495. }
  18496. /**
  18497. * Constructs a new function overloading node.
  18498. *
  18499. * @param {Texture} value - The input texture.
  18500. * @param {Node<vec2>} [uvNode=null] - The uv node.
  18501. * @param {Node<float>} [levelNode=null] - The level node.
  18502. */
  18503. constructor( value, uvNode = null, levelNode = null ) {
  18504. super( 'vec3' );
  18505. /**
  18506. * Reference to the input texture.
  18507. *
  18508. * @private
  18509. * @type {Texture}
  18510. */
  18511. this._value = value;
  18512. /**
  18513. * Reference to the generated PMREM.
  18514. *
  18515. * @private
  18516. * @type {Texture | null}
  18517. * @default null
  18518. */
  18519. this._pmrem = null;
  18520. /**
  18521. * The uv node.
  18522. *
  18523. * @type {Node<vec2>}
  18524. */
  18525. this.uvNode = uvNode;
  18526. /**
  18527. * The level node.
  18528. *
  18529. * @type {Node<float>}
  18530. */
  18531. this.levelNode = levelNode;
  18532. /**
  18533. * Reference to a PMREM generator.
  18534. *
  18535. * @private
  18536. * @type {?PMREMGenerator}
  18537. * @default null
  18538. */
  18539. this._generator = null;
  18540. const defaultTexture = new Texture();
  18541. defaultTexture.isRenderTargetTexture = true;
  18542. /**
  18543. * The texture node holding the generated PMREM.
  18544. *
  18545. * @private
  18546. * @type {TextureNode}
  18547. */
  18548. this._texture = texture( defaultTexture );
  18549. /**
  18550. * A uniform representing the PMREM's width.
  18551. *
  18552. * @private
  18553. * @type {UniformNode<float>}
  18554. */
  18555. this._width = uniform( 0 );
  18556. /**
  18557. * A uniform representing the PMREM's height.
  18558. *
  18559. * @private
  18560. * @type {UniformNode<float>}
  18561. */
  18562. this._height = uniform( 0 );
  18563. /**
  18564. * A uniform representing the PMREM's max Mip.
  18565. *
  18566. * @private
  18567. * @type {UniformNode<float>}
  18568. */
  18569. this._maxMip = uniform( 0 );
  18570. /**
  18571. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  18572. *
  18573. * @type {string}
  18574. * @default 'render'
  18575. */
  18576. this.updateBeforeType = NodeUpdateType.RENDER;
  18577. }
  18578. set value( value ) {
  18579. this._value = value;
  18580. this._pmrem = null;
  18581. }
  18582. /**
  18583. * The node's texture value.
  18584. *
  18585. * @type {Texture}
  18586. */
  18587. get value() {
  18588. return this._value;
  18589. }
  18590. /**
  18591. * Uses the given PMREM texture to update internal values.
  18592. *
  18593. * @param {Texture} texture - The PMREM texture.
  18594. */
  18595. updateFromTexture( texture ) {
  18596. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  18597. this._texture.value = texture;
  18598. this._width.value = cubeUVSize.texelWidth;
  18599. this._height.value = cubeUVSize.texelHeight;
  18600. this._maxMip.value = cubeUVSize.maxMip;
  18601. }
  18602. updateBefore( frame ) {
  18603. let pmrem = this._pmrem;
  18604. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  18605. const texture = this._value;
  18606. if ( pmremVersion !== texture.pmremVersion ) {
  18607. if ( texture.isPMREMTexture === true ) {
  18608. pmrem = texture;
  18609. } else {
  18610. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  18611. }
  18612. if ( pmrem !== null ) {
  18613. this._pmrem = pmrem;
  18614. this.updateFromTexture( pmrem );
  18615. }
  18616. }
  18617. }
  18618. setup( builder ) {
  18619. if ( this._generator === null ) {
  18620. this._generator = new PMREMGenerator( builder.renderer );
  18621. }
  18622. this.updateBefore( builder );
  18623. //
  18624. let uvNode = this.uvNode;
  18625. if ( uvNode === null && builder.context.getUV ) {
  18626. uvNode = builder.context.getUV( this, builder );
  18627. }
  18628. //
  18629. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  18630. //
  18631. let levelNode = this.levelNode;
  18632. if ( levelNode === null && builder.context.getTextureLevel ) {
  18633. levelNode = builder.context.getTextureLevel( this );
  18634. }
  18635. //
  18636. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  18637. }
  18638. dispose() {
  18639. super.dispose();
  18640. if ( this._generator !== null ) this._generator.dispose();
  18641. }
  18642. }
  18643. /**
  18644. * Returns `true` if the given cube map image has been fully loaded.
  18645. *
  18646. * @private
  18647. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  18648. * @return {boolean} Whether the given cube map is ready or not.
  18649. */
  18650. function isCubeMapReady( image ) {
  18651. if ( image === null || image === undefined ) return false;
  18652. let count = 0;
  18653. const length = 6;
  18654. for ( let i = 0; i < length; i ++ ) {
  18655. if ( image[ i ] !== undefined ) count ++;
  18656. }
  18657. return count === length;
  18658. }
  18659. /**
  18660. * Returns `true` if the given equirectangular image has been fully loaded.
  18661. *
  18662. * @private
  18663. * @param {(Image|Object)} image - The equirectangular image.
  18664. * @return {boolean} Whether the given cube map is ready or not.
  18665. */
  18666. function isEquirectangularMapReady( image ) {
  18667. if ( image === null || image === undefined ) return false;
  18668. return image.height > 0;
  18669. }
  18670. /**
  18671. * TSL function for creating a PMREM node.
  18672. *
  18673. * @tsl
  18674. * @function
  18675. * @param {Texture} value - The input texture.
  18676. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  18677. * @param {?Node<float>} [levelNode=null] - The level node.
  18678. * @returns {PMREMNode}
  18679. */
  18680. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  18681. const _envNodeCache = new WeakMap();
  18682. /**
  18683. * Represents a physical model for Image-based lighting (IBL). The environment
  18684. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  18685. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  18686. *
  18687. * @augments LightingNode
  18688. */
  18689. class EnvironmentNode extends LightingNode {
  18690. static get type() {
  18691. return 'EnvironmentNode';
  18692. }
  18693. /**
  18694. * Constructs a new environment node.
  18695. *
  18696. * @param {Node} [envNode=null] - A node representing the environment.
  18697. */
  18698. constructor( envNode = null ) {
  18699. super();
  18700. /**
  18701. * A node representing the environment.
  18702. *
  18703. * @type {?Node}
  18704. * @default null
  18705. */
  18706. this.envNode = envNode;
  18707. }
  18708. setup( builder ) {
  18709. const { material } = builder;
  18710. let envNode = this.envNode;
  18711. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  18712. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  18713. let cacheEnvNode = _envNodeCache.get( value );
  18714. if ( cacheEnvNode === undefined ) {
  18715. cacheEnvNode = pmremTexture( value );
  18716. _envNodeCache.set( value, cacheEnvNode );
  18717. }
  18718. envNode = cacheEnvNode;
  18719. }
  18720. //
  18721. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  18722. const radianceNormalView = useAnisotropy ? bentNormalView : normalView;
  18723. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  18724. const irradiance = envNode.context( createIrradianceContext( normalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  18725. const isolateRadiance = isolate( radiance );
  18726. const isolateIrradiance = isolate( irradiance );
  18727. //
  18728. builder.context.radiance.addAssign( isolateRadiance );
  18729. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  18730. //
  18731. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  18732. if ( clearcoatRadiance ) {
  18733. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, clearcoatNormalView ) ).mul( materialEnvIntensity );
  18734. const isolateClearcoatRadiance = isolate( clearcoatRadianceContext );
  18735. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  18736. }
  18737. }
  18738. }
  18739. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  18740. let reflectVec = null;
  18741. return {
  18742. getUV: () => {
  18743. if ( reflectVec === null ) {
  18744. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  18745. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  18746. reflectVec = pow4( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  18747. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  18748. }
  18749. return reflectVec;
  18750. },
  18751. getTextureLevel: () => {
  18752. return roughnessNode;
  18753. }
  18754. };
  18755. };
  18756. const createIrradianceContext = ( normalWorldNode ) => {
  18757. return {
  18758. getUV: () => {
  18759. return normalWorldNode;
  18760. },
  18761. getTextureLevel: () => {
  18762. return float( 1.0 );
  18763. }
  18764. };
  18765. };
  18766. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  18767. /**
  18768. * Node material version of {@link MeshStandardMaterial}.
  18769. *
  18770. * @augments NodeMaterial
  18771. */
  18772. class MeshStandardNodeMaterial extends NodeMaterial {
  18773. static get type() {
  18774. return 'MeshStandardNodeMaterial';
  18775. }
  18776. /**
  18777. * Constructs a new mesh standard node material.
  18778. *
  18779. * @param {Object} [parameters] - The configuration parameter.
  18780. */
  18781. constructor( parameters ) {
  18782. super();
  18783. /**
  18784. * This flag can be used for type testing.
  18785. *
  18786. * @type {boolean}
  18787. * @readonly
  18788. * @default true
  18789. */
  18790. this.isMeshStandardNodeMaterial = true;
  18791. /**
  18792. * Set to `true` because standard materials react on lights.
  18793. *
  18794. * @type {boolean}
  18795. * @default true
  18796. */
  18797. this.lights = true;
  18798. /**
  18799. * The emissive color of standard materials is by default inferred from the `emissive`,
  18800. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  18801. * overwrite the default and define the emissive color with a node instead.
  18802. *
  18803. * If you don't want to overwrite the emissive color but modify the existing
  18804. * value instead, use {@link materialEmissive}.
  18805. *
  18806. * @type {?Node<vec3>}
  18807. * @default null
  18808. */
  18809. this.emissiveNode = null;
  18810. /**
  18811. * The metalness of standard materials is by default inferred from the `metalness`,
  18812. * and `metalnessMap` properties. This node property allows to
  18813. * overwrite the default and define the metalness with a node instead.
  18814. *
  18815. * If you don't want to overwrite the metalness but modify the existing
  18816. * value instead, use {@link materialMetalness}.
  18817. *
  18818. * @type {?Node<float>}
  18819. * @default null
  18820. */
  18821. this.metalnessNode = null;
  18822. /**
  18823. * The roughness of standard materials is by default inferred from the `roughness`,
  18824. * and `roughnessMap` properties. This node property allows to
  18825. * overwrite the default and define the roughness with a node instead.
  18826. *
  18827. * If you don't want to overwrite the roughness but modify the existing
  18828. * value instead, use {@link materialRoughness}.
  18829. *
  18830. * @type {?Node<float>}
  18831. * @default null
  18832. */
  18833. this.roughnessNode = null;
  18834. this.setDefaultValues( _defaultValues$6 );
  18835. this.setValues( parameters );
  18836. }
  18837. /**
  18838. * Overwritten since this type of material uses {@link EnvironmentNode}
  18839. * to implement the PBR (PMREM based) environment mapping. Besides, the
  18840. * method honors `Scene.environment`.
  18841. *
  18842. * @param {NodeBuilder} builder - The current node builder.
  18843. * @return {?EnvironmentNode<vec3>} The environment node.
  18844. */
  18845. setupEnvironment( builder ) {
  18846. let envNode = super.setupEnvironment( builder );
  18847. if ( envNode === null && builder.environmentNode ) {
  18848. envNode = builder.environmentNode;
  18849. }
  18850. return envNode ? new EnvironmentNode( envNode ) : null;
  18851. }
  18852. /**
  18853. * Setups the lighting model.
  18854. *
  18855. * @return {PhysicalLightingModel} The lighting model.
  18856. */
  18857. setupLightingModel( /*builder*/ ) {
  18858. return new PhysicalLightingModel();
  18859. }
  18860. /**
  18861. * Setups the specular related node variables.
  18862. */
  18863. setupSpecular() {
  18864. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  18865. specularColor.assign( vec3( 0.04 ) );
  18866. specularColorBlended.assign( specularColorNode );
  18867. specularF90.assign( 1.0 );
  18868. }
  18869. /**
  18870. * Setups the standard specific node variables.
  18871. *
  18872. * @param {NodeBuilder} builder - The current node builder.
  18873. */
  18874. setupVariants() {
  18875. // METALNESS
  18876. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  18877. metalness.assign( metalnessNode );
  18878. // ROUGHNESS
  18879. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  18880. roughnessNode = getRoughness( { roughness: roughnessNode } );
  18881. roughness.assign( roughnessNode );
  18882. // SPECULAR COLOR
  18883. this.setupSpecular();
  18884. // DIFFUSE COLOR
  18885. diffuseContribution.assign( diffuseColor.rgb.mul( metalnessNode.oneMinus() ) );
  18886. }
  18887. copy( source ) {
  18888. this.emissiveNode = source.emissiveNode;
  18889. this.metalnessNode = source.metalnessNode;
  18890. this.roughnessNode = source.roughnessNode;
  18891. return super.copy( source );
  18892. }
  18893. }
  18894. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  18895. /**
  18896. * Node material version of {@link MeshPhysicalMaterial}.
  18897. *
  18898. * @augments MeshStandardNodeMaterial
  18899. */
  18900. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  18901. static get type() {
  18902. return 'MeshPhysicalNodeMaterial';
  18903. }
  18904. /**
  18905. * Constructs a new mesh physical node material.
  18906. *
  18907. * @param {Object} [parameters] - The configuration parameter.
  18908. */
  18909. constructor( parameters ) {
  18910. super();
  18911. /**
  18912. * This flag can be used for type testing.
  18913. *
  18914. * @type {boolean}
  18915. * @readonly
  18916. * @default true
  18917. */
  18918. this.isMeshPhysicalNodeMaterial = true;
  18919. /**
  18920. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  18921. * and `clearcoatMap` properties. This node property allows to overwrite the default
  18922. * and define the clearcoat with a node instead.
  18923. *
  18924. * If you don't want to overwrite the clearcoat but modify the existing
  18925. * value instead, use {@link materialClearcoat}.
  18926. *
  18927. * @type {?Node<float>}
  18928. * @default null
  18929. */
  18930. this.clearcoatNode = null;
  18931. /**
  18932. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  18933. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  18934. * and define the clearcoat roughness with a node instead.
  18935. *
  18936. * If you don't want to overwrite the clearcoat roughness but modify the existing
  18937. * value instead, use {@link materialClearcoatRoughness}.
  18938. *
  18939. * @type {?Node<float>}
  18940. * @default null
  18941. */
  18942. this.clearcoatRoughnessNode = null;
  18943. /**
  18944. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  18945. * property. This node property allows to overwrite the default
  18946. * and define the clearcoat normal with a node instead.
  18947. *
  18948. * If you don't want to overwrite the clearcoat normal but modify the existing
  18949. * value instead, use {@link materialClearcoatNormal}.
  18950. *
  18951. * @type {?Node<vec3>}
  18952. * @default null
  18953. */
  18954. this.clearcoatNormalNode = null;
  18955. /**
  18956. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  18957. * and `sheenColorMap` properties. This node property allows to overwrite the default
  18958. * and define the sheen with a node instead.
  18959. *
  18960. * If you don't want to overwrite the sheen but modify the existing
  18961. * value instead, use {@link materialSheen}.
  18962. *
  18963. * @type {?Node<vec3>}
  18964. * @default null
  18965. */
  18966. this.sheenNode = null;
  18967. /**
  18968. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  18969. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  18970. * and define the sheen roughness with a node instead.
  18971. *
  18972. * If you don't want to overwrite the sheen roughness but modify the existing
  18973. * value instead, use {@link materialSheenRoughness}.
  18974. *
  18975. * @type {?Node<float>}
  18976. * @default null
  18977. */
  18978. this.sheenRoughnessNode = null;
  18979. /**
  18980. * The iridescence of physical materials is by default inferred from the `iridescence`
  18981. * property. This node property allows to overwrite the default
  18982. * and define the iridescence with a node instead.
  18983. *
  18984. * If you don't want to overwrite the iridescence but modify the existing
  18985. * value instead, use {@link materialIridescence}.
  18986. *
  18987. * @type {?Node<float>}
  18988. * @default null
  18989. */
  18990. this.iridescenceNode = null;
  18991. /**
  18992. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  18993. * property. This node property allows to overwrite the default
  18994. * and define the iridescence IOR with a node instead.
  18995. *
  18996. * If you don't want to overwrite the iridescence IOR but modify the existing
  18997. * value instead, use {@link materialIridescenceIOR}.
  18998. *
  18999. * @type {?Node<float>}
  19000. * @default null
  19001. */
  19002. this.iridescenceIORNode = null;
  19003. /**
  19004. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  19005. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  19006. * and define the iridescence thickness with a node instead.
  19007. *
  19008. * If you don't want to overwrite the iridescence thickness but modify the existing
  19009. * value instead, use {@link materialIridescenceThickness}.
  19010. *
  19011. * @type {?Node<float>}
  19012. * @default null
  19013. */
  19014. this.iridescenceThicknessNode = null;
  19015. /**
  19016. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  19017. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  19018. * and define the specular intensity with a node instead.
  19019. *
  19020. * If you don't want to overwrite the specular intensity but modify the existing
  19021. * value instead, use {@link materialSpecularIntensity}.
  19022. *
  19023. * @type {?Node<float>}
  19024. * @default null
  19025. */
  19026. this.specularIntensityNode = null;
  19027. /**
  19028. * The specular color of physical materials is by default inferred from the `specularColor`
  19029. * and `specularColorMap` properties. This node property allows to overwrite the default
  19030. * and define the specular color with a node instead.
  19031. *
  19032. * If you don't want to overwrite the specular color but modify the existing
  19033. * value instead, use {@link materialSpecularColor}.
  19034. *
  19035. * @type {?Node<vec3>}
  19036. * @default null
  19037. */
  19038. this.specularColorNode = null;
  19039. /**
  19040. * The ior of physical materials is by default inferred from the `ior`
  19041. * property. This node property allows to overwrite the default
  19042. * and define the ior with a node instead.
  19043. *
  19044. * If you don't want to overwrite the ior but modify the existing
  19045. * value instead, use {@link materialIOR}.
  19046. *
  19047. * @type {?Node<float>}
  19048. * @default null
  19049. */
  19050. this.iorNode = null;
  19051. /**
  19052. * The transmission of physical materials is by default inferred from the `transmission` and
  19053. * `transmissionMap` properties. This node property allows to overwrite the default
  19054. * and define the transmission with a node instead.
  19055. *
  19056. * If you don't want to overwrite the transmission but modify the existing
  19057. * value instead, use {@link materialTransmission}.
  19058. *
  19059. * @type {?Node<float>}
  19060. * @default null
  19061. */
  19062. this.transmissionNode = null;
  19063. /**
  19064. * The thickness of physical materials is by default inferred from the `thickness` and
  19065. * `thicknessMap` properties. This node property allows to overwrite the default
  19066. * and define the thickness with a node instead.
  19067. *
  19068. * If you don't want to overwrite the thickness but modify the existing
  19069. * value instead, use {@link materialThickness}.
  19070. *
  19071. * @type {?Node<float>}
  19072. * @default null
  19073. */
  19074. this.thicknessNode = null;
  19075. /**
  19076. * The attenuation distance of physical materials is by default inferred from the
  19077. * `attenuationDistance` property. This node property allows to overwrite the default
  19078. * and define the attenuation distance with a node instead.
  19079. *
  19080. * If you don't want to overwrite the attenuation distance but modify the existing
  19081. * value instead, use {@link materialAttenuationDistance}.
  19082. *
  19083. * @type {?Node<float>}
  19084. * @default null
  19085. */
  19086. this.attenuationDistanceNode = null;
  19087. /**
  19088. * The attenuation color of physical materials is by default inferred from the
  19089. * `attenuationColor` property. This node property allows to overwrite the default
  19090. * and define the attenuation color with a node instead.
  19091. *
  19092. * If you don't want to overwrite the attenuation color but modify the existing
  19093. * value instead, use {@link materialAttenuationColor}.
  19094. *
  19095. * @type {?Node<vec3>}
  19096. * @default null
  19097. */
  19098. this.attenuationColorNode = null;
  19099. /**
  19100. * The dispersion of physical materials is by default inferred from the
  19101. * `dispersion` property. This node property allows to overwrite the default
  19102. * and define the dispersion with a node instead.
  19103. *
  19104. * If you don't want to overwrite the dispersion but modify the existing
  19105. * value instead, use {@link materialDispersion}.
  19106. *
  19107. * @type {?Node<float>}
  19108. * @default null
  19109. */
  19110. this.dispersionNode = null;
  19111. /**
  19112. * The anisotropy of physical materials is by default inferred from the
  19113. * `anisotropy` property. This node property allows to overwrite the default
  19114. * and define the anisotropy with a node instead.
  19115. *
  19116. * If you don't want to overwrite the anisotropy but modify the existing
  19117. * value instead, use {@link materialAnisotropy}.
  19118. *
  19119. * @type {?Node<float>}
  19120. * @default null
  19121. */
  19122. this.anisotropyNode = null;
  19123. this.setDefaultValues( _defaultValues$5 );
  19124. this.setValues( parameters );
  19125. }
  19126. /**
  19127. * Whether the lighting model should use clearcoat or not.
  19128. *
  19129. * @type {boolean}
  19130. * @default true
  19131. */
  19132. get useClearcoat() {
  19133. return this.clearcoat > 0 || this.clearcoatNode !== null;
  19134. }
  19135. /**
  19136. * Whether the lighting model should use iridescence or not.
  19137. *
  19138. * @type {boolean}
  19139. * @default true
  19140. */
  19141. get useIridescence() {
  19142. return this.iridescence > 0 || this.iridescenceNode !== null;
  19143. }
  19144. /**
  19145. * Whether the lighting model should use sheen or not.
  19146. *
  19147. * @type {boolean}
  19148. * @default true
  19149. */
  19150. get useSheen() {
  19151. return this.sheen > 0 || this.sheenNode !== null;
  19152. }
  19153. /**
  19154. * Whether the lighting model should use anisotropy or not.
  19155. *
  19156. * @type {boolean}
  19157. * @default true
  19158. */
  19159. get useAnisotropy() {
  19160. return this.anisotropy > 0 || this.anisotropyNode !== null;
  19161. }
  19162. /**
  19163. * Whether the lighting model should use transmission or not.
  19164. *
  19165. * @type {boolean}
  19166. * @default true
  19167. */
  19168. get useTransmission() {
  19169. return this.transmission > 0 || this.transmissionNode !== null;
  19170. }
  19171. /**
  19172. * Whether the lighting model should use dispersion or not.
  19173. *
  19174. * @type {boolean}
  19175. * @default true
  19176. */
  19177. get useDispersion() {
  19178. return this.dispersion > 0 || this.dispersionNode !== null;
  19179. }
  19180. /**
  19181. * Setups the specular related node variables.
  19182. */
  19183. setupSpecular() {
  19184. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  19185. ior.assign( iorNode );
  19186. specularColor.assign( min$1( pow2( ior.sub( 1.0 ).div( ior.add( 1.0 ) ) ).mul( materialSpecularColor ), vec3( 1.0 ) ).mul( materialSpecularIntensity ) );
  19187. specularColorBlended.assign( mix( specularColor, diffuseColor.rgb, metalness ) );
  19188. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  19189. }
  19190. /**
  19191. * Setups the lighting model.
  19192. *
  19193. * @return {PhysicalLightingModel} The lighting model.
  19194. */
  19195. setupLightingModel( /*builder*/ ) {
  19196. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  19197. }
  19198. /**
  19199. * Setups the physical specific node variables.
  19200. *
  19201. * @param {NodeBuilder} builder - The current node builder.
  19202. */
  19203. setupVariants( builder ) {
  19204. super.setupVariants( builder );
  19205. // CLEARCOAT
  19206. if ( this.useClearcoat ) {
  19207. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  19208. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  19209. clearcoat.assign( clearcoatNode );
  19210. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  19211. }
  19212. // SHEEN
  19213. if ( this.useSheen ) {
  19214. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  19215. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  19216. sheen.assign( sheenNode );
  19217. sheenRoughness.assign( sheenRoughnessNode );
  19218. }
  19219. // IRIDESCENCE
  19220. if ( this.useIridescence ) {
  19221. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  19222. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  19223. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  19224. iridescence.assign( iridescenceNode );
  19225. iridescenceIOR.assign( iridescenceIORNode );
  19226. iridescenceThickness.assign( iridescenceThicknessNode );
  19227. }
  19228. // ANISOTROPY
  19229. if ( this.useAnisotropy ) {
  19230. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  19231. anisotropy.assign( anisotropyV.length() );
  19232. If( anisotropy.equal( 0.0 ), () => {
  19233. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  19234. } ).Else( () => {
  19235. anisotropyV.divAssign( vec2( anisotropy ) );
  19236. anisotropy.assign( anisotropy.saturate() );
  19237. } );
  19238. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  19239. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  19240. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  19241. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  19242. }
  19243. // TRANSMISSION
  19244. if ( this.useTransmission ) {
  19245. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  19246. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  19247. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  19248. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  19249. transmission.assign( transmissionNode );
  19250. thickness.assign( thicknessNode );
  19251. attenuationDistance.assign( attenuationDistanceNode );
  19252. attenuationColor.assign( attenuationColorNode );
  19253. if ( this.useDispersion ) {
  19254. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  19255. dispersion.assign( dispersionNode );
  19256. }
  19257. }
  19258. }
  19259. /**
  19260. * Setups the clearcoat normal node.
  19261. *
  19262. * @return {Node<vec3>} The clearcoat normal.
  19263. */
  19264. setupClearcoatNormal() {
  19265. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  19266. }
  19267. setup( builder ) {
  19268. builder.context.setupClearcoatNormal = () => subBuild( this.setupClearcoatNormal( builder ), 'NORMAL', 'vec3' );
  19269. super.setup( builder );
  19270. }
  19271. copy( source ) {
  19272. this.clearcoatNode = source.clearcoatNode;
  19273. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  19274. this.clearcoatNormalNode = source.clearcoatNormalNode;
  19275. this.sheenNode = source.sheenNode;
  19276. this.sheenRoughnessNode = source.sheenRoughnessNode;
  19277. this.iridescenceNode = source.iridescenceNode;
  19278. this.iridescenceIORNode = source.iridescenceIORNode;
  19279. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  19280. this.specularIntensityNode = source.specularIntensityNode;
  19281. this.specularColorNode = source.specularColorNode;
  19282. this.transmissionNode = source.transmissionNode;
  19283. this.thicknessNode = source.thicknessNode;
  19284. this.attenuationDistanceNode = source.attenuationDistanceNode;
  19285. this.attenuationColorNode = source.attenuationColorNode;
  19286. this.dispersionNode = source.dispersionNode;
  19287. this.anisotropyNode = source.anisotropyNode;
  19288. return super.copy( source );
  19289. }
  19290. }
  19291. /**
  19292. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  19293. *
  19294. * @augments PhysicalLightingModel
  19295. */
  19296. class SSSLightingModel extends PhysicalLightingModel {
  19297. /**
  19298. * Constructs a new physical lighting model.
  19299. *
  19300. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  19301. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  19302. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  19303. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  19304. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  19305. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  19306. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  19307. */
  19308. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  19309. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  19310. /**
  19311. * Whether the lighting model should use SSS or not.
  19312. *
  19313. * @type {boolean}
  19314. * @default false
  19315. */
  19316. this.useSSS = sss;
  19317. }
  19318. /**
  19319. * Extends the default implementation with a SSS term.
  19320. *
  19321. * 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/)
  19322. *
  19323. * @param {Object} input - The input data.
  19324. * @param {NodeBuilder} builder - The current node builder.
  19325. */
  19326. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  19327. if ( this.useSSS === true ) {
  19328. const material = builder.material;
  19329. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  19330. const scatteringHalf = lightDirection.add( normalView.mul( thicknessDistortionNode ) ).normalize();
  19331. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  19332. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  19333. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  19334. }
  19335. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  19336. }
  19337. }
  19338. /**
  19339. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  19340. * that implements a Subsurface scattering (SSS) term.
  19341. *
  19342. * @augments MeshPhysicalNodeMaterial
  19343. */
  19344. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  19345. static get type() {
  19346. return 'MeshSSSNodeMaterial';
  19347. }
  19348. /**
  19349. * Constructs a new mesh SSS node material.
  19350. *
  19351. * @param {Object} [parameters] - The configuration parameter.
  19352. */
  19353. constructor( parameters ) {
  19354. super( parameters );
  19355. /**
  19356. * Represents the thickness color.
  19357. *
  19358. * @type {?Node<vec3>}
  19359. * @default null
  19360. */
  19361. this.thicknessColorNode = null;
  19362. /**
  19363. * Represents the distortion factor.
  19364. *
  19365. * @type {?Node<float>}
  19366. */
  19367. this.thicknessDistortionNode = float( 0.1 );
  19368. /**
  19369. * Represents the thickness ambient factor.
  19370. *
  19371. * @type {?Node<float>}
  19372. */
  19373. this.thicknessAmbientNode = float( 0.0 );
  19374. /**
  19375. * Represents the thickness attenuation.
  19376. *
  19377. * @type {?Node<float>}
  19378. */
  19379. this.thicknessAttenuationNode = float( .1 );
  19380. /**
  19381. * Represents the thickness power.
  19382. *
  19383. * @type {?Node<float>}
  19384. */
  19385. this.thicknessPowerNode = float( 2.0 );
  19386. /**
  19387. * Represents the thickness scale.
  19388. *
  19389. * @type {?Node<float>}
  19390. */
  19391. this.thicknessScaleNode = float( 10.0 );
  19392. }
  19393. /**
  19394. * Whether the lighting model should use SSS or not.
  19395. *
  19396. * @type {boolean}
  19397. * @default true
  19398. */
  19399. get useSSS() {
  19400. return this.thicknessColorNode !== null;
  19401. }
  19402. /**
  19403. * Setups the lighting model.
  19404. *
  19405. * @return {SSSLightingModel} The lighting model.
  19406. */
  19407. setupLightingModel( /*builder*/ ) {
  19408. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  19409. }
  19410. copy( source ) {
  19411. this.thicknessColorNode = source.thicknessColorNode;
  19412. this.thicknessDistortionNode = source.thicknessDistortionNode;
  19413. this.thicknessAmbientNode = source.thicknessAmbientNode;
  19414. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  19415. this.thicknessPowerNode = source.thicknessPowerNode;
  19416. this.thicknessScaleNode = source.thicknessScaleNode;
  19417. return super.copy( source );
  19418. }
  19419. }
  19420. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  19421. // dotNL will be from -1.0 to 1.0
  19422. const dotNL = normal.dot( lightDirection );
  19423. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  19424. if ( builder.material.gradientMap ) {
  19425. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  19426. return vec3( gradientMap.r );
  19427. } else {
  19428. const fw = coord.fwidth().mul( 0.5 );
  19429. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  19430. }
  19431. } );
  19432. /**
  19433. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  19434. *
  19435. * @augments LightingModel
  19436. */
  19437. class ToonLightingModel extends LightingModel {
  19438. /**
  19439. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  19440. * reduced to a small number of discrete shades to create a comic-like, flat look.
  19441. *
  19442. * @param {Object} lightData - The light data.
  19443. * @param {NodeBuilder} builder - The current node builder.
  19444. */
  19445. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  19446. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  19447. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  19448. }
  19449. /**
  19450. * Implements the indirect lighting.
  19451. *
  19452. * @param {NodeBuilder} builder - The current node builder.
  19453. */
  19454. indirect( builder ) {
  19455. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  19456. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  19457. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  19458. }
  19459. }
  19460. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  19461. /**
  19462. * Node material version of {@link MeshToonMaterial}.
  19463. *
  19464. * @augments NodeMaterial
  19465. */
  19466. class MeshToonNodeMaterial extends NodeMaterial {
  19467. static get type() {
  19468. return 'MeshToonNodeMaterial';
  19469. }
  19470. /**
  19471. * Constructs a new mesh toon node material.
  19472. *
  19473. * @param {Object} [parameters] - The configuration parameter.
  19474. */
  19475. constructor( parameters ) {
  19476. super();
  19477. /**
  19478. * This flag can be used for type testing.
  19479. *
  19480. * @type {boolean}
  19481. * @readonly
  19482. * @default true
  19483. */
  19484. this.isMeshToonNodeMaterial = true;
  19485. /**
  19486. * Set to `true` because toon materials react on lights.
  19487. *
  19488. * @type {boolean}
  19489. * @default true
  19490. */
  19491. this.lights = true;
  19492. this.setDefaultValues( _defaultValues$4 );
  19493. this.setValues( parameters );
  19494. }
  19495. /**
  19496. * Setups the lighting model.
  19497. *
  19498. * @return {ToonLightingModel} The lighting model.
  19499. */
  19500. setupLightingModel( /*builder*/ ) {
  19501. return new ToonLightingModel();
  19502. }
  19503. }
  19504. /**
  19505. * TSL function for creating a matcap uv node.
  19506. *
  19507. * Can be used to compute texture coordinates for projecting a
  19508. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  19509. *
  19510. * @tsl
  19511. * @function
  19512. * @returns {Node<vec2>} The matcap UV coordinates.
  19513. */
  19514. const matcapUV = /*@__PURE__*/ Fn( () => {
  19515. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  19516. const y = positionViewDirection.cross( x );
  19517. return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  19518. } ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' );
  19519. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  19520. /**
  19521. * Node material version of {@link MeshMatcapMaterial}.
  19522. *
  19523. * @augments NodeMaterial
  19524. */
  19525. class MeshMatcapNodeMaterial extends NodeMaterial {
  19526. static get type() {
  19527. return 'MeshMatcapNodeMaterial';
  19528. }
  19529. /**
  19530. * Constructs a new mesh normal node material.
  19531. *
  19532. * @param {Object} [parameters] - The configuration parameter.
  19533. */
  19534. constructor( parameters ) {
  19535. super();
  19536. /**
  19537. * This flag can be used for type testing.
  19538. *
  19539. * @type {boolean}
  19540. * @readonly
  19541. * @default true
  19542. */
  19543. this.isMeshMatcapNodeMaterial = true;
  19544. this.setDefaultValues( _defaultValues$3 );
  19545. this.setValues( parameters );
  19546. }
  19547. /**
  19548. * Setups the matcap specific node variables.
  19549. *
  19550. * @param {NodeBuilder} builder - The current node builder.
  19551. */
  19552. setupVariants( builder ) {
  19553. const uv = matcapUV;
  19554. let matcapColor;
  19555. if ( builder.material.matcap ) {
  19556. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  19557. } else {
  19558. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  19559. }
  19560. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  19561. }
  19562. }
  19563. /**
  19564. * Applies a rotation to the given position node.
  19565. *
  19566. * @augments TempNode
  19567. */
  19568. class RotateNode extends TempNode {
  19569. static get type() {
  19570. return 'RotateNode';
  19571. }
  19572. /**
  19573. * Constructs a new rotate node.
  19574. *
  19575. * @param {Node} positionNode - The position node.
  19576. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  19577. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19578. */
  19579. constructor( positionNode, rotationNode ) {
  19580. super();
  19581. /**
  19582. * The position node.
  19583. *
  19584. * @type {Node}
  19585. */
  19586. this.positionNode = positionNode;
  19587. /**
  19588. * Represents the rotation that is applied to the position node.
  19589. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19590. *
  19591. * @type {Node}
  19592. */
  19593. this.rotationNode = rotationNode;
  19594. }
  19595. /**
  19596. * The type of the {@link RotateNode#positionNode} defines the node's type.
  19597. *
  19598. * @param {NodeBuilder} builder - The current node builder.
  19599. * @return {string} The node's type.
  19600. */
  19601. getNodeType( builder ) {
  19602. return this.positionNode.getNodeType( builder );
  19603. }
  19604. setup( builder ) {
  19605. const { rotationNode, positionNode } = this;
  19606. const nodeType = this.getNodeType( builder );
  19607. if ( nodeType === 'vec2' ) {
  19608. const cosAngle = rotationNode.cos();
  19609. const sinAngle = rotationNode.sin();
  19610. const rotationMatrix = mat2(
  19611. cosAngle, sinAngle,
  19612. sinAngle.negate(), cosAngle
  19613. );
  19614. return rotationMatrix.mul( positionNode );
  19615. } else {
  19616. const rotation = rotationNode;
  19617. 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 ) );
  19618. 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 ) );
  19619. 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 ) );
  19620. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  19621. }
  19622. }
  19623. }
  19624. /**
  19625. * TSL function for creating a rotate node.
  19626. *
  19627. * @tsl
  19628. * @function
  19629. * @param {Node} positionNode - The position node.
  19630. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  19631. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19632. * @returns {RotateNode}
  19633. */
  19634. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  19635. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  19636. /**
  19637. * Node material version of {@link SpriteMaterial}.
  19638. *
  19639. * @augments NodeMaterial
  19640. */
  19641. class SpriteNodeMaterial extends NodeMaterial {
  19642. static get type() {
  19643. return 'SpriteNodeMaterial';
  19644. }
  19645. /**
  19646. * Constructs a new sprite node material.
  19647. *
  19648. * @param {Object} [parameters] - The configuration parameter.
  19649. */
  19650. constructor( parameters ) {
  19651. super();
  19652. /**
  19653. * This flag can be used for type testing.
  19654. *
  19655. * @type {boolean}
  19656. * @readonly
  19657. * @default true
  19658. */
  19659. this.isSpriteNodeMaterial = true;
  19660. this._useSizeAttenuation = true;
  19661. /**
  19662. * This property makes it possible to define the position of the sprite with a
  19663. * node. That can be useful when the material is used with instanced rendering
  19664. * and node data are defined with an instanced attribute node:
  19665. * ```js
  19666. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  19667. * material.positionNode = instancedBufferAttribute( positionAttribute );
  19668. * ```
  19669. * Another possibility is to compute the instanced data with a compute shader:
  19670. * ```js
  19671. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  19672. * particleMaterial.positionNode = positionBuffer.toAttribute();
  19673. * ```
  19674. *
  19675. * @type {?Node<vec2>}
  19676. * @default null
  19677. */
  19678. this.positionNode = null;
  19679. /**
  19680. * The rotation of sprite materials is by default inferred from the `rotation`,
  19681. * property. This node property allows to overwrite the default and define
  19682. * the rotation with a node instead.
  19683. *
  19684. * If you don't want to overwrite the rotation but modify the existing
  19685. * value instead, use {@link materialRotation}.
  19686. *
  19687. * @type {?Node<float>}
  19688. * @default null
  19689. */
  19690. this.rotationNode = null;
  19691. /**
  19692. * This node property provides an additional way to scale sprites next to
  19693. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  19694. * is multiplied with the scale value of this node in the vertex shader.
  19695. *
  19696. * @type {?Node<vec2>}
  19697. * @default null
  19698. */
  19699. this.scaleNode = null;
  19700. /**
  19701. * In Sprites, the transparent property is enabled by default.
  19702. *
  19703. * @type {boolean}
  19704. * @default true
  19705. */
  19706. this.transparent = true;
  19707. this.setDefaultValues( _defaultValues$2 );
  19708. this.setValues( parameters );
  19709. }
  19710. /**
  19711. * Setups the position node in view space. This method implements
  19712. * the sprite specific vertex shader.
  19713. *
  19714. * @param {NodeBuilder} builder - The current node builder.
  19715. * @return {Node<vec3>} The position in view space.
  19716. */
  19717. setupPositionView( builder ) {
  19718. const { object, camera } = builder;
  19719. const { positionNode, rotationNode, scaleNode, sizeAttenuation } = this;
  19720. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  19721. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  19722. if ( scaleNode !== null ) {
  19723. scale = scale.mul( vec2( scaleNode ) );
  19724. }
  19725. if ( camera.isPerspectiveCamera && sizeAttenuation === false ) {
  19726. scale = scale.mul( mvPosition.z.negate() );
  19727. }
  19728. let alignedPosition = positionGeometry.xy;
  19729. if ( object.center && object.center.isVector2 === true ) {
  19730. const center = reference$1( 'center', 'vec2', object );
  19731. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  19732. }
  19733. alignedPosition = alignedPosition.mul( scale );
  19734. const rotation = float( rotationNode || materialRotation );
  19735. const rotatedPosition = rotate( alignedPosition, rotation );
  19736. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  19737. }
  19738. copy( source ) {
  19739. this.positionNode = source.positionNode;
  19740. this.rotationNode = source.rotationNode;
  19741. this.scaleNode = source.scaleNode;
  19742. return super.copy( source );
  19743. }
  19744. /**
  19745. * Whether to use size attenuation or not.
  19746. *
  19747. * @type {boolean}
  19748. * @default true
  19749. */
  19750. get sizeAttenuation() {
  19751. return this._useSizeAttenuation;
  19752. }
  19753. set sizeAttenuation( value ) {
  19754. if ( this._useSizeAttenuation !== value ) {
  19755. this._useSizeAttenuation = value;
  19756. this.needsUpdate = true;
  19757. }
  19758. }
  19759. }
  19760. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  19761. const _size$4 = /*@__PURE__*/ new Vector2();
  19762. /**
  19763. * Node material version of {@link PointsMaterial}.
  19764. *
  19765. * This material can be used in two ways:
  19766. *
  19767. * - By rendering point primitives with {@link Points}. Since WebGPU only supports point primitives
  19768. * with a pixel size of `1`, it's not possible to define a size.
  19769. *
  19770. * ```js
  19771. * const pointCloud = new THREE.Points( geometry, new THREE.PointsNodeMaterial() );
  19772. * ```
  19773. *
  19774. * - By rendering point primitives with {@link Sprites}. In this case, size is honored,
  19775. * see {@link PointsNodeMaterial#sizeNode}.
  19776. *
  19777. * ```js
  19778. * const instancedPoints = new THREE.Sprite( new THREE.PointsNodeMaterial( { positionNode: instancedBufferAttribute( positionAttribute ) } ) );
  19779. * ```
  19780. *
  19781. * @augments SpriteNodeMaterial
  19782. */
  19783. class PointsNodeMaterial extends SpriteNodeMaterial {
  19784. static get type() {
  19785. return 'PointsNodeMaterial';
  19786. }
  19787. /**
  19788. * Constructs a new points node material.
  19789. *
  19790. * @param {Object} [parameters] - The configuration parameter.
  19791. */
  19792. constructor( parameters ) {
  19793. super();
  19794. /**
  19795. * This node property provides an additional way to set the point size.
  19796. *
  19797. * Note that WebGPU only supports point primitives with 1 pixel size. Consequently,
  19798. * this node has no effect when the material is used with {@link Points} and a WebGPU
  19799. * backend. If an application wants to render points with a size larger than 1 pixel,
  19800. * the material should be used with {@link Sprite} and instancing.
  19801. *
  19802. * @type {?Node<vec2>}
  19803. * @default null
  19804. */
  19805. this.sizeNode = null;
  19806. /**
  19807. * This flag can be used for type testing.
  19808. *
  19809. * @type {boolean}
  19810. * @readonly
  19811. * @default true
  19812. */
  19813. this.isPointsNodeMaterial = true;
  19814. this.setDefaultValues( _defaultValues$1 );
  19815. this.setValues( parameters );
  19816. }
  19817. setupPositionView() {
  19818. const { positionNode } = this;
  19819. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  19820. }
  19821. setupVertexSprite( builder ) {
  19822. const { material, camera } = builder;
  19823. const { rotationNode, scaleNode, sizeNode, sizeAttenuation } = this;
  19824. let mvp = super.setupVertex( builder );
  19825. // skip further processing if the material is not a node material
  19826. if ( material.isNodeMaterial !== true ) {
  19827. return mvp;
  19828. }
  19829. // point size
  19830. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  19831. pointSize = pointSize.mul( screenDPR );
  19832. // size attenuation
  19833. if ( camera.isPerspectiveCamera && sizeAttenuation === true ) {
  19834. // follow WebGLRenderer's implementation, and scale by half the canvas height in logical units
  19835. pointSize = pointSize.mul( scale.div( positionView.z.negate() ) );
  19836. }
  19837. // scale
  19838. if ( scaleNode && scaleNode.isNode ) {
  19839. pointSize = pointSize.mul( vec2( scaleNode ) );
  19840. }
  19841. // compute offset
  19842. let offset = positionGeometry.xy;
  19843. // apply rotation
  19844. if ( rotationNode && rotationNode.isNode ) {
  19845. const rotation = float( rotationNode );
  19846. offset = rotate( offset, rotation );
  19847. }
  19848. // account for point size
  19849. offset = offset.mul( pointSize );
  19850. // scale by viewport size
  19851. offset = offset.div( viewportSize.div( 2 ) );
  19852. // compensate for the perspective divide
  19853. offset = offset.mul( mvp.w );
  19854. // add offset
  19855. mvp = mvp.add( vec4( offset, 0, 0 ) );
  19856. return mvp;
  19857. }
  19858. setupVertex( builder ) {
  19859. if ( builder.object.isPoints ) {
  19860. return super.setupVertex( builder );
  19861. } else {
  19862. return this.setupVertexSprite( builder );
  19863. }
  19864. }
  19865. /**
  19866. * Whether alpha to coverage should be used or not.
  19867. *
  19868. * @type {boolean}
  19869. * @default true
  19870. */
  19871. get alphaToCoverage() {
  19872. return this._useAlphaToCoverage;
  19873. }
  19874. set alphaToCoverage( value ) {
  19875. if ( this._useAlphaToCoverage !== value ) {
  19876. this._useAlphaToCoverage = value;
  19877. this.needsUpdate = true;
  19878. }
  19879. }
  19880. }
  19881. const scale = /*@__PURE__*/ uniform( 1 ).onFrameUpdate( function ( { renderer } ) {
  19882. const size = renderer.getSize( _size$4 ); // logical units
  19883. this.value = 0.5 * size.y;
  19884. } );
  19885. /**
  19886. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  19887. *
  19888. * @augments LightingModel
  19889. */
  19890. class ShadowMaskModel extends LightingModel {
  19891. /**
  19892. * Constructs a new shadow mask model.
  19893. */
  19894. constructor() {
  19895. super();
  19896. /**
  19897. * The shadow mask node.
  19898. *
  19899. * @type {Node}
  19900. */
  19901. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  19902. }
  19903. /**
  19904. * Only used to save the shadow mask.
  19905. *
  19906. * @param {Object} input - The input data.
  19907. */
  19908. direct( { lightNode } ) {
  19909. if ( lightNode.shadowNode !== null ) {
  19910. this.shadowNode.mulAssign( lightNode.shadowNode );
  19911. }
  19912. }
  19913. /**
  19914. * Uses the shadow mask to produce the final color.
  19915. *
  19916. * @param {NodeBuilder} builder - The current node builder.
  19917. */
  19918. finish( { context } ) {
  19919. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  19920. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  19921. }
  19922. }
  19923. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  19924. /**
  19925. * Node material version of {@link ShadowMaterial}.
  19926. *
  19927. * @augments NodeMaterial
  19928. */
  19929. class ShadowNodeMaterial extends NodeMaterial {
  19930. static get type() {
  19931. return 'ShadowNodeMaterial';
  19932. }
  19933. /**
  19934. * Constructs a new shadow node material.
  19935. *
  19936. * @param {Object} [parameters] - The configuration parameter.
  19937. */
  19938. constructor( parameters ) {
  19939. super();
  19940. /**
  19941. * This flag can be used for type testing.
  19942. *
  19943. * @type {boolean}
  19944. * @readonly
  19945. * @default true
  19946. */
  19947. this.isShadowNodeMaterial = true;
  19948. /**
  19949. * Set to `true` because so it's possible to implement
  19950. * the shadow mask effect.
  19951. *
  19952. * @type {boolean}
  19953. * @default true
  19954. */
  19955. this.lights = true;
  19956. /**
  19957. * Overwritten since shadow materials are transparent
  19958. * by default.
  19959. *
  19960. * @type {boolean}
  19961. * @default true
  19962. */
  19963. this.transparent = true;
  19964. this.setDefaultValues( _defaultValues );
  19965. this.setValues( parameters );
  19966. }
  19967. /**
  19968. * Setups the lighting model.
  19969. *
  19970. * @return {ShadowMaskModel} The lighting model.
  19971. */
  19972. setupLightingModel( /*builder*/ ) {
  19973. return new ShadowMaskModel();
  19974. }
  19975. }
  19976. const scatteringDensity = property( 'vec3' );
  19977. const linearDepthRay = property( 'vec3' );
  19978. const outgoingRayLight = property( 'vec3' );
  19979. /**
  19980. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  19981. * This model calculates the scattering and transmittance of light through a volumetric medium.
  19982. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  19983. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  19984. *
  19985. * @augments LightingModel
  19986. */
  19987. class VolumetricLightingModel extends LightingModel {
  19988. constructor() {
  19989. super();
  19990. }
  19991. start( builder ) {
  19992. const { material } = builder;
  19993. const startPos = property( 'vec3' );
  19994. const endPos = property( 'vec3' );
  19995. // This approach dynamically changes the direction of the ray,
  19996. // 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.
  19997. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  19998. startPos.assign( cameraPosition );
  19999. endPos.assign( positionWorld );
  20000. } ).Else( () => {
  20001. startPos.assign( positionWorld );
  20002. endPos.assign( cameraPosition );
  20003. } );
  20004. //
  20005. const viewVector = endPos.sub( startPos );
  20006. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  20007. const stepSize = viewVector.length().div( steps ).toVar();
  20008. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  20009. const distTravelled = float( 0.0 ).toVar();
  20010. const transmittance = vec3( 1 ).toVar();
  20011. if ( material.offsetNode ) {
  20012. // reduce banding
  20013. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  20014. }
  20015. Loop( steps, () => {
  20016. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  20017. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  20018. if ( material.depthNode !== null ) {
  20019. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  20020. builder.context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  20021. }
  20022. builder.context.positionWorld = positionRay;
  20023. builder.context.shadowPositionWorld = positionRay;
  20024. builder.context.positionView = positionViewRay;
  20025. scatteringDensity.assign( 0 );
  20026. let scatteringNode;
  20027. if ( material.scatteringNode ) {
  20028. scatteringNode = material.scatteringNode( {
  20029. positionRay
  20030. } );
  20031. }
  20032. super.start( builder );
  20033. if ( scatteringNode ) {
  20034. scatteringDensity.mulAssign( scatteringNode );
  20035. }
  20036. // beer's law
  20037. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  20038. transmittance.mulAssign( falloff );
  20039. // move along the ray
  20040. distTravelled.addAssign( stepSize );
  20041. } );
  20042. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  20043. }
  20044. scatteringLight( lightColor, builder ) {
  20045. const sceneDepthNode = builder.context.sceneDepthNode;
  20046. if ( sceneDepthNode ) {
  20047. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  20048. scatteringDensity.addAssign( lightColor );
  20049. } );
  20050. } else {
  20051. scatteringDensity.addAssign( lightColor );
  20052. }
  20053. }
  20054. direct( { lightNode, lightColor }, builder ) {
  20055. // Ignore lights with infinite distance
  20056. if ( lightNode.light.distance === undefined ) return;
  20057. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  20058. const directLight = lightColor.xyz.toVar();
  20059. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  20060. this.scatteringLight( directLight, builder );
  20061. }
  20062. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  20063. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  20064. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  20065. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  20066. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  20067. const P = builder.context.positionView;
  20068. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  20069. this.scatteringLight( directLight, builder );
  20070. }
  20071. finish( builder ) {
  20072. builder.context.outgoingLight.assign( outgoingRayLight );
  20073. }
  20074. }
  20075. /**
  20076. * Volume node material.
  20077. *
  20078. * @augments NodeMaterial
  20079. */
  20080. class VolumeNodeMaterial extends NodeMaterial {
  20081. static get type() {
  20082. return 'VolumeNodeMaterial';
  20083. }
  20084. /**
  20085. * Constructs a new volume node material.
  20086. *
  20087. * @param {Object} [parameters] - The configuration parameter.
  20088. */
  20089. constructor( parameters ) {
  20090. super();
  20091. /**
  20092. * This flag can be used for type testing.
  20093. *
  20094. * @type {boolean}
  20095. * @readonly
  20096. * @default true
  20097. */
  20098. this.isVolumeNodeMaterial = true;
  20099. /**
  20100. * Number of steps used for raymarching.
  20101. *
  20102. * @type {number}
  20103. * @default 25
  20104. */
  20105. this.steps = 25;
  20106. /**
  20107. * Offsets the distance a ray has been traveled through a volume.
  20108. * Can be used to implement dithering to reduce banding.
  20109. *
  20110. * @type {Node<float>}
  20111. * @default null
  20112. */
  20113. this.offsetNode = null;
  20114. /**
  20115. * Node used for scattering calculations.
  20116. *
  20117. * @type {Function|FunctionNode<vec4>}
  20118. * @default null
  20119. */
  20120. this.scatteringNode = null;
  20121. this.lights = true;
  20122. this.transparent = true;
  20123. this.side = BackSide;
  20124. this.depthTest = false;
  20125. this.depthWrite = false;
  20126. this.setValues( parameters );
  20127. }
  20128. setupLightingModel() {
  20129. return new VolumetricLightingModel();
  20130. }
  20131. }
  20132. /**
  20133. * This module manages the internal animation loop of the renderer.
  20134. *
  20135. * @private
  20136. */
  20137. class Animation {
  20138. /**
  20139. * Constructs a new animation loop management component.
  20140. *
  20141. * @param {Renderer} renderer - A reference to the main renderer.
  20142. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20143. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20144. */
  20145. constructor( renderer, nodes, info ) {
  20146. /**
  20147. * A reference to the main renderer.
  20148. *
  20149. * @type {Renderer}
  20150. */
  20151. this.renderer = renderer;
  20152. /**
  20153. * Renderer component for managing nodes related logic.
  20154. *
  20155. * @type {Nodes}
  20156. */
  20157. this.nodes = nodes;
  20158. /**
  20159. * Renderer component for managing metrics and monitoring data.
  20160. *
  20161. * @type {Info}
  20162. */
  20163. this.info = info;
  20164. /**
  20165. * A reference to the context from `requestAnimationFrame()` can
  20166. * be called (usually `window`).
  20167. *
  20168. * @type {?(Window|XRSession)}
  20169. */
  20170. this._context = typeof self !== 'undefined' ? self : null;
  20171. /**
  20172. * The user-defined animation loop.
  20173. *
  20174. * @type {?Function}
  20175. * @default null
  20176. */
  20177. this._animationLoop = null;
  20178. /**
  20179. * The requestId which is returned from the `requestAnimationFrame()` call.
  20180. * Can be used to cancel the stop the animation loop.
  20181. *
  20182. * @type {?number}
  20183. * @default null
  20184. */
  20185. this._requestId = null;
  20186. }
  20187. /**
  20188. * Starts the internal animation loop.
  20189. */
  20190. start() {
  20191. const update = ( time, xrFrame ) => {
  20192. this._requestId = this._context.requestAnimationFrame( update );
  20193. if ( this.info.autoReset === true ) this.info.reset();
  20194. this.nodes.nodeFrame.update();
  20195. this.info.frame = this.nodes.nodeFrame.frameId;
  20196. this.renderer._inspector.begin();
  20197. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  20198. this.renderer._inspector.finish();
  20199. };
  20200. update();
  20201. }
  20202. /**
  20203. * Stops the internal animation loop.
  20204. */
  20205. stop() {
  20206. this._context.cancelAnimationFrame( this._requestId );
  20207. this._requestId = null;
  20208. }
  20209. /**
  20210. * Returns the user-level animation loop.
  20211. *
  20212. * @return {?Function} The animation loop.
  20213. */
  20214. getAnimationLoop() {
  20215. return this._animationLoop;
  20216. }
  20217. /**
  20218. * Defines the user-level animation loop.
  20219. *
  20220. * @param {?Function} callback - The animation loop.
  20221. */
  20222. setAnimationLoop( callback ) {
  20223. this._animationLoop = callback;
  20224. }
  20225. /**
  20226. * Returns the animation context.
  20227. *
  20228. * @return {Window|XRSession} The animation context.
  20229. */
  20230. getContext() {
  20231. return this._context;
  20232. }
  20233. /**
  20234. * Defines the context in which `requestAnimationFrame()` is executed.
  20235. *
  20236. * @param {Window|XRSession} context - The context to set.
  20237. */
  20238. setContext( context ) {
  20239. this._context = context;
  20240. }
  20241. /**
  20242. * Frees all internal resources and stops the animation loop.
  20243. */
  20244. dispose() {
  20245. this.stop();
  20246. }
  20247. }
  20248. /**
  20249. * Data structure for the renderer. It allows defining values
  20250. * with chained, hierarchical keys. Keys are meant to be
  20251. * objects since the module internally works with Weak Maps
  20252. * for performance reasons.
  20253. *
  20254. * @private
  20255. */
  20256. class ChainMap {
  20257. /**
  20258. * Constructs a new Chain Map.
  20259. */
  20260. constructor() {
  20261. /**
  20262. * A map of Weak Maps by their key length.
  20263. *
  20264. * @type {Object<number, WeakMap>}
  20265. */
  20266. this.weakMaps = {};
  20267. }
  20268. /**
  20269. * Returns the Weak Map for the given keys.
  20270. *
  20271. * @param {Array<Object>} keys - List of keys.
  20272. * @return {WeakMap} The weak map.
  20273. */
  20274. _getWeakMap( keys ) {
  20275. const length = keys.length;
  20276. let weakMap = this.weakMaps[ length ];
  20277. if ( weakMap === undefined ) {
  20278. weakMap = new WeakMap();
  20279. this.weakMaps[ length ] = weakMap;
  20280. }
  20281. return weakMap;
  20282. }
  20283. /**
  20284. * Returns the value for the given array of keys.
  20285. *
  20286. * @param {Array<Object>} keys - List of keys.
  20287. * @return {any} The value. Returns `undefined` if no value was found.
  20288. */
  20289. get( keys ) {
  20290. let map = this._getWeakMap( keys );
  20291. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20292. map = map.get( keys[ i ] );
  20293. if ( map === undefined ) return undefined;
  20294. }
  20295. return map.get( keys[ keys.length - 1 ] );
  20296. }
  20297. /**
  20298. * Sets the value for the given keys.
  20299. *
  20300. * @param {Array<Object>} keys - List of keys.
  20301. * @param {any} value - The value to set.
  20302. * @return {ChainMap} A reference to this Chain Map.
  20303. */
  20304. set( keys, value ) {
  20305. let map = this._getWeakMap( keys );
  20306. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20307. const key = keys[ i ];
  20308. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  20309. map = map.get( key );
  20310. }
  20311. map.set( keys[ keys.length - 1 ], value );
  20312. return this;
  20313. }
  20314. /**
  20315. * Deletes a value for the given keys.
  20316. *
  20317. * @param {Array<Object>} keys - The keys.
  20318. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  20319. */
  20320. delete( keys ) {
  20321. let map = this._getWeakMap( keys );
  20322. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20323. map = map.get( keys[ i ] );
  20324. if ( map === undefined ) return false;
  20325. }
  20326. return map.delete( keys[ keys.length - 1 ] );
  20327. }
  20328. }
  20329. let _id$a = 0;
  20330. function getKeys( obj ) {
  20331. const keys = Object.keys( obj );
  20332. let proto = Object.getPrototypeOf( obj );
  20333. while ( proto ) {
  20334. const descriptors = Object.getOwnPropertyDescriptors( proto );
  20335. for ( const key in descriptors ) {
  20336. if ( descriptors[ key ] !== undefined ) {
  20337. const descriptor = descriptors[ key ];
  20338. if ( descriptor && typeof descriptor.get === 'function' ) {
  20339. keys.push( key );
  20340. }
  20341. }
  20342. }
  20343. proto = Object.getPrototypeOf( proto );
  20344. }
  20345. return keys;
  20346. }
  20347. /**
  20348. * A render object is the renderer's representation of single entity that gets drawn
  20349. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  20350. * scene since render objects also depend from the used material, the current render context
  20351. * and the current scene's lighting.
  20352. *
  20353. * In general, the basic process of the renderer is:
  20354. *
  20355. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  20356. * - Process the render lists by calling one or more render commands for each render item.
  20357. * - For each render command, request a render object and perform the draw.
  20358. *
  20359. * The module provides an interface to get data required for the draw command like the actual
  20360. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  20361. * creating render objects should only be done when necessary.
  20362. *
  20363. * @private
  20364. */
  20365. class RenderObject {
  20366. /**
  20367. * Constructs a new render object.
  20368. *
  20369. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20370. * @param {Geometries} geometries - Renderer component for managing geometries.
  20371. * @param {Renderer} renderer - The renderer.
  20372. * @param {Object3D} object - The 3D object.
  20373. * @param {Material} material - The 3D object's material.
  20374. * @param {Scene} scene - The scene the 3D object belongs to.
  20375. * @param {Camera} camera - The camera the object should be rendered with.
  20376. * @param {LightsNode} lightsNode - The lights node.
  20377. * @param {RenderContext} renderContext - The render context.
  20378. * @param {ClippingContext} clippingContext - The clipping context.
  20379. */
  20380. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  20381. this.id = _id$a ++;
  20382. /**
  20383. * Renderer component for managing nodes related logic.
  20384. *
  20385. * @type {Nodes}
  20386. * @private
  20387. */
  20388. this._nodes = nodes;
  20389. /**
  20390. * Renderer component for managing geometries.
  20391. *
  20392. * @type {Geometries}
  20393. * @private
  20394. */
  20395. this._geometries = geometries;
  20396. /**
  20397. * The renderer.
  20398. *
  20399. * @type {Renderer}
  20400. */
  20401. this.renderer = renderer;
  20402. /**
  20403. * The 3D object.
  20404. *
  20405. * @type {Object3D}
  20406. */
  20407. this.object = object;
  20408. /**
  20409. * The 3D object's material.
  20410. *
  20411. * @type {Material}
  20412. */
  20413. this.material = material;
  20414. /**
  20415. * The scene the 3D object belongs to.
  20416. *
  20417. * @type {Scene}
  20418. */
  20419. this.scene = scene;
  20420. /**
  20421. * The camera the 3D object should be rendered with.
  20422. *
  20423. * @type {Camera}
  20424. */
  20425. this.camera = camera;
  20426. /**
  20427. * The lights node.
  20428. *
  20429. * @type {LightsNode}
  20430. */
  20431. this.lightsNode = lightsNode;
  20432. /**
  20433. * The render context.
  20434. *
  20435. * @type {RenderContext}
  20436. */
  20437. this.context = renderContext;
  20438. /**
  20439. * The 3D object's geometry.
  20440. *
  20441. * @type {BufferGeometry}
  20442. */
  20443. this.geometry = object.geometry;
  20444. /**
  20445. * The render object's version.
  20446. *
  20447. * @type {number}
  20448. */
  20449. this.version = material.version;
  20450. /**
  20451. * The draw range of the geometry.
  20452. *
  20453. * @type {?Object}
  20454. * @default null
  20455. */
  20456. this.drawRange = null;
  20457. /**
  20458. * An array holding the buffer attributes
  20459. * of the render object. This entails attribute
  20460. * definitions on geometry and node level.
  20461. *
  20462. * @type {?Array<BufferAttribute>}
  20463. * @default null
  20464. */
  20465. this.attributes = null;
  20466. /**
  20467. * An object holding the version of the
  20468. * attributes. The keys are the attribute names
  20469. * and the values are the attribute versions.
  20470. *
  20471. * @type {?Object<string, number>}
  20472. * @default null
  20473. */
  20474. this.attributesId = null;
  20475. /**
  20476. * A reference to a render pipeline the render
  20477. * object is processed with.
  20478. *
  20479. * @type {RenderPipeline}
  20480. * @default null
  20481. */
  20482. this.pipeline = null;
  20483. /**
  20484. * Only relevant for objects using
  20485. * multiple materials. This represents a group entry
  20486. * from the respective `BufferGeometry`.
  20487. *
  20488. * @type {?{start: number, count: number}}
  20489. * @default null
  20490. */
  20491. this.group = null;
  20492. /**
  20493. * An array holding the vertex buffers which can
  20494. * be buffer attributes but also interleaved buffers.
  20495. *
  20496. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  20497. * @default null
  20498. */
  20499. this.vertexBuffers = null;
  20500. /**
  20501. * The parameters for the draw command.
  20502. *
  20503. * @type {?Object}
  20504. * @default null
  20505. */
  20506. this.drawParams = null;
  20507. /**
  20508. * If this render object is used inside a render bundle,
  20509. * this property points to the respective bundle group.
  20510. *
  20511. * @type {?BundleGroup}
  20512. * @default null
  20513. */
  20514. this.bundle = null;
  20515. /**
  20516. * The clipping context.
  20517. *
  20518. * @type {ClippingContext}
  20519. */
  20520. this.clippingContext = clippingContext;
  20521. /**
  20522. * The clipping context's cache key.
  20523. *
  20524. * @type {string}
  20525. */
  20526. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  20527. /**
  20528. * The initial node cache key.
  20529. *
  20530. * @type {number}
  20531. */
  20532. this.initialNodesCacheKey = this.getDynamicCacheKey();
  20533. /**
  20534. * The initial cache key.
  20535. *
  20536. * @type {number}
  20537. */
  20538. this.initialCacheKey = this.getCacheKey();
  20539. /**
  20540. * The node builder state.
  20541. *
  20542. * @type {?NodeBuilderState}
  20543. * @private
  20544. * @default null
  20545. */
  20546. this._nodeBuilderState = null;
  20547. /**
  20548. * An array of bindings.
  20549. *
  20550. * @type {?Array<BindGroup>}
  20551. * @private
  20552. * @default null
  20553. */
  20554. this._bindings = null;
  20555. /**
  20556. * Reference to the node material observer.
  20557. *
  20558. * @type {?NodeMaterialObserver}
  20559. * @private
  20560. * @default null
  20561. */
  20562. this._monitor = null;
  20563. /**
  20564. * An event listener which is defined by `RenderObjects`. It performs
  20565. * clean up tasks when `dispose()` on this render object.
  20566. *
  20567. * @method
  20568. */
  20569. this.onDispose = null;
  20570. /**
  20571. * This flag can be used for type testing.
  20572. *
  20573. * @type {boolean}
  20574. * @readonly
  20575. * @default true
  20576. */
  20577. this.isRenderObject = true;
  20578. /**
  20579. * An event listener which is executed when `dispose()` is called on
  20580. * the material of this render object.
  20581. *
  20582. * @method
  20583. */
  20584. this.onMaterialDispose = () => {
  20585. this.dispose();
  20586. };
  20587. /**
  20588. * An event listener which is executed when `dispose()` is called on
  20589. * the geometry of this render object.
  20590. *
  20591. * @method
  20592. */
  20593. this.onGeometryDispose = () => {
  20594. // clear geometry cache attributes
  20595. this.attributes = null;
  20596. this.attributesId = null;
  20597. };
  20598. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  20599. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  20600. }
  20601. /**
  20602. * Updates the clipping context.
  20603. *
  20604. * @param {ClippingContext} context - The clipping context to set.
  20605. */
  20606. updateClipping( context ) {
  20607. this.clippingContext = context;
  20608. }
  20609. /**
  20610. * Whether the clipping requires an update or not.
  20611. *
  20612. * @type {boolean}
  20613. * @readonly
  20614. */
  20615. get clippingNeedsUpdate() {
  20616. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  20617. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  20618. return true;
  20619. }
  20620. /**
  20621. * The number of clipping planes defined in context of hardware clipping.
  20622. *
  20623. * @type {number}
  20624. * @readonly
  20625. */
  20626. get hardwareClippingPlanes() {
  20627. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  20628. }
  20629. /**
  20630. * Returns the node builder state of this render object.
  20631. *
  20632. * @return {NodeBuilderState} The node builder state.
  20633. */
  20634. getNodeBuilderState() {
  20635. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  20636. }
  20637. /**
  20638. * Returns the node material observer of this render object.
  20639. *
  20640. * @return {NodeMaterialObserver} The node material observer.
  20641. */
  20642. getMonitor() {
  20643. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  20644. }
  20645. /**
  20646. * Returns an array of bind groups of this render object.
  20647. *
  20648. * @return {Array<BindGroup>} The bindings.
  20649. */
  20650. getBindings() {
  20651. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  20652. }
  20653. /**
  20654. * Returns a binding group by group name of this render object.
  20655. *
  20656. * @param {string} name - The name of the binding group.
  20657. * @return {?BindGroup} The bindings.
  20658. */
  20659. getBindingGroup( name ) {
  20660. for ( const bindingGroup of this.getBindings() ) {
  20661. if ( bindingGroup.name === name ) {
  20662. return bindingGroup;
  20663. }
  20664. }
  20665. }
  20666. /**
  20667. * Returns the index of the render object's geometry.
  20668. *
  20669. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  20670. */
  20671. getIndex() {
  20672. return this._geometries.getIndex( this );
  20673. }
  20674. /**
  20675. * Returns the indirect buffer attribute.
  20676. *
  20677. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  20678. */
  20679. getIndirect() {
  20680. return this._geometries.getIndirect( this );
  20681. }
  20682. /**
  20683. * Returns the byte offset into the indirect attribute buffer.
  20684. *
  20685. * @return {number|Array<number>} The byte offset into the indirect attribute buffer.
  20686. */
  20687. getIndirectOffset() {
  20688. return this._geometries.getIndirectOffset( this );
  20689. }
  20690. /**
  20691. * Returns an array that acts as a key for identifying the render object in a chain map.
  20692. *
  20693. * @return {Array<Object>} An array with object references.
  20694. */
  20695. getChainArray() {
  20696. return [ this.object, this.material, this.context, this.lightsNode ];
  20697. }
  20698. /**
  20699. * This method is used when the geometry of a 3D object has been exchanged and the
  20700. * respective render object now requires an update.
  20701. *
  20702. * @param {BufferGeometry} geometry - The geometry to set.
  20703. */
  20704. setGeometry( geometry ) {
  20705. this.geometry = geometry;
  20706. this.attributes = null;
  20707. this.attributesId = null;
  20708. }
  20709. /**
  20710. * Returns the buffer attributes of the render object. The returned array holds
  20711. * attribute definitions on geometry and node level.
  20712. *
  20713. * @return {Array<BufferAttribute>} An array with buffer attributes.
  20714. */
  20715. getAttributes() {
  20716. if ( this.attributes !== null ) return this.attributes;
  20717. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  20718. const geometry = this.geometry;
  20719. const attributes = [];
  20720. const vertexBuffers = new Set();
  20721. const attributesId = {};
  20722. for ( const nodeAttribute of nodeAttributes ) {
  20723. let attribute;
  20724. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  20725. // node attribute
  20726. attribute = nodeAttribute.node.attribute;
  20727. } else {
  20728. // geometry attribute
  20729. attribute = geometry.getAttribute( nodeAttribute.name );
  20730. attributesId[ nodeAttribute.name ] = attribute.version;
  20731. }
  20732. if ( attribute === undefined ) continue;
  20733. attributes.push( attribute );
  20734. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  20735. vertexBuffers.add( bufferAttribute );
  20736. }
  20737. this.attributes = attributes;
  20738. this.attributesId = attributesId;
  20739. this.vertexBuffers = Array.from( vertexBuffers.values() );
  20740. return attributes;
  20741. }
  20742. /**
  20743. * Returns the vertex buffers of the render object.
  20744. *
  20745. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  20746. */
  20747. getVertexBuffers() {
  20748. if ( this.vertexBuffers === null ) this.getAttributes();
  20749. return this.vertexBuffers;
  20750. }
  20751. /**
  20752. * Returns the draw parameters for the render object.
  20753. *
  20754. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  20755. */
  20756. getDrawParameters() {
  20757. const { object, material, geometry, group, drawRange } = this;
  20758. const drawParams = this.drawParams || ( this.drawParams = {
  20759. vertexCount: 0,
  20760. firstVertex: 0,
  20761. instanceCount: 0,
  20762. firstInstance: 0
  20763. } );
  20764. const index = this.getIndex();
  20765. const hasIndex = ( index !== null );
  20766. let instanceCount = 1;
  20767. if ( geometry.isInstancedBufferGeometry === true ) {
  20768. instanceCount = geometry.instanceCount;
  20769. } else if ( object.count !== undefined ) {
  20770. instanceCount = Math.max( 0, object.count );
  20771. }
  20772. if ( instanceCount === 0 ) return null;
  20773. drawParams.instanceCount = instanceCount;
  20774. if ( object.isBatchedMesh === true ) return drawParams;
  20775. let rangeFactor = 1;
  20776. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  20777. rangeFactor = 2;
  20778. }
  20779. let firstVertex = drawRange.start * rangeFactor;
  20780. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  20781. if ( group !== null ) {
  20782. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  20783. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  20784. }
  20785. const position = geometry.attributes.position;
  20786. let itemCount = Infinity;
  20787. if ( hasIndex ) {
  20788. itemCount = index.count;
  20789. } else if ( position !== undefined && position !== null ) {
  20790. itemCount = position.count;
  20791. }
  20792. firstVertex = Math.max( firstVertex, 0 );
  20793. lastVertex = Math.min( lastVertex, itemCount );
  20794. const count = lastVertex - firstVertex;
  20795. if ( count < 0 || count === Infinity ) return null;
  20796. drawParams.vertexCount = count;
  20797. drawParams.firstVertex = firstVertex;
  20798. return drawParams;
  20799. }
  20800. /**
  20801. * Returns the render object's geometry cache key.
  20802. *
  20803. * The geometry cache key is part of the material cache key.
  20804. *
  20805. * @return {string} The geometry cache key.
  20806. */
  20807. getGeometryCacheKey() {
  20808. const { geometry } = this;
  20809. let cacheKey = '';
  20810. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  20811. const attribute = geometry.attributes[ name ];
  20812. cacheKey += name + ',';
  20813. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  20814. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  20815. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  20816. if ( attribute.normalized ) cacheKey += 'n,';
  20817. }
  20818. // structural equality isn't sufficient for morph targets since the
  20819. // data are maintained in textures. only if the targets are all equal
  20820. // the texture and thus the instance of `MorphNode` can be shared.
  20821. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  20822. const targets = geometry.morphAttributes[ name ];
  20823. cacheKey += 'morph-' + name + ',';
  20824. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  20825. const attribute = targets[ i ];
  20826. cacheKey += attribute.id + ',';
  20827. }
  20828. }
  20829. if ( geometry.index ) {
  20830. cacheKey += 'index,';
  20831. }
  20832. return cacheKey;
  20833. }
  20834. /**
  20835. * Returns the render object's material cache key.
  20836. *
  20837. * The material cache key is part of the render object cache key.
  20838. *
  20839. * @return {number} The material cache key.
  20840. */
  20841. getMaterialCacheKey() {
  20842. const { object, material, renderer } = this;
  20843. let cacheKey = material.customProgramCacheKey();
  20844. for ( const property of getKeys( material ) ) {
  20845. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  20846. const value = material[ property ];
  20847. let valueKey;
  20848. if ( value !== null ) {
  20849. // some material values require a formatting
  20850. const type = typeof value;
  20851. if ( type === 'number' ) {
  20852. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  20853. } else if ( type === 'object' ) {
  20854. valueKey = '{';
  20855. if ( value.isTexture ) {
  20856. valueKey += value.mapping;
  20857. // WebGPU must honor the sampler data because they are part of the bindings
  20858. if ( renderer.backend.isWebGPUBackend === true ) {
  20859. valueKey += value.magFilter;
  20860. valueKey += value.minFilter;
  20861. valueKey += value.wrapS;
  20862. valueKey += value.wrapT;
  20863. valueKey += value.wrapR;
  20864. }
  20865. }
  20866. valueKey += '}';
  20867. } else {
  20868. valueKey = String( value );
  20869. }
  20870. } else {
  20871. valueKey = String( value );
  20872. }
  20873. cacheKey += /*property + ':' +*/ valueKey + ',';
  20874. }
  20875. cacheKey += this.clippingContextCacheKey + ',';
  20876. if ( object.geometry ) {
  20877. cacheKey += this.getGeometryCacheKey();
  20878. }
  20879. if ( object.skeleton ) {
  20880. cacheKey += object.skeleton.bones.length + ',';
  20881. }
  20882. if ( object.isBatchedMesh ) {
  20883. cacheKey += object._matricesTexture.uuid + ',';
  20884. if ( object._colorsTexture !== null ) {
  20885. cacheKey += object._colorsTexture.uuid + ',';
  20886. }
  20887. }
  20888. if ( object.isInstancedMesh || object.count > 1 || Array.isArray( object.morphTargetInfluences ) ) {
  20889. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  20890. cacheKey += object.uuid + ',';
  20891. }
  20892. cacheKey += this.context.id + ',';
  20893. cacheKey += object.receiveShadow + ',';
  20894. return hashString( cacheKey );
  20895. }
  20896. /**
  20897. * Whether the geometry requires an update or not.
  20898. *
  20899. * @type {boolean}
  20900. * @readonly
  20901. */
  20902. get needsGeometryUpdate() {
  20903. if ( this.geometry.id !== this.object.geometry.id ) return true;
  20904. if ( this.attributes !== null ) {
  20905. const attributesId = this.attributesId;
  20906. for ( const name in attributesId ) {
  20907. const attribute = this.geometry.getAttribute( name );
  20908. if ( attribute === undefined || attributesId[ name ] !== attribute.id ) {
  20909. return true;
  20910. }
  20911. }
  20912. }
  20913. return false;
  20914. }
  20915. /**
  20916. * Whether the render object requires an update or not.
  20917. *
  20918. * Note: There are two distinct places where render objects are checked for an update.
  20919. *
  20920. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  20921. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  20922. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  20923. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  20924. * a need for a refresh due to material, geometry or object related value changes.
  20925. *
  20926. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  20927. * that performs the 'needsUpdate' check.
  20928. *
  20929. * @type {boolean}
  20930. * @readonly
  20931. */
  20932. get needsUpdate() {
  20933. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  20934. }
  20935. /**
  20936. * Returns the dynamic cache key which represents a key that is computed per draw command.
  20937. *
  20938. * @return {number} The cache key.
  20939. */
  20940. getDynamicCacheKey() {
  20941. let cacheKey = 0;
  20942. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  20943. // the renderer is inside a shadow pass.
  20944. if ( this.material.isShadowPassMaterial !== true ) {
  20945. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  20946. }
  20947. if ( this.camera.isArrayCamera ) {
  20948. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  20949. }
  20950. if ( this.object.receiveShadow ) {
  20951. cacheKey = hash$1( cacheKey, 1 );
  20952. }
  20953. cacheKey = hash$1( cacheKey, this.camera.id, this.renderer.contextNode.id, this.renderer.contextNode.version );
  20954. return cacheKey;
  20955. }
  20956. /**
  20957. * Returns the render object's cache key.
  20958. *
  20959. * @return {number} The cache key.
  20960. */
  20961. getCacheKey() {
  20962. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  20963. }
  20964. /**
  20965. * Frees internal resources.
  20966. */
  20967. dispose() {
  20968. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  20969. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  20970. this.onDispose();
  20971. }
  20972. }
  20973. const _chainKeys$5 = [];
  20974. /**
  20975. * This module manages the render objects of the renderer.
  20976. *
  20977. * @private
  20978. */
  20979. class RenderObjects {
  20980. /**
  20981. * Constructs a new render object management component.
  20982. *
  20983. * @param {Renderer} renderer - The renderer.
  20984. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20985. * @param {Geometries} geometries - Renderer component for managing geometries.
  20986. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  20987. * @param {Bindings} bindings - Renderer component for managing bindings.
  20988. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20989. */
  20990. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  20991. /**
  20992. * The renderer.
  20993. *
  20994. * @type {Renderer}
  20995. */
  20996. this.renderer = renderer;
  20997. /**
  20998. * Renderer component for managing nodes related logic.
  20999. *
  21000. * @type {Nodes}
  21001. */
  21002. this.nodes = nodes;
  21003. /**
  21004. * Renderer component for managing geometries.
  21005. *
  21006. * @type {Geometries}
  21007. */
  21008. this.geometries = geometries;
  21009. /**
  21010. * Renderer component for managing pipelines.
  21011. *
  21012. * @type {Pipelines}
  21013. */
  21014. this.pipelines = pipelines;
  21015. /**
  21016. * Renderer component for managing bindings.
  21017. *
  21018. * @type {Bindings}
  21019. */
  21020. this.bindings = bindings;
  21021. /**
  21022. * Renderer component for managing metrics and monitoring data.
  21023. *
  21024. * @type {Info}
  21025. */
  21026. this.info = info;
  21027. /**
  21028. * A dictionary that manages render contexts in chain maps
  21029. * for each pass ID.
  21030. *
  21031. * @type {Object<string,ChainMap>}
  21032. */
  21033. this.chainMaps = {};
  21034. }
  21035. /**
  21036. * Returns a render object for the given object and state data.
  21037. *
  21038. * @param {Object3D} object - The 3D object.
  21039. * @param {Material} material - The 3D object's material.
  21040. * @param {Scene} scene - The scene the 3D object belongs to.
  21041. * @param {Camera} camera - The camera the 3D object should be rendered with.
  21042. * @param {LightsNode} lightsNode - The lights node.
  21043. * @param {RenderContext} renderContext - The render context.
  21044. * @param {ClippingContext} clippingContext - The clipping context.
  21045. * @param {string} [passId] - An optional ID for identifying the pass.
  21046. * @return {RenderObject} The render object.
  21047. */
  21048. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  21049. const chainMap = this.getChainMap( passId );
  21050. // reuse chainArray
  21051. _chainKeys$5[ 0 ] = object;
  21052. _chainKeys$5[ 1 ] = material;
  21053. _chainKeys$5[ 2 ] = renderContext;
  21054. _chainKeys$5[ 3 ] = lightsNode;
  21055. let renderObject = chainMap.get( _chainKeys$5 );
  21056. if ( renderObject === undefined ) {
  21057. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  21058. chainMap.set( _chainKeys$5, renderObject );
  21059. } else {
  21060. renderObject.updateClipping( clippingContext );
  21061. if ( renderObject.needsGeometryUpdate ) {
  21062. renderObject.setGeometry( object.geometry );
  21063. }
  21064. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  21065. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  21066. renderObject.dispose();
  21067. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  21068. } else {
  21069. renderObject.version = material.version;
  21070. }
  21071. }
  21072. }
  21073. _chainKeys$5.length = 0;
  21074. return renderObject;
  21075. }
  21076. /**
  21077. * Returns a chain map for the given pass ID.
  21078. *
  21079. * @param {string} [passId='default'] - The pass ID.
  21080. * @return {ChainMap} The chain map.
  21081. */
  21082. getChainMap( passId = 'default' ) {
  21083. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  21084. }
  21085. /**
  21086. * Frees internal resources.
  21087. */
  21088. dispose() {
  21089. this.chainMaps = {};
  21090. }
  21091. /**
  21092. * Factory method for creating render objects with the given list of parameters.
  21093. *
  21094. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21095. * @param {Geometries} geometries - Renderer component for managing geometries.
  21096. * @param {Renderer} renderer - The renderer.
  21097. * @param {Object3D} object - The 3D object.
  21098. * @param {Material} material - The object's material.
  21099. * @param {Scene} scene - The scene the 3D object belongs to.
  21100. * @param {Camera} camera - The camera the object should be rendered with.
  21101. * @param {LightsNode} lightsNode - The lights node.
  21102. * @param {RenderContext} renderContext - The render context.
  21103. * @param {ClippingContext} clippingContext - The clipping context.
  21104. * @param {string} [passId] - An optional ID for identifying the pass.
  21105. * @return {RenderObject} The render object.
  21106. */
  21107. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  21108. const chainMap = this.getChainMap( passId );
  21109. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  21110. renderObject.onDispose = () => {
  21111. this.pipelines.delete( renderObject );
  21112. this.bindings.deleteForRender( renderObject );
  21113. this.nodes.delete( renderObject );
  21114. chainMap.delete( renderObject.getChainArray() );
  21115. };
  21116. return renderObject;
  21117. }
  21118. }
  21119. /**
  21120. * Data structure for the renderer. It is intended to manage
  21121. * data of objects in dictionaries.
  21122. *
  21123. * @private
  21124. */
  21125. class DataMap {
  21126. /**
  21127. * Constructs a new data map.
  21128. */
  21129. constructor() {
  21130. /**
  21131. * `DataMap` internally uses a weak map
  21132. * to manage its data.
  21133. *
  21134. * @type {WeakMap<Object, Object>}
  21135. */
  21136. this.data = new WeakMap();
  21137. }
  21138. /**
  21139. * Returns the dictionary for the given object.
  21140. *
  21141. * @param {Object} object - The object.
  21142. * @return {Object} The dictionary.
  21143. */
  21144. get( object ) {
  21145. let map = this.data.get( object );
  21146. if ( map === undefined ) {
  21147. map = {};
  21148. this.data.set( object, map );
  21149. }
  21150. return map;
  21151. }
  21152. /**
  21153. * Deletes the dictionary for the given object.
  21154. *
  21155. * @param {Object} object - The object.
  21156. * @return {?Object} The deleted dictionary.
  21157. */
  21158. delete( object ) {
  21159. let map = null;
  21160. if ( this.data.has( object ) ) {
  21161. map = this.data.get( object );
  21162. this.data.delete( object );
  21163. }
  21164. return map;
  21165. }
  21166. /**
  21167. * Returns `true` if the given object has a dictionary defined.
  21168. *
  21169. * @param {Object} object - The object to test.
  21170. * @return {boolean} Whether a dictionary is defined or not.
  21171. */
  21172. has( object ) {
  21173. return this.data.has( object );
  21174. }
  21175. /**
  21176. * Frees internal resources.
  21177. */
  21178. dispose() {
  21179. this.data = new WeakMap();
  21180. }
  21181. }
  21182. const AttributeType = {
  21183. VERTEX: 1,
  21184. INDEX: 2,
  21185. STORAGE: 3,
  21186. INDIRECT: 4
  21187. };
  21188. // size of a chunk in bytes (STD140 layout)
  21189. const GPU_CHUNK_BYTES = 16;
  21190. // @TODO: Move to src/constants.js
  21191. const BlendColorFactor = 211;
  21192. const OneMinusBlendColorFactor = 212;
  21193. /**
  21194. * This renderer module manages geometry attributes.
  21195. *
  21196. * @private
  21197. * @augments DataMap
  21198. */
  21199. class Attributes extends DataMap {
  21200. /**
  21201. * Constructs a new attribute management component.
  21202. *
  21203. * @param {Backend} backend - The renderer's backend.
  21204. */
  21205. constructor( backend ) {
  21206. super();
  21207. /**
  21208. * The renderer's backend.
  21209. *
  21210. * @type {Backend}
  21211. */
  21212. this.backend = backend;
  21213. }
  21214. /**
  21215. * Deletes the data for the given attribute.
  21216. *
  21217. * @param {BufferAttribute} attribute - The attribute.
  21218. * @return {?Object} The deleted attribute data.
  21219. */
  21220. delete( attribute ) {
  21221. const attributeData = super.delete( attribute );
  21222. if ( attributeData !== null ) {
  21223. this.backend.destroyAttribute( attribute );
  21224. }
  21225. return attributeData;
  21226. }
  21227. /**
  21228. * Updates the given attribute. This method creates attribute buffers
  21229. * for new attributes and updates data for existing ones.
  21230. *
  21231. * @param {BufferAttribute} attribute - The attribute to update.
  21232. * @param {number} type - The attribute type.
  21233. */
  21234. update( attribute, type ) {
  21235. const data = this.get( attribute );
  21236. if ( data.version === undefined ) {
  21237. if ( type === AttributeType.VERTEX ) {
  21238. this.backend.createAttribute( attribute );
  21239. } else if ( type === AttributeType.INDEX ) {
  21240. this.backend.createIndexAttribute( attribute );
  21241. } else if ( type === AttributeType.STORAGE ) {
  21242. this.backend.createStorageAttribute( attribute );
  21243. } else if ( type === AttributeType.INDIRECT ) {
  21244. this.backend.createIndirectStorageAttribute( attribute );
  21245. }
  21246. data.version = this._getBufferAttribute( attribute ).version;
  21247. } else {
  21248. const bufferAttribute = this._getBufferAttribute( attribute );
  21249. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  21250. this.backend.updateAttribute( attribute );
  21251. data.version = bufferAttribute.version;
  21252. }
  21253. }
  21254. }
  21255. /**
  21256. * Utility method for handling interleaved buffer attributes correctly.
  21257. * To process them, their `InterleavedBuffer` is returned.
  21258. *
  21259. * @param {BufferAttribute} attribute - The attribute.
  21260. * @return {BufferAttribute|InterleavedBuffer}
  21261. */
  21262. _getBufferAttribute( attribute ) {
  21263. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  21264. return attribute;
  21265. }
  21266. }
  21267. /**
  21268. * Returns the wireframe version for the given geometry.
  21269. *
  21270. * @private
  21271. * @function
  21272. * @param {BufferGeometry} geometry - The geometry.
  21273. * @return {number} The version.
  21274. */
  21275. function getWireframeVersion( geometry ) {
  21276. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  21277. }
  21278. /**
  21279. * Returns a wireframe index attribute for the given geometry.
  21280. *
  21281. * @private
  21282. * @function
  21283. * @param {BufferGeometry} geometry - The geometry.
  21284. * @return {BufferAttribute} The wireframe index attribute.
  21285. */
  21286. function getWireframeIndex( geometry ) {
  21287. const indices = [];
  21288. const geometryIndex = geometry.index;
  21289. const geometryPosition = geometry.attributes.position;
  21290. if ( geometryIndex !== null ) {
  21291. const array = geometryIndex.array;
  21292. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  21293. const a = array[ i + 0 ];
  21294. const b = array[ i + 1 ];
  21295. const c = array[ i + 2 ];
  21296. indices.push( a, b, b, c, c, a );
  21297. }
  21298. } else {
  21299. const array = geometryPosition.array;
  21300. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  21301. const a = i + 0;
  21302. const b = i + 1;
  21303. const c = i + 2;
  21304. indices.push( a, b, b, c, c, a );
  21305. }
  21306. }
  21307. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  21308. attribute.version = getWireframeVersion( geometry );
  21309. return attribute;
  21310. }
  21311. /**
  21312. * This renderer module manages geometries.
  21313. *
  21314. * @private
  21315. * @augments DataMap
  21316. */
  21317. class Geometries extends DataMap {
  21318. /**
  21319. * Constructs a new geometry management component.
  21320. *
  21321. * @param {Attributes} attributes - Renderer component for managing attributes.
  21322. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21323. */
  21324. constructor( attributes, info ) {
  21325. super();
  21326. /**
  21327. * Renderer component for managing attributes.
  21328. *
  21329. * @type {Attributes}
  21330. */
  21331. this.attributes = attributes;
  21332. /**
  21333. * Renderer component for managing metrics and monitoring data.
  21334. *
  21335. * @type {Info}
  21336. */
  21337. this.info = info;
  21338. /**
  21339. * Weak Map for managing attributes for wireframe rendering.
  21340. *
  21341. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  21342. */
  21343. this.wireframes = new WeakMap();
  21344. /**
  21345. * This Weak Map is used to make sure buffer attributes are
  21346. * updated only once per render call.
  21347. *
  21348. * @type {WeakMap<BufferAttribute,number>}
  21349. */
  21350. this.attributeCall = new WeakMap();
  21351. /**
  21352. * Stores the event listeners attached to geometries.
  21353. *
  21354. * @private
  21355. * @type {Map<BufferGeometry,Function>}
  21356. */
  21357. this._geometryDisposeListeners = new Map();
  21358. }
  21359. /**
  21360. * Returns `true` if the given render object has an initialized geometry.
  21361. *
  21362. * @param {RenderObject} renderObject - The render object.
  21363. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  21364. */
  21365. has( renderObject ) {
  21366. const geometry = renderObject.geometry;
  21367. return super.has( geometry ) && this.get( geometry ).initialized === true;
  21368. }
  21369. /**
  21370. * Prepares the geometry of the given render object for rendering.
  21371. *
  21372. * @param {RenderObject} renderObject - The render object.
  21373. */
  21374. updateForRender( renderObject ) {
  21375. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  21376. this.updateAttributes( renderObject );
  21377. }
  21378. /**
  21379. * Initializes the geometry of the given render object.
  21380. *
  21381. * @param {RenderObject} renderObject - The render object.
  21382. */
  21383. initGeometry( renderObject ) {
  21384. const geometry = renderObject.geometry;
  21385. const geometryData = this.get( geometry );
  21386. geometryData.initialized = true;
  21387. this.info.memory.geometries ++;
  21388. const onDispose = () => {
  21389. this.info.memory.geometries --;
  21390. const index = geometry.index;
  21391. const geometryAttributes = renderObject.getAttributes();
  21392. if ( index !== null ) {
  21393. this.attributes.delete( index );
  21394. }
  21395. for ( const geometryAttribute of geometryAttributes ) {
  21396. this.attributes.delete( geometryAttribute );
  21397. }
  21398. const wireframeAttribute = this.wireframes.get( geometry );
  21399. if ( wireframeAttribute !== undefined ) {
  21400. this.attributes.delete( wireframeAttribute );
  21401. }
  21402. geometry.removeEventListener( 'dispose', onDispose );
  21403. this._geometryDisposeListeners.delete( geometry );
  21404. };
  21405. geometry.addEventListener( 'dispose', onDispose );
  21406. // see #31798 why tracking separate remove listeners is required right now
  21407. // TODO: Re-evaluate how onDispose() is managed in this component
  21408. this._geometryDisposeListeners.set( geometry, onDispose );
  21409. }
  21410. /**
  21411. * Updates the geometry attributes of the given render object.
  21412. *
  21413. * @param {RenderObject} renderObject - The render object.
  21414. */
  21415. updateAttributes( renderObject ) {
  21416. // attributes
  21417. const attributes = renderObject.getAttributes();
  21418. for ( const attribute of attributes ) {
  21419. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  21420. this.updateAttribute( attribute, AttributeType.STORAGE );
  21421. } else {
  21422. this.updateAttribute( attribute, AttributeType.VERTEX );
  21423. }
  21424. }
  21425. // indexes
  21426. const index = this.getIndex( renderObject );
  21427. if ( index !== null ) {
  21428. this.updateAttribute( index, AttributeType.INDEX );
  21429. }
  21430. // indirect
  21431. const indirect = renderObject.geometry.indirect;
  21432. if ( indirect !== null ) {
  21433. this.updateAttribute( indirect, AttributeType.INDIRECT );
  21434. }
  21435. }
  21436. /**
  21437. * Updates the given attribute.
  21438. *
  21439. * @param {BufferAttribute} attribute - The attribute to update.
  21440. * @param {number} type - The attribute type.
  21441. */
  21442. updateAttribute( attribute, type ) {
  21443. const callId = this.info.render.calls;
  21444. if ( ! attribute.isInterleavedBufferAttribute ) {
  21445. if ( this.attributeCall.get( attribute ) !== callId ) {
  21446. this.attributes.update( attribute, type );
  21447. this.attributeCall.set( attribute, callId );
  21448. }
  21449. } else {
  21450. if ( this.attributeCall.get( attribute ) === undefined ) {
  21451. this.attributes.update( attribute, type );
  21452. this.attributeCall.set( attribute, callId );
  21453. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  21454. this.attributes.update( attribute, type );
  21455. this.attributeCall.set( attribute.data, callId );
  21456. this.attributeCall.set( attribute, callId );
  21457. }
  21458. }
  21459. }
  21460. /**
  21461. * Returns the indirect buffer attribute of the given render object.
  21462. *
  21463. * @param {RenderObject} renderObject - The render object.
  21464. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  21465. */
  21466. getIndirect( renderObject ) {
  21467. return renderObject.geometry.indirect;
  21468. }
  21469. /**
  21470. * Returns the byte offset into the indirect attribute buffer of the given render object.
  21471. *
  21472. * @param {RenderObject} renderObject - The render object.
  21473. * @return {number} The byte offset into the indirect attribute buffer.
  21474. */
  21475. getIndirectOffset( renderObject ) {
  21476. return renderObject.geometry.indirectOffset;
  21477. }
  21478. /**
  21479. * Returns the index of the given render object's geometry. This is implemented
  21480. * in a method to return a wireframe index if necessary.
  21481. *
  21482. * @param {RenderObject} renderObject - The render object.
  21483. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  21484. */
  21485. getIndex( renderObject ) {
  21486. const { geometry, material } = renderObject;
  21487. let index = geometry.index;
  21488. if ( material.wireframe === true ) {
  21489. const wireframes = this.wireframes;
  21490. let wireframeAttribute = wireframes.get( geometry );
  21491. if ( wireframeAttribute === undefined ) {
  21492. wireframeAttribute = getWireframeIndex( geometry );
  21493. wireframes.set( geometry, wireframeAttribute );
  21494. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  21495. this.attributes.delete( wireframeAttribute );
  21496. wireframeAttribute = getWireframeIndex( geometry );
  21497. wireframes.set( geometry, wireframeAttribute );
  21498. }
  21499. index = wireframeAttribute;
  21500. }
  21501. return index;
  21502. }
  21503. dispose() {
  21504. for ( const [ geometry, onDispose ] of this._geometryDisposeListeners.entries() ) {
  21505. geometry.removeEventListener( 'dispose', onDispose );
  21506. }
  21507. this._geometryDisposeListeners.clear();
  21508. }
  21509. }
  21510. /**
  21511. * This renderer module provides a series of statistical information
  21512. * about the GPU memory and the rendering process. Useful for debugging
  21513. * and monitoring.
  21514. */
  21515. class Info {
  21516. /**
  21517. * Constructs a new info component.
  21518. */
  21519. constructor() {
  21520. /**
  21521. * Whether frame related metrics should automatically
  21522. * be resetted or not. This property should be set to `false`
  21523. * by apps which manage their own animation loop. They must
  21524. * then call `renderer.info.reset()` once per frame manually.
  21525. *
  21526. * @type {boolean}
  21527. * @default true
  21528. */
  21529. this.autoReset = true;
  21530. /**
  21531. * The current frame ID. This ID is managed
  21532. * by `NodeFrame`.
  21533. *
  21534. * @type {number}
  21535. * @readonly
  21536. * @default 0
  21537. */
  21538. this.frame = 0;
  21539. /**
  21540. * The number of render calls since the
  21541. * app has been started.
  21542. *
  21543. * @type {number}
  21544. * @readonly
  21545. * @default 0
  21546. */
  21547. this.calls = 0;
  21548. /**
  21549. * Render related metrics.
  21550. *
  21551. * @type {Object}
  21552. * @readonly
  21553. * @property {number} calls - The number of render calls since the app has been started.
  21554. * @property {number} frameCalls - The number of render calls of the current frame.
  21555. * @property {number} drawCalls - The number of draw calls of the current frame.
  21556. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  21557. * @property {number} points - The number of rendered point primitives of the current frame.
  21558. * @property {number} lines - The number of rendered line primitives of the current frame.
  21559. * @property {number} timestamp - The timestamp of the frame.
  21560. */
  21561. this.render = {
  21562. calls: 0,
  21563. frameCalls: 0,
  21564. drawCalls: 0,
  21565. triangles: 0,
  21566. points: 0,
  21567. lines: 0,
  21568. timestamp: 0,
  21569. };
  21570. /**
  21571. * Compute related metrics.
  21572. *
  21573. * @type {Object}
  21574. * @readonly
  21575. * @property {number} calls - The number of compute calls since the app has been started.
  21576. * @property {number} frameCalls - The number of compute calls of the current frame.
  21577. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  21578. */
  21579. this.compute = {
  21580. calls: 0,
  21581. frameCalls: 0,
  21582. timestamp: 0
  21583. };
  21584. /**
  21585. * Memory related metrics.
  21586. *
  21587. * @type {Object}
  21588. * @readonly
  21589. * @property {number} geometries - The number of active geometries.
  21590. * @property {number} frameCalls - The number of active textures.
  21591. */
  21592. this.memory = {
  21593. geometries: 0,
  21594. textures: 0
  21595. };
  21596. }
  21597. /**
  21598. * This method should be executed per draw call and updates the corresponding metrics.
  21599. *
  21600. * @param {Object3D} object - The 3D object that is going to be rendered.
  21601. * @param {number} count - The vertex or index count.
  21602. * @param {number} instanceCount - The instance count.
  21603. */
  21604. update( object, count, instanceCount ) {
  21605. this.render.drawCalls ++;
  21606. if ( object.isMesh || object.isSprite ) {
  21607. this.render.triangles += instanceCount * ( count / 3 );
  21608. } else if ( object.isPoints ) {
  21609. this.render.points += instanceCount * count;
  21610. } else if ( object.isLineSegments ) {
  21611. this.render.lines += instanceCount * ( count / 2 );
  21612. } else if ( object.isLine ) {
  21613. this.render.lines += instanceCount * ( count - 1 );
  21614. } else {
  21615. error( 'WebGPUInfo: Unknown object type.' );
  21616. }
  21617. }
  21618. /**
  21619. * Resets frame related metrics.
  21620. */
  21621. reset() {
  21622. this.render.drawCalls = 0;
  21623. this.render.frameCalls = 0;
  21624. this.compute.frameCalls = 0;
  21625. this.render.triangles = 0;
  21626. this.render.points = 0;
  21627. this.render.lines = 0;
  21628. }
  21629. /**
  21630. * Performs a complete reset of the object.
  21631. */
  21632. dispose() {
  21633. this.reset();
  21634. this.calls = 0;
  21635. this.render.calls = 0;
  21636. this.compute.calls = 0;
  21637. this.render.timestamp = 0;
  21638. this.compute.timestamp = 0;
  21639. this.memory.geometries = 0;
  21640. this.memory.textures = 0;
  21641. }
  21642. }
  21643. /**
  21644. * Abstract class for representing pipelines.
  21645. *
  21646. * @private
  21647. * @abstract
  21648. */
  21649. class Pipeline {
  21650. /**
  21651. * Constructs a new pipeline.
  21652. *
  21653. * @param {string} cacheKey - The pipeline's cache key.
  21654. */
  21655. constructor( cacheKey ) {
  21656. /**
  21657. * The pipeline's cache key.
  21658. *
  21659. * @type {string}
  21660. */
  21661. this.cacheKey = cacheKey;
  21662. /**
  21663. * How often the pipeline is currently in use.
  21664. *
  21665. * @type {number}
  21666. * @default 0
  21667. */
  21668. this.usedTimes = 0;
  21669. }
  21670. }
  21671. /**
  21672. * Class for representing render pipelines.
  21673. *
  21674. * @private
  21675. * @augments Pipeline
  21676. */
  21677. class RenderPipeline extends Pipeline {
  21678. /**
  21679. * Constructs a new render pipeline.
  21680. *
  21681. * @param {string} cacheKey - The pipeline's cache key.
  21682. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  21683. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  21684. */
  21685. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  21686. super( cacheKey );
  21687. /**
  21688. * The pipeline's vertex shader.
  21689. *
  21690. * @type {ProgrammableStage}
  21691. */
  21692. this.vertexProgram = vertexProgram;
  21693. /**
  21694. * The pipeline's fragment shader.
  21695. *
  21696. * @type {ProgrammableStage}
  21697. */
  21698. this.fragmentProgram = fragmentProgram;
  21699. }
  21700. }
  21701. /**
  21702. * Class for representing compute pipelines.
  21703. *
  21704. * @private
  21705. * @augments Pipeline
  21706. */
  21707. class ComputePipeline extends Pipeline {
  21708. /**
  21709. * Constructs a new render pipeline.
  21710. *
  21711. * @param {string} cacheKey - The pipeline's cache key.
  21712. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  21713. */
  21714. constructor( cacheKey, computeProgram ) {
  21715. super( cacheKey );
  21716. /**
  21717. * The pipeline's compute shader.
  21718. *
  21719. * @type {ProgrammableStage}
  21720. */
  21721. this.computeProgram = computeProgram;
  21722. /**
  21723. * This flag can be used for type testing.
  21724. *
  21725. * @type {boolean}
  21726. * @readonly
  21727. * @default true
  21728. */
  21729. this.isComputePipeline = true;
  21730. }
  21731. }
  21732. let _id$9 = 0;
  21733. /**
  21734. * Class for representing programmable stages which are vertex,
  21735. * fragment or compute shaders. Unlike fixed-function states (like blending),
  21736. * they represent the programmable part of a pipeline.
  21737. *
  21738. * @private
  21739. */
  21740. class ProgrammableStage {
  21741. /**
  21742. * Constructs a new programmable stage.
  21743. *
  21744. * @param {string} code - The shader code.
  21745. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  21746. * @param {string} name - The name of the shader.
  21747. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21748. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21749. */
  21750. constructor( code, stage, name, transforms = null, attributes = null ) {
  21751. /**
  21752. * The id of the programmable stage.
  21753. *
  21754. * @type {number}
  21755. */
  21756. this.id = _id$9 ++;
  21757. /**
  21758. * The shader code.
  21759. *
  21760. * @type {string}
  21761. */
  21762. this.code = code;
  21763. /**
  21764. * The type of stage.
  21765. *
  21766. * @type {string}
  21767. */
  21768. this.stage = stage;
  21769. /**
  21770. * The name of the stage.
  21771. * This is used for debugging purposes.
  21772. *
  21773. * @type {string}
  21774. */
  21775. this.name = name;
  21776. /**
  21777. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21778. *
  21779. * @type {?Array<Object>}
  21780. */
  21781. this.transforms = transforms;
  21782. /**
  21783. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21784. *
  21785. * @type {?Array<Object>}
  21786. */
  21787. this.attributes = attributes;
  21788. /**
  21789. * How often the programmable stage is currently in use.
  21790. *
  21791. * @type {number}
  21792. * @default 0
  21793. */
  21794. this.usedTimes = 0;
  21795. }
  21796. }
  21797. /**
  21798. * This renderer module manages the pipelines of the renderer.
  21799. *
  21800. * @private
  21801. * @augments DataMap
  21802. */
  21803. class Pipelines extends DataMap {
  21804. /**
  21805. * Constructs a new pipeline management component.
  21806. *
  21807. * @param {Backend} backend - The renderer's backend.
  21808. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21809. */
  21810. constructor( backend, nodes ) {
  21811. super();
  21812. /**
  21813. * The renderer's backend.
  21814. *
  21815. * @type {Backend}
  21816. */
  21817. this.backend = backend;
  21818. /**
  21819. * Renderer component for managing nodes related logic.
  21820. *
  21821. * @type {Nodes}
  21822. */
  21823. this.nodes = nodes;
  21824. /**
  21825. * A references to the bindings management component.
  21826. * This reference will be set inside the `Bindings`
  21827. * constructor.
  21828. *
  21829. * @type {?Bindings}
  21830. * @default null
  21831. */
  21832. this.bindings = null;
  21833. /**
  21834. * Internal cache for maintaining pipelines.
  21835. * The key of the map is a cache key, the value the pipeline.
  21836. *
  21837. * @type {Map<string,Pipeline>}
  21838. */
  21839. this.caches = new Map();
  21840. /**
  21841. * This dictionary maintains for each shader stage type (vertex,
  21842. * fragment and compute) the programmable stage objects which
  21843. * represent the actual shader code.
  21844. *
  21845. * @type {Object<string,Map<string, ProgrammableStage>>}
  21846. */
  21847. this.programs = {
  21848. vertex: new Map(),
  21849. fragment: new Map(),
  21850. compute: new Map()
  21851. };
  21852. }
  21853. /**
  21854. * Returns a compute pipeline for the given compute node.
  21855. *
  21856. * @param {Node} computeNode - The compute node.
  21857. * @param {Array<BindGroup>} bindings - The bindings.
  21858. * @return {ComputePipeline} The compute pipeline.
  21859. */
  21860. getForCompute( computeNode, bindings ) {
  21861. const { backend } = this;
  21862. const data = this.get( computeNode );
  21863. if ( this._needsComputeUpdate( computeNode ) ) {
  21864. const previousPipeline = data.pipeline;
  21865. if ( previousPipeline ) {
  21866. previousPipeline.usedTimes --;
  21867. previousPipeline.computeProgram.usedTimes --;
  21868. }
  21869. // get shader
  21870. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  21871. // programmable stage
  21872. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  21873. if ( stageCompute === undefined ) {
  21874. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  21875. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  21876. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  21877. backend.createProgram( stageCompute );
  21878. }
  21879. // determine compute pipeline
  21880. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  21881. let pipeline = this.caches.get( cacheKey );
  21882. if ( pipeline === undefined ) {
  21883. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21884. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  21885. }
  21886. // keep track of all used times
  21887. pipeline.usedTimes ++;
  21888. stageCompute.usedTimes ++;
  21889. //
  21890. data.version = computeNode.version;
  21891. data.pipeline = pipeline;
  21892. }
  21893. return data.pipeline;
  21894. }
  21895. /**
  21896. * Returns a render pipeline for the given render object.
  21897. *
  21898. * @param {RenderObject} renderObject - The render object.
  21899. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  21900. * @return {RenderPipeline} The render pipeline.
  21901. */
  21902. getForRender( renderObject, promises = null ) {
  21903. const { backend } = this;
  21904. const data = this.get( renderObject );
  21905. if ( this._needsRenderUpdate( renderObject ) ) {
  21906. const previousPipeline = data.pipeline;
  21907. if ( previousPipeline ) {
  21908. previousPipeline.usedTimes --;
  21909. previousPipeline.vertexProgram.usedTimes --;
  21910. previousPipeline.fragmentProgram.usedTimes --;
  21911. }
  21912. // get shader
  21913. const nodeBuilderState = renderObject.getNodeBuilderState();
  21914. const name = renderObject.material ? renderObject.material.name : '';
  21915. // programmable stages
  21916. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  21917. if ( stageVertex === undefined ) {
  21918. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  21919. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  21920. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  21921. backend.createProgram( stageVertex );
  21922. }
  21923. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  21924. if ( stageFragment === undefined ) {
  21925. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  21926. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  21927. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  21928. backend.createProgram( stageFragment );
  21929. }
  21930. // determine render pipeline
  21931. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  21932. let pipeline = this.caches.get( cacheKey );
  21933. if ( pipeline === undefined ) {
  21934. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21935. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  21936. } else {
  21937. renderObject.pipeline = pipeline;
  21938. }
  21939. // keep track of all used times
  21940. pipeline.usedTimes ++;
  21941. stageVertex.usedTimes ++;
  21942. stageFragment.usedTimes ++;
  21943. //
  21944. data.pipeline = pipeline;
  21945. }
  21946. return data.pipeline;
  21947. }
  21948. /**
  21949. * Deletes the pipeline for the given render object.
  21950. *
  21951. * @param {RenderObject} object - The render object.
  21952. * @return {?Object} The deleted dictionary.
  21953. */
  21954. delete( object ) {
  21955. const pipeline = this.get( object ).pipeline;
  21956. if ( pipeline ) {
  21957. // pipeline
  21958. pipeline.usedTimes --;
  21959. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  21960. // programs
  21961. if ( pipeline.isComputePipeline ) {
  21962. pipeline.computeProgram.usedTimes --;
  21963. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  21964. } else {
  21965. pipeline.fragmentProgram.usedTimes --;
  21966. pipeline.vertexProgram.usedTimes --;
  21967. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  21968. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  21969. }
  21970. }
  21971. return super.delete( object );
  21972. }
  21973. /**
  21974. * Frees internal resources.
  21975. */
  21976. dispose() {
  21977. super.dispose();
  21978. this.caches = new Map();
  21979. this.programs = {
  21980. vertex: new Map(),
  21981. fragment: new Map(),
  21982. compute: new Map()
  21983. };
  21984. }
  21985. /**
  21986. * Updates the pipeline for the given render object.
  21987. *
  21988. * @param {RenderObject} renderObject - The render object.
  21989. */
  21990. updateForRender( renderObject ) {
  21991. this.getForRender( renderObject );
  21992. }
  21993. /**
  21994. * Returns a compute pipeline for the given parameters.
  21995. *
  21996. * @private
  21997. * @param {Node} computeNode - The compute node.
  21998. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21999. * @param {string} cacheKey - The cache key.
  22000. * @param {Array<BindGroup>} bindings - The bindings.
  22001. * @return {ComputePipeline} The compute pipeline.
  22002. */
  22003. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  22004. // check for existing pipeline
  22005. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  22006. let pipeline = this.caches.get( cacheKey );
  22007. if ( pipeline === undefined ) {
  22008. pipeline = new ComputePipeline( cacheKey, stageCompute );
  22009. this.caches.set( cacheKey, pipeline );
  22010. this.backend.createComputePipeline( pipeline, bindings );
  22011. }
  22012. return pipeline;
  22013. }
  22014. /**
  22015. * Returns a render pipeline for the given parameters.
  22016. *
  22017. * @private
  22018. * @param {RenderObject} renderObject - The render object.
  22019. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  22020. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  22021. * @param {string} cacheKey - The cache key.
  22022. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  22023. * @return {ComputePipeline} The compute pipeline.
  22024. */
  22025. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  22026. // check for existing pipeline
  22027. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22028. let pipeline = this.caches.get( cacheKey );
  22029. if ( pipeline === undefined ) {
  22030. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  22031. this.caches.set( cacheKey, pipeline );
  22032. renderObject.pipeline = pipeline;
  22033. // The `promises` array is `null` by default and only set to an empty array when
  22034. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  22035. // pending promises that resolve when the render pipelines are ready for rendering.
  22036. this.backend.createRenderPipeline( renderObject, promises );
  22037. }
  22038. return pipeline;
  22039. }
  22040. /**
  22041. * Computes a cache key representing a compute pipeline.
  22042. *
  22043. * @private
  22044. * @param {Node} computeNode - The compute node.
  22045. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  22046. * @return {string} The cache key.
  22047. */
  22048. _getComputeCacheKey( computeNode, stageCompute ) {
  22049. return computeNode.id + ',' + stageCompute.id;
  22050. }
  22051. /**
  22052. * Computes a cache key representing a render pipeline.
  22053. *
  22054. * @private
  22055. * @param {RenderObject} renderObject - The render object.
  22056. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  22057. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  22058. * @return {string} The cache key.
  22059. */
  22060. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  22061. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  22062. }
  22063. /**
  22064. * Releases the given pipeline.
  22065. *
  22066. * @private
  22067. * @param {Pipeline} pipeline - The pipeline to release.
  22068. */
  22069. _releasePipeline( pipeline ) {
  22070. this.caches.delete( pipeline.cacheKey );
  22071. }
  22072. /**
  22073. * Releases the shader program.
  22074. *
  22075. * @private
  22076. * @param {Object} program - The shader program to release.
  22077. */
  22078. _releaseProgram( program ) {
  22079. const code = program.code;
  22080. const stage = program.stage;
  22081. this.programs[ stage ].delete( code );
  22082. }
  22083. /**
  22084. * Returns `true` if the compute pipeline for the given compute node requires an update.
  22085. *
  22086. * @private
  22087. * @param {Node} computeNode - The compute node.
  22088. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  22089. */
  22090. _needsComputeUpdate( computeNode ) {
  22091. const data = this.get( computeNode );
  22092. return data.pipeline === undefined || data.version !== computeNode.version;
  22093. }
  22094. /**
  22095. * Returns `true` if the render pipeline for the given render object requires an update.
  22096. *
  22097. * @private
  22098. * @param {RenderObject} renderObject - The render object.
  22099. * @return {boolean} Whether the render object for the given render object requires an update or not.
  22100. */
  22101. _needsRenderUpdate( renderObject ) {
  22102. const data = this.get( renderObject );
  22103. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  22104. }
  22105. }
  22106. /**
  22107. * This renderer module manages the bindings of the renderer.
  22108. *
  22109. * @private
  22110. * @augments DataMap
  22111. */
  22112. class Bindings extends DataMap {
  22113. /**
  22114. * Constructs a new bindings management component.
  22115. *
  22116. * @param {Backend} backend - The renderer's backend.
  22117. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  22118. * @param {Textures} textures - Renderer component for managing textures.
  22119. * @param {Attributes} attributes - Renderer component for managing attributes.
  22120. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  22121. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22122. */
  22123. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  22124. super();
  22125. /**
  22126. * The renderer's backend.
  22127. *
  22128. * @type {Backend}
  22129. */
  22130. this.backend = backend;
  22131. /**
  22132. * Renderer component for managing textures.
  22133. *
  22134. * @type {Textures}
  22135. */
  22136. this.textures = textures;
  22137. /**
  22138. * Renderer component for managing pipelines.
  22139. *
  22140. * @type {Pipelines}
  22141. */
  22142. this.pipelines = pipelines;
  22143. /**
  22144. * Renderer component for managing attributes.
  22145. *
  22146. * @type {Attributes}
  22147. */
  22148. this.attributes = attributes;
  22149. /**
  22150. * Renderer component for managing nodes related logic.
  22151. *
  22152. * @type {Nodes}
  22153. */
  22154. this.nodes = nodes;
  22155. /**
  22156. * Renderer component for managing metrics and monitoring data.
  22157. *
  22158. * @type {Info}
  22159. */
  22160. this.info = info;
  22161. this.pipelines.bindings = this; // assign bindings to pipelines
  22162. }
  22163. /**
  22164. * Returns the bind groups for the given render object.
  22165. *
  22166. * @param {RenderObject} renderObject - The render object.
  22167. * @return {Array<BindGroup>} The bind groups.
  22168. */
  22169. getForRender( renderObject ) {
  22170. const bindings = renderObject.getBindings();
  22171. for ( const bindGroup of bindings ) {
  22172. const groupData = this.get( bindGroup );
  22173. if ( groupData.bindGroup === undefined ) {
  22174. // each object defines an array of bindings (ubos, textures, samplers etc.)
  22175. this._init( bindGroup );
  22176. this.backend.createBindings( bindGroup, bindings, 0 );
  22177. groupData.bindGroup = bindGroup;
  22178. }
  22179. }
  22180. return bindings;
  22181. }
  22182. /**
  22183. * Returns the bind groups for the given compute node.
  22184. *
  22185. * @param {Node} computeNode - The compute node.
  22186. * @return {Array<BindGroup>} The bind groups.
  22187. */
  22188. getForCompute( computeNode ) {
  22189. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  22190. for ( const bindGroup of bindings ) {
  22191. const groupData = this.get( bindGroup );
  22192. if ( groupData.bindGroup === undefined ) {
  22193. this._init( bindGroup );
  22194. this.backend.createBindings( bindGroup, bindings, 0 );
  22195. groupData.bindGroup = bindGroup;
  22196. }
  22197. }
  22198. return bindings;
  22199. }
  22200. /**
  22201. * Updates the bindings for the given compute node.
  22202. *
  22203. * @param {Node} computeNode - The compute node.
  22204. */
  22205. updateForCompute( computeNode ) {
  22206. this._updateBindings( this.getForCompute( computeNode ) );
  22207. }
  22208. /**
  22209. * Updates the bindings for the given render object.
  22210. *
  22211. * @param {RenderObject} renderObject - The render object.
  22212. */
  22213. updateForRender( renderObject ) {
  22214. this._updateBindings( this.getForRender( renderObject ) );
  22215. }
  22216. /**
  22217. * Deletes the bindings for the given compute node.
  22218. *
  22219. * @param {Node} computeNode - The compute node.
  22220. */
  22221. deleteForCompute( computeNode ) {
  22222. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  22223. for ( const bindGroup of bindings ) {
  22224. this.backend.deleteBindGroupData( bindGroup );
  22225. this.delete( bindGroup );
  22226. }
  22227. }
  22228. /**
  22229. * Deletes the bindings for the given renderObject node.
  22230. *
  22231. * @param {RenderObject} renderObject - The renderObject.
  22232. */
  22233. deleteForRender( renderObject ) {
  22234. const bindings = renderObject.getBindings();
  22235. for ( const bindGroup of bindings ) {
  22236. this.backend.deleteBindGroupData( bindGroup );
  22237. this.delete( bindGroup );
  22238. }
  22239. }
  22240. /**
  22241. * Updates the given array of bindings.
  22242. *
  22243. * @param {Array<BindGroup>} bindings - The bind groups.
  22244. */
  22245. _updateBindings( bindings ) {
  22246. for ( const bindGroup of bindings ) {
  22247. this._update( bindGroup, bindings );
  22248. }
  22249. }
  22250. /**
  22251. * Initializes the given bind group.
  22252. *
  22253. * @param {BindGroup} bindGroup - The bind group to initialize.
  22254. */
  22255. _init( bindGroup ) {
  22256. for ( const binding of bindGroup.bindings ) {
  22257. if ( binding.isSampledTexture ) {
  22258. this.textures.updateTexture( binding.texture );
  22259. } else if ( binding.isSampler ) {
  22260. this.textures.updateSampler( binding.texture );
  22261. } else if ( binding.isStorageBuffer ) {
  22262. const attribute = binding.attribute;
  22263. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  22264. this.attributes.update( attribute, attributeType );
  22265. }
  22266. }
  22267. }
  22268. /**
  22269. * Updates the given bind group.
  22270. *
  22271. * @param {BindGroup} bindGroup - The bind group to update.
  22272. * @param {Array<BindGroup>} bindings - The bind groups.
  22273. */
  22274. _update( bindGroup, bindings ) {
  22275. const { backend } = this;
  22276. let needsBindingsUpdate = false;
  22277. let cacheBindings = true;
  22278. let cacheIndex = 0;
  22279. let version = 0;
  22280. // iterate over all bindings and check if buffer updates or a new binding group is required
  22281. for ( const binding of bindGroup.bindings ) {
  22282. const updatedGroup = this.nodes.updateGroup( binding );
  22283. // every uniforms group is a uniform buffer. So if no update is required,
  22284. // we move one with the next binding. Otherwise the next if block will update the group.
  22285. if ( updatedGroup === false ) continue;
  22286. //
  22287. if ( binding.isStorageBuffer ) {
  22288. const attribute = binding.attribute;
  22289. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  22290. this.attributes.update( attribute, attributeType );
  22291. }
  22292. if ( binding.isUniformBuffer ) {
  22293. const updated = binding.update();
  22294. if ( updated ) {
  22295. backend.updateBinding( binding );
  22296. }
  22297. } else if ( binding.isSampledTexture ) {
  22298. const updated = binding.update();
  22299. // get the texture data after the update, to sync the texture reference from node
  22300. const texture = binding.texture;
  22301. const texturesTextureData = this.textures.get( texture );
  22302. if ( updated ) {
  22303. // version: update the texture data or create a new one
  22304. this.textures.updateTexture( texture );
  22305. // generation: update the bindings if a new texture has been created
  22306. if ( binding.generation !== texturesTextureData.generation ) {
  22307. binding.generation = texturesTextureData.generation;
  22308. needsBindingsUpdate = true;
  22309. cacheBindings = false;
  22310. }
  22311. }
  22312. const textureData = backend.get( texture );
  22313. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  22314. cacheBindings = false;
  22315. } else {
  22316. cacheIndex = cacheIndex * 10 + texture.id;
  22317. version += texture.version;
  22318. }
  22319. if ( texture.isStorageTexture === true && texture.mipmapsAutoUpdate === true ) {
  22320. const textureData = this.get( texture );
  22321. if ( binding.store === true ) {
  22322. textureData.needsMipmap = true;
  22323. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  22324. this.backend.generateMipmaps( texture );
  22325. textureData.needsMipmap = false;
  22326. }
  22327. }
  22328. } else if ( binding.isSampler ) {
  22329. const updated = binding.update();
  22330. if ( updated ) {
  22331. const samplerKey = this.textures.updateSampler( binding.texture );
  22332. if ( binding.samplerKey !== samplerKey ) {
  22333. binding.samplerKey = samplerKey;
  22334. needsBindingsUpdate = true;
  22335. cacheBindings = false;
  22336. }
  22337. }
  22338. }
  22339. }
  22340. if ( needsBindingsUpdate === true ) {
  22341. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  22342. }
  22343. }
  22344. }
  22345. /**
  22346. * Default sorting function for opaque render items.
  22347. *
  22348. * @private
  22349. * @function
  22350. * @param {Object} a - The first render item.
  22351. * @param {Object} b - The second render item.
  22352. * @return {number} A numeric value which defines the sort order.
  22353. */
  22354. function painterSortStable( a, b ) {
  22355. if ( a.groupOrder !== b.groupOrder ) {
  22356. return a.groupOrder - b.groupOrder;
  22357. } else if ( a.renderOrder !== b.renderOrder ) {
  22358. return a.renderOrder - b.renderOrder;
  22359. } else if ( a.z !== b.z ) {
  22360. return a.z - b.z;
  22361. } else {
  22362. return a.id - b.id;
  22363. }
  22364. }
  22365. /**
  22366. * Default sorting function for transparent render items.
  22367. *
  22368. * @private
  22369. * @function
  22370. * @param {Object} a - The first render item.
  22371. * @param {Object} b - The second render item.
  22372. * @return {number} A numeric value which defines the sort order.
  22373. */
  22374. function reversePainterSortStable( a, b ) {
  22375. if ( a.groupOrder !== b.groupOrder ) {
  22376. return a.groupOrder - b.groupOrder;
  22377. } else if ( a.renderOrder !== b.renderOrder ) {
  22378. return a.renderOrder - b.renderOrder;
  22379. } else if ( a.z !== b.z ) {
  22380. return b.z - a.z;
  22381. } else {
  22382. return a.id - b.id;
  22383. }
  22384. }
  22385. /**
  22386. * Returns `true` if the given transparent material requires a double pass.
  22387. *
  22388. * @private
  22389. * @function
  22390. * @param {Material} material - The transparent material.
  22391. * @return {boolean} Whether the given material requires a double pass or not.
  22392. */
  22393. function needsDoublePass( material ) {
  22394. const hasTransmission = material.transmission > 0 || ( material.transmissionNode && material.transmissionNode.isNode );
  22395. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  22396. }
  22397. /**
  22398. * When the renderer analyzes the scene at the beginning of a render call,
  22399. * it stores 3D object for further processing in render lists. Depending on the
  22400. * properties of a 3D objects (like their transformation or material state), the
  22401. * objects are maintained in ordered lists for the actual rendering.
  22402. *
  22403. * Render lists are unique per scene and camera combination.
  22404. *
  22405. * @private
  22406. * @augments Pipeline
  22407. */
  22408. class RenderList {
  22409. /**
  22410. * Constructs a render list.
  22411. *
  22412. * @param {Lighting} lighting - The lighting management component.
  22413. * @param {Scene} scene - The scene.
  22414. * @param {Camera} camera - The camera the scene is rendered with.
  22415. */
  22416. constructor( lighting, scene, camera ) {
  22417. /**
  22418. * 3D objects are transformed into render items and stored in this array.
  22419. *
  22420. * @type {Array<Object>}
  22421. */
  22422. this.renderItems = [];
  22423. /**
  22424. * The current render items index.
  22425. *
  22426. * @type {number}
  22427. * @default 0
  22428. */
  22429. this.renderItemsIndex = 0;
  22430. /**
  22431. * A list with opaque render items.
  22432. *
  22433. * @type {Array<Object>}
  22434. */
  22435. this.opaque = [];
  22436. /**
  22437. * A list with transparent render items which require
  22438. * double pass rendering (e.g. transmissive objects).
  22439. *
  22440. * @type {Array<Object>}
  22441. */
  22442. this.transparentDoublePass = [];
  22443. /**
  22444. * A list with transparent render items.
  22445. *
  22446. * @type {Array<Object>}
  22447. */
  22448. this.transparent = [];
  22449. /**
  22450. * A list with transparent render bundle data.
  22451. *
  22452. * @type {Array<Object>}
  22453. */
  22454. this.bundles = [];
  22455. /**
  22456. * The render list's lights node. This node is later
  22457. * relevant for the actual analytical light nodes which
  22458. * compute the scene's lighting in the shader.
  22459. *
  22460. * @type {LightsNode}
  22461. */
  22462. this.lightsNode = lighting.getNode( scene, camera );
  22463. /**
  22464. * The scene's lights stored in an array. This array
  22465. * is used to setup the lights node.
  22466. *
  22467. * @type {Array<Light>}
  22468. */
  22469. this.lightsArray = [];
  22470. /**
  22471. * The scene.
  22472. *
  22473. * @type {Scene}
  22474. */
  22475. this.scene = scene;
  22476. /**
  22477. * The camera the scene is rendered with.
  22478. *
  22479. * @type {Camera}
  22480. */
  22481. this.camera = camera;
  22482. /**
  22483. * How many objects perform occlusion query tests.
  22484. *
  22485. * @type {number}
  22486. * @default 0
  22487. */
  22488. this.occlusionQueryCount = 0;
  22489. }
  22490. /**
  22491. * This method is called right at the beginning of a render call
  22492. * before the scene is analyzed. It prepares the internal data
  22493. * structures for the upcoming render lists generation.
  22494. *
  22495. * @return {RenderList} A reference to this render list.
  22496. */
  22497. begin() {
  22498. this.renderItemsIndex = 0;
  22499. this.opaque.length = 0;
  22500. this.transparentDoublePass.length = 0;
  22501. this.transparent.length = 0;
  22502. this.bundles.length = 0;
  22503. this.lightsArray.length = 0;
  22504. this.occlusionQueryCount = 0;
  22505. return this;
  22506. }
  22507. /**
  22508. * Returns a render item for the giving render item state. The state is defined
  22509. * by a series of object-related parameters.
  22510. *
  22511. * The method avoids object creation by holding render items and reusing them in
  22512. * subsequent render calls (just with different property values).
  22513. *
  22514. * @param {Object3D} object - The 3D object.
  22515. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22516. * @param {Material} material - The 3D object's material.
  22517. * @param {number} groupOrder - The current group order.
  22518. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22519. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22520. * @param {ClippingContext} clippingContext - The current clipping context.
  22521. * @return {Object} The render item.
  22522. */
  22523. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22524. let renderItem = this.renderItems[ this.renderItemsIndex ];
  22525. if ( renderItem === undefined ) {
  22526. renderItem = {
  22527. id: object.id,
  22528. object: object,
  22529. geometry: geometry,
  22530. material: material,
  22531. groupOrder: groupOrder,
  22532. renderOrder: object.renderOrder,
  22533. z: z,
  22534. group: group,
  22535. clippingContext: clippingContext
  22536. };
  22537. this.renderItems[ this.renderItemsIndex ] = renderItem;
  22538. } else {
  22539. renderItem.id = object.id;
  22540. renderItem.object = object;
  22541. renderItem.geometry = geometry;
  22542. renderItem.material = material;
  22543. renderItem.groupOrder = groupOrder;
  22544. renderItem.renderOrder = object.renderOrder;
  22545. renderItem.z = z;
  22546. renderItem.group = group;
  22547. renderItem.clippingContext = clippingContext;
  22548. }
  22549. this.renderItemsIndex ++;
  22550. return renderItem;
  22551. }
  22552. /**
  22553. * Pushes the given object as a render item to the internal render lists.
  22554. * The selected lists depend on the object properties.
  22555. *
  22556. * @param {Object3D} object - The 3D object.
  22557. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22558. * @param {Material} material - The 3D object's material.
  22559. * @param {number} groupOrder - The current group order.
  22560. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22561. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22562. * @param {ClippingContext} clippingContext - The current clipping context.
  22563. */
  22564. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22565. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  22566. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  22567. if ( material.transparent === true || material.transmission > 0 ||
  22568. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  22569. ( material.backdropNode && material.backdropNode.isNode ) ) {
  22570. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  22571. this.transparent.push( renderItem );
  22572. } else {
  22573. this.opaque.push( renderItem );
  22574. }
  22575. }
  22576. /**
  22577. * Inserts the given object as a render item at the start of the internal render lists.
  22578. * The selected lists depend on the object properties.
  22579. *
  22580. * @param {Object3D} object - The 3D object.
  22581. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22582. * @param {Material} material - The 3D object's material.
  22583. * @param {number} groupOrder - The current group order.
  22584. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22585. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22586. * @param {ClippingContext} clippingContext - The current clipping context.
  22587. */
  22588. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22589. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  22590. if ( material.transparent === true || material.transmission > 0 ||
  22591. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  22592. ( material.backdropNode && material.backdropNode.isNode ) ) {
  22593. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  22594. this.transparent.unshift( renderItem );
  22595. } else {
  22596. this.opaque.unshift( renderItem );
  22597. }
  22598. }
  22599. /**
  22600. * Pushes render bundle group data into the render list.
  22601. *
  22602. * @param {Object} group - Bundle group data.
  22603. */
  22604. pushBundle( group ) {
  22605. this.bundles.push( group );
  22606. }
  22607. /**
  22608. * Pushes a light into the render list.
  22609. *
  22610. * @param {Light} light - The light.
  22611. */
  22612. pushLight( light ) {
  22613. this.lightsArray.push( light );
  22614. }
  22615. /**
  22616. * Sorts the internal render lists.
  22617. *
  22618. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  22619. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  22620. */
  22621. sort( customOpaqueSort, customTransparentSort ) {
  22622. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  22623. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  22624. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  22625. }
  22626. /**
  22627. * This method performs finalizing tasks right after the render lists
  22628. * have been generated.
  22629. */
  22630. finish() {
  22631. // update lights
  22632. this.lightsNode.setLights( this.lightsArray );
  22633. // Clear references from inactive renderItems in the list
  22634. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  22635. const renderItem = this.renderItems[ i ];
  22636. if ( renderItem.id === null ) break;
  22637. renderItem.id = null;
  22638. renderItem.object = null;
  22639. renderItem.geometry = null;
  22640. renderItem.material = null;
  22641. renderItem.groupOrder = null;
  22642. renderItem.renderOrder = null;
  22643. renderItem.z = null;
  22644. renderItem.group = null;
  22645. renderItem.clippingContext = null;
  22646. }
  22647. }
  22648. }
  22649. const _chainKeys$4 = [];
  22650. /**
  22651. * This renderer module manages the render lists which are unique
  22652. * per scene and camera combination.
  22653. *
  22654. * @private
  22655. */
  22656. class RenderLists {
  22657. /**
  22658. * Constructs a render lists management component.
  22659. *
  22660. * @param {Lighting} lighting - The lighting management component.
  22661. */
  22662. constructor( lighting ) {
  22663. /**
  22664. * The lighting management component.
  22665. *
  22666. * @type {Lighting}
  22667. */
  22668. this.lighting = lighting;
  22669. /**
  22670. * The internal chain map which holds the render lists.
  22671. *
  22672. * @type {ChainMap}
  22673. */
  22674. this.lists = new ChainMap();
  22675. }
  22676. /**
  22677. * Returns a render list for the given scene and camera.
  22678. *
  22679. * @param {Scene} scene - The scene.
  22680. * @param {Camera} camera - The camera.
  22681. * @return {RenderList} The render list.
  22682. */
  22683. get( scene, camera ) {
  22684. const lists = this.lists;
  22685. _chainKeys$4[ 0 ] = scene;
  22686. _chainKeys$4[ 1 ] = camera;
  22687. let list = lists.get( _chainKeys$4 );
  22688. if ( list === undefined ) {
  22689. list = new RenderList( this.lighting, scene, camera );
  22690. lists.set( _chainKeys$4, list );
  22691. }
  22692. _chainKeys$4.length = 0;
  22693. return list;
  22694. }
  22695. /**
  22696. * Frees all internal resources.
  22697. */
  22698. dispose() {
  22699. this.lists = new ChainMap();
  22700. }
  22701. }
  22702. let _id$8 = 0;
  22703. /**
  22704. * Any render or compute command is executed in a specific context that defines
  22705. * the state of the renderer and its backend. Typical examples for such context
  22706. * data are the current clear values or data from the active framebuffer. This
  22707. * module is used to represent these contexts as objects.
  22708. *
  22709. * @private
  22710. */
  22711. class RenderContext {
  22712. /**
  22713. * Constructs a new render context.
  22714. */
  22715. constructor() {
  22716. /**
  22717. * The context's ID.
  22718. *
  22719. * @type {number}
  22720. */
  22721. this.id = _id$8 ++;
  22722. /**
  22723. * Whether the current active framebuffer has a color attachment.
  22724. *
  22725. * @type {boolean}
  22726. * @default true
  22727. */
  22728. this.color = true;
  22729. /**
  22730. * Whether the color attachment should be cleared or not.
  22731. *
  22732. * @type {boolean}
  22733. * @default true
  22734. */
  22735. this.clearColor = true;
  22736. /**
  22737. * The clear color value.
  22738. *
  22739. * @type {Object}
  22740. * @default true
  22741. */
  22742. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  22743. /**
  22744. * Whether the current active framebuffer has a depth attachment.
  22745. *
  22746. * @type {boolean}
  22747. * @default true
  22748. */
  22749. this.depth = true;
  22750. /**
  22751. * Whether the depth attachment should be cleared or not.
  22752. *
  22753. * @type {boolean}
  22754. * @default true
  22755. */
  22756. this.clearDepth = true;
  22757. /**
  22758. * The clear depth value.
  22759. *
  22760. * @type {number}
  22761. * @default 1
  22762. */
  22763. this.clearDepthValue = 1;
  22764. /**
  22765. * Whether the current active framebuffer has a stencil attachment.
  22766. *
  22767. * @type {boolean}
  22768. * @default false
  22769. */
  22770. this.stencil = false;
  22771. /**
  22772. * Whether the stencil attachment should be cleared or not.
  22773. *
  22774. * @type {boolean}
  22775. * @default true
  22776. */
  22777. this.clearStencil = true;
  22778. /**
  22779. * The clear stencil value.
  22780. *
  22781. * @type {number}
  22782. * @default 1
  22783. */
  22784. this.clearStencilValue = 1;
  22785. /**
  22786. * By default the viewport encloses the entire framebuffer If a smaller
  22787. * viewport is manually defined, this property is to `true` by the renderer.
  22788. *
  22789. * @type {boolean}
  22790. * @default false
  22791. */
  22792. this.viewport = false;
  22793. /**
  22794. * The viewport value. This value is in physical pixels meaning it incorporates
  22795. * the renderer's pixel ratio. The viewport property of render targets or
  22796. * the renderer is in logical pixels.
  22797. *
  22798. * @type {Vector4}
  22799. */
  22800. this.viewportValue = new Vector4();
  22801. /**
  22802. * When the scissor test is active and scissor rectangle smaller than the
  22803. * framebuffers dimensions, this property is to `true` by the renderer.
  22804. *
  22805. * @type {boolean}
  22806. * @default false
  22807. */
  22808. this.scissor = false;
  22809. /**
  22810. * The scissor rectangle.
  22811. *
  22812. * @type {Vector4}
  22813. */
  22814. this.scissorValue = new Vector4();
  22815. /**
  22816. * The active render target.
  22817. *
  22818. * @type {?RenderTarget}
  22819. * @default null
  22820. */
  22821. this.renderTarget = null;
  22822. /**
  22823. * The textures of the active render target.
  22824. * `null` when no render target is set.
  22825. *
  22826. * @type {?Array<Texture>}
  22827. * @default null
  22828. */
  22829. this.textures = null;
  22830. /**
  22831. * The depth texture of the active render target.
  22832. * `null` when no render target is set.
  22833. *
  22834. * @type {?DepthTexture}
  22835. * @default null
  22836. */
  22837. this.depthTexture = null;
  22838. /**
  22839. * The active cube face.
  22840. *
  22841. * @type {number}
  22842. * @default 0
  22843. */
  22844. this.activeCubeFace = 0;
  22845. /**
  22846. * The active mipmap level.
  22847. *
  22848. * @type {number}
  22849. * @default 0
  22850. */
  22851. this.activeMipmapLevel = 0;
  22852. /**
  22853. * The number of MSAA samples. This value is always `1` when
  22854. * MSAA isn't used.
  22855. *
  22856. * @type {number}
  22857. * @default 1
  22858. */
  22859. this.sampleCount = 1;
  22860. /**
  22861. * The active render target's width in physical pixels.
  22862. *
  22863. * @type {number}
  22864. * @default 0
  22865. */
  22866. this.width = 0;
  22867. /**
  22868. * The active render target's height in physical pixels.
  22869. *
  22870. * @type {number}
  22871. * @default 0
  22872. */
  22873. this.height = 0;
  22874. /**
  22875. * The occlusion query count.
  22876. *
  22877. * @type {number}
  22878. * @default 0
  22879. */
  22880. this.occlusionQueryCount = 0;
  22881. /**
  22882. * The current clipping context.
  22883. *
  22884. * @type {?ClippingContext}
  22885. * @default null
  22886. */
  22887. this.clippingContext = null;
  22888. /**
  22889. * This flag can be used for type testing.
  22890. *
  22891. * @type {boolean}
  22892. * @readonly
  22893. * @default true
  22894. */
  22895. this.isRenderContext = true;
  22896. }
  22897. /**
  22898. * Returns the cache key of this render context.
  22899. *
  22900. * @return {number} The cache key.
  22901. */
  22902. getCacheKey() {
  22903. return getCacheKey( this );
  22904. }
  22905. }
  22906. /**
  22907. * Computes a cache key for the given render context. This key
  22908. * should identify the render target state so it is possible to
  22909. * configure the correct attachments in the respective backend.
  22910. *
  22911. * @param {RenderContext} renderContext - The render context.
  22912. * @return {number} The cache key.
  22913. */
  22914. function getCacheKey( renderContext ) {
  22915. const { textures, activeCubeFace, activeMipmapLevel } = renderContext;
  22916. const values = [ activeCubeFace, activeMipmapLevel ];
  22917. for ( const texture of textures ) {
  22918. values.push( texture.id );
  22919. }
  22920. return hashArray( values );
  22921. }
  22922. const _chainKeys$3 = [];
  22923. const _defaultScene = /*@__PURE__*/ new Scene();
  22924. const _defaultCamera = /*@__PURE__*/ new Camera();
  22925. /**
  22926. * This module manages the render contexts of the renderer.
  22927. *
  22928. * @private
  22929. */
  22930. class RenderContexts {
  22931. /**
  22932. * Constructs a new render context management component.
  22933. */
  22934. constructor() {
  22935. /**
  22936. * A dictionary that manages render contexts in chain maps
  22937. * for each attachment state.
  22938. *
  22939. * @type {Object<string,ChainMap>}
  22940. */
  22941. this.chainMaps = {};
  22942. }
  22943. /**
  22944. * Returns a render context for the given scene, camera and render target.
  22945. *
  22946. * @param {Scene} scene - The scene.
  22947. * @param {Camera} camera - The camera that is used to render the scene.
  22948. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  22949. * @param {?MRT} [mrt=null] - The active multiple render target.
  22950. * @return {RenderContext} The render context.
  22951. */
  22952. get( scene, camera, renderTarget = null, mrt = null ) {
  22953. _chainKeys$3[ 0 ] = scene;
  22954. _chainKeys$3[ 1 ] = camera;
  22955. if ( mrt !== null ) {
  22956. _chainKeys$3[ 2 ] = mrt;
  22957. }
  22958. let attachmentState;
  22959. if ( renderTarget === null ) {
  22960. attachmentState = 'default';
  22961. } else {
  22962. const format = renderTarget.texture.format;
  22963. const count = renderTarget.textures.length;
  22964. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  22965. }
  22966. const chainMap = this._getChainMap( attachmentState );
  22967. let renderState = chainMap.get( _chainKeys$3 );
  22968. if ( renderState === undefined ) {
  22969. renderState = new RenderContext();
  22970. chainMap.set( _chainKeys$3, renderState );
  22971. }
  22972. _chainKeys$3.length = 0;
  22973. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  22974. return renderState;
  22975. }
  22976. /**
  22977. * Returns a render context intended for clear operations.
  22978. *
  22979. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  22980. * @return {RenderContext} The render context.
  22981. */
  22982. getForClear( renderTarget = null ) {
  22983. return this.get( _defaultScene, _defaultCamera, renderTarget );
  22984. }
  22985. /**
  22986. * Returns a chain map for the given attachment state.
  22987. *
  22988. * @private
  22989. * @param {string} attachmentState - The attachment state.
  22990. * @return {ChainMap} The chain map.
  22991. */
  22992. _getChainMap( attachmentState ) {
  22993. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  22994. }
  22995. /**
  22996. * Frees internal resources.
  22997. */
  22998. dispose() {
  22999. this.chainMaps = {};
  23000. }
  23001. }
  23002. const _size$3 = /*@__PURE__*/ new Vector3();
  23003. /**
  23004. * This module manages the textures of the renderer.
  23005. *
  23006. * @private
  23007. * @augments DataMap
  23008. */
  23009. class Textures extends DataMap {
  23010. /**
  23011. * Constructs a new texture management component.
  23012. *
  23013. * @param {Renderer} renderer - The renderer.
  23014. * @param {Backend} backend - The renderer's backend.
  23015. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  23016. */
  23017. constructor( renderer, backend, info ) {
  23018. super();
  23019. /**
  23020. * The renderer.
  23021. *
  23022. * @type {Renderer}
  23023. */
  23024. this.renderer = renderer;
  23025. /**
  23026. * The backend.
  23027. *
  23028. * @type {Backend}
  23029. */
  23030. this.backend = backend;
  23031. /**
  23032. * Renderer component for managing metrics and monitoring data.
  23033. *
  23034. * @type {Info}
  23035. */
  23036. this.info = info;
  23037. }
  23038. /**
  23039. * Updates the given render target. Based on the given render target configuration,
  23040. * it updates the texture states representing the attachments of the framebuffer.
  23041. *
  23042. * @param {RenderTarget} renderTarget - The render target to update.
  23043. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  23044. */
  23045. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  23046. const renderTargetData = this.get( renderTarget );
  23047. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  23048. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  23049. const textures = renderTarget.textures;
  23050. const size = this.getSize( textures[ 0 ] );
  23051. const mipWidth = size.width >> activeMipmapLevel;
  23052. const mipHeight = size.height >> activeMipmapLevel;
  23053. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  23054. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  23055. let textureNeedsUpdate = false;
  23056. if ( depthTexture === undefined && useDepthTexture ) {
  23057. depthTexture = new DepthTexture();
  23058. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  23059. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  23060. depthTexture.image.width = mipWidth;
  23061. depthTexture.image.height = mipHeight;
  23062. depthTexture.image.depth = size.depth;
  23063. depthTexture.renderTarget = renderTarget;
  23064. depthTexture.isArrayTexture = renderTarget.multiview === true && size.depth > 1;
  23065. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  23066. }
  23067. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  23068. textureNeedsUpdate = true;
  23069. if ( depthTexture ) {
  23070. depthTexture.needsUpdate = true;
  23071. depthTexture.image.width = mipWidth;
  23072. depthTexture.image.height = mipHeight;
  23073. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  23074. }
  23075. }
  23076. renderTargetData.width = size.width;
  23077. renderTargetData.height = size.height;
  23078. renderTargetData.textures = textures;
  23079. renderTargetData.depthTexture = depthTexture || null;
  23080. renderTargetData.depth = renderTarget.depthBuffer;
  23081. renderTargetData.stencil = renderTarget.stencilBuffer;
  23082. renderTargetData.renderTarget = renderTarget;
  23083. if ( renderTargetData.sampleCount !== sampleCount ) {
  23084. textureNeedsUpdate = true;
  23085. if ( depthTexture ) {
  23086. depthTexture.needsUpdate = true;
  23087. }
  23088. renderTargetData.sampleCount = sampleCount;
  23089. }
  23090. //
  23091. const options = { sampleCount };
  23092. // XR render targets require no texture updates
  23093. if ( renderTarget.isXRRenderTarget !== true ) {
  23094. for ( let i = 0; i < textures.length; i ++ ) {
  23095. const texture = textures[ i ];
  23096. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  23097. this.updateTexture( texture, options );
  23098. }
  23099. if ( depthTexture ) {
  23100. this.updateTexture( depthTexture, options );
  23101. }
  23102. }
  23103. // dispose handler
  23104. if ( renderTargetData.initialized !== true ) {
  23105. renderTargetData.initialized = true;
  23106. // dispose
  23107. renderTargetData.onDispose = () => {
  23108. this._destroyRenderTarget( renderTarget );
  23109. };
  23110. renderTarget.addEventListener( 'dispose', renderTargetData.onDispose );
  23111. }
  23112. }
  23113. /**
  23114. * Updates the given texture. Depending on the texture state, this method
  23115. * triggers the upload of texture data to the GPU memory. If the texture data are
  23116. * not yet ready for the upload, it uses default texture data for as a placeholder.
  23117. *
  23118. * @param {Texture} texture - The texture to update.
  23119. * @param {Object} [options={}] - The options.
  23120. */
  23121. updateTexture( texture, options = {} ) {
  23122. const textureData = this.get( texture );
  23123. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  23124. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  23125. const backend = this.backend;
  23126. if ( isRenderTarget && textureData.initialized === true ) {
  23127. // it's an update
  23128. backend.destroyTexture( texture );
  23129. }
  23130. //
  23131. if ( texture.isFramebufferTexture ) {
  23132. const renderTarget = this.renderer.getRenderTarget();
  23133. if ( renderTarget ) {
  23134. texture.type = renderTarget.texture.type;
  23135. } else {
  23136. texture.type = UnsignedByteType;
  23137. }
  23138. }
  23139. //
  23140. const { width, height, depth } = this.getSize( texture );
  23141. options.width = width;
  23142. options.height = height;
  23143. options.depth = depth;
  23144. options.needsMipmaps = this.needsMipmaps( texture );
  23145. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  23146. // TODO: Uniformly handle mipmap definitions
  23147. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  23148. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  23149. if ( texture.isCubeTexture && texture.mipmaps.length > 0 ) options.levels ++;
  23150. //
  23151. if ( isRenderTarget || texture.isStorageTexture === true || texture.isExternalTexture === true ) {
  23152. backend.createTexture( texture, options );
  23153. textureData.generation = texture.version;
  23154. } else {
  23155. if ( texture.version > 0 ) {
  23156. const image = texture.image;
  23157. if ( image === undefined ) {
  23158. warn( 'Renderer: Texture marked for update but image is undefined.' );
  23159. } else if ( image.complete === false ) {
  23160. warn( 'Renderer: Texture marked for update but image is incomplete.' );
  23161. } else {
  23162. if ( texture.images ) {
  23163. const images = [];
  23164. for ( const image of texture.images ) {
  23165. images.push( image );
  23166. }
  23167. options.images = images;
  23168. } else {
  23169. options.image = image;
  23170. }
  23171. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  23172. backend.createTexture( texture, options );
  23173. textureData.isDefaultTexture = false;
  23174. textureData.generation = texture.version;
  23175. }
  23176. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  23177. const skipAutoGeneration = texture.isStorageTexture === true && texture.mipmapsAutoUpdate === false;
  23178. if ( options.needsMipmaps && texture.mipmaps.length === 0 && ! skipAutoGeneration ) {
  23179. backend.generateMipmaps( texture );
  23180. }
  23181. if ( texture.onUpdate ) texture.onUpdate( texture );
  23182. }
  23183. } else {
  23184. // async update
  23185. backend.createDefaultTexture( texture );
  23186. textureData.isDefaultTexture = true;
  23187. textureData.generation = texture.version;
  23188. }
  23189. }
  23190. // dispose handler
  23191. if ( textureData.initialized !== true ) {
  23192. textureData.initialized = true;
  23193. textureData.generation = texture.version;
  23194. //
  23195. this.info.memory.textures ++;
  23196. //
  23197. if ( texture.isVideoTexture && ColorManagement.enabled === true && ColorManagement.getTransfer( texture.colorSpace ) !== SRGBTransfer ) {
  23198. warn( 'WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace.' );
  23199. }
  23200. // dispose
  23201. textureData.onDispose = () => {
  23202. this._destroyTexture( texture );
  23203. };
  23204. texture.addEventListener( 'dispose', textureData.onDispose );
  23205. }
  23206. //
  23207. textureData.version = texture.version;
  23208. }
  23209. /**
  23210. * Updates the sampler for the given texture. This method has no effect
  23211. * for the WebGL backend since it has no concept of samplers. Texture
  23212. * parameters are configured with the `texParameter()` command for each
  23213. * texture.
  23214. *
  23215. * In WebGPU, samplers are objects like textures and it's possible to share
  23216. * them when the texture parameters match.
  23217. *
  23218. * @param {Texture} texture - The texture to update the sampler for.
  23219. * @return {string} The current sampler key.
  23220. */
  23221. updateSampler( texture ) {
  23222. return this.backend.updateSampler( texture );
  23223. }
  23224. /**
  23225. * Computes the size of the given texture and writes the result
  23226. * into the target vector. This vector is also returned by the
  23227. * method.
  23228. *
  23229. * If no texture data are available for the compute yet, the method
  23230. * returns default size values.
  23231. *
  23232. * @param {Texture} texture - The texture to compute the size for.
  23233. * @param {Vector3} target - The target vector.
  23234. * @return {Vector3} The target vector.
  23235. */
  23236. getSize( texture, target = _size$3 ) {
  23237. let image = texture.images ? texture.images[ 0 ] : texture.image;
  23238. if ( image ) {
  23239. if ( image.image !== undefined ) image = image.image;
  23240. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( image instanceof HTMLVideoElement ) ) {
  23241. target.width = image.videoWidth || 1;
  23242. target.height = image.videoHeight || 1;
  23243. target.depth = 1;
  23244. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( image instanceof VideoFrame ) ) {
  23245. target.width = image.displayWidth || 1;
  23246. target.height = image.displayHeight || 1;
  23247. target.depth = 1;
  23248. } else {
  23249. target.width = image.width || 1;
  23250. target.height = image.height || 1;
  23251. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  23252. }
  23253. } else {
  23254. target.width = target.height = target.depth = 1;
  23255. }
  23256. return target;
  23257. }
  23258. /**
  23259. * Computes the number of mipmap levels for the given texture.
  23260. *
  23261. * @param {Texture} texture - The texture.
  23262. * @param {number} width - The texture's width.
  23263. * @param {number} height - The texture's height.
  23264. * @return {number} The number of mipmap levels.
  23265. */
  23266. getMipLevels( texture, width, height ) {
  23267. let mipLevelCount;
  23268. if ( texture.mipmaps.length > 0 ) {
  23269. mipLevelCount = texture.mipmaps.length;
  23270. } else {
  23271. if ( texture.isCompressedTexture === true ) {
  23272. // it is not possible to compute mipmaps for compressed textures. So
  23273. // when no mipmaps are defined in "texture.mipmaps", force a texture
  23274. // level of 1
  23275. mipLevelCount = 1;
  23276. } else {
  23277. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  23278. }
  23279. }
  23280. return mipLevelCount;
  23281. }
  23282. /**
  23283. * Returns `true` if the given texture makes use of mipmapping.
  23284. *
  23285. * @param {Texture} texture - The texture.
  23286. * @return {boolean} Whether mipmaps are required or not.
  23287. */
  23288. needsMipmaps( texture ) {
  23289. return texture.generateMipmaps === true || texture.mipmaps.length > 0;
  23290. }
  23291. /**
  23292. * Frees internal resources when the given render target isn't
  23293. * required anymore.
  23294. *
  23295. * @param {RenderTarget} renderTarget - The render target to destroy.
  23296. */
  23297. _destroyRenderTarget( renderTarget ) {
  23298. if ( this.has( renderTarget ) === true ) {
  23299. const renderTargetData = this.get( renderTarget );
  23300. const textures = renderTargetData.textures;
  23301. const depthTexture = renderTargetData.depthTexture;
  23302. //
  23303. renderTarget.removeEventListener( 'dispose', renderTargetData.onDispose );
  23304. //
  23305. for ( let i = 0; i < textures.length; i ++ ) {
  23306. this._destroyTexture( textures[ i ] );
  23307. }
  23308. if ( depthTexture ) {
  23309. this._destroyTexture( depthTexture );
  23310. }
  23311. this.delete( renderTarget );
  23312. this.backend.delete( renderTarget );
  23313. }
  23314. }
  23315. /**
  23316. * Frees internal resource when the given texture isn't
  23317. * required anymore.
  23318. *
  23319. * @param {Texture} texture - The texture to destroy.
  23320. */
  23321. _destroyTexture( texture ) {
  23322. if ( this.has( texture ) === true ) {
  23323. const textureData = this.get( texture );
  23324. //
  23325. texture.removeEventListener( 'dispose', textureData.onDispose );
  23326. // if a texture is not ready for use, it falls back to a default texture so it's possible
  23327. // to use it for rendering. If a texture in this state is disposed, it's important to
  23328. // not destroy/delete the underlying GPU texture object since it is cached and shared with
  23329. // other textures.
  23330. const isDefaultTexture = textureData.isDefaultTexture;
  23331. this.backend.destroyTexture( texture, isDefaultTexture );
  23332. this.delete( texture );
  23333. this.info.memory.textures --;
  23334. }
  23335. }
  23336. }
  23337. /**
  23338. * A four-component version of {@link Color} which is internally
  23339. * used by the renderer to represents clear color with alpha as
  23340. * one object.
  23341. *
  23342. * @private
  23343. * @augments Color
  23344. */
  23345. class Color4 extends Color {
  23346. /**
  23347. * Constructs a new four-component color.
  23348. * You can also pass a single THREE.Color, hex or
  23349. * string argument to this constructor.
  23350. *
  23351. * @param {number|string} [r=1] - The red value.
  23352. * @param {number} [g=1] - The green value.
  23353. * @param {number} [b=1] - The blue value.
  23354. * @param {number} [a=1] - The alpha value.
  23355. */
  23356. constructor( r, g, b, a = 1 ) {
  23357. super( r, g, b );
  23358. this.a = a;
  23359. }
  23360. /**
  23361. * Overwrites the default to honor alpha.
  23362. * You can also pass a single THREE.Color, hex or
  23363. * string argument to this method.
  23364. *
  23365. * @param {number|string|Color} r - The red value.
  23366. * @param {number} [g] - The green value.
  23367. * @param {number} [b] - The blue value.
  23368. * @param {number} [a=1] - The alpha value.
  23369. * @return {Color4} A reference to this object.
  23370. */
  23371. set( r, g, b, a = 1 ) {
  23372. this.a = a;
  23373. return super.set( r, g, b );
  23374. }
  23375. /**
  23376. * Overwrites the default to honor alpha.
  23377. *
  23378. * @param {Color4} color - The color to copy.
  23379. * @return {Color4} A reference to this object.
  23380. */
  23381. copy( color ) {
  23382. if ( color.a !== undefined ) this.a = color.a;
  23383. return super.copy( color );
  23384. }
  23385. /**
  23386. * Overwrites the default to honor alpha.
  23387. *
  23388. * @return {Color4} The cloned color.
  23389. */
  23390. clone() {
  23391. return new this.constructor( this.r, this.g, this.b, this.a );
  23392. }
  23393. }
  23394. /**
  23395. * Special version of {@link PropertyNode} which is used for parameters.
  23396. *
  23397. * @augments PropertyNode
  23398. */
  23399. class ParameterNode extends PropertyNode {
  23400. static get type() {
  23401. return 'ParameterNode';
  23402. }
  23403. /**
  23404. * Constructs a new parameter node.
  23405. *
  23406. * @param {string} nodeType - The type of the node.
  23407. * @param {?string} [name=null] - The name of the parameter in the shader.
  23408. */
  23409. constructor( nodeType, name = null ) {
  23410. super( nodeType, name );
  23411. /**
  23412. * This flag can be used for type testing.
  23413. *
  23414. * @type {boolean}
  23415. * @readonly
  23416. * @default true
  23417. */
  23418. this.isParameterNode = true;
  23419. }
  23420. /**
  23421. * Gets the type of a member variable in the parameter node.
  23422. *
  23423. * @param {NodeBuilder} builder - The node builder.
  23424. * @param {string} name - The name of the member variable.
  23425. * @returns {string}
  23426. */
  23427. getMemberType( builder, name ) {
  23428. const type = this.getNodeType( builder );
  23429. const struct = builder.getStructTypeNode( type );
  23430. let memberType;
  23431. if ( struct !== null ) {
  23432. memberType = struct.getMemberType( builder, name );
  23433. } else {
  23434. error( `TSL: Member "${ name }" not found in struct "${ type }".` );
  23435. memberType = 'float';
  23436. }
  23437. return memberType;
  23438. }
  23439. getHash() {
  23440. return this.uuid;
  23441. }
  23442. generate() {
  23443. return this.name;
  23444. }
  23445. }
  23446. /**
  23447. * TSL function for creating a parameter node.
  23448. *
  23449. * @tsl
  23450. * @function
  23451. * @param {string} type - The type of the node.
  23452. * @param {?string} name - The name of the parameter in the shader.
  23453. * @returns {ParameterNode}
  23454. */
  23455. const parameter = ( type, name ) => new ParameterNode( type, name );
  23456. /**
  23457. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  23458. * They are usually needed in cases like `If`, `Else`.
  23459. *
  23460. * @augments Node
  23461. */
  23462. class StackNode extends Node {
  23463. static get type() {
  23464. return 'StackNode';
  23465. }
  23466. /**
  23467. * Constructs a new stack node.
  23468. *
  23469. * @param {?StackNode} [parent=null] - The parent stack node.
  23470. */
  23471. constructor( parent = null ) {
  23472. super();
  23473. /**
  23474. * List of nodes.
  23475. *
  23476. * @type {Array<Node>}
  23477. */
  23478. this.nodes = [];
  23479. /**
  23480. * The output node.
  23481. *
  23482. * @type {?Node}
  23483. * @default null
  23484. */
  23485. this.outputNode = null;
  23486. /**
  23487. * The parent stack node.
  23488. *
  23489. * @type {?StackNode}
  23490. * @default null
  23491. */
  23492. this.parent = parent;
  23493. /**
  23494. * The current conditional node.
  23495. *
  23496. * @private
  23497. * @type {ConditionalNode}
  23498. * @default null
  23499. */
  23500. this._currentCond = null;
  23501. /**
  23502. * The expression node. Only
  23503. * relevant for Switch/Case.
  23504. *
  23505. * @private
  23506. * @type {Node}
  23507. * @default null
  23508. */
  23509. this._expressionNode = null;
  23510. /**
  23511. * The current node being processed.
  23512. *
  23513. * @private
  23514. * @type {Node}
  23515. * @default null
  23516. */
  23517. this._currentNode = null;
  23518. /**
  23519. * This flag can be used for type testing.
  23520. *
  23521. * @type {boolean}
  23522. * @readonly
  23523. * @default true
  23524. */
  23525. this.isStackNode = true;
  23526. }
  23527. getElementType( builder ) {
  23528. return this.hasOutput ? this.outputNode.getElementType( builder ) : 'void';
  23529. }
  23530. getNodeType( builder ) {
  23531. return this.hasOutput ? this.outputNode.getNodeType( builder ) : 'void';
  23532. }
  23533. getMemberType( builder, name ) {
  23534. return this.hasOutput ? this.outputNode.getMemberType( builder, name ) : 'void';
  23535. }
  23536. /**
  23537. * Adds a node to this stack.
  23538. *
  23539. * @param {Node} node - The node to add.
  23540. * @param {number} [index=this.nodes.length] - The index where the node should be added.
  23541. * @return {StackNode} A reference to this stack node.
  23542. */
  23543. addToStack( node, index = this.nodes.length ) {
  23544. if ( node.isNode !== true ) {
  23545. error( 'TSL: Invalid node added to stack.' );
  23546. return this;
  23547. }
  23548. this.nodes.splice( index, 0, node );
  23549. return this;
  23550. }
  23551. /**
  23552. * Adds a node to the stack before the current node.
  23553. *
  23554. * @param {Node} node - The node to add.
  23555. * @return {StackNode} A reference to this stack node.
  23556. */
  23557. addToStackBefore( node ) {
  23558. const index = this._currentNode ? this.nodes.indexOf( this._currentNode ) : 0;
  23559. return this.addToStack( node, index );
  23560. }
  23561. /**
  23562. * Represent an `if` statement in TSL.
  23563. *
  23564. * @param {Node} boolNode - Represents the condition.
  23565. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23566. * @return {StackNode} A reference to this stack node.
  23567. */
  23568. If( boolNode, method ) {
  23569. const methodNode = new ShaderNode( method );
  23570. this._currentCond = select( boolNode, methodNode );
  23571. return this.addToStack( this._currentCond );
  23572. }
  23573. /**
  23574. * Represent an `elseif` statement in TSL.
  23575. *
  23576. * @param {Node} boolNode - Represents the condition.
  23577. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23578. * @return {StackNode} A reference to this stack node.
  23579. */
  23580. ElseIf( boolNode, method ) {
  23581. const methodNode = new ShaderNode( method );
  23582. const ifNode = select( boolNode, methodNode );
  23583. this._currentCond.elseNode = ifNode;
  23584. this._currentCond = ifNode;
  23585. return this;
  23586. }
  23587. /**
  23588. * Represent an `else` statement in TSL.
  23589. *
  23590. * @param {Function} method - TSL code which is executed in the `else` case.
  23591. * @return {StackNode} A reference to this stack node.
  23592. */
  23593. Else( method ) {
  23594. this._currentCond.elseNode = new ShaderNode( method );
  23595. return this;
  23596. }
  23597. /**
  23598. * Represents a `switch` statement in TSL.
  23599. *
  23600. * @param {any} expression - Represents the expression.
  23601. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23602. * @return {StackNode} A reference to this stack node.
  23603. */
  23604. Switch( expression ) {
  23605. this._expressionNode = nodeObject( expression );
  23606. return this;
  23607. }
  23608. /**
  23609. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  23610. * The last parameter must be the callback method that should be executed in the `true` case.
  23611. *
  23612. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  23613. * @return {StackNode} A reference to this stack node.
  23614. */
  23615. Case( ...params ) {
  23616. const caseNodes = [];
  23617. // extract case nodes from the parameter list
  23618. if ( params.length >= 2 ) {
  23619. for ( let i = 0; i < params.length - 1; i ++ ) {
  23620. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  23621. }
  23622. } else {
  23623. error( 'TSL: Invalid parameter length. Case() requires at least two parameters.' );
  23624. }
  23625. // extract method
  23626. const method = params[ params.length - 1 ];
  23627. const methodNode = new ShaderNode( method );
  23628. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  23629. let caseNode = caseNodes[ 0 ];
  23630. for ( let i = 1; i < caseNodes.length; i ++ ) {
  23631. caseNode = caseNode.or( caseNodes[ i ] );
  23632. }
  23633. // build condition
  23634. const condNode = select( caseNode, methodNode );
  23635. if ( this._currentCond === null ) {
  23636. this._currentCond = condNode;
  23637. return this.addToStack( this._currentCond );
  23638. } else {
  23639. this._currentCond.elseNode = condNode;
  23640. this._currentCond = condNode;
  23641. return this;
  23642. }
  23643. }
  23644. /**
  23645. * Represents the default code block of a Switch/Case statement.
  23646. *
  23647. * @param {Function} method - TSL code which is executed in the `else` case.
  23648. * @return {StackNode} A reference to this stack node.
  23649. */
  23650. Default( method ) {
  23651. this.Else( method );
  23652. return this;
  23653. }
  23654. setup( builder ) {
  23655. const nodeProperties = builder.getNodeProperties( this );
  23656. let index = 0;
  23657. for ( const childNode of this.getChildren() ) {
  23658. if ( childNode.isVarNode && childNode.isIntent( builder ) ) {
  23659. if ( childNode.isAssign( builder ) !== true ) {
  23660. continue;
  23661. }
  23662. }
  23663. nodeProperties[ 'node' + index ++ ] = childNode;
  23664. }
  23665. // return a outputNode if exists or null
  23666. return nodeProperties.outputNode || null;
  23667. }
  23668. get hasOutput() {
  23669. return this.outputNode && this.outputNode.isNode;
  23670. }
  23671. build( builder, ...params ) {
  23672. const previousStack = getCurrentStack();
  23673. const buildStage = builder.buildStage;
  23674. setCurrentStack( this );
  23675. builder.setActiveStack( this );
  23676. //
  23677. const buildNode = ( node ) => {
  23678. this._currentNode = node;
  23679. if ( node.isVarNode && node.isIntent( builder ) ) {
  23680. if ( node.isAssign( builder ) !== true ) {
  23681. return;
  23682. }
  23683. }
  23684. if ( buildStage === 'setup' ) {
  23685. node.build( builder );
  23686. } else if ( buildStage === 'analyze' ) {
  23687. node.build( builder, this );
  23688. } else if ( buildStage === 'generate' ) {
  23689. const stages = builder.getDataFromNode( node, 'any' ).stages;
  23690. const parents = stages && stages[ builder.shaderStage ];
  23691. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  23692. return; // skip var nodes that are only used in .toVarying()
  23693. }
  23694. node.build( builder, 'void' );
  23695. }
  23696. };
  23697. //
  23698. const nodes = [ ...this.nodes ];
  23699. for ( const node of nodes ) {
  23700. buildNode( node );
  23701. }
  23702. this._currentNode = null;
  23703. const newNodes = this.nodes.filter( ( node ) => nodes.indexOf( node ) === -1 );
  23704. for ( const node of newNodes ) {
  23705. buildNode( node );
  23706. }
  23707. //
  23708. let result;
  23709. if ( this.hasOutput ) {
  23710. result = this.outputNode.build( builder, ...params );
  23711. } else {
  23712. result = super.build( builder, ...params );
  23713. }
  23714. setCurrentStack( previousStack );
  23715. builder.removeActiveStack( this );
  23716. return result;
  23717. }
  23718. }
  23719. /**
  23720. * TSL function for creating a stack node.
  23721. *
  23722. * @tsl
  23723. * @function
  23724. * @param {?StackNode} [parent=null] - The parent stack node.
  23725. * @returns {StackNode}
  23726. */
  23727. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  23728. /**
  23729. * Generates a layout for struct members.
  23730. * This function takes an object representing struct members and returns an array of member layouts.
  23731. * Each member layout includes the member's name, type, and whether it is atomic.
  23732. *
  23733. * @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.
  23734. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  23735. */
  23736. function getMembersLayout( members ) {
  23737. return Object.entries( members ).map( ( [ name, value ] ) => {
  23738. if ( typeof value === 'string' ) {
  23739. return { name, type: value, atomic: false };
  23740. }
  23741. return { name, type: value.type, atomic: value.atomic || false };
  23742. } );
  23743. }
  23744. /**
  23745. * Represents a struct type node in the node-based system.
  23746. * This class is used to define and manage the layout and types of struct members.
  23747. * It extends the base Node class and provides methods to get the length of the struct,
  23748. * retrieve member types, and generate the struct type for a builder.
  23749. *
  23750. * @augments Node
  23751. */
  23752. class StructTypeNode extends Node {
  23753. static get type() {
  23754. return 'StructTypeNode';
  23755. }
  23756. /**
  23757. * Creates an instance of StructTypeNode.
  23758. *
  23759. * @param {Object} membersLayout - The layout of the members for the struct.
  23760. * @param {?string} [name=null] - The optional name of the struct.
  23761. */
  23762. constructor( membersLayout, name = null ) {
  23763. super( 'struct' );
  23764. /**
  23765. * The layout of the members for the struct
  23766. *
  23767. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  23768. */
  23769. this.membersLayout = getMembersLayout( membersLayout );
  23770. /**
  23771. * The name of the struct.
  23772. *
  23773. * @type {?string}
  23774. * @default null
  23775. */
  23776. this.name = name;
  23777. /**
  23778. * This flag can be used for type testing.
  23779. *
  23780. * @type {boolean}
  23781. * @readonly
  23782. * @default true
  23783. */
  23784. this.isStructLayoutNode = true;
  23785. }
  23786. /**
  23787. * Returns the length of the struct.
  23788. * The length is calculated by summing the lengths of the struct's members.
  23789. *
  23790. * @returns {number} The length of the struct.
  23791. */
  23792. getLength() {
  23793. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  23794. let maxAlignment = 1; // maximum alignment value in this struct
  23795. let offset = 0; // global buffer offset in 4 byte elements
  23796. for ( const member of this.membersLayout ) {
  23797. const type = member.type;
  23798. const itemSize = getMemoryLengthFromType( type );
  23799. const alignment = getAlignmentFromType( type ) / BYTES_PER_ELEMENT;
  23800. maxAlignment = Math.max( maxAlignment, alignment );
  23801. const chunkOffset = offset % maxAlignment; // offset in the current chunk of maxAlignment elements
  23802. const overhang = chunkOffset % alignment; // distance from the last aligned offset
  23803. if ( overhang !== 0 ) {
  23804. offset += alignment - overhang; // move to next aligned offset
  23805. }
  23806. offset += itemSize;
  23807. }
  23808. return ( Math.ceil( offset / maxAlignment ) * maxAlignment ); // ensure length is a multiple of maxAlignment
  23809. }
  23810. getMemberType( builder, name ) {
  23811. const member = this.membersLayout.find( m => m.name === name );
  23812. return member ? member.type : 'void';
  23813. }
  23814. getNodeType( builder ) {
  23815. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  23816. return structType.name;
  23817. }
  23818. setup( builder ) {
  23819. builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  23820. builder.addInclude( this );
  23821. }
  23822. generate( builder ) {
  23823. return this.getNodeType( builder );
  23824. }
  23825. }
  23826. /**
  23827. * StructNode allows to create custom structures with multiple members.
  23828. * This can also be used to define structures in attribute and uniform data.
  23829. *
  23830. * ```js
  23831. * // Define a custom struct
  23832. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  23833. *
  23834. * // Create a new instance of the struct
  23835. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  23836. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  23837. *
  23838. * // Access the struct members
  23839. * const min = bb.get( 'min' );
  23840. *
  23841. * // Assign a new value to a member
  23842. * min.assign( vec3() );
  23843. * ```
  23844. * @augments Node
  23845. */
  23846. class StructNode extends Node {
  23847. static get type() {
  23848. return 'StructNode';
  23849. }
  23850. constructor( structTypeNode, values ) {
  23851. super( 'vec3' );
  23852. this.structTypeNode = structTypeNode;
  23853. this.values = values;
  23854. this.isStructNode = true;
  23855. }
  23856. getNodeType( builder ) {
  23857. return this.structTypeNode.getNodeType( builder );
  23858. }
  23859. getMemberType( builder, name ) {
  23860. return this.structTypeNode.getMemberType( builder, name );
  23861. }
  23862. generate( builder ) {
  23863. const nodeVar = builder.getVarFromNode( this );
  23864. const structType = nodeVar.type;
  23865. const propertyName = builder.getPropertyName( nodeVar );
  23866. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structTypeNode.membersLayout, this.values ) }`, this );
  23867. return nodeVar.name;
  23868. }
  23869. }
  23870. /**
  23871. * TSL function for creating a struct node.
  23872. *
  23873. * @tsl
  23874. * @function
  23875. * @param {Object} membersLayout - The layout of the struct members.
  23876. * @param {?string} [name=null] - The name of the struct.
  23877. * @returns {Function} The struct function.
  23878. */
  23879. const struct = ( membersLayout, name = null ) => {
  23880. const structLayout = new StructTypeNode( membersLayout, name );
  23881. const struct = ( ...params ) => {
  23882. let values = null;
  23883. if ( params.length > 0 ) {
  23884. if ( params[ 0 ].isNode ) {
  23885. values = {};
  23886. const names = Object.keys( membersLayout );
  23887. for ( let i = 0; i < params.length; i ++ ) {
  23888. values[ names[ i ] ] = params[ i ];
  23889. }
  23890. } else {
  23891. values = params[ 0 ];
  23892. }
  23893. }
  23894. return new StructNode( structLayout, values );
  23895. };
  23896. struct.layout = structLayout;
  23897. struct.isStruct = true;
  23898. return struct;
  23899. };
  23900. /**
  23901. * This node can be used to define multiple outputs in a shader programs.
  23902. *
  23903. * @augments Node
  23904. */
  23905. class OutputStructNode extends Node {
  23906. static get type() {
  23907. return 'OutputStructNode';
  23908. }
  23909. /**
  23910. * Constructs a new output struct node. The constructor can be invoked with an
  23911. * arbitrary number of nodes representing the members.
  23912. *
  23913. * @param {...Node} members - A parameter list of nodes.
  23914. */
  23915. constructor( ...members ) {
  23916. super();
  23917. /**
  23918. * An array of nodes which defines the output.
  23919. *
  23920. * @type {Array<Node>}
  23921. */
  23922. this.members = members;
  23923. /**
  23924. * This flag can be used for type testing.
  23925. *
  23926. * @type {boolean}
  23927. * @readonly
  23928. * @default true
  23929. */
  23930. this.isOutputStructNode = true;
  23931. }
  23932. getNodeType( builder ) {
  23933. const properties = builder.getNodeProperties( this );
  23934. if ( properties.membersLayout === undefined ) {
  23935. const members = this.members;
  23936. const membersLayout = [];
  23937. for ( let i = 0; i < members.length; i ++ ) {
  23938. const name = 'm' + i;
  23939. const type = members[ i ].getNodeType( builder );
  23940. membersLayout.push( { name, type, index: i } );
  23941. }
  23942. properties.membersLayout = membersLayout;
  23943. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  23944. }
  23945. return properties.structType.name;
  23946. }
  23947. generate( builder ) {
  23948. const propertyName = builder.getOutputStructName();
  23949. const members = this.members;
  23950. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  23951. for ( let i = 0; i < members.length; i ++ ) {
  23952. const snippet = members[ i ].build( builder );
  23953. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  23954. }
  23955. return propertyName;
  23956. }
  23957. }
  23958. /**
  23959. * TSL function for creating an output struct node.
  23960. *
  23961. * @tsl
  23962. * @function
  23963. * @param {...Node} members - A parameter list of nodes.
  23964. * @returns {OutputStructNode}
  23965. */
  23966. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  23967. /**
  23968. * Returns the MRT texture index for the given name.
  23969. *
  23970. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  23971. * @param {string} name - The name of the MRT texture which index is requested.
  23972. * @return {number} The texture index.
  23973. */
  23974. function getTextureIndex( textures, name ) {
  23975. for ( let i = 0; i < textures.length; i ++ ) {
  23976. if ( textures[ i ].name === name ) {
  23977. return i;
  23978. }
  23979. }
  23980. return -1;
  23981. }
  23982. /**
  23983. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  23984. * post-processing is shown below:
  23985. * ```js
  23986. * const mrtNode = mrt( {
  23987. * output: output,
  23988. * normal: normalView
  23989. * } ) );
  23990. * ```
  23991. * The MRT output is defined as a dictionary.
  23992. *
  23993. * @augments OutputStructNode
  23994. */
  23995. class MRTNode extends OutputStructNode {
  23996. static get type() {
  23997. return 'MRTNode';
  23998. }
  23999. /**
  24000. * Constructs a new output struct node.
  24001. *
  24002. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  24003. */
  24004. constructor( outputNodes ) {
  24005. super();
  24006. /**
  24007. * A dictionary representing the MRT outputs. The key
  24008. * is the name of the output, the value the node which produces
  24009. * the output result.
  24010. *
  24011. * @type {Object<string, Node>}
  24012. */
  24013. this.outputNodes = outputNodes;
  24014. /**
  24015. * This flag can be used for type testing.
  24016. *
  24017. * @type {boolean}
  24018. * @readonly
  24019. * @default true
  24020. */
  24021. this.isMRTNode = true;
  24022. }
  24023. /**
  24024. * Returns `true` if the MRT node has an output with the given name.
  24025. *
  24026. * @param {string} name - The name of the output.
  24027. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  24028. */
  24029. has( name ) {
  24030. return this.outputNodes[ name ] !== undefined;
  24031. }
  24032. /**
  24033. * Returns the output node for the given name.
  24034. *
  24035. * @param {string} name - The name of the output.
  24036. * @return {Node} The output node.
  24037. */
  24038. get( name ) {
  24039. return this.outputNodes[ name ];
  24040. }
  24041. /**
  24042. * Merges the outputs of the given MRT node with the outputs of this node.
  24043. *
  24044. * @param {MRTNode} mrtNode - The MRT to merge.
  24045. * @return {MRTNode} A new MRT node with merged outputs..
  24046. */
  24047. merge( mrtNode ) {
  24048. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  24049. return mrt( outputs );
  24050. }
  24051. setup( builder ) {
  24052. const outputNodes = this.outputNodes;
  24053. const mrt = builder.renderer.getRenderTarget();
  24054. const members = [];
  24055. const textures = mrt.textures;
  24056. for ( const name in outputNodes ) {
  24057. const index = getTextureIndex( textures, name );
  24058. members[ index ] = vec4( outputNodes[ name ] );
  24059. }
  24060. this.members = members;
  24061. return super.setup( builder );
  24062. }
  24063. }
  24064. /**
  24065. * TSL function for creating a MRT node.
  24066. *
  24067. * @tsl
  24068. * @function
  24069. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  24070. * @returns {MRTNode}
  24071. */
  24072. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  24073. /**
  24074. * This node represents an operation that reinterprets the bit representation of a value
  24075. * in one type as a value in another type.
  24076. *
  24077. * @augments TempNode
  24078. */
  24079. class BitcastNode extends TempNode {
  24080. static get type() {
  24081. return 'BitcastNode';
  24082. }
  24083. /**
  24084. * Constructs a new bitcast node.
  24085. *
  24086. * @param {Node} valueNode - The value to convert.
  24087. * @param {string} conversionType - The type to convert to.
  24088. * @param {?string} [inputType = null] - The expected input data type of the bitcast operation.
  24089. */
  24090. constructor( valueNode, conversionType, inputType = null ) {
  24091. super();
  24092. /**
  24093. * The data to bitcast to a new type.
  24094. *
  24095. * @type {Node}
  24096. */
  24097. this.valueNode = valueNode;
  24098. /**
  24099. * The type the value will be converted to.
  24100. *
  24101. * @type {string}
  24102. */
  24103. this.conversionType = conversionType;
  24104. /**
  24105. * The expected input data type of the bitcast operation.
  24106. *
  24107. *
  24108. * @type {string}
  24109. * @default null
  24110. */
  24111. this.inputType = inputType;
  24112. /**
  24113. * This flag can be used for type testing.
  24114. *
  24115. * @type {boolean}
  24116. * @readonly
  24117. * @default true
  24118. */
  24119. this.isBitcastNode = true;
  24120. }
  24121. getNodeType( builder ) {
  24122. // GLSL aliasing
  24123. if ( this.inputType !== null ) {
  24124. const valueType = this.valueNode.getNodeType( builder );
  24125. const valueLength = builder.getTypeLength( valueType );
  24126. return builder.getTypeFromLength( valueLength, this.conversionType );
  24127. }
  24128. return this.conversionType;
  24129. }
  24130. generate( builder ) {
  24131. const type = this.getNodeType( builder );
  24132. let inputType = '';
  24133. if ( this.inputType !== null ) {
  24134. const valueType = this.valueNode.getNodeType( builder );
  24135. const valueTypeLength = builder.getTypeLength( valueType );
  24136. inputType = valueTypeLength === 1 ? this.inputType : builder.changeComponentType( valueType, this.inputType );
  24137. } else {
  24138. inputType = this.valueNode.getNodeType( builder );
  24139. }
  24140. return `${ builder.getBitcastMethod( type, inputType ) }( ${ this.valueNode.build( builder, inputType ) } )`;
  24141. }
  24142. }
  24143. /**
  24144. * Reinterpret the bit representation of a value in one type as a value in another type.
  24145. *
  24146. * @tsl
  24147. * @function
  24148. * @param {Node | number} x - The parameter.
  24149. * @param {string} y - The new type.
  24150. * @returns {Node}
  24151. */
  24152. const bitcast = /*@__PURE__*/ nodeProxyIntent( BitcastNode ).setParameterLength( 2 );
  24153. /**
  24154. * Bitcasts a float or a vector of floats to a corresponding integer type with the same element size.
  24155. *
  24156. * @tsl
  24157. * @function
  24158. * @param {Node<float>} value - The float or vector of floats to bitcast.
  24159. * @returns {BitcastNode}
  24160. */
  24161. const floatBitsToInt = ( value ) => new BitcastNode( value, 'int', 'float' );
  24162. /**
  24163. * Bitcasts a float or a vector of floats to a corresponding unsigned integer type with the same element size.
  24164. *
  24165. * @tsl
  24166. * @function
  24167. * @param {Node<float>} value - The float or vector of floats to bitcast.
  24168. * @returns {BitcastNode}
  24169. */
  24170. const floatBitsToUint = ( value ) => new BitcastNode( value, 'uint', 'float' );
  24171. /**
  24172. * Bitcasts an integer or a vector of integers to a corresponding float type with the same element size.
  24173. *
  24174. * @tsl
  24175. * @function
  24176. * @param {Node<int>} value - The integer or vector of integers to bitcast.
  24177. * @returns {BitcastNode}
  24178. */
  24179. const intBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'int' );
  24180. /**
  24181. * Bitcast an unsigned integer or a vector of unsigned integers to a corresponding float type with the same element size.
  24182. *
  24183. * @tsl
  24184. * @function
  24185. * @param {Node<uint>} value - The unsigned integer or vector of unsigned integers to bitcast.
  24186. * @returns {BitcastNode}
  24187. */
  24188. const uintBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'uint' );
  24189. const registeredBitcountFunctions = {};
  24190. /**
  24191. * This node represents an operation that counts the bits of a piece of shader data.
  24192. *
  24193. * @augments MathNode
  24194. */
  24195. class BitcountNode extends MathNode {
  24196. static get type() {
  24197. return 'BitcountNode';
  24198. }
  24199. /**
  24200. * Constructs a new math node.
  24201. *
  24202. * @param {'countTrailingZeros'|'countLeadingZeros'|'countOneBits'} method - The method name.
  24203. * @param {Node} aNode - The first input.
  24204. */
  24205. constructor( method, aNode ) {
  24206. super( method, aNode );
  24207. /**
  24208. * This flag can be used for type testing.
  24209. *
  24210. * @type {boolean}
  24211. * @readonly
  24212. * @default true
  24213. */
  24214. this.isBitcountNode = true;
  24215. }
  24216. /**
  24217. * Casts the input value of the function to an integer if necessary.
  24218. *
  24219. * @private
  24220. * @param {Node<uint>|Node<int>} inputNode - The input value.
  24221. * @param {Node<uint>} outputNode - The output value.
  24222. * @param {string} elementType - The type of the input value.
  24223. */
  24224. _resolveElementType( inputNode, outputNode, elementType ) {
  24225. if ( elementType === 'int' ) {
  24226. outputNode.assign( bitcast( inputNode, 'uint' ) );
  24227. } else {
  24228. outputNode.assign( inputNode );
  24229. }
  24230. }
  24231. _returnDataNode( inputType ) {
  24232. switch ( inputType ) {
  24233. case 'uint': {
  24234. return uint;
  24235. }
  24236. case 'int': {
  24237. return int;
  24238. }
  24239. case 'uvec2': {
  24240. return uvec2;
  24241. }
  24242. case 'uvec3': {
  24243. return uvec3;
  24244. }
  24245. case 'uvec4': {
  24246. return uvec4;
  24247. }
  24248. case 'ivec2': {
  24249. return ivec2;
  24250. }
  24251. case 'ivec3': {
  24252. return ivec3;
  24253. }
  24254. case 'ivec4': {
  24255. return ivec4;
  24256. }
  24257. }
  24258. }
  24259. /**
  24260. * Creates and registers a reusable GLSL function that emulates the behavior of countTrailingZeros.
  24261. *
  24262. * @private
  24263. * @param {string} method - The name of the function to create.
  24264. * @param {string} elementType - The type of the input value.
  24265. * @returns {Function} - The generated function
  24266. */
  24267. _createTrailingZerosBaseLayout( method, elementType ) {
  24268. const outputConvertNode = this._returnDataNode( elementType );
  24269. const fnDef = Fn( ( [ value ] ) => {
  24270. const v = uint( 0.0 );
  24271. this._resolveElementType( value, v, elementType );
  24272. const f = float( v.bitAnd( negate( v ) ) );
  24273. const uintBits = floatBitsToUint( f );
  24274. const numTrailingZeros = ( uintBits.shiftRight( 23 ) ).sub( 127 );
  24275. return outputConvertNode( numTrailingZeros );
  24276. } ).setLayout( {
  24277. name: method,
  24278. type: elementType,
  24279. inputs: [
  24280. { name: 'value', type: elementType }
  24281. ]
  24282. } );
  24283. return fnDef;
  24284. }
  24285. /**
  24286. * Creates and registers a reusable GLSL function that emulates the behavior of countLeadingZeros.
  24287. *
  24288. * @private
  24289. * @param {string} method - The name of the function to create.
  24290. * @param {string} elementType - The type of the input value.
  24291. * @returns {Function} - The generated function
  24292. */
  24293. _createLeadingZerosBaseLayout( method, elementType ) {
  24294. const outputConvertNode = this._returnDataNode( elementType );
  24295. const fnDef = Fn( ( [ value ] ) => {
  24296. If( value.equal( uint( 0 ) ), () => {
  24297. return uint( 32 );
  24298. } );
  24299. const v = uint( 0 );
  24300. const n = uint( 0 );
  24301. this._resolveElementType( value, v, elementType );
  24302. If( v.shiftRight( 16 ).equal( 0 ), () => {
  24303. n.addAssign( 16 );
  24304. v.shiftLeftAssign( 16 );
  24305. } );
  24306. If( v.shiftRight( 24 ).equal( 0 ), () => {
  24307. n.addAssign( 8 );
  24308. v.shiftLeftAssign( 8 );
  24309. } );
  24310. If( v.shiftRight( 28 ).equal( 0 ), () => {
  24311. n.addAssign( 4 );
  24312. v.shiftLeftAssign( 4 );
  24313. } );
  24314. If( v.shiftRight( 30 ).equal( 0 ), () => {
  24315. n.addAssign( 2 );
  24316. v.shiftLeftAssign( 2 );
  24317. } );
  24318. If( v.shiftRight( 31 ).equal( 0 ), () => {
  24319. n.addAssign( 1 );
  24320. } );
  24321. return outputConvertNode( n );
  24322. } ).setLayout( {
  24323. name: method,
  24324. type: elementType,
  24325. inputs: [
  24326. { name: 'value', type: elementType }
  24327. ]
  24328. } );
  24329. return fnDef;
  24330. }
  24331. /**
  24332. * Creates and registers a reusable GLSL function that emulates the behavior of countOneBits.
  24333. *
  24334. * @private
  24335. * @param {string} method - The name of the function to create.
  24336. * @param {string} elementType - The type of the input value.
  24337. * @returns {Function} - The generated function
  24338. */
  24339. _createOneBitsBaseLayout( method, elementType ) {
  24340. const outputConvertNode = this._returnDataNode( elementType );
  24341. const fnDef = Fn( ( [ value ] ) => {
  24342. const v = uint( 0.0 );
  24343. this._resolveElementType( value, v, elementType );
  24344. v.assign( v.sub( v.shiftRight( uint( 1 ) ).bitAnd( uint( 0x55555555 ) ) ) );
  24345. v.assign( v.bitAnd( uint( 0x33333333 ) ).add( v.shiftRight( uint( 2 ) ).bitAnd( uint( 0x33333333 ) ) ) );
  24346. const numBits = v.add( v.shiftRight( uint( 4 ) ) ).bitAnd( uint( 0xF0F0F0F ) ).mul( uint( 0x1010101 ) ).shiftRight( uint( 24 ) );
  24347. return outputConvertNode( numBits );
  24348. } ).setLayout( {
  24349. name: method,
  24350. type: elementType,
  24351. inputs: [
  24352. { name: 'value', type: elementType }
  24353. ]
  24354. } );
  24355. return fnDef;
  24356. }
  24357. /**
  24358. * Creates and registers a reusable GLSL function that emulates the behavior of the specified bitcount function.
  24359. * including considerations for component-wise bitcounts on vector type inputs.
  24360. *
  24361. * @private
  24362. * @param {string} method - The name of the function to create.
  24363. * @param {string} inputType - The type of the input value.
  24364. * @param {number} typeLength - The vec length of the input value.
  24365. * @param {Function} baseFn - The base function that operates on an individual component of the vector.
  24366. * @returns {Function} - The alias function for the specified bitcount method.
  24367. */
  24368. _createMainLayout( method, inputType, typeLength, baseFn ) {
  24369. const outputConvertNode = this._returnDataNode( inputType );
  24370. const fnDef = Fn( ( [ value ] ) => {
  24371. if ( typeLength === 1 ) {
  24372. return outputConvertNode( baseFn( value ) );
  24373. } else {
  24374. const vec = outputConvertNode( 0 );
  24375. const components = [ 'x', 'y', 'z', 'w' ];
  24376. for ( let i = 0; i < typeLength; i ++ ) {
  24377. const component = components[ i ];
  24378. vec[ component ].assign( baseFn( value[ component ] ) );
  24379. }
  24380. return vec;
  24381. }
  24382. } ).setLayout( {
  24383. name: method,
  24384. type: inputType,
  24385. inputs: [
  24386. { name: 'value', type: inputType }
  24387. ]
  24388. } );
  24389. return fnDef;
  24390. }
  24391. setup( builder ) {
  24392. const { method, aNode } = this;
  24393. const { renderer } = builder;
  24394. if ( renderer.backend.isWebGPUBackend ) {
  24395. // use built-in WGSL functions for WebGPU
  24396. return super.setup( builder );
  24397. }
  24398. const inputType = this.getInputType( builder );
  24399. const elementType = builder.getElementType( inputType );
  24400. const typeLength = builder.getTypeLength( inputType );
  24401. const baseMethod = `${method}_base_${elementType}`;
  24402. const newMethod = `${method}_${inputType}`;
  24403. let baseFn = registeredBitcountFunctions[ baseMethod ];
  24404. if ( baseFn === undefined ) {
  24405. switch ( method ) {
  24406. case BitcountNode.COUNT_LEADING_ZEROS: {
  24407. baseFn = this._createLeadingZerosBaseLayout( baseMethod, elementType );
  24408. break;
  24409. }
  24410. case BitcountNode.COUNT_TRAILING_ZEROS: {
  24411. baseFn = this._createTrailingZerosBaseLayout( baseMethod, elementType );
  24412. break;
  24413. }
  24414. case BitcountNode.COUNT_ONE_BITS: {
  24415. baseFn = this._createOneBitsBaseLayout( baseMethod, elementType );
  24416. break;
  24417. }
  24418. }
  24419. registeredBitcountFunctions[ baseMethod ] = baseFn;
  24420. }
  24421. let fn = registeredBitcountFunctions[ newMethod ];
  24422. if ( fn === undefined ) {
  24423. fn = this._createMainLayout( newMethod, inputType, typeLength, baseFn );
  24424. registeredBitcountFunctions[ newMethod ] = fn;
  24425. }
  24426. const output = Fn( () => {
  24427. return fn(
  24428. aNode,
  24429. );
  24430. } );
  24431. return output();
  24432. }
  24433. }
  24434. BitcountNode.COUNT_TRAILING_ZEROS = 'countTrailingZeros';
  24435. BitcountNode.COUNT_LEADING_ZEROS = 'countLeadingZeros';
  24436. BitcountNode.COUNT_ONE_BITS = 'countOneBits';
  24437. /**
  24438. * Finds the number of consecutive 0 bits from the least significant bit of the input value,
  24439. * which is also the index of the least significant bit of the input value.
  24440. *
  24441. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  24442. *
  24443. * @tsl
  24444. * @function
  24445. * @param {Node | number} x - The input value.
  24446. * @returns {Node}
  24447. */
  24448. const countTrailingZeros = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_TRAILING_ZEROS ).setParameterLength( 1 );
  24449. /**
  24450. * Finds the number of consecutive 0 bits starting from the most significant bit of the input value.
  24451. *
  24452. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  24453. *
  24454. * @tsl
  24455. * @function
  24456. * @param {Node | number} x - The input value.
  24457. * @returns {Node}
  24458. */
  24459. const countLeadingZeros = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_LEADING_ZEROS ).setParameterLength( 1 );
  24460. /**
  24461. * Finds the number of '1' bits set in the input value
  24462. *
  24463. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  24464. *
  24465. * @tsl
  24466. * @function
  24467. * @returns {Node}
  24468. */
  24469. const countOneBits = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_ONE_BITS ).setParameterLength( 1 );
  24470. /**
  24471. * Generates a hash value in the range `[0, 1]` from the given seed.
  24472. *
  24473. * @tsl
  24474. * @function
  24475. * @param {Node<float>} seed - The seed.
  24476. * @return {Node<float>} The hash value.
  24477. */
  24478. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  24479. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  24480. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  24481. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  24482. const result = word.shiftRight( 22 ).bitXor( word );
  24483. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  24484. } );
  24485. /**
  24486. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  24487. * The corners are mapped to `0` and the center to `1`.
  24488. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24489. *
  24490. * @tsl
  24491. * @function
  24492. * @param {Node<float>} x - The value to remap.
  24493. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  24494. * @return {Node<float>} The remapped value.
  24495. */
  24496. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  24497. /**
  24498. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  24499. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  24500. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24501. *
  24502. * @tsl
  24503. * @function
  24504. * @param {Node<float>} x - The value to remap.
  24505. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  24506. * @return {Node<float>} The remapped value.
  24507. */
  24508. 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 ) );
  24509. /**
  24510. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  24511. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  24512. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24513. *
  24514. * @tsl
  24515. * @function
  24516. * @param {Node<float>} x - The value to remap.
  24517. * @param {Node<float>} a - First control parameter.
  24518. * @param {Node<float>} b - Second control parameter.
  24519. * @return {Node<float>} The remapped value.
  24520. */
  24521. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  24522. /**
  24523. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  24524. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24525. *
  24526. * @tsl
  24527. * @function
  24528. * @param {Node<float>} x - The value to compute the sin for.
  24529. * @param {Node<float>} k - Controls the amount of bounces.
  24530. * @return {Node<float>} The result value.
  24531. */
  24532. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  24533. /**
  24534. * This node represents an operation that packs floating-point values of a vector into an unsigned 32-bit integer
  24535. *
  24536. * @augments TempNode
  24537. */
  24538. class PackFloatNode extends TempNode {
  24539. static get type() {
  24540. return 'PackFloatNode';
  24541. }
  24542. /**
  24543. *
  24544. * @param {'snorm' | 'unorm' | 'float16'} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  24545. * @param {Node} vectorNode - The vector node to be packed
  24546. */
  24547. constructor( encoding, vectorNode ) {
  24548. super();
  24549. /**
  24550. * The vector to be packed.
  24551. *
  24552. * @type {Node}
  24553. */
  24554. this.vectorNode = vectorNode;
  24555. /**
  24556. * The numeric encoding.
  24557. *
  24558. * @type {string}
  24559. */
  24560. this.encoding = encoding;
  24561. /**
  24562. * This flag can be used for type testing.
  24563. *
  24564. * @type {boolean}
  24565. * @readonly
  24566. * @default true
  24567. */
  24568. this.isPackFloatNode = true;
  24569. }
  24570. getNodeType() {
  24571. return 'uint';
  24572. }
  24573. generate( builder ) {
  24574. const inputType = this.vectorNode.getNodeType( builder );
  24575. return `${ builder.getFloatPackingMethod( this.encoding ) }(${ this.vectorNode.build( builder, inputType )})`;
  24576. }
  24577. }
  24578. /**
  24579. * Converts each component of the normalized float to 16-bit integer values. The results are packed into a single unsigned integer.
  24580. * round(clamp(c, -1, +1) * 32767.0)
  24581. *
  24582. * @tsl
  24583. * @function
  24584. * @param {Node<vec2>} value - The 2-component vector to be packed
  24585. * @returns {Node}
  24586. */
  24587. const packSnorm2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'snorm' ).setParameterLength( 1 );
  24588. /**
  24589. * Converts each component of the normalized float to 16-bit integer values. The results are packed into a single unsigned integer.
  24590. * round(clamp(c, 0, +1) * 65535.0)
  24591. *
  24592. * @tsl
  24593. * @function
  24594. * @param {Node<vec2>} value - The 2-component vector to be packed
  24595. * @returns {Node}
  24596. */
  24597. const packUnorm2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'unorm' ).setParameterLength( 1 );
  24598. /**
  24599. * Converts each component of the vec2 to 16-bit floating-point values. The results are packed into a single unsigned integer.
  24600. *
  24601. * @tsl
  24602. * @function
  24603. * @param {Node<vec2>} value - The 2-component vector to be packed
  24604. * @returns {Node}
  24605. */
  24606. const packHalf2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'float16' ).setParameterLength( 1 );
  24607. /**
  24608. * This node represents an operation that unpacks values from a 32-bit unsigned integer, reinterpreting the results as a floating-point vector
  24609. *
  24610. * @augments TempNode
  24611. */
  24612. class UnpackFloatNode extends TempNode {
  24613. static get type() {
  24614. return 'UnpackFloatNode';
  24615. }
  24616. /**
  24617. *
  24618. * @param {'snorm' | 'unorm' | 'float16'} encoding - The numeric encoding that describes how the integer values are mapped to the float range
  24619. * @param {Node} uintNode - The uint node to be unpacked
  24620. */
  24621. constructor( encoding, uintNode ) {
  24622. super();
  24623. /**
  24624. * The unsigned integer to be unpacked.
  24625. *
  24626. * @type {Node}
  24627. */
  24628. this.uintNode = uintNode;
  24629. /**
  24630. * The numeric encoding.
  24631. *
  24632. * @type {string}
  24633. */
  24634. this.encoding = encoding;
  24635. /**
  24636. * This flag can be used for type testing.
  24637. *
  24638. * @type {boolean}
  24639. * @readonly
  24640. * @default true
  24641. */
  24642. this.isUnpackFloatNode = true;
  24643. }
  24644. getNodeType() {
  24645. return 'vec2';
  24646. }
  24647. generate( builder ) {
  24648. const inputType = this.uintNode.getNodeType( builder );
  24649. return `${ builder.getFloatUnpackingMethod( this.encoding ) }(${ this.uintNode.build( builder, inputType )})`;
  24650. }
  24651. }
  24652. /**
  24653. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as normalized signed integers. Returns a vec2 with both values.
  24654. *
  24655. * @tsl
  24656. * @function
  24657. * @param {Node<uint>} value - The unsigned integer to be unpacked
  24658. * @returns {Node}
  24659. */
  24660. const unpackSnorm2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'snorm' ).setParameterLength( 1 );
  24661. /**
  24662. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as normalized unsigned integers. Returns a vec2 with both values.
  24663. *
  24664. * @tsl
  24665. * @function
  24666. * @param {Node<uint>} value - The unsigned integer to be unpacked
  24667. * @returns {Node}
  24668. */
  24669. const unpackUnorm2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'unorm' ).setParameterLength( 1 );
  24670. /**
  24671. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as 16-bit floating-point numbers. Returns a vec2 with both values.
  24672. *
  24673. * @tsl
  24674. * @function
  24675. * @param {Node<uint>} value - The unsigned integer to be unpacked
  24676. * @returns {Node}
  24677. */
  24678. const unpackHalf2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'float16' ).setParameterLength( 1 );
  24679. // https://github.com/cabbibo/glsl-tri-noise-3d
  24680. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  24681. return x.fract().sub( .5 ).abs();
  24682. } ).setLayout( {
  24683. name: 'tri',
  24684. type: 'float',
  24685. inputs: [
  24686. { name: 'x', type: 'float' }
  24687. ]
  24688. } );
  24689. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  24690. 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. ) ) ) ) );
  24691. } ).setLayout( {
  24692. name: 'tri3',
  24693. type: 'vec3',
  24694. inputs: [
  24695. { name: 'p', type: 'vec3' }
  24696. ]
  24697. } );
  24698. /**
  24699. * Generates a noise value from the given position, speed and time parameters.
  24700. *
  24701. * @tsl
  24702. * @function
  24703. * @param {Node<vec3>} position - The position.
  24704. * @param {Node<float>} speed - The speed.
  24705. * @param {Node<float>} time - The time.
  24706. * @return {Node<float>} The generated noise.
  24707. */
  24708. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  24709. const p = vec3( position ).toVar();
  24710. const z = float( 1.4 ).toVar();
  24711. const rz = float( 0.0 ).toVar();
  24712. const bp = vec3( p ).toVar();
  24713. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  24714. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  24715. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  24716. bp.mulAssign( 1.8 );
  24717. z.mulAssign( 1.5 );
  24718. p.mulAssign( 1.2 );
  24719. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  24720. rz.addAssign( t.div( z ) );
  24721. bp.addAssign( 0.14 );
  24722. } );
  24723. return rz;
  24724. } ).setLayout( {
  24725. name: 'triNoise3D',
  24726. type: 'float',
  24727. inputs: [
  24728. { name: 'position', type: 'vec3' },
  24729. { name: 'speed', type: 'float' },
  24730. { name: 'time', type: 'float' }
  24731. ]
  24732. } );
  24733. /**
  24734. * This class allows to define multiple overloaded versions
  24735. * of the same function. Depending on the parameters of the function
  24736. * call, the node picks the best-fit overloaded version.
  24737. *
  24738. * @augments Node
  24739. */
  24740. class FunctionOverloadingNode extends Node {
  24741. static get type() {
  24742. return 'FunctionOverloadingNode';
  24743. }
  24744. /**
  24745. * Constructs a new function overloading node.
  24746. *
  24747. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  24748. * @param {...Node} parametersNodes - A list of parameter nodes.
  24749. */
  24750. constructor( functionNodes = [], ...parametersNodes ) {
  24751. super();
  24752. /**
  24753. * Array of `Fn` function definitions.
  24754. *
  24755. * @type {Array<Function>}
  24756. */
  24757. this.functionNodes = functionNodes;
  24758. /**
  24759. * A list of parameter nodes.
  24760. *
  24761. * @type {Array<Node>}
  24762. */
  24763. this.parametersNodes = parametersNodes;
  24764. /**
  24765. * The selected overloaded function call.
  24766. *
  24767. * @private
  24768. * @type {ShaderCallNodeInternal}
  24769. */
  24770. this._candidateFn = null;
  24771. /**
  24772. * This node is marked as global.
  24773. *
  24774. * @type {boolean}
  24775. * @default true
  24776. */
  24777. this.global = true;
  24778. }
  24779. /**
  24780. * This method is overwritten since the node type is inferred from
  24781. * the function's return type.
  24782. *
  24783. * @param {NodeBuilder} builder - The current node builder.
  24784. * @return {string} The node type.
  24785. */
  24786. getNodeType( builder ) {
  24787. const candidateFn = this.getCandidateFn( builder );
  24788. return candidateFn.shaderNode.layout.type;
  24789. }
  24790. /**
  24791. * Returns the candidate function for the current parameters.
  24792. *
  24793. * @param {NodeBuilder} builder - The current node builder.
  24794. * @return {FunctionNode} The candidate function.
  24795. */
  24796. getCandidateFn( builder ) {
  24797. const params = this.parametersNodes;
  24798. let candidateFn = this._candidateFn;
  24799. if ( candidateFn === null ) {
  24800. let bestCandidateFn = null;
  24801. let bestScore = -1;
  24802. for ( const functionNode of this.functionNodes ) {
  24803. const shaderNode = functionNode.shaderNode;
  24804. const layout = shaderNode.layout;
  24805. if ( layout === null ) {
  24806. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  24807. }
  24808. const inputs = layout.inputs;
  24809. if ( params.length === inputs.length ) {
  24810. let currentScore = 0;
  24811. for ( let i = 0; i < params.length; i ++ ) {
  24812. const param = params[ i ];
  24813. const input = inputs[ i ];
  24814. if ( param.getNodeType( builder ) === input.type ) {
  24815. currentScore ++;
  24816. }
  24817. }
  24818. if ( currentScore > bestScore ) {
  24819. bestCandidateFn = functionNode;
  24820. bestScore = currentScore;
  24821. }
  24822. }
  24823. }
  24824. this._candidateFn = candidateFn = bestCandidateFn;
  24825. }
  24826. return candidateFn;
  24827. }
  24828. /**
  24829. * Sets up the node for the current parameters.
  24830. *
  24831. * @param {NodeBuilder} builder - The current node builder.
  24832. * @return {Node} The setup node.
  24833. */
  24834. setup( builder ) {
  24835. const candidateFn = this.getCandidateFn( builder );
  24836. return candidateFn( ...this.parametersNodes );
  24837. }
  24838. }
  24839. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  24840. /**
  24841. * TSL function for creating a function overloading node.
  24842. *
  24843. * @tsl
  24844. * @function
  24845. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  24846. * @returns {FunctionOverloadingNode}
  24847. */
  24848. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  24849. /**
  24850. * Represents the elapsed time in seconds.
  24851. *
  24852. * @tsl
  24853. * @type {UniformNode<float>}
  24854. */
  24855. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  24856. /**
  24857. * Represents the delta time in seconds.
  24858. *
  24859. * @tsl
  24860. * @type {UniformNode<float>}
  24861. */
  24862. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  24863. /**
  24864. * Represents the current frame ID.
  24865. *
  24866. * @tsl
  24867. * @type {UniformNode<uint>}
  24868. */
  24869. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  24870. /**
  24871. * Generates a sine wave oscillation based on a timer.
  24872. *
  24873. * @tsl
  24874. * @function
  24875. * @param {Node<float>} t - The timer to generate the oscillation with.
  24876. * @return {Node<float>} The oscillation node.
  24877. */
  24878. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  24879. /**
  24880. * Generates a square wave oscillation based on a timer.
  24881. *
  24882. * @tsl
  24883. * @function
  24884. * @param {Node<float>} t - The timer to generate the oscillation with.
  24885. * @return {Node<float>} The oscillation node.
  24886. */
  24887. const oscSquare = ( t = time ) => t.fract().round();
  24888. /**
  24889. * Generates a triangle wave oscillation based on a timer.
  24890. *
  24891. * @tsl
  24892. * @function
  24893. * @param {Node<float>} t - The timer to generate the oscillation with.
  24894. * @return {Node<float>} The oscillation node.
  24895. */
  24896. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  24897. /**
  24898. * Generates a sawtooth wave oscillation based on a timer.
  24899. *
  24900. * @tsl
  24901. * @function
  24902. * @param {Node<float>} t - The timer to generate the oscillation with.
  24903. * @return {Node<float>} The oscillation node.
  24904. */
  24905. const oscSawtooth = ( t = time ) => t.fract();
  24906. /**
  24907. * Replaces the default UV coordinates used in texture lookups.
  24908. *
  24909. * ```js
  24910. *material.contextNode = replaceDefaultUV( ( textureNode ) => {
  24911. *
  24912. * // ...
  24913. * return customUVCoordinates;
  24914. *
  24915. *} );
  24916. *```
  24917. *
  24918. * @tsl
  24919. * @function
  24920. * @param {function(Node):Node<vec2>} callback - A callback that receives the texture node
  24921. * and must return the new uv coordinates.
  24922. * @param {Node} [node=null] - An optional node to which the context will be applied.
  24923. * @return {ContextNode} A context node that replaces the default UV coordinates.
  24924. */
  24925. function replaceDefaultUV( callback, node = null ) {
  24926. return context( node, { getUV: callback } );
  24927. }
  24928. /**
  24929. * Rotates the given uv coordinates around a center point
  24930. *
  24931. * @tsl
  24932. * @function
  24933. * @param {Node<vec2>} uv - The uv coordinates.
  24934. * @param {Node<float>} rotation - The rotation defined in radians.
  24935. * @param {Node<vec2>} center - The center of rotation
  24936. * @return {Node<vec2>} The rotated uv coordinates.
  24937. */
  24938. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  24939. return rotate( uv.sub( center ), rotation ).add( center );
  24940. } );
  24941. /**
  24942. * Applies a spherical warping effect to the given uv coordinates.
  24943. *
  24944. * @tsl
  24945. * @function
  24946. * @param {Node<vec2>} uv - The uv coordinates.
  24947. * @param {Node<float>} strength - The strength of the effect.
  24948. * @param {Node<vec2>} center - The center point
  24949. * @return {Node<vec2>} The updated uv coordinates.
  24950. */
  24951. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  24952. const delta = uv.sub( center );
  24953. const delta2 = delta.dot( delta );
  24954. const delta4 = delta2.mul( delta2 );
  24955. const deltaOffset = delta4.mul( strength );
  24956. return uv.add( delta.mul( deltaOffset ) );
  24957. } );
  24958. /**
  24959. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  24960. * oriented always towards the camera.
  24961. *
  24962. * ```js
  24963. * material.vertexNode = billboarding();
  24964. * ```
  24965. *
  24966. * @tsl
  24967. * @function
  24968. * @param {Object} config - The configuration object.
  24969. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  24970. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  24971. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  24972. * @return {Node<vec3>} The updated vertex position in clip space.
  24973. */
  24974. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  24975. let worldMatrix;
  24976. if ( position !== null ) {
  24977. worldMatrix = modelWorldMatrix.toVar();
  24978. worldMatrix[ 3 ][ 0 ] = position.x;
  24979. worldMatrix[ 3 ][ 1 ] = position.y;
  24980. worldMatrix[ 3 ][ 2 ] = position.z;
  24981. } else {
  24982. worldMatrix = modelWorldMatrix;
  24983. }
  24984. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  24985. if ( defined( horizontal ) ) {
  24986. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  24987. modelViewMatrix[ 0 ][ 1 ] = 0;
  24988. modelViewMatrix[ 0 ][ 2 ] = 0;
  24989. }
  24990. if ( defined( vertical ) ) {
  24991. modelViewMatrix[ 1 ][ 0 ] = 0;
  24992. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  24993. modelViewMatrix[ 1 ][ 2 ] = 0;
  24994. }
  24995. modelViewMatrix[ 2 ][ 0 ] = 0;
  24996. modelViewMatrix[ 2 ][ 1 ] = 0;
  24997. modelViewMatrix[ 2 ][ 2 ] = 1;
  24998. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  24999. } );
  25000. /**
  25001. * A special version of a screen uv function that involves a depth comparison
  25002. * when computing the final uvs. The function mitigates visual errors when
  25003. * using viewport texture nodes for refraction purposes. Without this function
  25004. * objects in front of a refractive surface might appear on the refractive surface
  25005. * which is incorrect.
  25006. *
  25007. * @tsl
  25008. * @function
  25009. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  25010. * @return {Node<vec2>} The update uv coordinates.
  25011. */
  25012. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  25013. const depth = linearDepth();
  25014. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  25015. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  25016. return finalUV;
  25017. } );
  25018. /**
  25019. * Can be used to compute texture coordinates for animated sprite sheets.
  25020. *
  25021. * ```js
  25022. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  25023. *
  25024. * material.colorNode = texture( spriteSheet, uvNode );
  25025. * ```
  25026. *
  25027. * @augments Node
  25028. */
  25029. class SpriteSheetUVNode extends Node {
  25030. static get type() {
  25031. return 'SpriteSheetUVNode';
  25032. }
  25033. /**
  25034. * Constructs a new sprite sheet uv node.
  25035. *
  25036. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  25037. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  25038. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  25039. */
  25040. constructor( countNode, uvNode = uv$1(), frameNode = float( 0 ) ) {
  25041. super( 'vec2' );
  25042. /**
  25043. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  25044. *
  25045. * @type {Node<vec2>}
  25046. */
  25047. this.countNode = countNode;
  25048. /**
  25049. * The uv node.
  25050. *
  25051. * @type {Node<vec2>}
  25052. */
  25053. this.uvNode = uvNode;
  25054. /**
  25055. * The node that defines the current frame/sprite.
  25056. *
  25057. * @type {Node<float>}
  25058. */
  25059. this.frameNode = frameNode;
  25060. }
  25061. setup() {
  25062. const { frameNode, uvNode, countNode } = this;
  25063. const { width, height } = countNode;
  25064. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  25065. const column = frameNum.mod( width );
  25066. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  25067. const scale = countNode.reciprocal();
  25068. const uvFrameOffset = vec2( column, row );
  25069. return uvNode.add( uvFrameOffset ).mul( scale );
  25070. }
  25071. }
  25072. /**
  25073. * TSL function for creating a sprite sheet uv node.
  25074. *
  25075. * @tsl
  25076. * @function
  25077. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  25078. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  25079. * @param {?Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  25080. * @returns {SpriteSheetUVNode}
  25081. */
  25082. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 );
  25083. /**
  25084. * TSL function for creating a triplanar textures node.
  25085. *
  25086. * Can be used for triplanar texture mapping.
  25087. *
  25088. * ```js
  25089. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  25090. * ```
  25091. *
  25092. * @tsl
  25093. * @function
  25094. * @param {Node} textureXNode - First texture node.
  25095. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  25096. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  25097. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  25098. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  25099. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  25100. * @returns {Node<vec4>}
  25101. */
  25102. const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => {
  25103. // Reference: https://github.com/keijiro/StandardTriplanar
  25104. // Blending factor of triplanar mapping
  25105. let bf = normalNode.abs().normalize();
  25106. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  25107. // Triplanar mapping
  25108. const tx = positionNode.yz.mul( scaleNode );
  25109. const ty = positionNode.zx.mul( scaleNode );
  25110. const tz = positionNode.xy.mul( scaleNode );
  25111. // Base color
  25112. const textureX = textureXNode.value;
  25113. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  25114. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  25115. const cx = texture( textureX, tx ).mul( bf.x );
  25116. const cy = texture( textureY, ty ).mul( bf.y );
  25117. const cz = texture( textureZ, tz ).mul( bf.z );
  25118. return add( cx, cy, cz );
  25119. } );
  25120. /**
  25121. * TSL function for creating a triplanar textures node.
  25122. *
  25123. * @tsl
  25124. * @function
  25125. * @param {Node} textureXNode - First texture node.
  25126. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  25127. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  25128. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  25129. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  25130. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  25131. * @returns {Node<vec4>}
  25132. */
  25133. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  25134. const _reflectorPlane = new Plane();
  25135. const _normal = new Vector3();
  25136. const _reflectorWorldPosition = new Vector3();
  25137. const _cameraWorldPosition = new Vector3();
  25138. const _rotationMatrix = new Matrix4();
  25139. const _lookAtPosition = new Vector3( 0, 0, -1 );
  25140. const clipPlane = new Vector4();
  25141. const _view = new Vector3();
  25142. const _target = new Vector3();
  25143. const _q = new Vector4();
  25144. const _size$2 = new Vector2();
  25145. const _defaultRT = new RenderTarget();
  25146. const _defaultUV = screenUV.flipX();
  25147. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  25148. let _inReflector = false;
  25149. /**
  25150. * This node can be used to implement mirror-like flat reflective surfaces.
  25151. *
  25152. * ```js
  25153. * const groundReflector = reflector();
  25154. * material.colorNode = groundReflector;
  25155. *
  25156. * const plane = new Mesh( geometry, material );
  25157. * plane.add( groundReflector.target );
  25158. * ```
  25159. *
  25160. * @augments TextureNode
  25161. */
  25162. class ReflectorNode extends TextureNode {
  25163. static get type() {
  25164. return 'ReflectorNode';
  25165. }
  25166. /**
  25167. * Constructs a new reflector node.
  25168. *
  25169. * @param {Object} [parameters={}] - An object holding configuration parameters.
  25170. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  25171. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  25172. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  25173. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  25174. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  25175. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  25176. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  25177. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  25178. */
  25179. constructor( parameters = {} ) {
  25180. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  25181. /**
  25182. * A reference to the internal reflector base node which holds the actual implementation.
  25183. *
  25184. * @private
  25185. * @type {ReflectorBaseNode}
  25186. * @default ReflectorBaseNode
  25187. */
  25188. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  25189. /**
  25190. * A reference to the internal depth node.
  25191. *
  25192. * @private
  25193. * @type {?Node}
  25194. * @default null
  25195. */
  25196. this._depthNode = null;
  25197. this.setUpdateMatrix( false );
  25198. }
  25199. /**
  25200. * A reference to the internal reflector node.
  25201. *
  25202. * @type {ReflectorBaseNode}
  25203. */
  25204. get reflector() {
  25205. return this._reflectorBaseNode;
  25206. }
  25207. /**
  25208. * A reference to 3D object the reflector is linked to.
  25209. *
  25210. * @type {Object3D}
  25211. */
  25212. get target() {
  25213. return this._reflectorBaseNode.target;
  25214. }
  25215. /**
  25216. * Returns a node representing the mirror's depth. That can be used
  25217. * to implement more advanced reflection effects like distance attenuation.
  25218. *
  25219. * @return {Node} The depth node.
  25220. */
  25221. getDepthNode() {
  25222. if ( this._depthNode === null ) {
  25223. if ( this._reflectorBaseNode.depth !== true ) {
  25224. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  25225. }
  25226. this._depthNode = nodeObject( new ReflectorNode( {
  25227. defaultTexture: _defaultRT.depthTexture,
  25228. reflector: this._reflectorBaseNode
  25229. } ) );
  25230. }
  25231. return this._depthNode;
  25232. }
  25233. setup( builder ) {
  25234. // ignore if used in post-processing
  25235. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  25236. return super.setup( builder );
  25237. }
  25238. clone() {
  25239. const newNode = new this.constructor( this.reflectorNode );
  25240. newNode.uvNode = this.uvNode;
  25241. newNode.levelNode = this.levelNode;
  25242. newNode.biasNode = this.biasNode;
  25243. newNode.sampler = this.sampler;
  25244. newNode.depthNode = this.depthNode;
  25245. newNode.compareNode = this.compareNode;
  25246. newNode.gradNode = this.gradNode;
  25247. newNode.offsetNode = this.offsetNode;
  25248. newNode._reflectorBaseNode = this._reflectorBaseNode;
  25249. return newNode;
  25250. }
  25251. /**
  25252. * Frees internal resources. Should be called when the node is no longer in use.
  25253. */
  25254. dispose() {
  25255. super.dispose();
  25256. this._reflectorBaseNode.dispose();
  25257. }
  25258. }
  25259. /**
  25260. * Holds the actual implementation of the reflector.
  25261. *
  25262. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  25263. * in `ReflectorNode`, see #29619.
  25264. *
  25265. * @private
  25266. * @augments Node
  25267. */
  25268. class ReflectorBaseNode extends Node {
  25269. static get type() {
  25270. return 'ReflectorBaseNode';
  25271. }
  25272. /**
  25273. * Constructs a new reflector base node.
  25274. *
  25275. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  25276. * @param {Object} [parameters={}] - An object holding configuration parameters.
  25277. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  25278. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  25279. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  25280. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  25281. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  25282. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  25283. */
  25284. constructor( textureNode, parameters = {} ) {
  25285. super();
  25286. const {
  25287. target = new Object3D(),
  25288. resolutionScale = 1,
  25289. generateMipmaps = false,
  25290. bounces = true,
  25291. depth = false,
  25292. samples = 0
  25293. } = parameters;
  25294. /**
  25295. * Represents the rendered reflections as a texture node.
  25296. *
  25297. * @type {TextureNode}
  25298. */
  25299. this.textureNode = textureNode;
  25300. /**
  25301. * The 3D object the reflector is linked to.
  25302. *
  25303. * @type {Object3D}
  25304. * @default {new Object3D()}
  25305. */
  25306. this.target = target;
  25307. /**
  25308. * The resolution scale.
  25309. *
  25310. * @type {number}
  25311. * @default {1}
  25312. */
  25313. this.resolutionScale = resolutionScale;
  25314. if ( parameters.resolution !== undefined ) {
  25315. warnOnce( 'ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".' ); // @deprecated r180
  25316. this.resolutionScale = parameters.resolution;
  25317. }
  25318. /**
  25319. * Whether mipmaps should be generated or not.
  25320. *
  25321. * @type {boolean}
  25322. * @default {false}
  25323. */
  25324. this.generateMipmaps = generateMipmaps;
  25325. /**
  25326. * Whether reflectors can render other reflector nodes or not.
  25327. *
  25328. * @type {boolean}
  25329. * @default {true}
  25330. */
  25331. this.bounces = bounces;
  25332. /**
  25333. * Whether depth data should be generated or not.
  25334. *
  25335. * @type {boolean}
  25336. * @default {false}
  25337. */
  25338. this.depth = depth;
  25339. /**
  25340. * The number of anti-aliasing samples for the render-target
  25341. *
  25342. * @type {number}
  25343. * @default {0}
  25344. */
  25345. this.samples = samples;
  25346. /**
  25347. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  25348. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  25349. *
  25350. * @type {string}
  25351. * @default 'render'
  25352. */
  25353. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  25354. /**
  25355. * Weak map for managing virtual cameras.
  25356. *
  25357. * @type {WeakMap<Camera, Camera>}
  25358. */
  25359. this.virtualCameras = new WeakMap();
  25360. /**
  25361. * Weak map for managing render targets.
  25362. *
  25363. * @type {Map<Camera, RenderTarget>}
  25364. */
  25365. this.renderTargets = new Map();
  25366. /**
  25367. * Force render even if reflector is facing away from camera.
  25368. *
  25369. * @type {boolean}
  25370. * @default {false}
  25371. */
  25372. this.forceUpdate = false;
  25373. /**
  25374. * Whether the reflector has been rendered or not.
  25375. *
  25376. * When the reflector is facing away from the camera,
  25377. * this flag is set to `false` and the texture will be empty(black).
  25378. *
  25379. * @type {boolean}
  25380. * @default {false}
  25381. */
  25382. this.hasOutput = false;
  25383. }
  25384. /**
  25385. * Updates the resolution of the internal render target.
  25386. *
  25387. * @private
  25388. * @param {RenderTarget} renderTarget - The render target to resize.
  25389. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  25390. */
  25391. _updateResolution( renderTarget, renderer ) {
  25392. const resolution = this.resolutionScale;
  25393. renderer.getDrawingBufferSize( _size$2 );
  25394. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  25395. }
  25396. setup( builder ) {
  25397. this._updateResolution( _defaultRT, builder.renderer );
  25398. return super.setup( builder );
  25399. }
  25400. /**
  25401. * Frees internal resources. Should be called when the node is no longer in use.
  25402. */
  25403. dispose() {
  25404. super.dispose();
  25405. for ( const renderTarget of this.renderTargets.values() ) {
  25406. renderTarget.dispose();
  25407. }
  25408. }
  25409. /**
  25410. * Returns a virtual camera for the given camera. The virtual camera is used to
  25411. * render the scene from the reflector's view so correct reflections can be produced.
  25412. *
  25413. * @param {Camera} camera - The scene's camera.
  25414. * @return {Camera} The corresponding virtual camera.
  25415. */
  25416. getVirtualCamera( camera ) {
  25417. let virtualCamera = this.virtualCameras.get( camera );
  25418. if ( virtualCamera === undefined ) {
  25419. virtualCamera = camera.clone();
  25420. this.virtualCameras.set( camera, virtualCamera );
  25421. }
  25422. return virtualCamera;
  25423. }
  25424. /**
  25425. * Returns a render target for the given camera. The reflections are rendered
  25426. * into this render target.
  25427. *
  25428. * @param {Camera} camera - The scene's camera.
  25429. * @return {RenderTarget} The render target.
  25430. */
  25431. getRenderTarget( camera ) {
  25432. let renderTarget = this.renderTargets.get( camera );
  25433. if ( renderTarget === undefined ) {
  25434. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType, samples: this.samples } );
  25435. if ( this.generateMipmaps === true ) {
  25436. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  25437. renderTarget.texture.generateMipmaps = true;
  25438. }
  25439. if ( this.depth === true ) {
  25440. renderTarget.depthTexture = new DepthTexture();
  25441. }
  25442. this.renderTargets.set( camera, renderTarget );
  25443. }
  25444. return renderTarget;
  25445. }
  25446. updateBefore( frame ) {
  25447. if ( this.bounces === false && _inReflector ) return false;
  25448. _inReflector = true;
  25449. const { scene, camera, renderer, material } = frame;
  25450. const { target } = this;
  25451. const virtualCamera = this.getVirtualCamera( camera );
  25452. const renderTarget = this.getRenderTarget( virtualCamera );
  25453. renderer.getDrawingBufferSize( _size$2 );
  25454. this._updateResolution( renderTarget, renderer );
  25455. //
  25456. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  25457. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  25458. _rotationMatrix.extractRotation( target.matrixWorld );
  25459. _normal.set( 0, 0, 1 );
  25460. _normal.applyMatrix4( _rotationMatrix );
  25461. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  25462. // Avoid rendering when reflector is facing away unless forcing an update
  25463. const isFacingAway = _view.dot( _normal ) > 0;
  25464. let needsClear = false;
  25465. if ( isFacingAway === true && this.forceUpdate === false ) {
  25466. if ( this.hasOutput === false ) {
  25467. _inReflector = false;
  25468. return;
  25469. }
  25470. needsClear = true;
  25471. }
  25472. _view.reflect( _normal ).negate();
  25473. _view.add( _reflectorWorldPosition );
  25474. _rotationMatrix.extractRotation( camera.matrixWorld );
  25475. _lookAtPosition.set( 0, 0, -1 );
  25476. _lookAtPosition.applyMatrix4( _rotationMatrix );
  25477. _lookAtPosition.add( _cameraWorldPosition );
  25478. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  25479. _target.reflect( _normal ).negate();
  25480. _target.add( _reflectorWorldPosition );
  25481. //
  25482. virtualCamera.coordinateSystem = camera.coordinateSystem;
  25483. virtualCamera.position.copy( _view );
  25484. virtualCamera.up.set( 0, 1, 0 );
  25485. virtualCamera.up.applyMatrix4( _rotationMatrix );
  25486. virtualCamera.up.reflect( _normal );
  25487. virtualCamera.lookAt( _target );
  25488. virtualCamera.near = camera.near;
  25489. virtualCamera.far = camera.far;
  25490. virtualCamera.updateMatrixWorld();
  25491. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  25492. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  25493. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  25494. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  25495. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  25496. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  25497. const projectionMatrix = virtualCamera.projectionMatrix;
  25498. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  25499. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  25500. _q.z = -1;
  25501. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  25502. // Calculate the scaled plane vector
  25503. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  25504. const clipBias = 0;
  25505. // Replacing the third row of the projection matrix
  25506. projectionMatrix.elements[ 2 ] = clipPlane.x;
  25507. projectionMatrix.elements[ 6 ] = clipPlane.y;
  25508. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  25509. projectionMatrix.elements[ 14 ] = clipPlane.w;
  25510. //
  25511. this.textureNode.value = renderTarget.texture;
  25512. if ( this.depth === true ) {
  25513. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  25514. }
  25515. material.visible = false;
  25516. const currentRenderTarget = renderer.getRenderTarget();
  25517. const currentMRT = renderer.getMRT();
  25518. const currentAutoClear = renderer.autoClear;
  25519. renderer.setMRT( null );
  25520. renderer.setRenderTarget( renderTarget );
  25521. renderer.autoClear = true;
  25522. const previousName = scene.name;
  25523. scene.name = ( scene.name || 'Scene' ) + ' [ Reflector ]'; // TODO: Add bounce index
  25524. if ( needsClear ) {
  25525. renderer.clear();
  25526. this.hasOutput = false;
  25527. } else {
  25528. renderer.render( scene, virtualCamera );
  25529. this.hasOutput = true;
  25530. }
  25531. scene.name = previousName;
  25532. renderer.setMRT( currentMRT );
  25533. renderer.setRenderTarget( currentRenderTarget );
  25534. renderer.autoClear = currentAutoClear;
  25535. material.visible = true;
  25536. _inReflector = false;
  25537. this.forceUpdate = false;
  25538. }
  25539. /**
  25540. * The resolution scale.
  25541. *
  25542. * @deprecated
  25543. * @type {number}
  25544. * @default {1}
  25545. */
  25546. get resolution() {
  25547. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  25548. return this.resolutionScale;
  25549. }
  25550. set resolution( value ) {
  25551. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  25552. this.resolutionScale = value;
  25553. }
  25554. }
  25555. /**
  25556. * TSL function for creating a reflector node.
  25557. *
  25558. * @tsl
  25559. * @function
  25560. * @param {Object} [parameters={}] - An object holding configuration parameters.
  25561. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  25562. * @param {number} [parameters.resolution=1] - The resolution scale.
  25563. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  25564. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  25565. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  25566. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  25567. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  25568. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  25569. * @returns {ReflectorNode}
  25570. */
  25571. const reflector = ( parameters ) => new ReflectorNode( parameters );
  25572. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  25573. /**
  25574. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  25575. *
  25576. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  25577. *
  25578. * @private
  25579. * @augments BufferGeometry
  25580. */
  25581. class QuadGeometry extends BufferGeometry {
  25582. /**
  25583. * Constructs a new quad geometry.
  25584. *
  25585. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  25586. */
  25587. constructor( flipY = false ) {
  25588. super();
  25589. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  25590. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  25591. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  25592. }
  25593. }
  25594. const _geometry = /*@__PURE__*/ new QuadGeometry();
  25595. /**
  25596. * This module is a helper for passes which need to render a full
  25597. * screen effect which is quite common in context of post processing.
  25598. *
  25599. * The intended usage is to reuse a single quad mesh for rendering
  25600. * subsequent passes by just reassigning the `material` reference.
  25601. *
  25602. * Note: This module can only be used with `WebGPURenderer`.
  25603. *
  25604. * @augments Mesh
  25605. */
  25606. class QuadMesh extends Mesh {
  25607. /**
  25608. * Constructs a new quad mesh.
  25609. *
  25610. * @param {?Material} [material=null] - The material to render the quad mesh with.
  25611. */
  25612. constructor( material = null ) {
  25613. super( _geometry, material );
  25614. /**
  25615. * The camera to render the quad mesh with.
  25616. *
  25617. * @type {OrthographicCamera}
  25618. * @readonly
  25619. */
  25620. this.camera = _camera;
  25621. /**
  25622. * This flag can be used for type testing.
  25623. *
  25624. * @type {boolean}
  25625. * @readonly
  25626. * @default true
  25627. */
  25628. this.isQuadMesh = true;
  25629. }
  25630. /**
  25631. * Async version of `render()`.
  25632. *
  25633. * @async
  25634. * @deprecated
  25635. * @param {Renderer} renderer - The renderer.
  25636. * @return {Promise} A Promise that resolves when the render has been finished.
  25637. */
  25638. async renderAsync( renderer ) {
  25639. warnOnce( 'QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  25640. await renderer.init();
  25641. renderer.render( this, _camera );
  25642. }
  25643. /**
  25644. * Renders the quad mesh
  25645. *
  25646. * @param {Renderer} renderer - The renderer.
  25647. */
  25648. render( renderer ) {
  25649. renderer.render( this, _camera );
  25650. }
  25651. }
  25652. const _size$1 = /*@__PURE__*/ new Vector2();
  25653. /**
  25654. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  25655. * This module is especially relevant in context of post processing where certain nodes require
  25656. * texture input for their effects. With the helper function `convertToTexture()` which is based
  25657. * on this module, the node system can automatically ensure texture input if required.
  25658. *
  25659. * @augments TextureNode
  25660. */
  25661. class RTTNode extends TextureNode {
  25662. static get type() {
  25663. return 'RTTNode';
  25664. }
  25665. /**
  25666. * Constructs a new RTT node.
  25667. *
  25668. * @param {Node} node - The node to render a texture with.
  25669. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  25670. * @param {?number} [height=null] - The height of the internal render target.
  25671. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  25672. */
  25673. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  25674. const renderTarget = new RenderTarget( width, height, options );
  25675. super( renderTarget.texture, uv$1() );
  25676. /**
  25677. * This flag can be used for type testing.
  25678. *
  25679. * @type {boolean}
  25680. * @readonly
  25681. * @default true
  25682. */
  25683. this.isRTTNode = true;
  25684. /**
  25685. * The node to render a texture with.
  25686. *
  25687. * @type {Node}
  25688. */
  25689. this.node = node;
  25690. /**
  25691. * The width of the internal render target.
  25692. * If not width is applied, the render target is automatically resized.
  25693. *
  25694. * @type {?number}
  25695. * @default null
  25696. */
  25697. this.width = width;
  25698. /**
  25699. * The height of the internal render target.
  25700. *
  25701. * @type {?number}
  25702. * @default null
  25703. */
  25704. this.height = height;
  25705. /**
  25706. * The pixel ratio
  25707. *
  25708. * @type {number}
  25709. * @default 1
  25710. */
  25711. this.pixelRatio = 1;
  25712. /**
  25713. * The render target
  25714. *
  25715. * @type {RenderTarget}
  25716. */
  25717. this.renderTarget = renderTarget;
  25718. /**
  25719. * Whether the texture requires an update or not.
  25720. *
  25721. * @type {boolean}
  25722. * @default true
  25723. */
  25724. this.textureNeedsUpdate = true;
  25725. /**
  25726. * Whether the texture should automatically be updated or not.
  25727. *
  25728. * @type {boolean}
  25729. * @default true
  25730. */
  25731. this.autoUpdate = true;
  25732. /**
  25733. * The node which is used with the quad mesh for RTT.
  25734. *
  25735. * @private
  25736. * @type {Node}
  25737. * @default null
  25738. */
  25739. this._rttNode = null;
  25740. /**
  25741. * The internal quad mesh for RTT.
  25742. *
  25743. * @private
  25744. * @type {QuadMesh}
  25745. */
  25746. this._quadMesh = new QuadMesh( new NodeMaterial() );
  25747. /**
  25748. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  25749. * the texture once per render in its {@link RTTNode#updateBefore} method.
  25750. *
  25751. * @type {string}
  25752. * @default 'render'
  25753. */
  25754. this.updateBeforeType = NodeUpdateType.RENDER;
  25755. }
  25756. /**
  25757. * Whether the internal render target should automatically be resized or not.
  25758. *
  25759. * @type {boolean}
  25760. * @readonly
  25761. * @default true
  25762. */
  25763. get autoResize() {
  25764. return this.width === null;
  25765. }
  25766. setup( builder ) {
  25767. this._rttNode = this.node.context( builder.getSharedContext() );
  25768. this._quadMesh.material.name = 'RTT';
  25769. this._quadMesh.material.needsUpdate = true;
  25770. return super.setup( builder );
  25771. }
  25772. /**
  25773. * Sets the size of the internal render target
  25774. *
  25775. * @param {number} width - The width to set.
  25776. * @param {number} height - The width to set.
  25777. */
  25778. setSize( width, height ) {
  25779. this.width = width;
  25780. this.height = height;
  25781. const effectiveWidth = width * this.pixelRatio;
  25782. const effectiveHeight = height * this.pixelRatio;
  25783. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  25784. this.textureNeedsUpdate = true;
  25785. }
  25786. /**
  25787. * Sets the pixel ratio. This will also resize the render target.
  25788. *
  25789. * @param {number} pixelRatio - The pixel ratio to set.
  25790. */
  25791. setPixelRatio( pixelRatio ) {
  25792. this.pixelRatio = pixelRatio;
  25793. this.setSize( this.width, this.height );
  25794. }
  25795. updateBefore( { renderer } ) {
  25796. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  25797. this.textureNeedsUpdate = false;
  25798. //
  25799. if ( this.autoResize === true ) {
  25800. const pixelRatio = renderer.getPixelRatio();
  25801. const size = renderer.getSize( _size$1 );
  25802. const effectiveWidth = Math.floor( size.width * pixelRatio );
  25803. const effectiveHeight = Math.floor( size.height * pixelRatio );
  25804. if ( effectiveWidth !== this.renderTarget.width || effectiveHeight !== this.renderTarget.height ) {
  25805. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  25806. this.textureNeedsUpdate = true;
  25807. }
  25808. }
  25809. //
  25810. let name = 'RTT';
  25811. if ( this.node.name ) {
  25812. name = this.node.name + ' [ ' + name + ' ]';
  25813. }
  25814. this._quadMesh.material.fragmentNode = this._rttNode;
  25815. this._quadMesh.name = name;
  25816. //
  25817. const currentRenderTarget = renderer.getRenderTarget();
  25818. renderer.setRenderTarget( this.renderTarget );
  25819. this._quadMesh.render( renderer );
  25820. renderer.setRenderTarget( currentRenderTarget );
  25821. }
  25822. clone() {
  25823. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  25824. newNode.sampler = this.sampler;
  25825. newNode.referenceNode = this;
  25826. return newNode;
  25827. }
  25828. }
  25829. /**
  25830. * TSL function for creating a RTT node.
  25831. *
  25832. * @tsl
  25833. * @function
  25834. * @param {Node} node - The node to render a texture with.
  25835. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  25836. * @param {?number} [height=null] - The height of the internal render target.
  25837. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  25838. * @returns {RTTNode}
  25839. */
  25840. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  25841. /**
  25842. * TSL function for converting nodes to textures nodes.
  25843. *
  25844. * @tsl
  25845. * @function
  25846. * @param {Node} node - The node to render a texture with.
  25847. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  25848. * @param {?number} [height=null] - The height of the internal render target.
  25849. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  25850. * @returns {RTTNode}
  25851. */
  25852. const convertToTexture = ( node, ...params ) => {
  25853. if ( node.isSampleNode || node.isTextureNode ) return node;
  25854. if ( node.isPassNode ) return node.getTextureNode();
  25855. return rtt( node, ...params );
  25856. };
  25857. /**
  25858. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  25859. * depth value and the camera's inverse projection matrix.
  25860. *
  25861. * @tsl
  25862. * @function
  25863. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  25864. * @param {Node<float>} depth - The fragment's depth value.
  25865. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  25866. * @return {Node<vec3>} The fragments position in view space.
  25867. */
  25868. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  25869. let clipSpacePosition;
  25870. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  25871. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  25872. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  25873. } else {
  25874. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  25875. }
  25876. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  25877. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  25878. } );
  25879. /**
  25880. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  25881. * and the camera's projection matrix
  25882. *
  25883. * @tsl
  25884. * @function
  25885. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  25886. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  25887. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  25888. */
  25889. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  25890. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  25891. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  25892. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  25893. } );
  25894. /**
  25895. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  25896. * target is available or if flat surface normals are required.
  25897. *
  25898. * @tsl
  25899. * @function
  25900. * @param {Node<vec2>} uv - The texture coordinate.
  25901. * @param {DepthTexture} depthTexture - The depth texture.
  25902. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  25903. * @return {Node<vec3>} The computed normal vector.
  25904. */
  25905. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  25906. const size = textureSize( textureLoad( depthTexture ) );
  25907. const p = ivec2( uv.mul( size ) ).toVar();
  25908. const c0 = textureLoad( depthTexture, p ).toVar();
  25909. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  25910. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  25911. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  25912. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  25913. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  25914. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  25915. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  25916. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  25917. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  25918. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  25919. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  25920. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  25921. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  25922. 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 ) ) );
  25923. 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 ) ) );
  25924. return normalize( cross( dpdx, dpdy ) );
  25925. } );
  25926. /**
  25927. * Interleaved Gradient Noise (IGN) from Jimenez 2014.
  25928. *
  25929. * IGN has "low discrepancy" resulting in evenly distributed samples. It's superior compared to
  25930. * default white noise, blue noise or Bayer.
  25931. *
  25932. * References:
  25933. * - {@link https://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare/}
  25934. * - {@link https://blog.demofox.org/2022/01/01/interleaved-gradient-noise-a-different-kind-of-low-discrepancy-sequence/}
  25935. *
  25936. * @tsl
  25937. * @function
  25938. * @param {Node<vec2>} position - The input position, usually screen coordinates.
  25939. * @return {Node<float>} The noise value.
  25940. */
  25941. const interleavedGradientNoise = Fn( ( [ position ] ) => {
  25942. return fract( float( 52.9829189 ).mul( fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) ) );
  25943. } ).setLayout( {
  25944. name: 'interleavedGradientNoise',
  25945. type: 'float',
  25946. inputs: [
  25947. { name: 'position', type: 'vec2' }
  25948. ]
  25949. } );
  25950. /**
  25951. * Vogel disk sampling for uniform circular distribution.
  25952. *
  25953. * This function generates sample points distributed uniformly on a disk using the golden angle,
  25954. * resulting in an efficient low-discrepancy sequence for sampling. The rotation parameter (phi)
  25955. * allows randomizing the pattern per-pixel when combined with IGN.
  25956. *
  25957. * @tsl
  25958. * @function
  25959. * @param {Node<int>} sampleIndex - The index of the current sample (0-based).
  25960. * @param {Node<int>} samplesCount - The total number of samples.
  25961. * @param {Node<float>} phi - Rotation angle in radians (typically from IGN * 2π).
  25962. * @return {Node<vec2>} A 2D point on the unit disk.
  25963. */
  25964. const vogelDiskSample = Fn( ( [ sampleIndex, samplesCount, phi ] ) => {
  25965. const goldenAngle = float( 2.399963229728653 ); // 2π * (2 - φ) where φ is golden ratio
  25966. const r = sqrt( float( sampleIndex ).add( 0.5 ).div( float( samplesCount ) ) );
  25967. const theta = float( sampleIndex ).mul( goldenAngle ).add( phi );
  25968. return vec2( cos( theta ), sin( theta ) ).mul( r );
  25969. } ).setLayout( {
  25970. name: 'vogelDiskSample',
  25971. type: 'vec2',
  25972. inputs: [
  25973. { name: 'sampleIndex', type: 'int' },
  25974. { name: 'samplesCount', type: 'int' },
  25975. { name: 'phi', type: 'float' }
  25976. ]
  25977. } );
  25978. /**
  25979. * Class representing a node that samples a value using a provided callback function.
  25980. *
  25981. * @extends Node
  25982. */
  25983. class SampleNode extends Node {
  25984. /**
  25985. * Returns the type of the node.
  25986. *
  25987. * @type {string}
  25988. * @readonly
  25989. * @static
  25990. */
  25991. static get type() {
  25992. return 'SampleNode';
  25993. }
  25994. /**
  25995. * Creates an instance of SampleNode.
  25996. *
  25997. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  25998. * @param {?Node<vec2>} [uvNode=null] - The UV node to be used in the texture sampling.
  25999. */
  26000. constructor( callback, uvNode = null ) {
  26001. super();
  26002. this.callback = callback;
  26003. /**
  26004. * Represents the texture coordinates.
  26005. *
  26006. * @type {?Node<vec2|vec3>}
  26007. * @default null
  26008. */
  26009. this.uvNode = uvNode;
  26010. /**
  26011. * This flag can be used for type testing.
  26012. *
  26013. * @type {boolean}
  26014. * @readonly
  26015. * @default true
  26016. */
  26017. this.isSampleNode = true;
  26018. }
  26019. /**
  26020. * Sets up the node by sampling with the default UV accessor.
  26021. *
  26022. * @returns {Node} The result of the callback function when called with the UV node.
  26023. */
  26024. setup() {
  26025. return this.sample( uv$1() );
  26026. }
  26027. /**
  26028. * Calls the callback function with the provided UV node.
  26029. *
  26030. * @param {Node<vec2>} uv - The UV node or value to be passed to the callback.
  26031. * @returns {Node} The result of the callback function.
  26032. */
  26033. sample( uv ) {
  26034. return this.callback( uv );
  26035. }
  26036. }
  26037. /**
  26038. * Helper function to create a SampleNode wrapped as a node object.
  26039. *
  26040. * @function
  26041. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  26042. * @param {?Node<vec2>} [uv=null] - The UV node to be used in the texture sampling.
  26043. * @returns {SampleNode} The created SampleNode instance wrapped as a node object.
  26044. */
  26045. const sample = ( callback, uv = null ) => new SampleNode( callback, nodeObject( uv ) );
  26046. /**
  26047. * EventNode is a node that executes a callback during specific update phases.
  26048. *
  26049. * @augments Node
  26050. */
  26051. class EventNode extends Node {
  26052. static get type() {
  26053. return 'EventNode';
  26054. }
  26055. /**
  26056. * Creates an EventNode.
  26057. *
  26058. * @param {string} eventType - The type of event
  26059. * @param {Function} callback - The callback to execute on update.
  26060. */
  26061. constructor( eventType, callback ) {
  26062. super( 'void' );
  26063. this.eventType = eventType;
  26064. this.callback = callback;
  26065. if ( eventType === EventNode.OBJECT ) {
  26066. this.updateType = NodeUpdateType.OBJECT;
  26067. } else if ( eventType === EventNode.MATERIAL ) {
  26068. this.updateType = NodeUpdateType.RENDER;
  26069. } else if ( eventType === EventNode.BEFORE_OBJECT ) {
  26070. this.updateBeforeType = NodeUpdateType.OBJECT;
  26071. } else if ( eventType === EventNode.BEFORE_MATERIAL ) {
  26072. this.updateBeforeType = NodeUpdateType.RENDER;
  26073. }
  26074. }
  26075. update( frame ) {
  26076. this.callback( frame );
  26077. }
  26078. updateBefore( frame ) {
  26079. this.callback( frame );
  26080. }
  26081. }
  26082. EventNode.OBJECT = 'object';
  26083. EventNode.MATERIAL = 'material';
  26084. EventNode.BEFORE_OBJECT = 'beforeObject';
  26085. EventNode.BEFORE_MATERIAL = 'beforeMaterial';
  26086. /**
  26087. * Helper to create an EventNode and add it to the stack.
  26088. *
  26089. * @param {string} type - The event type.
  26090. * @param {Function} callback - The callback function.
  26091. * @returns {EventNode}
  26092. */
  26093. const createEvent = ( type, callback ) => new EventNode( type, callback ).toStack();
  26094. /**
  26095. * Creates an event that triggers a function every time an object (Mesh|Sprite) is rendered.
  26096. *
  26097. * 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.
  26098. *
  26099. * @param {Function} callback - The callback function.
  26100. * @returns {EventNode}
  26101. */
  26102. const OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback );
  26103. /**
  26104. * Creates an event that triggers a function when the first object that uses the material is rendered.
  26105. *
  26106. * 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.
  26107. *
  26108. * @param {Function} callback - The callback function.
  26109. * @returns {EventNode}
  26110. */
  26111. const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback );
  26112. /**
  26113. * Creates an event that triggers a function before an object (Mesh|Sprite) is updated.
  26114. *
  26115. * 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.
  26116. *
  26117. * @param {Function} callback - The callback function.
  26118. * @returns {EventNode}
  26119. */
  26120. const OnBeforeObjectUpdate = ( callback ) => createEvent( EventNode.BEFORE_OBJECT, callback );
  26121. /**
  26122. * Creates an event that triggers a function before the material is updated.
  26123. *
  26124. * 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.
  26125. *
  26126. * @param {Function} callback - The callback function.
  26127. * @returns {EventNode}
  26128. */
  26129. const OnBeforeMaterialUpdate = ( callback ) => createEvent( EventNode.BEFORE_MATERIAL, callback );
  26130. /**
  26131. * This special type of instanced buffer attribute is intended for compute shaders.
  26132. * In earlier three.js versions it was only possible to update attribute data
  26133. * on the CPU via JavaScript and then upload the data to the GPU. With the
  26134. * new material system and renderer it is now possible to use compute shaders
  26135. * to compute the data for an attribute more efficiently on the GPU.
  26136. *
  26137. * The idea is to create an instance of this class and provide it as an input
  26138. * to {@link StorageBufferNode}.
  26139. *
  26140. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  26141. *
  26142. * @augments InstancedBufferAttribute
  26143. */
  26144. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  26145. /**
  26146. * Constructs a new storage instanced buffer attribute.
  26147. *
  26148. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  26149. * The subsequent parameters are then obsolete.
  26150. * @param {number} itemSize - The item size.
  26151. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  26152. */
  26153. constructor( count, itemSize, typeClass = Float32Array ) {
  26154. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  26155. super( array, itemSize );
  26156. /**
  26157. * This flag can be used for type testing.
  26158. *
  26159. * @type {boolean}
  26160. * @readonly
  26161. * @default true
  26162. */
  26163. this.isStorageInstancedBufferAttribute = true;
  26164. }
  26165. }
  26166. /**
  26167. * This special type of buffer attribute is intended for compute shaders.
  26168. * In earlier three.js versions it was only possible to update attribute data
  26169. * on the CPU via JavaScript and then upload the data to the GPU. With the
  26170. * new material system and renderer it is now possible to use compute shaders
  26171. * to compute the data for an attribute more efficiently on the GPU.
  26172. *
  26173. * The idea is to create an instance of this class and provide it as an input
  26174. * to {@link StorageBufferNode}.
  26175. *
  26176. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  26177. *
  26178. * @augments BufferAttribute
  26179. */
  26180. class StorageBufferAttribute extends BufferAttribute {
  26181. /**
  26182. * Constructs a new storage buffer attribute.
  26183. *
  26184. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  26185. * The subsequent parameters are then obsolete.
  26186. * @param {number} itemSize - The item size.
  26187. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  26188. */
  26189. constructor( count, itemSize, typeClass = Float32Array ) {
  26190. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  26191. super( array, itemSize );
  26192. /**
  26193. * This flag can be used for type testing.
  26194. *
  26195. * @type {boolean}
  26196. * @readonly
  26197. * @default true
  26198. */
  26199. this.isStorageBufferAttribute = true;
  26200. }
  26201. }
  26202. /**
  26203. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  26204. *
  26205. * @tsl
  26206. * @function
  26207. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  26208. * @param {string|Struct} [type='float'] - The data type.
  26209. * @returns {StorageBufferNode}
  26210. */
  26211. const attributeArray = ( count, type = 'float' ) => {
  26212. let itemSize, typedArray;
  26213. if ( type.isStruct === true ) {
  26214. itemSize = type.layout.getLength();
  26215. typedArray = getTypedArrayFromType( 'float' );
  26216. } else {
  26217. itemSize = getLengthFromType( type );
  26218. typedArray = getTypedArrayFromType( type );
  26219. }
  26220. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  26221. const node = storage( buffer, type, count );
  26222. return node;
  26223. };
  26224. /**
  26225. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  26226. *
  26227. * @tsl
  26228. * @function
  26229. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  26230. * @param {string|Struct} [type='float'] - The data type.
  26231. * @returns {StorageBufferNode}
  26232. */
  26233. const instancedArray = ( count, type = 'float' ) => {
  26234. let itemSize, typedArray;
  26235. if ( type.isStruct === true ) {
  26236. itemSize = type.layout.getLength();
  26237. typedArray = getTypedArrayFromType( 'float' );
  26238. } else {
  26239. itemSize = getLengthFromType( type );
  26240. typedArray = getTypedArrayFromType( type );
  26241. }
  26242. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  26243. const node = storage( buffer, type, count );
  26244. return node;
  26245. };
  26246. /**
  26247. * A node for representing the uv coordinates of points.
  26248. *
  26249. * Can only be used with a WebGL backend. In WebGPU, point
  26250. * primitives always have the size of one pixel and can thus
  26251. * can't be used as sprite-like objects that display textures.
  26252. *
  26253. * @augments Node
  26254. */
  26255. class PointUVNode extends Node {
  26256. static get type() {
  26257. return 'PointUVNode';
  26258. }
  26259. /**
  26260. * Constructs a new point uv node.
  26261. */
  26262. constructor() {
  26263. super( 'vec2' );
  26264. /**
  26265. * This flag can be used for type testing.
  26266. *
  26267. * @type {boolean}
  26268. * @readonly
  26269. * @default true
  26270. */
  26271. this.isPointUVNode = true;
  26272. }
  26273. generate( /*builder*/ ) {
  26274. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  26275. }
  26276. }
  26277. /**
  26278. * TSL object that represents the uv coordinates of points.
  26279. *
  26280. * @tsl
  26281. * @type {PointUVNode}
  26282. */
  26283. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  26284. const _e1 = /*@__PURE__*/ new Euler();
  26285. const _m1 = /*@__PURE__*/ new Matrix4();
  26286. /**
  26287. * This module allows access to a collection of scene properties. The following predefined TSL objects
  26288. * are available for easier use:
  26289. *
  26290. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  26291. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  26292. * - `backgroundRotation`: A node that represents the scene's background rotation.
  26293. *
  26294. * @augments Node
  26295. */
  26296. class SceneNode extends Node {
  26297. static get type() {
  26298. return 'SceneNode';
  26299. }
  26300. /**
  26301. * Constructs a new scene node.
  26302. *
  26303. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  26304. * @param {?Scene} [scene=null] - A reference to the scene.
  26305. */
  26306. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  26307. super();
  26308. /**
  26309. * The scope defines the type of scene property that is accessed.
  26310. *
  26311. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  26312. */
  26313. this.scope = scope;
  26314. /**
  26315. * A reference to the scene that is going to be accessed.
  26316. *
  26317. * @type {?Scene}
  26318. * @default null
  26319. */
  26320. this.scene = scene;
  26321. }
  26322. /**
  26323. * Depending on the scope, the method returns a different type of node that represents
  26324. * the respective scene property.
  26325. *
  26326. * @param {NodeBuilder} builder - The current node builder.
  26327. * @return {Node} The output node.
  26328. */
  26329. setup( builder ) {
  26330. const scope = this.scope;
  26331. const scene = this.scene !== null ? this.scene : builder.scene;
  26332. let output;
  26333. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  26334. output = reference( 'backgroundBlurriness', 'float', scene );
  26335. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  26336. output = reference( 'backgroundIntensity', 'float', scene );
  26337. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  26338. output = uniform( 'mat4' ).setName( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  26339. const background = scene.background;
  26340. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  26341. _e1.copy( scene.backgroundRotation );
  26342. // accommodate left-handed frame
  26343. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  26344. _m1.makeRotationFromEuler( _e1 );
  26345. } else {
  26346. _m1.identity();
  26347. }
  26348. return _m1;
  26349. } );
  26350. } else {
  26351. error( 'SceneNode: Unknown scope:', scope );
  26352. }
  26353. return output;
  26354. }
  26355. }
  26356. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  26357. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  26358. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  26359. /**
  26360. * TSL object that represents the scene's background blurriness.
  26361. *
  26362. * @tsl
  26363. * @type {SceneNode}
  26364. */
  26365. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  26366. /**
  26367. * TSL object that represents the scene's background intensity.
  26368. *
  26369. * @tsl
  26370. * @type {SceneNode}
  26371. */
  26372. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  26373. /**
  26374. * TSL object that represents the scene's background rotation.
  26375. *
  26376. * @tsl
  26377. * @type {SceneNode}
  26378. */
  26379. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  26380. /**
  26381. * This special version of a texture node can be used to
  26382. * write data into a storage texture with a compute shader.
  26383. *
  26384. * ```js
  26385. * const storageTexture = new THREE.StorageTexture( width, height );
  26386. *
  26387. * const computeTexture = Fn( ( { storageTexture } ) => {
  26388. *
  26389. * const posX = instanceIndex.mod( width );
  26390. * const posY = instanceIndex.div( width );
  26391. * const indexUV = uvec2( posX, posY );
  26392. *
  26393. * // generate RGB values
  26394. *
  26395. * const r = 1;
  26396. * const g = 1;
  26397. * const b = 1;
  26398. *
  26399. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  26400. *
  26401. * } );
  26402. *
  26403. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  26404. * renderer.computeAsync( computeNode );
  26405. * ```
  26406. *
  26407. * This node can only be used with a WebGPU backend.
  26408. *
  26409. * @augments TextureNode
  26410. */
  26411. class StorageTextureNode extends TextureNode {
  26412. static get type() {
  26413. return 'StorageTextureNode';
  26414. }
  26415. /**
  26416. * Constructs a new storage texture node.
  26417. *
  26418. * @param {StorageTexture} value - The storage texture.
  26419. * @param {Node<vec2|vec3>} uvNode - The uv node.
  26420. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  26421. */
  26422. constructor( value, uvNode, storeNode = null ) {
  26423. super( value, uvNode );
  26424. /**
  26425. * The value node that should be stored in the texture.
  26426. *
  26427. * @type {?Node}
  26428. * @default null
  26429. */
  26430. this.storeNode = storeNode;
  26431. /**
  26432. * The mip level to write to for storage textures.
  26433. *
  26434. * @type {number}
  26435. * @default 0
  26436. */
  26437. this.mipLevel = 0;
  26438. /**
  26439. * This flag can be used for type testing.
  26440. *
  26441. * @type {boolean}
  26442. * @readonly
  26443. * @default true
  26444. */
  26445. this.isStorageTextureNode = true;
  26446. /**
  26447. * The access type of the texture node.
  26448. *
  26449. * @type {string}
  26450. * @default 'writeOnly'
  26451. */
  26452. this.access = NodeAccess.WRITE_ONLY;
  26453. }
  26454. /**
  26455. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  26456. *
  26457. * @param {NodeBuilder} builder - The current node builder.
  26458. * @return {string} The input type.
  26459. */
  26460. getInputType( /*builder*/ ) {
  26461. return 'storageTexture';
  26462. }
  26463. setup( builder ) {
  26464. super.setup( builder );
  26465. const properties = builder.getNodeProperties( this );
  26466. properties.storeNode = this.storeNode;
  26467. return properties;
  26468. }
  26469. /**
  26470. * Defines the node access.
  26471. *
  26472. * @param {string} value - The node access.
  26473. * @return {StorageTextureNode} A reference to this node.
  26474. */
  26475. setAccess( value ) {
  26476. this.access = value;
  26477. return this;
  26478. }
  26479. /**
  26480. * Sets the mip level to write to.
  26481. *
  26482. * @param {number} level - The mip level.
  26483. * @return {StorageTextureNode} A reference to this node.
  26484. */
  26485. setMipLevel( level ) {
  26486. this.mipLevel = level;
  26487. return this;
  26488. }
  26489. /**
  26490. * Generates the code snippet of the storage node. If no `storeNode`
  26491. * is defined, the texture node is generated as normal texture.
  26492. *
  26493. * @param {NodeBuilder} builder - The current node builder.
  26494. * @param {string} output - The current output.
  26495. * @return {string} The generated code snippet.
  26496. */
  26497. generate( builder, output ) {
  26498. let snippet;
  26499. if ( this.storeNode !== null ) {
  26500. snippet = this.generateStore( builder );
  26501. } else {
  26502. snippet = super.generate( builder, output );
  26503. }
  26504. return snippet;
  26505. }
  26506. /**
  26507. * Convenience method for configuring a read/write node access.
  26508. *
  26509. * @return {StorageTextureNode} A reference to this node.
  26510. */
  26511. toReadWrite() {
  26512. return this.setAccess( NodeAccess.READ_WRITE );
  26513. }
  26514. /**
  26515. * Convenience method for configuring a read-only node access.
  26516. *
  26517. * @return {StorageTextureNode} A reference to this node.
  26518. */
  26519. toReadOnly() {
  26520. return this.setAccess( NodeAccess.READ_ONLY );
  26521. }
  26522. /**
  26523. * Convenience method for configuring a write-only node access.
  26524. *
  26525. * @return {StorageTextureNode} A reference to this node.
  26526. */
  26527. toWriteOnly() {
  26528. return this.setAccess( NodeAccess.WRITE_ONLY );
  26529. }
  26530. /**
  26531. * Generates the code snippet of the storage texture node.
  26532. *
  26533. * @param {NodeBuilder} builder - The current node builder.
  26534. */
  26535. generateStore( builder ) {
  26536. const properties = builder.getNodeProperties( this );
  26537. const { uvNode, storeNode, depthNode } = properties;
  26538. const textureProperty = super.generate( builder, 'property' );
  26539. const uvSnippet = uvNode.build( builder, this.value.is3DTexture === true ? 'uvec3' : 'uvec2' );
  26540. const storeSnippet = storeNode.build( builder, 'vec4' );
  26541. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  26542. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  26543. builder.addLineFlowCode( snippet, this );
  26544. }
  26545. clone() {
  26546. const newNode = super.clone();
  26547. newNode.storeNode = this.storeNode;
  26548. newNode.mipLevel = this.mipLevel;
  26549. return newNode;
  26550. }
  26551. }
  26552. /**
  26553. * TSL function for creating a storage texture node.
  26554. *
  26555. * @tsl
  26556. * @function
  26557. * @param {StorageTexture} value - The storage texture.
  26558. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  26559. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  26560. * @returns {StorageTextureNode}
  26561. */
  26562. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  26563. /**
  26564. * TODO: Explain difference to `storageTexture()`.
  26565. *
  26566. * @tsl
  26567. * @function
  26568. * @param {StorageTexture} value - The storage texture.
  26569. * @param {Node<vec2|vec3>} uvNode - The uv node.
  26570. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  26571. * @returns {StorageTextureNode}
  26572. */
  26573. const textureStore = ( value, uvNode, storeNode ) => {
  26574. const node = storageTexture( value, uvNode, storeNode );
  26575. if ( storeNode !== null ) node.toStack();
  26576. return node;
  26577. };
  26578. const normal = Fn( ( { texture, uv } ) => {
  26579. const epsilon = 0.0001;
  26580. const ret = vec3().toVar();
  26581. If( uv.x.lessThan( epsilon ), () => {
  26582. ret.assign( vec3( 1, 0, 0 ) );
  26583. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  26584. ret.assign( vec3( 0, 1, 0 ) );
  26585. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  26586. ret.assign( vec3( 0, 0, 1 ) );
  26587. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  26588. ret.assign( vec3( -1, 0, 0 ) );
  26589. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  26590. ret.assign( vec3( 0, -1, 0 ) );
  26591. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  26592. ret.assign( vec3( 0, 0, -1 ) );
  26593. } ).Else( () => {
  26594. const step = 0.01;
  26595. 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 );
  26596. 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 );
  26597. 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 );
  26598. ret.assign( vec3( x, y, z ) );
  26599. } );
  26600. return ret.normalize();
  26601. } );
  26602. /**
  26603. * This type of uniform node represents a 3D texture.
  26604. *
  26605. * @augments TextureNode
  26606. */
  26607. class Texture3DNode extends TextureNode {
  26608. static get type() {
  26609. return 'Texture3DNode';
  26610. }
  26611. /**
  26612. * Constructs a new 3D texture node.
  26613. *
  26614. * @param {Data3DTexture} value - The 3D texture.
  26615. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  26616. * @param {?Node<int>} [levelNode=null] - The level node.
  26617. */
  26618. constructor( value, uvNode = null, levelNode = null ) {
  26619. super( value, uvNode, levelNode );
  26620. /**
  26621. * This flag can be used for type testing.
  26622. *
  26623. * @type {boolean}
  26624. * @readonly
  26625. * @default true
  26626. */
  26627. this.isTexture3DNode = true;
  26628. }
  26629. /**
  26630. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  26631. *
  26632. * @param {NodeBuilder} builder - The current node builder.
  26633. * @return {string} The input type.
  26634. */
  26635. getInputType( /*builder*/ ) {
  26636. return 'texture3D';
  26637. }
  26638. /**
  26639. * Returns a default uv node which is in context of 3D textures a three-dimensional
  26640. * uv node.
  26641. *
  26642. * @return {Node<vec3>} The default uv node.
  26643. */
  26644. getDefaultUV() {
  26645. return vec3( 0.5, 0.5, 0.5 );
  26646. }
  26647. /**
  26648. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  26649. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  26650. *
  26651. * @param {boolean} value - The update toggle.
  26652. */
  26653. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  26654. /**
  26655. * Overwrites the default implementation to return the unmodified uv node.
  26656. *
  26657. * @param {NodeBuilder} builder - The current node builder.
  26658. * @param {Node} uvNode - The uv node to setup.
  26659. * @return {Node} The unmodified uv node.
  26660. */
  26661. setupUV( builder, uvNode ) {
  26662. const texture = this.value;
  26663. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  26664. if ( this.sampler ) {
  26665. uvNode = uvNode.flipY();
  26666. } else {
  26667. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  26668. }
  26669. }
  26670. return uvNode;
  26671. }
  26672. /**
  26673. * Generates the uv code snippet.
  26674. *
  26675. * @param {NodeBuilder} builder - The current node builder.
  26676. * @param {Node} uvNode - The uv node to generate code for.
  26677. * @return {string} The generated code snippet.
  26678. */
  26679. generateUV( builder, uvNode ) {
  26680. return uvNode.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  26681. }
  26682. /**
  26683. * Generates the offset code snippet.
  26684. *
  26685. * @param {NodeBuilder} builder - The current node builder.
  26686. * @param {Node} offsetNode - The offset node to generate code for.
  26687. * @return {string} The generated code snippet.
  26688. */
  26689. generateOffset( builder, offsetNode ) {
  26690. return offsetNode.build( builder, 'ivec3' );
  26691. }
  26692. /**
  26693. * TODO.
  26694. *
  26695. * @param {Node<vec3>} uvNode - The uv node .
  26696. * @return {Node<vec3>} TODO.
  26697. */
  26698. normal( uvNode ) {
  26699. return normal( { texture: this, uv: uvNode } );
  26700. }
  26701. }
  26702. /**
  26703. * TSL function for creating a 3D texture node.
  26704. *
  26705. * @tsl
  26706. * @function
  26707. * @param {Data3DTexture} value - The 3D texture.
  26708. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  26709. * @param {?Node<int>} [levelNode=null] - The level node.
  26710. * @returns {Texture3DNode}
  26711. */
  26712. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  26713. /**
  26714. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  26715. *
  26716. * @tsl
  26717. * @function
  26718. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  26719. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  26720. * @param {?Node<int>} [levelNode=null] - The level node.
  26721. * @param {?Node<float>} [biasNode=null] - The bias node.
  26722. * @returns {TextureNode}
  26723. */
  26724. const texture3DLoad = ( ...params ) => texture3D( ...params ).setSampler( false );
  26725. /**
  26726. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  26727. *
  26728. * @tsl
  26729. * @function
  26730. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  26731. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  26732. * @param {?Node<int>} [levelNode=null] - The level node.
  26733. * @returns {TextureNode}
  26734. */
  26735. const texture3DLevel = ( value, uvNode, levelNode ) => texture3D( value, uvNode ).level( levelNode );
  26736. /**
  26737. * A special type of reference node that allows to link values in
  26738. * `userData` fields to node objects.
  26739. * ```js
  26740. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  26741. *
  26742. * const material = new THREE.SpriteNodeMaterial();
  26743. * material.rotationNode = userData( 'rotation', 'float' );
  26744. * ```
  26745. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  26746. * will automatically be updated when the `rotation` user data field changes.
  26747. *
  26748. * @augments ReferenceNode
  26749. */
  26750. class UserDataNode extends ReferenceNode {
  26751. static get type() {
  26752. return 'UserDataNode';
  26753. }
  26754. /**
  26755. * Constructs a new user data node.
  26756. *
  26757. * @param {string} property - The property name that should be referenced by the node.
  26758. * @param {string} inputType - The node data type of the reference.
  26759. * @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.
  26760. */
  26761. constructor( property, inputType, userData = null ) {
  26762. super( property, inputType, userData );
  26763. /**
  26764. * A reference to the `userData` object. If not provided, the `userData`
  26765. * property of the 3D object that uses the node material is evaluated.
  26766. *
  26767. * @type {?Object}
  26768. * @default null
  26769. */
  26770. this.userData = userData;
  26771. }
  26772. /**
  26773. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  26774. * `userData` field.
  26775. *
  26776. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  26777. * @return {Object} A reference to the `userData` field.
  26778. */
  26779. updateReference( state ) {
  26780. this.reference = this.userData !== null ? this.userData : state.object.userData;
  26781. return this.reference;
  26782. }
  26783. }
  26784. /**
  26785. * TSL function for creating a user data node.
  26786. *
  26787. * @tsl
  26788. * @function
  26789. * @param {string} name - The property name that should be referenced by the node.
  26790. * @param {string} inputType - The node data type of the reference.
  26791. * @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.
  26792. * @returns {UserDataNode}
  26793. */
  26794. const userData = ( name, inputType, userData ) => new UserDataNode( name, inputType, userData );
  26795. const _objectData = new WeakMap();
  26796. /**
  26797. * A node for representing motion or velocity vectors. Foundation
  26798. * for advanced post processing effects like motion blur or TRAA.
  26799. *
  26800. * The node keeps track of the model, view and projection matrices
  26801. * of the previous frame and uses them to compute offsets in NDC space.
  26802. * These offsets represent the final velocity.
  26803. *
  26804. * @augments TempNode
  26805. */
  26806. class VelocityNode extends TempNode {
  26807. static get type() {
  26808. return 'VelocityNode';
  26809. }
  26810. /**
  26811. * Constructs a new vertex color node.
  26812. */
  26813. constructor() {
  26814. super( 'vec2' );
  26815. /**
  26816. * The current projection matrix.
  26817. *
  26818. * @type {?Matrix4}
  26819. * @default null
  26820. */
  26821. this.projectionMatrix = null;
  26822. /**
  26823. * Overwritten since velocity nodes are updated per object.
  26824. *
  26825. * @type {string}
  26826. * @default 'object'
  26827. */
  26828. this.updateType = NodeUpdateType.OBJECT;
  26829. /**
  26830. * Overwritten since velocity nodes save data after the update.
  26831. *
  26832. * @type {string}
  26833. * @default 'object'
  26834. */
  26835. this.updateAfterType = NodeUpdateType.OBJECT;
  26836. /**
  26837. * Uniform node representing the previous model matrix in world space.
  26838. *
  26839. * @type {UniformNode<mat4>}
  26840. * @default null
  26841. */
  26842. this.previousModelWorldMatrix = uniform( new Matrix4() );
  26843. /**
  26844. * Uniform node representing the previous projection matrix.
  26845. *
  26846. * @type {UniformNode<mat4>}
  26847. * @default null
  26848. */
  26849. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  26850. /**
  26851. * Uniform node representing the previous view matrix.
  26852. *
  26853. * @type {UniformNode<mat4>}
  26854. * @default null
  26855. */
  26856. this.previousCameraViewMatrix = uniform( new Matrix4() );
  26857. }
  26858. /**
  26859. * Sets the given projection matrix.
  26860. *
  26861. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  26862. */
  26863. setProjectionMatrix( projectionMatrix ) {
  26864. this.projectionMatrix = projectionMatrix;
  26865. }
  26866. /**
  26867. * Updates velocity specific uniforms.
  26868. *
  26869. * @param {NodeFrame} frame - A reference to the current node frame.
  26870. */
  26871. update( { frameId, camera, object } ) {
  26872. const previousModelMatrix = getPreviousMatrix( object );
  26873. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  26874. //
  26875. const cameraData = getData( camera );
  26876. if ( cameraData.frameId !== frameId ) {
  26877. cameraData.frameId = frameId;
  26878. if ( cameraData.previousProjectionMatrix === undefined ) {
  26879. cameraData.previousProjectionMatrix = new Matrix4();
  26880. cameraData.previousCameraViewMatrix = new Matrix4();
  26881. cameraData.currentProjectionMatrix = new Matrix4();
  26882. cameraData.currentCameraViewMatrix = new Matrix4();
  26883. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  26884. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  26885. } else {
  26886. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  26887. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  26888. }
  26889. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  26890. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  26891. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  26892. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  26893. }
  26894. }
  26895. /**
  26896. * Overwritten to updated velocity specific uniforms.
  26897. *
  26898. * @param {NodeFrame} frame - A reference to the current node frame.
  26899. */
  26900. updateAfter( { object } ) {
  26901. getPreviousMatrix( object ).copy( object.matrixWorld );
  26902. }
  26903. /**
  26904. * Implements the velocity computation based on the previous and current vertex data.
  26905. *
  26906. * @param {NodeBuilder} builder - A reference to the current node builder.
  26907. * @return {Node<vec2>} The motion vector.
  26908. */
  26909. setup( /*builder*/ ) {
  26910. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  26911. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  26912. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  26913. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  26914. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  26915. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  26916. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  26917. return velocity;
  26918. }
  26919. }
  26920. function getData( object ) {
  26921. let objectData = _objectData.get( object );
  26922. if ( objectData === undefined ) {
  26923. objectData = {};
  26924. _objectData.set( object, objectData );
  26925. }
  26926. return objectData;
  26927. }
  26928. function getPreviousMatrix( object, index = 0 ) {
  26929. const objectData = getData( object );
  26930. let matrix = objectData[ index ];
  26931. if ( matrix === undefined ) {
  26932. objectData[ index ] = matrix = new Matrix4();
  26933. objectData[ index ].copy( object.matrixWorld );
  26934. }
  26935. return matrix;
  26936. }
  26937. /**
  26938. * TSL object that represents the velocity of a render pass.
  26939. *
  26940. * @tsl
  26941. * @type {VelocityNode}
  26942. */
  26943. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  26944. /**
  26945. * Computes a grayscale value for the given RGB color value.
  26946. *
  26947. * @tsl
  26948. * @function
  26949. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  26950. * @return {Node<vec3>} The grayscale color.
  26951. */
  26952. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  26953. return luminance( color.rgb );
  26954. } );
  26955. /**
  26956. * Super-saturates or desaturates the given RGB color.
  26957. *
  26958. * @tsl
  26959. * @function
  26960. * @param {Node<vec3>} color - The input color.
  26961. * @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.
  26962. * @return {Node<vec3>} The saturated color.
  26963. */
  26964. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  26965. return adjustment.mix( luminance( color.rgb ), color.rgb );
  26966. } );
  26967. /**
  26968. * Selectively enhance the intensity of less saturated RGB colors. Can result
  26969. * in a more natural and visually appealing image with enhanced color depth
  26970. * compared to {@link ColorAdjustment#saturation}.
  26971. *
  26972. * @tsl
  26973. * @function
  26974. * @param {Node<vec3>} color - The input color.
  26975. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  26976. * @return {Node<vec3>} The updated color.
  26977. */
  26978. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  26979. const average = add( color.r, color.g, color.b ).div( 3.0 );
  26980. const mx = color.r.max( color.g.max( color.b ) );
  26981. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  26982. return mix( color.rgb, mx, amt );
  26983. } );
  26984. /**
  26985. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  26986. *
  26987. * @tsl
  26988. * @function
  26989. * @param {Node<vec3>} color - The input color.
  26990. * @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.
  26991. * @return {Node<vec3>} The updated color.
  26992. */
  26993. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  26994. const k = vec3( 0.57735, 0.57735, 0.57735 );
  26995. const cosAngle = adjustment.cos();
  26996. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  26997. } );
  26998. /**
  26999. * Computes the luminance for the given RGB color value.
  27000. *
  27001. * @tsl
  27002. * @function
  27003. * @param {Node<vec3>} color - The color value to compute the luminance for.
  27004. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  27005. * @return {Node<float>} The luminance.
  27006. */
  27007. const luminance = (
  27008. color,
  27009. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  27010. ) => dot( color, luminanceCoefficients );
  27011. /**
  27012. * Color Decision List (CDL) v1.2
  27013. *
  27014. * Compact representation of color grading information, defined by slope, offset, power, and
  27015. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  27016. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  27017. *
  27018. * @tsl
  27019. * @function
  27020. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  27021. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  27022. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  27023. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  27024. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  27025. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  27026. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  27027. *
  27028. * References:
  27029. * - ASC CDL v1.2
  27030. * - {@link https://blender.stackexchange.com/a/55239/43930}
  27031. * - {@link https://docs.acescentral.com/specifications/acescc/}
  27032. */
  27033. const cdl = /*@__PURE__*/ Fn( ( [
  27034. color,
  27035. slope = vec3( 1 ),
  27036. offset = vec3( 0 ),
  27037. power = vec3( 1 ),
  27038. saturation = float( 1 ),
  27039. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  27040. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  27041. ] ) => {
  27042. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  27043. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  27044. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  27045. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  27046. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  27047. const pv = v.pow( power ).toVar();
  27048. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  27049. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  27050. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  27051. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  27052. return vec4( v.rgb, color.a );
  27053. } );
  27054. /**
  27055. * Represents a posterize effect which reduces the number of colors
  27056. * in an image, resulting in a more blocky and stylized appearance.
  27057. *
  27058. * @augments TempNode
  27059. */
  27060. class PosterizeNode extends TempNode {
  27061. static get type() {
  27062. return 'PosterizeNode';
  27063. }
  27064. /**
  27065. * Constructs a new posterize node.
  27066. *
  27067. * @param {Node} sourceNode - The input color.
  27068. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  27069. */
  27070. constructor( sourceNode, stepsNode ) {
  27071. super();
  27072. /**
  27073. * The input color.
  27074. *
  27075. * @type {Node}
  27076. */
  27077. this.sourceNode = sourceNode;
  27078. /**
  27079. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  27080. *
  27081. * @type {Node}
  27082. */
  27083. this.stepsNode = stepsNode;
  27084. }
  27085. setup() {
  27086. const { sourceNode, stepsNode } = this;
  27087. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  27088. }
  27089. }
  27090. /**
  27091. * TSL function for creating a posterize node.
  27092. *
  27093. * @tsl
  27094. * @function
  27095. * @param {Node} sourceNode - The input color.
  27096. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  27097. * @returns {PosterizeNode}
  27098. */
  27099. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ).setParameterLength( 2 );
  27100. const _size = /*@__PURE__*/ new Vector2();
  27101. /**
  27102. * Represents the texture of a pass node.
  27103. *
  27104. * @augments TextureNode
  27105. */
  27106. class PassTextureNode extends TextureNode {
  27107. static get type() {
  27108. return 'PassTextureNode';
  27109. }
  27110. /**
  27111. * Constructs a new pass texture node.
  27112. *
  27113. * @param {PassNode} passNode - The pass node.
  27114. * @param {Texture} texture - The output texture.
  27115. */
  27116. constructor( passNode, texture ) {
  27117. super( texture );
  27118. /**
  27119. * A reference to the pass node.
  27120. *
  27121. * @type {PassNode}
  27122. */
  27123. this.passNode = passNode;
  27124. this.setUpdateMatrix( false );
  27125. }
  27126. setup( builder ) {
  27127. this.passNode.build( builder );
  27128. return super.setup( builder );
  27129. }
  27130. clone() {
  27131. return new this.constructor( this.passNode, this.value );
  27132. }
  27133. }
  27134. /**
  27135. * An extension of `PassTextureNode` which allows to manage more than one
  27136. * internal texture. Relevant for the `getPreviousTexture()` related API.
  27137. *
  27138. * @augments PassTextureNode
  27139. */
  27140. class PassMultipleTextureNode extends PassTextureNode {
  27141. static get type() {
  27142. return 'PassMultipleTextureNode';
  27143. }
  27144. /**
  27145. * Constructs a new pass texture node.
  27146. *
  27147. * @param {PassNode} passNode - The pass node.
  27148. * @param {string} textureName - The output texture name.
  27149. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  27150. */
  27151. constructor( passNode, textureName, previousTexture = false ) {
  27152. // null is passed to the super call since this class does not
  27153. // use an external texture for rendering pass data into. Instead
  27154. // the texture is managed by the pass node itself
  27155. super( passNode, null );
  27156. /**
  27157. * The output texture name.
  27158. *
  27159. * @type {string}
  27160. */
  27161. this.textureName = textureName;
  27162. /**
  27163. * Whether previous frame data should be used or not.
  27164. *
  27165. * @type {boolean}
  27166. */
  27167. this.previousTexture = previousTexture;
  27168. }
  27169. /**
  27170. * Updates the texture reference of this node.
  27171. */
  27172. updateTexture() {
  27173. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  27174. }
  27175. setup( builder ) {
  27176. this.updateTexture();
  27177. return super.setup( builder );
  27178. }
  27179. clone() {
  27180. const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture );
  27181. newNode.uvNode = this.uvNode;
  27182. newNode.levelNode = this.levelNode;
  27183. newNode.biasNode = this.biasNode;
  27184. newNode.sampler = this.sampler;
  27185. newNode.depthNode = this.depthNode;
  27186. newNode.compareNode = this.compareNode;
  27187. newNode.gradNode = this.gradNode;
  27188. newNode.offsetNode = this.offsetNode;
  27189. return newNode;
  27190. }
  27191. }
  27192. /**
  27193. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  27194. * This pass produces a render for the given scene and camera and can provide multiple outputs
  27195. * via MRT for further processing.
  27196. *
  27197. * ```js
  27198. * const postProcessing = new PostProcessing( renderer );
  27199. *
  27200. * const scenePass = pass( scene, camera );
  27201. *
  27202. * postProcessing.outputNode = scenePass;
  27203. * ```
  27204. *
  27205. * @augments TempNode
  27206. */
  27207. class PassNode extends TempNode {
  27208. static get type() {
  27209. return 'PassNode';
  27210. }
  27211. /**
  27212. * Constructs a new pass node.
  27213. *
  27214. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  27215. * @param {Scene} scene - A reference to the scene.
  27216. * @param {Camera} camera - A reference to the camera.
  27217. * @param {Object} options - Options for the internal render target.
  27218. */
  27219. constructor( scope, scene, camera, options = {} ) {
  27220. super( 'vec4' );
  27221. /**
  27222. * The scope of the pass. The scope determines whether the node outputs color or depth.
  27223. *
  27224. * @type {('color'|'depth')}
  27225. */
  27226. this.scope = scope;
  27227. /**
  27228. * A reference to the scene.
  27229. *
  27230. * @type {Scene}
  27231. */
  27232. this.scene = scene;
  27233. /**
  27234. * A reference to the camera.
  27235. *
  27236. * @type {Camera}
  27237. */
  27238. this.camera = camera;
  27239. /**
  27240. * Options for the internal render target.
  27241. *
  27242. * @type {Object}
  27243. */
  27244. this.options = options;
  27245. /**
  27246. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  27247. *
  27248. * @private
  27249. * @type {number}
  27250. * @default 1
  27251. */
  27252. this._pixelRatio = 1;
  27253. /**
  27254. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  27255. * @private
  27256. * @type {number}
  27257. * @default 1
  27258. */
  27259. this._width = 1;
  27260. /**
  27261. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  27262. * @private
  27263. * @type {number}
  27264. * @default 1
  27265. */
  27266. this._height = 1;
  27267. const depthTexture = new DepthTexture();
  27268. depthTexture.isRenderTargetTexture = true;
  27269. //depthTexture.type = FloatType;
  27270. depthTexture.name = 'depth';
  27271. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  27272. renderTarget.texture.name = 'output';
  27273. renderTarget.depthTexture = depthTexture;
  27274. /**
  27275. * The pass's render target.
  27276. *
  27277. * @type {RenderTarget}
  27278. */
  27279. this.renderTarget = renderTarget;
  27280. /**
  27281. * An optional override material for the pass.
  27282. *
  27283. * @type {Material|null}
  27284. */
  27285. this.overrideMaterial = null;
  27286. /**
  27287. * Whether the pass is transparent.
  27288. *
  27289. * @type {boolean}
  27290. * @default false
  27291. */
  27292. this.transparent = true;
  27293. /**
  27294. * Whether the pass is opaque.
  27295. *
  27296. * @type {boolean}
  27297. * @default true
  27298. */
  27299. this.opaque = true;
  27300. /**
  27301. * An optional global context for the pass.
  27302. *
  27303. * @type {ContextNode|null}
  27304. */
  27305. this.contextNode = null;
  27306. /**
  27307. * A cache for the context node.
  27308. *
  27309. * @private
  27310. * @type {?Object}
  27311. * @default null
  27312. */
  27313. this._contextNodeCache = null;
  27314. /**
  27315. * A dictionary holding the internal result textures.
  27316. *
  27317. * @private
  27318. * @type {Object<string, Texture>}
  27319. */
  27320. this._textures = {
  27321. output: renderTarget.texture,
  27322. depth: depthTexture
  27323. };
  27324. /**
  27325. * A dictionary holding the internal texture nodes.
  27326. *
  27327. * @private
  27328. * @type {Object<string, TextureNode>}
  27329. */
  27330. this._textureNodes = {};
  27331. /**
  27332. * A dictionary holding the internal depth nodes.
  27333. *
  27334. * @private
  27335. * @type {Object}
  27336. */
  27337. this._linearDepthNodes = {};
  27338. /**
  27339. * A dictionary holding the internal viewZ nodes.
  27340. *
  27341. * @private
  27342. * @type {Object}
  27343. */
  27344. this._viewZNodes = {};
  27345. /**
  27346. * A dictionary holding the texture data of the previous frame.
  27347. * Used for computing velocity/motion vectors.
  27348. *
  27349. * @private
  27350. * @type {Object<string, Texture>}
  27351. */
  27352. this._previousTextures = {};
  27353. /**
  27354. * A dictionary holding the texture nodes of the previous frame.
  27355. * Used for computing velocity/motion vectors.
  27356. *
  27357. * @private
  27358. * @type {Object<string, TextureNode>}
  27359. */
  27360. this._previousTextureNodes = {};
  27361. /**
  27362. * The `near` property of the camera as a uniform.
  27363. *
  27364. * @private
  27365. * @type {UniformNode}
  27366. */
  27367. this._cameraNear = uniform( 0 );
  27368. /**
  27369. * The `far` property of the camera as a uniform.
  27370. *
  27371. * @private
  27372. * @type {UniformNode}
  27373. */
  27374. this._cameraFar = uniform( 0 );
  27375. /**
  27376. * A MRT node configuring the MRT settings.
  27377. *
  27378. * @private
  27379. * @type {?MRTNode}
  27380. * @default null
  27381. */
  27382. this._mrt = null;
  27383. /**
  27384. * Layer object for configuring the camera that is used
  27385. * to produce the pass.
  27386. *
  27387. * @private
  27388. * @type {?Layers}
  27389. * @default null
  27390. */
  27391. this._layers = null;
  27392. /**
  27393. * Scales the resolution of the internal render target.
  27394. *
  27395. * @private
  27396. * @type {number}
  27397. * @default 1
  27398. */
  27399. this._resolutionScale = 1;
  27400. /**
  27401. * Custom viewport definition.
  27402. *
  27403. * @private
  27404. * @type {?Vector4}
  27405. * @default null
  27406. */
  27407. this._viewport = null;
  27408. /**
  27409. * Custom scissor definition.
  27410. *
  27411. * @private
  27412. * @type {?Vector4}
  27413. * @default null
  27414. */
  27415. this._scissor = null;
  27416. /**
  27417. * This flag can be used for type testing.
  27418. *
  27419. * @type {boolean}
  27420. * @readonly
  27421. * @default true
  27422. */
  27423. this.isPassNode = true;
  27424. /**
  27425. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  27426. * scene once per frame in its {@link PassNode#updateBefore} method.
  27427. *
  27428. * @type {string}
  27429. * @default 'frame'
  27430. */
  27431. this.updateBeforeType = NodeUpdateType.FRAME;
  27432. /**
  27433. * This flag is used for global cache.
  27434. *
  27435. * @type {boolean}
  27436. * @default true
  27437. */
  27438. this.global = true;
  27439. }
  27440. /**
  27441. * Sets the resolution scale for the pass.
  27442. * The resolution scale is a factor that is multiplied with the renderer's width and height.
  27443. *
  27444. * @param {number} resolutionScale - The resolution scale to set. A value of `1` means full resolution.
  27445. * @return {PassNode} A reference to this pass.
  27446. */
  27447. setResolutionScale( resolutionScale ) {
  27448. this._resolutionScale = resolutionScale;
  27449. return this;
  27450. }
  27451. /**
  27452. * Gets the current resolution scale of the pass.
  27453. *
  27454. * @return {number} The current resolution scale. A value of `1` means full resolution.
  27455. */
  27456. getResolutionScale() {
  27457. return this._resolutionScale;
  27458. }
  27459. /**
  27460. * Sets the resolution for the pass.
  27461. * The resolution is a factor that is multiplied with the renderer's width and height.
  27462. *
  27463. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  27464. * @return {PassNode} A reference to this pass.
  27465. * @deprecated since r181. Use {@link PassNode#setResolutionScale `setResolutionScale()`} instead.
  27466. */
  27467. setResolution( resolution ) { // @deprecated, r181
  27468. warn( 'PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead.' );
  27469. return this.setResolutionScale( resolution );
  27470. }
  27471. /**
  27472. * Gets the current resolution of the pass.
  27473. *
  27474. * @return {number} The current resolution. A value of `1` means full resolution.
  27475. * @deprecated since r181. Use {@link PassNode#getResolutionScale `getResolutionScale()`} instead.
  27476. */
  27477. getResolution() { // @deprecated, r181
  27478. warn( 'PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead.' );
  27479. return this.getResolutionScale();
  27480. }
  27481. /**
  27482. * Sets the layer configuration that should be used when rendering the pass.
  27483. *
  27484. * @param {Layers} layers - The layers object to set.
  27485. * @return {PassNode} A reference to this pass.
  27486. */
  27487. setLayers( layers ) {
  27488. this._layers = layers;
  27489. return this;
  27490. }
  27491. /**
  27492. * Gets the current layer configuration of the pass.
  27493. *
  27494. * @return {?Layers} .
  27495. */
  27496. getLayers() {
  27497. return this._layers;
  27498. }
  27499. /**
  27500. * Sets the given MRT node to setup MRT for this pass.
  27501. *
  27502. * @param {MRTNode} mrt - The MRT object.
  27503. * @return {PassNode} A reference to this pass.
  27504. */
  27505. setMRT( mrt ) {
  27506. this._mrt = mrt;
  27507. return this;
  27508. }
  27509. /**
  27510. * Returns the current MRT node.
  27511. *
  27512. * @return {MRTNode} The current MRT node.
  27513. */
  27514. getMRT() {
  27515. return this._mrt;
  27516. }
  27517. /**
  27518. * Returns the texture for the given output name.
  27519. *
  27520. * @param {string} name - The output name to get the texture for.
  27521. * @return {Texture} The texture.
  27522. */
  27523. getTexture( name ) {
  27524. let texture = this._textures[ name ];
  27525. if ( texture === undefined ) {
  27526. const refTexture = this.renderTarget.texture;
  27527. texture = refTexture.clone();
  27528. texture.name = name;
  27529. this._textures[ name ] = texture;
  27530. this.renderTarget.textures.push( texture );
  27531. }
  27532. return texture;
  27533. }
  27534. /**
  27535. * Returns the texture holding the data of the previous frame for the given output name.
  27536. *
  27537. * @param {string} name - The output name to get the texture for.
  27538. * @return {Texture} The texture holding the data of the previous frame.
  27539. */
  27540. getPreviousTexture( name ) {
  27541. let texture = this._previousTextures[ name ];
  27542. if ( texture === undefined ) {
  27543. texture = this.getTexture( name ).clone();
  27544. this._previousTextures[ name ] = texture;
  27545. }
  27546. return texture;
  27547. }
  27548. /**
  27549. * Switches current and previous textures for the given output name.
  27550. *
  27551. * @param {string} name - The output name.
  27552. */
  27553. toggleTexture( name ) {
  27554. const prevTexture = this._previousTextures[ name ];
  27555. if ( prevTexture !== undefined ) {
  27556. const texture = this._textures[ name ];
  27557. const index = this.renderTarget.textures.indexOf( texture );
  27558. this.renderTarget.textures[ index ] = prevTexture;
  27559. this._textures[ name ] = prevTexture;
  27560. this._previousTextures[ name ] = texture;
  27561. this._textureNodes[ name ].updateTexture();
  27562. this._previousTextureNodes[ name ].updateTexture();
  27563. }
  27564. }
  27565. /**
  27566. * Returns the texture node for the given output name.
  27567. *
  27568. * @param {string} [name='output'] - The output name to get the texture node for.
  27569. * @return {TextureNode} The texture node.
  27570. */
  27571. getTextureNode( name = 'output' ) {
  27572. let textureNode = this._textureNodes[ name ];
  27573. if ( textureNode === undefined ) {
  27574. textureNode = new PassMultipleTextureNode( this, name );
  27575. textureNode.updateTexture();
  27576. this._textureNodes[ name ] = textureNode;
  27577. }
  27578. return textureNode;
  27579. }
  27580. /**
  27581. * Returns the previous texture node for the given output name.
  27582. *
  27583. * @param {string} [name='output'] - The output name to get the previous texture node for.
  27584. * @return {TextureNode} The previous texture node.
  27585. */
  27586. getPreviousTextureNode( name = 'output' ) {
  27587. let textureNode = this._previousTextureNodes[ name ];
  27588. if ( textureNode === undefined ) {
  27589. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  27590. textureNode = new PassMultipleTextureNode( this, name, true );
  27591. textureNode.updateTexture();
  27592. this._previousTextureNodes[ name ] = textureNode;
  27593. }
  27594. return textureNode;
  27595. }
  27596. /**
  27597. * Returns a viewZ node of this pass.
  27598. *
  27599. * @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.
  27600. * @return {Node} The viewZ node.
  27601. */
  27602. getViewZNode( name = 'depth' ) {
  27603. let viewZNode = this._viewZNodes[ name ];
  27604. if ( viewZNode === undefined ) {
  27605. const cameraNear = this._cameraNear;
  27606. const cameraFar = this._cameraFar;
  27607. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  27608. }
  27609. return viewZNode;
  27610. }
  27611. /**
  27612. * Returns a linear depth node of this pass.
  27613. *
  27614. * @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.
  27615. * @return {Node} The linear depth node.
  27616. */
  27617. getLinearDepthNode( name = 'depth' ) {
  27618. let linearDepthNode = this._linearDepthNodes[ name ];
  27619. if ( linearDepthNode === undefined ) {
  27620. const cameraNear = this._cameraNear;
  27621. const cameraFar = this._cameraFar;
  27622. const viewZNode = this.getViewZNode( name );
  27623. // TODO: just if ( builder.camera.isPerspectiveCamera )
  27624. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  27625. }
  27626. return linearDepthNode;
  27627. }
  27628. /**
  27629. * Precompiles the pass.
  27630. *
  27631. * Note that this method must be called after the pass configuration is complete.
  27632. * So calls like `setMRT()` and `getTextureNode()` must proceed the precompilation.
  27633. *
  27634. * @async
  27635. * @param {Renderer} renderer - The renderer.
  27636. * @return {Promise} A Promise that resolves when the compile has been finished.
  27637. * @see {@link Renderer#compileAsync}
  27638. */
  27639. async compileAsync( renderer ) {
  27640. const currentRenderTarget = renderer.getRenderTarget();
  27641. const currentMRT = renderer.getMRT();
  27642. renderer.setRenderTarget( this.renderTarget );
  27643. renderer.setMRT( this._mrt );
  27644. await renderer.compileAsync( this.scene, this.camera );
  27645. renderer.setRenderTarget( currentRenderTarget );
  27646. renderer.setMRT( currentMRT );
  27647. }
  27648. setup( { renderer } ) {
  27649. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  27650. this.renderTarget.texture.type = renderer.getOutputBufferType();
  27651. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  27652. }
  27653. updateBefore( frame ) {
  27654. const { renderer } = frame;
  27655. const { scene } = this;
  27656. let camera;
  27657. let pixelRatio;
  27658. const outputRenderTarget = renderer.getOutputRenderTarget();
  27659. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  27660. pixelRatio = 1;
  27661. camera = renderer.xr.getCamera();
  27662. renderer.xr.updateCamera( camera );
  27663. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  27664. } else {
  27665. camera = this.camera;
  27666. pixelRatio = renderer.getPixelRatio();
  27667. renderer.getSize( _size );
  27668. }
  27669. this._pixelRatio = pixelRatio;
  27670. this.setSize( _size.width, _size.height );
  27671. const currentRenderTarget = renderer.getRenderTarget();
  27672. const currentMRT = renderer.getMRT();
  27673. const currentAutoClear = renderer.autoClear;
  27674. const currentTransparent = renderer.transparent;
  27675. const currentOpaque = renderer.opaque;
  27676. const currentMask = camera.layers.mask;
  27677. const currentContextNode = renderer.contextNode;
  27678. const currentOverrideMaterial = scene.overrideMaterial;
  27679. this._cameraNear.value = camera.near;
  27680. this._cameraFar.value = camera.far;
  27681. if ( this._layers !== null ) {
  27682. camera.layers.mask = this._layers.mask;
  27683. }
  27684. for ( const name in this._previousTextures ) {
  27685. this.toggleTexture( name );
  27686. }
  27687. if ( this.overrideMaterial !== null ) {
  27688. scene.overrideMaterial = this.overrideMaterial;
  27689. }
  27690. renderer.setRenderTarget( this.renderTarget );
  27691. renderer.setMRT( this._mrt );
  27692. renderer.autoClear = true;
  27693. renderer.transparent = this.transparent;
  27694. renderer.opaque = this.opaque;
  27695. if ( this.contextNode !== null ) {
  27696. if ( this._contextNodeCache === null || this._contextNodeCache.version !== this.version ) {
  27697. this._contextNodeCache = {
  27698. version: this.version,
  27699. context: context( { ...renderer.contextNode.getFlowContextData(), ...this.contextNode.getFlowContextData() } )
  27700. };
  27701. }
  27702. renderer.contextNode = this._contextNodeCache.context;
  27703. }
  27704. const currentSceneName = scene.name;
  27705. scene.name = this.name ? this.name : scene.name;
  27706. renderer.render( scene, camera );
  27707. scene.name = currentSceneName;
  27708. scene.overrideMaterial = currentOverrideMaterial;
  27709. renderer.setRenderTarget( currentRenderTarget );
  27710. renderer.setMRT( currentMRT );
  27711. renderer.autoClear = currentAutoClear;
  27712. renderer.transparent = currentTransparent;
  27713. renderer.opaque = currentOpaque;
  27714. renderer.contextNode = currentContextNode;
  27715. camera.layers.mask = currentMask;
  27716. }
  27717. /**
  27718. * Sets the size of the pass's render target. Honors the pixel ratio.
  27719. *
  27720. * @param {number} width - The width to set.
  27721. * @param {number} height - The height to set.
  27722. */
  27723. setSize( width, height ) {
  27724. this._width = width;
  27725. this._height = height;
  27726. const effectiveWidth = Math.floor( this._width * this._pixelRatio * this._resolutionScale );
  27727. const effectiveHeight = Math.floor( this._height * this._pixelRatio * this._resolutionScale );
  27728. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  27729. if ( this._scissor !== null ) this.renderTarget.scissor.copy( this._scissor );
  27730. if ( this._viewport !== null ) this.renderTarget.viewport.copy( this._viewport );
  27731. }
  27732. /**
  27733. * This method allows to define the pass's scissor rectangle. By default, the scissor rectangle is kept
  27734. * in sync with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  27735. * with `null` as the single argument.
  27736. *
  27737. * @param {?(number | Vector4)} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  27738. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  27739. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  27740. * @param {number} width - The width of the scissor box in logical pixel unit.
  27741. * @param {number} height - The height of the scissor box in logical pixel unit.
  27742. */
  27743. setScissor( x, y, width, height ) {
  27744. if ( x === null ) {
  27745. this._scissor = null;
  27746. } else {
  27747. if ( this._scissor === null ) this._scissor = new Vector4();
  27748. if ( x.isVector4 ) {
  27749. this._scissor.copy( x );
  27750. } else {
  27751. this._scissor.set( x, y, width, height );
  27752. }
  27753. this._scissor.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  27754. }
  27755. }
  27756. /**
  27757. * This method allows to define the pass's viewport. By default, the viewport is kept in sync
  27758. * with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  27759. * with `null` as the single argument.
  27760. *
  27761. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  27762. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  27763. * @param {number} width - The width of the viewport in logical pixel unit.
  27764. * @param {number} height - The height of the viewport in logical pixel unit.
  27765. */
  27766. setViewport( x, y, width, height ) {
  27767. if ( x === null ) {
  27768. this._viewport = null;
  27769. } else {
  27770. if ( this._viewport === null ) this._viewport = new Vector4();
  27771. if ( x.isVector4 ) {
  27772. this._viewport.copy( x );
  27773. } else {
  27774. this._viewport.set( x, y, width, height );
  27775. }
  27776. this._viewport.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  27777. }
  27778. }
  27779. /**
  27780. * Sets the pixel ratio the pass's render target and updates the size.
  27781. *
  27782. * @param {number} pixelRatio - The pixel ratio to set.
  27783. */
  27784. setPixelRatio( pixelRatio ) {
  27785. this._pixelRatio = pixelRatio;
  27786. this.setSize( this._width, this._height );
  27787. }
  27788. /**
  27789. * Frees internal resources. Should be called when the node is no longer in use.
  27790. */
  27791. dispose() {
  27792. this.renderTarget.dispose();
  27793. }
  27794. }
  27795. /**
  27796. * @static
  27797. * @type {'color'}
  27798. * @default 'color'
  27799. */
  27800. PassNode.COLOR = 'color';
  27801. /**
  27802. * @static
  27803. * @type {'depth'}
  27804. * @default 'depth'
  27805. */
  27806. PassNode.DEPTH = 'depth';
  27807. /**
  27808. * TSL function for creating a pass node.
  27809. *
  27810. * @tsl
  27811. * @function
  27812. * @param {Scene} scene - A reference to the scene.
  27813. * @param {Camera} camera - A reference to the camera.
  27814. * @param {Object} options - Options for the internal render target.
  27815. * @returns {PassNode}
  27816. */
  27817. const pass = ( scene, camera, options ) => new PassNode( PassNode.COLOR, scene, camera, options );
  27818. /**
  27819. * TSL function for creating a pass texture node.
  27820. *
  27821. * @tsl
  27822. * @function
  27823. * @param {PassNode} pass - The pass node.
  27824. * @param {Texture} texture - The output texture.
  27825. * @returns {PassTextureNode}
  27826. */
  27827. const passTexture = ( pass, texture ) => new PassTextureNode( pass, texture );
  27828. /**
  27829. * TSL function for creating a depth pass node.
  27830. *
  27831. * @tsl
  27832. * @function
  27833. * @param {Scene} scene - A reference to the scene.
  27834. * @param {Camera} camera - A reference to the camera.
  27835. * @param {Object} options - Options for the internal render target.
  27836. * @returns {PassNode}
  27837. */
  27838. const depthPass = ( scene, camera, options ) => new PassNode( PassNode.DEPTH, scene, camera, options );
  27839. /**
  27840. * Represents a render pass for producing a toon outline effect on compatible objects.
  27841. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  27842. * will receive the outline.
  27843. *
  27844. * ```js
  27845. * const postProcessing = new PostProcessing( renderer );
  27846. *
  27847. * const scenePass = toonOutlinePass( scene, camera );
  27848. *
  27849. * postProcessing.outputNode = scenePass;
  27850. * ```
  27851. * @augments PassNode
  27852. */
  27853. class ToonOutlinePassNode extends PassNode {
  27854. static get type() {
  27855. return 'ToonOutlinePassNode';
  27856. }
  27857. /**
  27858. * Constructs a new outline pass node.
  27859. *
  27860. * @param {Scene} scene - A reference to the scene.
  27861. * @param {Camera} camera - A reference to the camera.
  27862. * @param {Node} colorNode - Defines the outline's color.
  27863. * @param {Node} thicknessNode - Defines the outline's thickness.
  27864. * @param {Node} alphaNode - Defines the outline's alpha.
  27865. */
  27866. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  27867. super( PassNode.COLOR, scene, camera );
  27868. /**
  27869. * Defines the outline's color.
  27870. *
  27871. * @type {Node}
  27872. */
  27873. this.colorNode = colorNode;
  27874. /**
  27875. * Defines the outline's thickness.
  27876. *
  27877. * @type {Node}
  27878. */
  27879. this.thicknessNode = thicknessNode;
  27880. /**
  27881. * Defines the outline's alpha.
  27882. *
  27883. * @type {Node}
  27884. */
  27885. this.alphaNode = alphaNode;
  27886. /**
  27887. * An internal material cache.
  27888. *
  27889. * @private
  27890. * @type {WeakMap<Material, NodeMaterial>}
  27891. */
  27892. this._materialCache = new WeakMap();
  27893. /**
  27894. * The name of this pass.
  27895. *
  27896. * @type {string}
  27897. * @default 'Outline Pass'
  27898. */
  27899. this.name = 'Outline Pass';
  27900. }
  27901. updateBefore( frame ) {
  27902. const { renderer } = frame;
  27903. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  27904. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  27905. // only render outline for supported materials
  27906. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  27907. if ( material.wireframe === false ) {
  27908. const outlineMaterial = this._getOutlineMaterial( material );
  27909. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  27910. }
  27911. }
  27912. // default
  27913. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  27914. } );
  27915. super.updateBefore( frame );
  27916. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  27917. }
  27918. /**
  27919. * Creates the material used for outline rendering.
  27920. *
  27921. * @private
  27922. * @return {NodeMaterial} The outline material.
  27923. */
  27924. _createMaterial() {
  27925. const material = new NodeMaterial();
  27926. material.isMeshToonOutlineMaterial = true;
  27927. material.name = 'Toon_Outline';
  27928. material.side = BackSide;
  27929. // vertex node
  27930. const outlineNormal = normalLocal.negate();
  27931. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  27932. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  27933. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  27934. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  27935. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  27936. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  27937. // color node
  27938. material.colorNode = vec4( this.colorNode, this.alphaNode );
  27939. return material;
  27940. }
  27941. /**
  27942. * For the given toon material, this method returns a corresponding
  27943. * outline material.
  27944. *
  27945. * @private
  27946. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  27947. * @return {NodeMaterial} The outline material.
  27948. */
  27949. _getOutlineMaterial( originalMaterial ) {
  27950. let outlineMaterial = this._materialCache.get( originalMaterial );
  27951. if ( outlineMaterial === undefined ) {
  27952. outlineMaterial = this._createMaterial();
  27953. this._materialCache.set( originalMaterial, outlineMaterial );
  27954. }
  27955. return outlineMaterial;
  27956. }
  27957. }
  27958. /**
  27959. * TSL function for creating a toon outline pass node.
  27960. *
  27961. * @tsl
  27962. * @function
  27963. * @param {Scene} scene - A reference to the scene.
  27964. * @param {Camera} camera - A reference to the camera.
  27965. * @param {Color} color - Defines the outline's color.
  27966. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  27967. * @param {number} [alpha=1] - Defines the outline's alpha.
  27968. * @returns {ToonOutlinePassNode}
  27969. */
  27970. const toonOutlinePass = ( scene, camera, color = new Color( 0, 0, 0 ), thickness = 0.003, alpha = 1 ) => nodeObject( new ToonOutlinePassNode( scene, camera, nodeObject( color ), nodeObject( thickness ), nodeObject( alpha ) ) );
  27971. /**
  27972. * Linear tone mapping, exposure only.
  27973. *
  27974. * @tsl
  27975. * @function
  27976. * @param {Node<vec3>} color - The color that should be tone mapped.
  27977. * @param {Node<float>} exposure - The exposure.
  27978. * @return {Node<vec3>} The tone mapped color.
  27979. */
  27980. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27981. return color.mul( exposure ).clamp();
  27982. } ).setLayout( {
  27983. name: 'linearToneMapping',
  27984. type: 'vec3',
  27985. inputs: [
  27986. { name: 'color', type: 'vec3' },
  27987. { name: 'exposure', type: 'float' }
  27988. ]
  27989. } );
  27990. /**
  27991. * Reinhard tone mapping.
  27992. *
  27993. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  27994. *
  27995. * @tsl
  27996. * @function
  27997. * @param {Node<vec3>} color - The color that should be tone mapped.
  27998. * @param {Node<float>} exposure - The exposure.
  27999. * @return {Node<vec3>} The tone mapped color.
  28000. */
  28001. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28002. color = color.mul( exposure );
  28003. return color.div( color.add( 1.0 ) ).clamp();
  28004. } ).setLayout( {
  28005. name: 'reinhardToneMapping',
  28006. type: 'vec3',
  28007. inputs: [
  28008. { name: 'color', type: 'vec3' },
  28009. { name: 'exposure', type: 'float' }
  28010. ]
  28011. } );
  28012. /**
  28013. * Cineon tone mapping.
  28014. *
  28015. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  28016. *
  28017. * @tsl
  28018. * @function
  28019. * @param {Node<vec3>} color - The color that should be tone mapped.
  28020. * @param {Node<float>} exposure - The exposure.
  28021. * @return {Node<vec3>} The tone mapped color.
  28022. */
  28023. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28024. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  28025. color = color.mul( exposure );
  28026. color = color.sub( 0.004 ).max( 0.0 );
  28027. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  28028. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  28029. return a.div( b ).pow( 2.2 );
  28030. } ).setLayout( {
  28031. name: 'cineonToneMapping',
  28032. type: 'vec3',
  28033. inputs: [
  28034. { name: 'color', type: 'vec3' },
  28035. { name: 'exposure', type: 'float' }
  28036. ]
  28037. } );
  28038. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  28039. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  28040. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  28041. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  28042. return a.div( b );
  28043. } );
  28044. /**
  28045. * ACESFilmic tone mapping.
  28046. *
  28047. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  28048. *
  28049. * @tsl
  28050. * @function
  28051. * @param {Node<vec3>} color - The color that should be tone mapped.
  28052. * @param {Node<float>} exposure - The exposure.
  28053. * @return {Node<vec3>} The tone mapped color.
  28054. */
  28055. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28056. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  28057. const ACESInputMat = mat3(
  28058. 0.59719, 0.35458, 0.04823,
  28059. 0.07600, 0.90834, 0.01566,
  28060. 0.02840, 0.13383, 0.83777
  28061. );
  28062. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  28063. const ACESOutputMat = mat3(
  28064. 1.60475, -0.53108, -0.07367,
  28065. -0.10208, 1.10813, -605e-5,
  28066. -327e-5, -0.07276, 1.07602
  28067. );
  28068. color = color.mul( exposure ).div( 0.6 );
  28069. color = ACESInputMat.mul( color );
  28070. // Apply RRT and ODT
  28071. color = RRTAndODTFit( color );
  28072. color = ACESOutputMat.mul( color );
  28073. // Clamp to [0, 1]
  28074. return color.clamp();
  28075. } ).setLayout( {
  28076. name: 'acesFilmicToneMapping',
  28077. type: 'vec3',
  28078. inputs: [
  28079. { name: 'color', type: 'vec3' },
  28080. { name: 'exposure', type: 'float' }
  28081. ]
  28082. } );
  28083. 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 ) );
  28084. 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 ) );
  28085. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  28086. const x = vec3( x_immutable ).toVar();
  28087. const x2 = vec3( x.mul( x ) ).toVar();
  28088. const x4 = vec3( x2.mul( x2 ) ).toVar();
  28089. 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 ) ) ) );
  28090. } );
  28091. /**
  28092. * AgX tone mapping.
  28093. *
  28094. * @tsl
  28095. * @function
  28096. * @param {Node<vec3>} color - The color that should be tone mapped.
  28097. * @param {Node<float>} exposure - The exposure.
  28098. * @return {Node<vec3>} The tone mapped color.
  28099. */
  28100. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28101. const colortone = vec3( color ).toVar();
  28102. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  28103. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  28104. const AgxMinEv = float( -12.47393 );
  28105. const AgxMaxEv = float( 4.026069 );
  28106. colortone.mulAssign( exposure );
  28107. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  28108. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  28109. colortone.assign( max$1( colortone, 1e-10 ) );
  28110. colortone.assign( log2( colortone ) );
  28111. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  28112. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  28113. colortone.assign( agxDefaultContrastApprox( colortone ) );
  28114. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  28115. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  28116. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  28117. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  28118. return colortone;
  28119. } ).setLayout( {
  28120. name: 'agxToneMapping',
  28121. type: 'vec3',
  28122. inputs: [
  28123. { name: 'color', type: 'vec3' },
  28124. { name: 'exposure', type: 'float' }
  28125. ]
  28126. } );
  28127. /**
  28128. * Neutral tone mapping.
  28129. *
  28130. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  28131. *
  28132. * @tsl
  28133. * @function
  28134. * @param {Node<vec3>} color - The color that should be tone mapped.
  28135. * @param {Node<float>} exposure - The exposure.
  28136. * @return {Node<vec3>} The tone mapped color.
  28137. */
  28138. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28139. const StartCompression = float( 0.8 - 0.04 );
  28140. const Desaturation = float( 0.15 );
  28141. color = color.mul( exposure );
  28142. const x = min$1( color.r, min$1( color.g, color.b ) );
  28143. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  28144. color.subAssign( offset );
  28145. const peak = max$1( color.r, max$1( color.g, color.b ) );
  28146. If( peak.lessThan( StartCompression ), () => {
  28147. return color;
  28148. } );
  28149. const d = sub( 1, StartCompression );
  28150. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  28151. color.mulAssign( newPeak.div( peak ) );
  28152. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  28153. return mix( color, vec3( newPeak ), g );
  28154. } ).setLayout( {
  28155. name: 'neutralToneMapping',
  28156. type: 'vec3',
  28157. inputs: [
  28158. { name: 'color', type: 'vec3' },
  28159. { name: 'exposure', type: 'float' }
  28160. ]
  28161. } );
  28162. /**
  28163. * This class represents native code sections. It is the base
  28164. * class for modules like {@link FunctionNode} which allows to implement
  28165. * functions with native shader languages.
  28166. *
  28167. * @augments Node
  28168. */
  28169. class CodeNode extends Node {
  28170. static get type() {
  28171. return 'CodeNode';
  28172. }
  28173. /**
  28174. * Constructs a new code node.
  28175. *
  28176. * @param {string} [code=''] - The native code.
  28177. * @param {Array<Node>} [includes=[]] - An array of includes.
  28178. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  28179. */
  28180. constructor( code = '', includes = [], language = '' ) {
  28181. super( 'code' );
  28182. /**
  28183. * This flag can be used for type testing.
  28184. *
  28185. * @type {boolean}
  28186. * @readonly
  28187. * @default true
  28188. */
  28189. this.isCodeNode = true;
  28190. /**
  28191. * This flag is used for global cache.
  28192. *
  28193. * @type {boolean}
  28194. * @default true
  28195. */
  28196. this.global = true;
  28197. /**
  28198. * The native code.
  28199. *
  28200. * @type {string}
  28201. * @default ''
  28202. */
  28203. this.code = code;
  28204. /**
  28205. * An array of includes
  28206. *
  28207. * @type {Array<Node>}
  28208. * @default []
  28209. */
  28210. this.includes = includes;
  28211. /**
  28212. * The used language.
  28213. *
  28214. * @type {('js'|'wgsl'|'glsl')}
  28215. * @default ''
  28216. */
  28217. this.language = language;
  28218. }
  28219. /**
  28220. * Sets the includes of this code node.
  28221. *
  28222. * @param {Array<Node>} includes - The includes to set.
  28223. * @return {CodeNode} A reference to this node.
  28224. */
  28225. setIncludes( includes ) {
  28226. this.includes = includes;
  28227. return this;
  28228. }
  28229. /**
  28230. * Returns the includes of this code node.
  28231. *
  28232. * @param {NodeBuilder} builder - The current node builder.
  28233. * @return {Array<Node>} The includes.
  28234. */
  28235. getIncludes( /*builder*/ ) {
  28236. return this.includes;
  28237. }
  28238. generate( builder ) {
  28239. const includes = this.getIncludes( builder );
  28240. for ( const include of includes ) {
  28241. include.build( builder );
  28242. }
  28243. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  28244. nodeCode.code = this.code;
  28245. return nodeCode.code;
  28246. }
  28247. serialize( data ) {
  28248. super.serialize( data );
  28249. data.code = this.code;
  28250. data.language = this.language;
  28251. }
  28252. deserialize( data ) {
  28253. super.deserialize( data );
  28254. this.code = data.code;
  28255. this.language = data.language;
  28256. }
  28257. }
  28258. /**
  28259. * TSL function for creating a code node.
  28260. *
  28261. * @tsl
  28262. * @function
  28263. * @param {string} [code] - The native code.
  28264. * @param {?Array<Node>} [includes=[]] - An array of includes.
  28265. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  28266. * @returns {CodeNode}
  28267. */
  28268. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  28269. /**
  28270. * TSL function for creating a JS code node.
  28271. *
  28272. * @tsl
  28273. * @function
  28274. * @param {string} src - The native code.
  28275. * @param {Array<Node>} includes - An array of includes.
  28276. * @returns {CodeNode}
  28277. */
  28278. const js = ( src, includes ) => code( src, includes, 'js' );
  28279. /**
  28280. * TSL function for creating a WGSL code node.
  28281. *
  28282. * @tsl
  28283. * @function
  28284. * @param {string} src - The native code.
  28285. * @param {Array<Node>} includes - An array of includes.
  28286. * @returns {CodeNode}
  28287. */
  28288. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  28289. /**
  28290. * TSL function for creating a GLSL code node.
  28291. *
  28292. * @tsl
  28293. * @function
  28294. * @param {string} src - The native code.
  28295. * @param {Array<Node>} includes - An array of includes.
  28296. * @returns {CodeNode}
  28297. */
  28298. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  28299. /**
  28300. * This class represents a native shader function. It can be used to implement
  28301. * certain aspects of a node material with native shader code. There are two predefined
  28302. * TSL functions for easier usage.
  28303. *
  28304. * - `wgslFn`: Creates a WGSL function node.
  28305. * - `glslFn`: Creates a GLSL function node.
  28306. *
  28307. * A basic example with one include looks like so:
  28308. *
  28309. * ```js
  28310. * const desaturateWGSLFn = wgslFn( `
  28311. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  28312. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  28313. * return vec3<f32>( dot( lum, color ) );
  28314. * }`
  28315. *);
  28316. * const someWGSLFn = wgslFn( `
  28317. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  28318. * return desaturate( color );
  28319. * }
  28320. * `, [ desaturateWGSLFn ] );
  28321. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  28322. *```
  28323. * @augments CodeNode
  28324. */
  28325. class FunctionNode extends CodeNode {
  28326. static get type() {
  28327. return 'FunctionNode';
  28328. }
  28329. /**
  28330. * Constructs a new function node.
  28331. *
  28332. * @param {string} [code=''] - The native code.
  28333. * @param {Array<Node>} [includes=[]] - An array of includes.
  28334. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  28335. */
  28336. constructor( code = '', includes = [], language = '' ) {
  28337. super( code, includes, language );
  28338. }
  28339. /**
  28340. * Returns the type of this function node.
  28341. *
  28342. * @param {NodeBuilder} builder - The current node builder.
  28343. * @return {string} The type.
  28344. */
  28345. getNodeType( builder ) {
  28346. return this.getNodeFunction( builder ).type;
  28347. }
  28348. /**
  28349. * Returns the type of a member of this function node.
  28350. *
  28351. * @param {NodeBuilder} builder - The current node builder.
  28352. * @param {string} name - The name of the member.
  28353. * @return {string} The type of the member.
  28354. */
  28355. getMemberType( builder, name ) {
  28356. const type = this.getNodeType( builder );
  28357. const structType = builder.getStructTypeNode( type );
  28358. return structType.getMemberType( builder, name );
  28359. }
  28360. /**
  28361. * Returns the inputs of this function node.
  28362. *
  28363. * @param {NodeBuilder} builder - The current node builder.
  28364. * @return {Array<NodeFunctionInput>} The inputs.
  28365. */
  28366. getInputs( builder ) {
  28367. return this.getNodeFunction( builder ).inputs;
  28368. }
  28369. /**
  28370. * Returns the node function for this function node.
  28371. *
  28372. * @param {NodeBuilder} builder - The current node builder.
  28373. * @return {NodeFunction} The node function.
  28374. */
  28375. getNodeFunction( builder ) {
  28376. const nodeData = builder.getDataFromNode( this );
  28377. let nodeFunction = nodeData.nodeFunction;
  28378. if ( nodeFunction === undefined ) {
  28379. nodeFunction = builder.parser.parseFunction( this.code );
  28380. nodeData.nodeFunction = nodeFunction;
  28381. }
  28382. return nodeFunction;
  28383. }
  28384. generate( builder, output ) {
  28385. super.generate( builder );
  28386. const nodeFunction = this.getNodeFunction( builder );
  28387. const name = nodeFunction.name;
  28388. const type = nodeFunction.type;
  28389. const nodeCode = builder.getCodeFromNode( this, type );
  28390. if ( name !== '' ) {
  28391. // use a custom property name
  28392. nodeCode.name = name;
  28393. }
  28394. const propertyName = builder.getPropertyName( nodeCode );
  28395. const code = this.getNodeFunction( builder ).getCode( propertyName );
  28396. nodeCode.code = code + '\n';
  28397. if ( output === 'property' ) {
  28398. return propertyName;
  28399. } else {
  28400. return builder.format( `${ propertyName }()`, type, output );
  28401. }
  28402. }
  28403. }
  28404. const nativeFn = ( code, includes = [], language = '' ) => {
  28405. for ( let i = 0; i < includes.length; i ++ ) {
  28406. const include = includes[ i ];
  28407. // TSL Function: glslFn, wgslFn
  28408. if ( typeof include === 'function' ) {
  28409. includes[ i ] = include.functionNode;
  28410. }
  28411. }
  28412. const functionNode = new FunctionNode( code, includes, language );
  28413. const fn = ( ...params ) => functionNode.call( ...params );
  28414. fn.functionNode = functionNode;
  28415. return fn;
  28416. };
  28417. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  28418. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  28419. /**
  28420. * `ScriptableNode` uses this class to manage script inputs and outputs.
  28421. *
  28422. * @augments Node
  28423. */
  28424. class ScriptableValueNode extends Node {
  28425. static get type() {
  28426. return 'ScriptableValueNode';
  28427. }
  28428. /**
  28429. * Constructs a new scriptable node.
  28430. *
  28431. * @param {any} [value=null] - The value.
  28432. */
  28433. constructor( value = null ) {
  28434. super();
  28435. /**
  28436. * A reference to the value.
  28437. *
  28438. * @private
  28439. * @default null
  28440. */
  28441. this._value = value;
  28442. /**
  28443. * Depending on the type of `_value`, this property might cache parsed data.
  28444. *
  28445. * @private
  28446. * @default null
  28447. */
  28448. this._cache = null;
  28449. /**
  28450. * If this node represents an input, this property represents the input type.
  28451. *
  28452. * @type {?string}
  28453. * @default null
  28454. */
  28455. this.inputType = null;
  28456. /**
  28457. * If this node represents an output, this property represents the output type.
  28458. *
  28459. * @type {?string}
  28460. * @default null
  28461. */
  28462. this.outputType = null;
  28463. /**
  28464. * An event dispatcher for managing events.
  28465. *
  28466. * @type {EventDispatcher}
  28467. */
  28468. this.events = new EventDispatcher();
  28469. /**
  28470. * This flag can be used for type testing.
  28471. *
  28472. * @type {boolean}
  28473. * @readonly
  28474. * @default true
  28475. */
  28476. this.isScriptableValueNode = true;
  28477. }
  28478. /**
  28479. * Whether this node represents an output or not.
  28480. *
  28481. * @type {boolean}
  28482. * @readonly
  28483. * @default true
  28484. */
  28485. get isScriptableOutputNode() {
  28486. return this.outputType !== null;
  28487. }
  28488. set value( val ) {
  28489. if ( this._value === val ) return;
  28490. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  28491. URL.revokeObjectURL( this._cache );
  28492. this._cache = null;
  28493. }
  28494. this._value = val;
  28495. this.events.dispatchEvent( { type: 'change' } );
  28496. this.refresh();
  28497. }
  28498. /**
  28499. * The node's value.
  28500. *
  28501. * @type {any}
  28502. */
  28503. get value() {
  28504. return this._value;
  28505. }
  28506. /**
  28507. * Dispatches the `refresh` event.
  28508. */
  28509. refresh() {
  28510. this.events.dispatchEvent( { type: 'refresh' } );
  28511. }
  28512. /**
  28513. * The `value` property usually represents a node or even binary data in form of array buffers.
  28514. * In this case, this method tries to return the actual value behind the complex type.
  28515. *
  28516. * @return {any} The value.
  28517. */
  28518. getValue() {
  28519. const value = this.value;
  28520. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  28521. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  28522. } else if ( value && value.value !== null && value.value !== undefined && (
  28523. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  28524. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  28525. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  28526. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  28527. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  28528. ( this.inputType === 'Color' && value.value.isColor ) ||
  28529. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  28530. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  28531. ) ) {
  28532. return value.value;
  28533. }
  28534. return this._cache || value;
  28535. }
  28536. /**
  28537. * Overwritten since the node type is inferred from the value.
  28538. *
  28539. * @param {NodeBuilder} builder - The current node builder.
  28540. * @return {string} The node type.
  28541. */
  28542. getNodeType( builder ) {
  28543. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  28544. }
  28545. setup() {
  28546. return this.value && this.value.isNode ? this.value : float();
  28547. }
  28548. serialize( data ) {
  28549. super.serialize( data );
  28550. if ( this.value !== null ) {
  28551. if ( this.inputType === 'ArrayBuffer' ) {
  28552. data.value = arrayBufferToBase64( this.value );
  28553. } else {
  28554. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  28555. }
  28556. } else {
  28557. data.value = null;
  28558. }
  28559. data.inputType = this.inputType;
  28560. data.outputType = this.outputType;
  28561. }
  28562. deserialize( data ) {
  28563. super.deserialize( data );
  28564. let value = null;
  28565. if ( data.value !== null ) {
  28566. if ( data.inputType === 'ArrayBuffer' ) {
  28567. value = base64ToArrayBuffer( data.value );
  28568. } else if ( data.inputType === 'Texture' ) {
  28569. value = data.meta.textures[ data.value ];
  28570. } else {
  28571. value = data.meta.nodes[ data.value ] || null;
  28572. }
  28573. }
  28574. this.value = value;
  28575. this.inputType = data.inputType;
  28576. this.outputType = data.outputType;
  28577. }
  28578. }
  28579. /**
  28580. * TSL function for creating a scriptable value node.
  28581. *
  28582. * @tsl
  28583. * @function
  28584. * @param {any} [value] - The value.
  28585. * @returns {ScriptableValueNode}
  28586. */
  28587. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ).setParameterLength( 1 );
  28588. /**
  28589. * A Map-like data structure for managing resources of scriptable nodes.
  28590. *
  28591. * @augments Map
  28592. */
  28593. class Resources extends Map {
  28594. get( key, callback = null, ...params ) {
  28595. if ( this.has( key ) ) return super.get( key );
  28596. if ( callback !== null ) {
  28597. const value = callback( ...params );
  28598. this.set( key, value );
  28599. return value;
  28600. }
  28601. }
  28602. }
  28603. class Parameters {
  28604. constructor( scriptableNode ) {
  28605. this.scriptableNode = scriptableNode;
  28606. }
  28607. get parameters() {
  28608. return this.scriptableNode.parameters;
  28609. }
  28610. get layout() {
  28611. return this.scriptableNode.getLayout();
  28612. }
  28613. getInputLayout( id ) {
  28614. return this.scriptableNode.getInputLayout( id );
  28615. }
  28616. get( name ) {
  28617. const param = this.parameters[ name ];
  28618. const value = param ? param.getValue() : null;
  28619. return value;
  28620. }
  28621. }
  28622. /**
  28623. * Defines the resources (e.g. namespaces) of scriptable nodes.
  28624. *
  28625. * @type {Resources}
  28626. */
  28627. const ScriptableNodeResources = new Resources();
  28628. /**
  28629. * This type of node allows to implement nodes with custom scripts. The script
  28630. * section is represented as an instance of `CodeNode` written with JavaScript.
  28631. * The script itself must adhere to a specific structure.
  28632. *
  28633. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  28634. * - layout: The layout object defines the script's interface (inputs and outputs).
  28635. *
  28636. * ```js
  28637. * ScriptableNodeResources.set( 'TSL', TSL );
  28638. *
  28639. * const scriptableNode = scriptable( js( `
  28640. * layout = {
  28641. * outputType: 'node',
  28642. * elements: [
  28643. * { name: 'source', inputType: 'node' },
  28644. * ]
  28645. * };
  28646. *
  28647. * const { mul, oscSine } = TSL;
  28648. *
  28649. * function main() {
  28650. * const source = parameters.get( 'source' ) || float();
  28651. * return mul( source, oscSine() ) );
  28652. * }
  28653. *
  28654. * ` ) );
  28655. *
  28656. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  28657. *
  28658. * const material = new THREE.MeshBasicNodeMaterial();
  28659. * material.colorNode = scriptableNode;
  28660. * ```
  28661. *
  28662. * @augments Node
  28663. */
  28664. class ScriptableNode extends Node {
  28665. static get type() {
  28666. return 'ScriptableNode';
  28667. }
  28668. /**
  28669. * Constructs a new scriptable node.
  28670. *
  28671. * @param {?CodeNode} [codeNode=null] - The code node.
  28672. * @param {Object} [parameters={}] - The parameters definition.
  28673. */
  28674. constructor( codeNode = null, parameters = {} ) {
  28675. super();
  28676. /**
  28677. * The code node.
  28678. *
  28679. * @type {?CodeNode}
  28680. * @default null
  28681. */
  28682. this.codeNode = codeNode;
  28683. /**
  28684. * The parameters definition.
  28685. *
  28686. * @type {Object}
  28687. * @default {}
  28688. */
  28689. this.parameters = parameters;
  28690. this._local = new Resources();
  28691. this._output = scriptableValue( null );
  28692. this._outputs = {};
  28693. this._source = this.source;
  28694. this._method = null;
  28695. this._object = null;
  28696. this._value = null;
  28697. this._needsOutputUpdate = true;
  28698. this.onRefresh = this.onRefresh.bind( this );
  28699. /**
  28700. * This flag can be used for type testing.
  28701. *
  28702. * @type {boolean}
  28703. * @readonly
  28704. * @default true
  28705. */
  28706. this.isScriptableNode = true;
  28707. }
  28708. /**
  28709. * The source code of the scriptable node.
  28710. *
  28711. * @type {string}
  28712. */
  28713. get source() {
  28714. return this.codeNode ? this.codeNode.code : '';
  28715. }
  28716. /**
  28717. * Sets the reference of a local script variable.
  28718. *
  28719. * @param {string} name - The variable name.
  28720. * @param {Object} value - The reference to set.
  28721. * @return {Resources} The resource map
  28722. */
  28723. setLocal( name, value ) {
  28724. return this._local.set( name, value );
  28725. }
  28726. /**
  28727. * Gets the value of a local script variable.
  28728. *
  28729. * @param {string} name - The variable name.
  28730. * @return {Object} The value.
  28731. */
  28732. getLocal( name ) {
  28733. return this._local.get( name );
  28734. }
  28735. /**
  28736. * Event listener for the `refresh` event.
  28737. */
  28738. onRefresh() {
  28739. this._refresh();
  28740. }
  28741. /**
  28742. * Returns an input from the layout with the given id/name.
  28743. *
  28744. * @param {string} id - The id/name of the input.
  28745. * @return {Object} The element entry.
  28746. */
  28747. getInputLayout( id ) {
  28748. for ( const element of this.getLayout() ) {
  28749. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  28750. return element;
  28751. }
  28752. }
  28753. }
  28754. /**
  28755. * Returns an output from the layout with the given id/name.
  28756. *
  28757. * @param {string} id - The id/name of the output.
  28758. * @return {Object} The element entry.
  28759. */
  28760. getOutputLayout( id ) {
  28761. for ( const element of this.getLayout() ) {
  28762. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  28763. return element;
  28764. }
  28765. }
  28766. }
  28767. /**
  28768. * Defines a script output for the given name and value.
  28769. *
  28770. * @param {string} name - The name of the output.
  28771. * @param {Node} value - The node value.
  28772. * @return {ScriptableNode} A reference to this node.
  28773. */
  28774. setOutput( name, value ) {
  28775. const outputs = this._outputs;
  28776. if ( outputs[ name ] === undefined ) {
  28777. outputs[ name ] = scriptableValue( value );
  28778. } else {
  28779. outputs[ name ].value = value;
  28780. }
  28781. return this;
  28782. }
  28783. /**
  28784. * Returns a script output for the given name.
  28785. *
  28786. * @param {string} name - The name of the output.
  28787. * @return {ScriptableValueNode} The node value.
  28788. */
  28789. getOutput( name ) {
  28790. return this._outputs[ name ];
  28791. }
  28792. /**
  28793. * Returns a parameter for the given name
  28794. *
  28795. * @param {string} name - The name of the parameter.
  28796. * @return {ScriptableValueNode} The node value.
  28797. */
  28798. getParameter( name ) {
  28799. return this.parameters[ name ];
  28800. }
  28801. /**
  28802. * Sets a value for the given parameter name.
  28803. *
  28804. * @param {string} name - The parameter name.
  28805. * @param {any} value - The parameter value.
  28806. * @return {ScriptableNode} A reference to this node.
  28807. */
  28808. setParameter( name, value ) {
  28809. const parameters = this.parameters;
  28810. if ( value && value.isScriptableNode ) {
  28811. this.deleteParameter( name );
  28812. parameters[ name ] = value;
  28813. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  28814. } else if ( value && value.isScriptableValueNode ) {
  28815. this.deleteParameter( name );
  28816. parameters[ name ] = value;
  28817. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  28818. } else if ( parameters[ name ] === undefined ) {
  28819. parameters[ name ] = scriptableValue( value );
  28820. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  28821. } else {
  28822. parameters[ name ].value = value;
  28823. }
  28824. return this;
  28825. }
  28826. /**
  28827. * Returns the value of this node which is the value of
  28828. * the default output.
  28829. *
  28830. * @return {Node} The value.
  28831. */
  28832. getValue() {
  28833. return this.getDefaultOutput().getValue();
  28834. }
  28835. /**
  28836. * Deletes a parameter from the script.
  28837. *
  28838. * @param {string} name - The parameter to remove.
  28839. * @return {ScriptableNode} A reference to this node.
  28840. */
  28841. deleteParameter( name ) {
  28842. let valueNode = this.parameters[ name ];
  28843. if ( valueNode ) {
  28844. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  28845. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  28846. }
  28847. return this;
  28848. }
  28849. /**
  28850. * Deletes all parameters from the script.
  28851. *
  28852. * @return {ScriptableNode} A reference to this node.
  28853. */
  28854. clearParameters() {
  28855. for ( const name of Object.keys( this.parameters ) ) {
  28856. this.deleteParameter( name );
  28857. }
  28858. this.needsUpdate = true;
  28859. return this;
  28860. }
  28861. /**
  28862. * Calls a function from the script.
  28863. *
  28864. * @param {string} name - The function name.
  28865. * @param {...any} params - A list of parameters.
  28866. * @return {any} The result of the function call.
  28867. */
  28868. call( name, ...params ) {
  28869. const object = this.getObject();
  28870. const method = object[ name ];
  28871. if ( typeof method === 'function' ) {
  28872. return method( ...params );
  28873. }
  28874. }
  28875. /**
  28876. * Asynchronously calls a function from the script.
  28877. *
  28878. * @param {string} name - The function name.
  28879. * @param {...any} params - A list of parameters.
  28880. * @return {Promise<any>} The result of the function call.
  28881. */
  28882. async callAsync( name, ...params ) {
  28883. const object = this.getObject();
  28884. const method = object[ name ];
  28885. if ( typeof method === 'function' ) {
  28886. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  28887. }
  28888. }
  28889. /**
  28890. * Overwritten since the node types is inferred from the script's output.
  28891. *
  28892. * @param {NodeBuilder} builder - The current node builder
  28893. * @return {string} The node type.
  28894. */
  28895. getNodeType( builder ) {
  28896. return this.getDefaultOutputNode().getNodeType( builder );
  28897. }
  28898. /**
  28899. * Refreshes the script node.
  28900. *
  28901. * @param {?string} [output=null] - An optional output.
  28902. */
  28903. refresh( output = null ) {
  28904. if ( output !== null ) {
  28905. this.getOutput( output ).refresh();
  28906. } else {
  28907. this._refresh();
  28908. }
  28909. }
  28910. /**
  28911. * Returns an object representation of the script.
  28912. *
  28913. * @return {Object} The result object.
  28914. */
  28915. getObject() {
  28916. if ( this.needsUpdate ) this.dispose();
  28917. if ( this._object !== null ) return this._object;
  28918. //
  28919. const refresh = () => this.refresh();
  28920. const setOutput = ( id, value ) => this.setOutput( id, value );
  28921. const parameters = new Parameters( this );
  28922. const THREE = ScriptableNodeResources.get( 'THREE' );
  28923. const TSL = ScriptableNodeResources.get( 'TSL' );
  28924. const method = this.getMethod();
  28925. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  28926. this._object = method( ...params );
  28927. const layout = this._object.layout;
  28928. if ( layout ) {
  28929. if ( layout.cache === false ) {
  28930. this._local.clear();
  28931. }
  28932. // default output
  28933. this._output.outputType = layout.outputType || null;
  28934. if ( Array.isArray( layout.elements ) ) {
  28935. for ( const element of layout.elements ) {
  28936. const id = element.id || element.name;
  28937. if ( element.inputType ) {
  28938. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  28939. this.getParameter( id ).inputType = element.inputType;
  28940. }
  28941. if ( element.outputType ) {
  28942. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  28943. this.getOutput( id ).outputType = element.outputType;
  28944. }
  28945. }
  28946. }
  28947. }
  28948. return this._object;
  28949. }
  28950. deserialize( data ) {
  28951. super.deserialize( data );
  28952. for ( const name in this.parameters ) {
  28953. let valueNode = this.parameters[ name ];
  28954. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  28955. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  28956. }
  28957. }
  28958. /**
  28959. * Returns the layout of the script.
  28960. *
  28961. * @return {Object} The script's layout.
  28962. */
  28963. getLayout() {
  28964. return this.getObject().layout;
  28965. }
  28966. /**
  28967. * Returns default node output of the script.
  28968. *
  28969. * @return {Node} The default node output.
  28970. */
  28971. getDefaultOutputNode() {
  28972. const output = this.getDefaultOutput().value;
  28973. if ( output && output.isNode ) {
  28974. return output;
  28975. }
  28976. return float();
  28977. }
  28978. /**
  28979. * Returns default output of the script.
  28980. *
  28981. * @return {ScriptableValueNode} The default output.
  28982. */
  28983. getDefaultOutput() {
  28984. return this._exec()._output;
  28985. }
  28986. /**
  28987. * Returns a function created from the node's script.
  28988. *
  28989. * @return {Function} The function representing the node's code.
  28990. */
  28991. getMethod() {
  28992. if ( this.needsUpdate ) this.dispose();
  28993. if ( this._method !== null ) return this._method;
  28994. //
  28995. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  28996. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  28997. const properties = interfaceProps.join( ', ' );
  28998. const declarations = 'var ' + properties + '; var output = {};\n';
  28999. const returns = '\nreturn { ...output, ' + properties + ' };';
  29000. const code = declarations + this.codeNode.code + returns;
  29001. //
  29002. this._method = new Function( ...parametersProps, code );
  29003. return this._method;
  29004. }
  29005. /**
  29006. * Frees all internal resources.
  29007. */
  29008. dispose() {
  29009. if ( this._method === null ) return;
  29010. if ( this._object && typeof this._object.dispose === 'function' ) {
  29011. this._object.dispose();
  29012. }
  29013. this._method = null;
  29014. this._object = null;
  29015. this._source = null;
  29016. this._value = null;
  29017. this._needsOutputUpdate = true;
  29018. this._output.value = null;
  29019. this._outputs = {};
  29020. }
  29021. setup() {
  29022. return this.getDefaultOutputNode();
  29023. }
  29024. getCacheKey( force ) {
  29025. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  29026. for ( const param in this.parameters ) {
  29027. values.push( this.parameters[ param ].getCacheKey( force ) );
  29028. }
  29029. return hashArray( values );
  29030. }
  29031. set needsUpdate( value ) {
  29032. if ( value === true ) this.dispose();
  29033. }
  29034. get needsUpdate() {
  29035. return this.source !== this._source;
  29036. }
  29037. /**
  29038. * Executes the `main` function of the script.
  29039. *
  29040. * @private
  29041. * @return {ScriptableNode} A reference to this node.
  29042. */
  29043. _exec() {
  29044. if ( this.codeNode === null ) return this;
  29045. if ( this._needsOutputUpdate === true ) {
  29046. this._value = this.call( 'main' );
  29047. this._needsOutputUpdate = false;
  29048. }
  29049. this._output.value = this._value;
  29050. return this;
  29051. }
  29052. /**
  29053. * Executes the refresh.
  29054. *
  29055. * @private
  29056. */
  29057. _refresh() {
  29058. this.needsUpdate = true;
  29059. this._exec();
  29060. this._output.refresh();
  29061. }
  29062. }
  29063. /**
  29064. * TSL function for creating a scriptable node.
  29065. *
  29066. * @tsl
  29067. * @function
  29068. * @param {CodeNode} [codeNode] - The code node.
  29069. * @param {?Object} [parameters={}] - The parameters definition.
  29070. * @returns {ScriptableNode}
  29071. */
  29072. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ).setParameterLength( 1, 2 );
  29073. /**
  29074. * Returns a node that represents the `z` coordinate in view space
  29075. * for the current fragment. It's a different representation of the
  29076. * default depth value.
  29077. *
  29078. * This value can be part of a computation that defines how the fog
  29079. * density increases when moving away from the camera.
  29080. *
  29081. * @param {NodeBuilder} builder - The current node builder.
  29082. * @return {Node} The viewZ node.
  29083. */
  29084. function getViewZNode( builder ) {
  29085. let viewZ;
  29086. const getViewZ = builder.context.getViewZ;
  29087. if ( getViewZ !== undefined ) {
  29088. viewZ = getViewZ( this );
  29089. }
  29090. return ( viewZ || positionView.z ).negate();
  29091. }
  29092. /**
  29093. * Constructs a new range factor node.
  29094. *
  29095. * @tsl
  29096. * @function
  29097. * @param {Node} near - Defines the near value.
  29098. * @param {Node} far - Defines the far value.
  29099. */
  29100. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  29101. const viewZ = getViewZNode( builder );
  29102. return smoothstep( near, far, viewZ );
  29103. } );
  29104. /**
  29105. * Represents an exponential squared fog. This type of fog gives
  29106. * a clear view near the camera and a faster than exponentially
  29107. * densening fog farther from the camera.
  29108. *
  29109. * @tsl
  29110. * @function
  29111. * @param {Node} density - Defines the fog density.
  29112. */
  29113. const densityFogFactor = Fn( ( [ density ], builder ) => {
  29114. const viewZ = getViewZNode( builder );
  29115. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  29116. } );
  29117. /**
  29118. * This class can be used to configure a fog for the scene.
  29119. * Nodes of this type are assigned to `Scene.fogNode`.
  29120. *
  29121. * @tsl
  29122. * @function
  29123. * @param {Node} color - Defines the color of the fog.
  29124. * @param {Node} factor - Defines how the fog is factored in the scene.
  29125. */
  29126. const fog = Fn( ( [ color, factor ] ) => {
  29127. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  29128. } );
  29129. // Deprecated
  29130. /**
  29131. * @tsl
  29132. * @function
  29133. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  29134. *
  29135. * @param {Node} color
  29136. * @param {Node} near
  29137. * @param {Node} far
  29138. * @returns {Function}
  29139. */
  29140. function rangeFog( color, near, far ) { // @deprecated, r171
  29141. warn( 'TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  29142. return fog( color, rangeFogFactor( near, far ) );
  29143. }
  29144. /**
  29145. * @tsl
  29146. * @function
  29147. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  29148. *
  29149. * @param {Node} color
  29150. * @param {Node} density
  29151. * @returns {Function}
  29152. */
  29153. function densityFog( color, density ) { // @deprecated, r171
  29154. warn( 'TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  29155. return fog( color, densityFogFactor( density ) );
  29156. }
  29157. let min = null;
  29158. let max = null;
  29159. /**
  29160. * `RangeNode` generates random instanced attribute data in a defined range.
  29161. * An exemplary use case for this utility node is to generate random per-instance
  29162. * colors:
  29163. * ```js
  29164. * const material = new MeshBasicNodeMaterial();
  29165. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  29166. * const mesh = new InstancedMesh( geometry, material, count );
  29167. * ```
  29168. * @augments Node
  29169. */
  29170. class RangeNode extends Node {
  29171. static get type() {
  29172. return 'RangeNode';
  29173. }
  29174. /**
  29175. * Constructs a new range node.
  29176. *
  29177. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  29178. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  29179. */
  29180. constructor( minNode = float(), maxNode = float() ) {
  29181. super();
  29182. /**
  29183. * A node defining the lower bound of the range.
  29184. *
  29185. * @type {Node<any>}
  29186. * @default float()
  29187. */
  29188. this.minNode = minNode;
  29189. /**
  29190. * A node defining the upper bound of the range.
  29191. *
  29192. * @type {Node<any>}
  29193. * @default float()
  29194. */
  29195. this.maxNode = maxNode;
  29196. }
  29197. /**
  29198. * Returns the vector length which is computed based on the range definition.
  29199. *
  29200. * @param {NodeBuilder} builder - The current node builder.
  29201. * @return {number} The vector length.
  29202. */
  29203. getVectorLength( builder ) {
  29204. const minNode = this.getConstNode( this.minNode );
  29205. const maxNode = this.getConstNode( this.maxNode );
  29206. const minLength = builder.getTypeLength( getValueType( minNode.value ) );
  29207. const maxLength = builder.getTypeLength( getValueType( maxNode.value ) );
  29208. return minLength > maxLength ? minLength : maxLength;
  29209. }
  29210. /**
  29211. * This method is overwritten since the node type is inferred from range definition.
  29212. *
  29213. * @param {NodeBuilder} builder - The current node builder.
  29214. * @return {string} The node type.
  29215. */
  29216. getNodeType( builder ) {
  29217. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  29218. }
  29219. /**
  29220. * Returns a constant node from the given node by traversing it.
  29221. *
  29222. * @param {Node} node - The node to traverse.
  29223. * @returns {Node} The constant node, if found.
  29224. */
  29225. getConstNode( node ) {
  29226. let output = null;
  29227. node.traverse( n => {
  29228. if ( n.isConstNode === true ) {
  29229. output = n;
  29230. }
  29231. } );
  29232. if ( output === null ) {
  29233. throw new Error( 'THREE.TSL: No "ConstNode" found in node graph.' );
  29234. }
  29235. return output;
  29236. }
  29237. setup( builder ) {
  29238. const object = builder.object;
  29239. let output = null;
  29240. if ( object.count > 1 ) {
  29241. const minNode = this.getConstNode( this.minNode );
  29242. const maxNode = this.getConstNode( this.maxNode );
  29243. const minValue = minNode.value;
  29244. const maxValue = maxNode.value;
  29245. const minLength = builder.getTypeLength( getValueType( minValue ) );
  29246. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  29247. min = min || new Vector4();
  29248. max = max || new Vector4();
  29249. min.setScalar( 0 );
  29250. max.setScalar( 0 );
  29251. if ( minLength === 1 ) min.setScalar( minValue );
  29252. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  29253. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  29254. if ( maxLength === 1 ) max.setScalar( maxValue );
  29255. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  29256. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  29257. const stride = 4;
  29258. const length = stride * object.count;
  29259. const array = new Float32Array( length );
  29260. for ( let i = 0; i < length; i ++ ) {
  29261. const index = i % stride;
  29262. const minElementValue = min.getComponent( index );
  29263. const maxElementValue = max.getComponent( index );
  29264. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  29265. }
  29266. const nodeType = this.getNodeType( builder );
  29267. if ( object.count <= 4096 ) {
  29268. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  29269. } else {
  29270. // TODO: Improve anonymous buffer attribute creation removing this part
  29271. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  29272. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  29273. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  29274. }
  29275. } else {
  29276. output = float( 0 );
  29277. }
  29278. return output;
  29279. }
  29280. }
  29281. /**
  29282. * TSL function for creating a range node.
  29283. *
  29284. * @tsl
  29285. * @function
  29286. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  29287. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  29288. * @returns {RangeNode}
  29289. */
  29290. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  29291. /**
  29292. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  29293. * about the currently running dispatch and/or the device it is running on.
  29294. *
  29295. * This node can only be used with a WebGPU backend.
  29296. *
  29297. * @augments Node
  29298. */
  29299. class ComputeBuiltinNode extends Node {
  29300. static get type() {
  29301. return 'ComputeBuiltinNode';
  29302. }
  29303. /**
  29304. * Constructs a new compute builtin node.
  29305. *
  29306. * @param {string} builtinName - The built-in name.
  29307. * @param {string} nodeType - The node type.
  29308. */
  29309. constructor( builtinName, nodeType ) {
  29310. super( nodeType );
  29311. /**
  29312. * The built-in name.
  29313. *
  29314. * @private
  29315. * @type {string}
  29316. */
  29317. this._builtinName = builtinName;
  29318. }
  29319. /**
  29320. * This method is overwritten since hash is derived from the built-in name.
  29321. *
  29322. * @param {NodeBuilder} builder - The current node builder.
  29323. * @return {string} The hash.
  29324. */
  29325. getHash( builder ) {
  29326. return this.getBuiltinName( builder );
  29327. }
  29328. /**
  29329. * This method is overwritten since the node type is simply derived from `nodeType`..
  29330. *
  29331. * @param {NodeBuilder} builder - The current node builder.
  29332. * @return {string} The node type.
  29333. */
  29334. getNodeType( /*builder*/ ) {
  29335. return this.nodeType;
  29336. }
  29337. /**
  29338. * Sets the builtin name.
  29339. *
  29340. * @param {string} builtinName - The built-in name.
  29341. * @return {ComputeBuiltinNode} A reference to this node.
  29342. */
  29343. setBuiltinName( builtinName ) {
  29344. this._builtinName = builtinName;
  29345. return this;
  29346. }
  29347. /**
  29348. * Returns the builtin name.
  29349. *
  29350. * @param {NodeBuilder} builder - The current node builder.
  29351. * @return {string} The builtin name.
  29352. */
  29353. getBuiltinName( /*builder*/ ) {
  29354. return this._builtinName;
  29355. }
  29356. /**
  29357. * Whether the current node builder has the builtin or not.
  29358. *
  29359. * @param {NodeBuilder} builder - The current node builder.
  29360. * @return {boolean} Whether the builder has the builtin or not.
  29361. */
  29362. hasBuiltin( builder ) {
  29363. return builder.hasBuiltin( this._builtinName );
  29364. }
  29365. generate( builder, output ) {
  29366. const builtinName = this.getBuiltinName( builder );
  29367. const nodeType = this.getNodeType( builder );
  29368. if ( builder.shaderStage === 'compute' ) {
  29369. return builder.format( builtinName, nodeType, output );
  29370. } else {
  29371. warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  29372. return builder.generateConst( nodeType );
  29373. }
  29374. }
  29375. serialize( data ) {
  29376. super.serialize( data );
  29377. data.global = this.global;
  29378. data._builtinName = this._builtinName;
  29379. }
  29380. deserialize( data ) {
  29381. super.deserialize( data );
  29382. this.global = data.global;
  29383. this._builtinName = data._builtinName;
  29384. }
  29385. }
  29386. /**
  29387. * TSL function for creating a compute builtin node.
  29388. *
  29389. * @tsl
  29390. * @function
  29391. * @param {string} name - The built-in name.
  29392. * @param {string} nodeType - The node type.
  29393. * @returns {ComputeBuiltinNode}
  29394. */
  29395. const computeBuiltin = ( name, nodeType ) => new ComputeBuiltinNode( name, nodeType );
  29396. /**
  29397. * Represents the number of workgroups dispatched by the compute shader.
  29398. * ```js
  29399. * // Run 512 invocations/threads with a workgroup size of 128.
  29400. * const computeFn = Fn(() => {
  29401. *
  29402. * // numWorkgroups.x = 4
  29403. * storageBuffer.element(0).assign(numWorkgroups.x)
  29404. *
  29405. * })().compute(512, [128]);
  29406. *
  29407. * // Run 512 invocations/threads with the default workgroup size of 64.
  29408. * const computeFn = Fn(() => {
  29409. *
  29410. * // numWorkgroups.x = 8
  29411. * storageBuffer.element(0).assign(numWorkgroups.x)
  29412. *
  29413. * })().compute(512);
  29414. * ```
  29415. *
  29416. * @tsl
  29417. * @type {ComputeBuiltinNode<uvec3>}
  29418. */
  29419. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  29420. /**
  29421. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  29422. * ```js
  29423. * // Execute 12 compute threads with a workgroup size of 3.
  29424. * const computeFn = Fn( () => {
  29425. *
  29426. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  29427. *
  29428. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  29429. *
  29430. * } ).Else( () => {
  29431. *
  29432. * storageBuffer.element( instanceIndex ).assign( 0 );
  29433. *
  29434. * } );
  29435. *
  29436. * } )().compute( 12, [ 3 ] );
  29437. *
  29438. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  29439. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  29440. * ```
  29441. *
  29442. * @tsl
  29443. * @type {ComputeBuiltinNode<uvec3>}
  29444. */
  29445. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  29446. /**
  29447. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  29448. *
  29449. * @tsl
  29450. * @type {ComputeBuiltinNode<uvec3>}
  29451. */
  29452. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  29453. /**
  29454. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  29455. *
  29456. * @tsl
  29457. * @type {ComputeBuiltinNode<uvec3>}
  29458. */
  29459. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  29460. /**
  29461. * A device dependent variable that exposes the size of the current invocation's subgroup.
  29462. *
  29463. * @tsl
  29464. * @type {ComputeBuiltinNode<uint>}
  29465. */
  29466. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  29467. /**
  29468. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  29469. *
  29470. * This node can only be used with a WebGPU backend.
  29471. *
  29472. * @augments Node
  29473. */
  29474. class BarrierNode extends Node {
  29475. /**
  29476. * Constructs a new barrier node.
  29477. *
  29478. * @param {string} scope - The scope defines the behavior of the node.
  29479. */
  29480. constructor( scope ) {
  29481. super();
  29482. this.scope = scope;
  29483. }
  29484. generate( builder ) {
  29485. const { scope } = this;
  29486. const { renderer } = builder;
  29487. if ( renderer.backend.isWebGLBackend === true ) {
  29488. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  29489. } else {
  29490. builder.addLineFlowCode( `${scope}Barrier()`, this );
  29491. }
  29492. }
  29493. }
  29494. /**
  29495. * TSL function for creating a barrier node.
  29496. *
  29497. * @tsl
  29498. * @function
  29499. * @param {string} scope - The scope defines the behavior of the node..
  29500. * @returns {BarrierNode}
  29501. */
  29502. const barrier = nodeProxy( BarrierNode );
  29503. /**
  29504. * TSL function for creating a workgroup barrier. All compute shader
  29505. * invocations must wait for each invocation within a workgroup to
  29506. * complete before the barrier can be surpassed.
  29507. *
  29508. * @tsl
  29509. * @function
  29510. * @returns {BarrierNode}
  29511. */
  29512. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  29513. /**
  29514. * TSL function for creating a storage barrier. All invocations must
  29515. * wait for each access to variables within the 'storage' address space
  29516. * to complete before the barrier can be passed.
  29517. *
  29518. * @tsl
  29519. * @function
  29520. * @returns {BarrierNode}
  29521. */
  29522. const storageBarrier = () => barrier( 'storage' ).toStack();
  29523. /**
  29524. * TSL function for creating a texture barrier. All invocations must
  29525. * wait for each access to variables within the 'texture' address space
  29526. * to complete before the barrier can be passed.
  29527. *
  29528. * @tsl
  29529. * @function
  29530. * @returns {BarrierNode}
  29531. */
  29532. const textureBarrier = () => barrier( 'texture' ).toStack();
  29533. /**
  29534. * Represents an element of a 'workgroup' scoped buffer.
  29535. *
  29536. * @augments ArrayElementNode
  29537. */
  29538. class WorkgroupInfoElementNode extends ArrayElementNode {
  29539. /**
  29540. * Constructs a new workgroup info element node.
  29541. *
  29542. * @param {Node} workgroupInfoNode - The workgroup info node.
  29543. * @param {Node} indexNode - The index node that defines the element access.
  29544. */
  29545. constructor( workgroupInfoNode, indexNode ) {
  29546. super( workgroupInfoNode, indexNode );
  29547. /**
  29548. * This flag can be used for type testing.
  29549. *
  29550. * @type {boolean}
  29551. * @readonly
  29552. * @default true
  29553. */
  29554. this.isWorkgroupInfoElementNode = true;
  29555. }
  29556. generate( builder, output ) {
  29557. let snippet;
  29558. const isAssignContext = builder.context.assign;
  29559. snippet = super.generate( builder );
  29560. if ( isAssignContext !== true ) {
  29561. const type = this.getNodeType( builder );
  29562. snippet = builder.format( snippet, type, output );
  29563. }
  29564. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  29565. return snippet;
  29566. }
  29567. }
  29568. /**
  29569. * A node allowing the user to create a 'workgroup' scoped buffer within the
  29570. * context of a compute shader. Typically, workgroup scoped buffers are
  29571. * created to hold data that is transferred from a global storage scope into
  29572. * a local workgroup scope. For invocations within a workgroup, data
  29573. * access speeds on 'workgroup' scoped buffers can be significantly faster
  29574. * than similar access operations on globally accessible storage buffers.
  29575. *
  29576. * This node can only be used with a WebGPU backend.
  29577. *
  29578. * @augments Node
  29579. */
  29580. class WorkgroupInfoNode extends Node {
  29581. /**
  29582. * Constructs a new buffer scoped to type scope.
  29583. *
  29584. * @param {string} scope - TODO.
  29585. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  29586. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  29587. */
  29588. constructor( scope, bufferType, bufferCount = 0 ) {
  29589. super( bufferType );
  29590. /**
  29591. * The buffer type.
  29592. *
  29593. * @type {string}
  29594. */
  29595. this.bufferType = bufferType;
  29596. /**
  29597. * The buffer count.
  29598. *
  29599. * @type {number}
  29600. * @default 0
  29601. */
  29602. this.bufferCount = bufferCount;
  29603. /**
  29604. * This flag can be used for type testing.
  29605. *
  29606. * @type {boolean}
  29607. * @readonly
  29608. * @default true
  29609. */
  29610. this.isWorkgroupInfoNode = true;
  29611. /**
  29612. * The data type of the array buffer.
  29613. *
  29614. * @type {string}
  29615. */
  29616. this.elementType = bufferType;
  29617. /**
  29618. * TODO.
  29619. *
  29620. * @type {string}
  29621. */
  29622. this.scope = scope;
  29623. /**
  29624. * The name of the workgroup scoped buffer.
  29625. *
  29626. * @type {string}
  29627. * @default ''
  29628. */
  29629. this.name = '';
  29630. }
  29631. /**
  29632. * Sets the name of this node.
  29633. *
  29634. * @param {string} name - The name to set.
  29635. * @return {WorkgroupInfoNode} A reference to this node.
  29636. */
  29637. setName( name ) {
  29638. this.name = name;
  29639. return this;
  29640. }
  29641. /**
  29642. * Sets the name/label of this node.
  29643. *
  29644. * @deprecated
  29645. * @param {string} name - The name to set.
  29646. * @return {WorkgroupInfoNode} A reference to this node.
  29647. */
  29648. label( name ) {
  29649. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  29650. return this.setName( name );
  29651. }
  29652. /**
  29653. * Sets the scope of this node.
  29654. *
  29655. * @param {string} scope - The scope to set.
  29656. * @return {WorkgroupInfoNode} A reference to this node.
  29657. */
  29658. setScope( scope ) {
  29659. this.scope = scope;
  29660. return this;
  29661. }
  29662. /**
  29663. * The data type of the array buffer.
  29664. *
  29665. * @return {string} The element type.
  29666. */
  29667. getElementType() {
  29668. return this.elementType;
  29669. }
  29670. /**
  29671. * Overwrites the default implementation since the input type
  29672. * is inferred from the scope.
  29673. *
  29674. * @param {NodeBuilder} builder - The current node builder.
  29675. * @return {string} The input type.
  29676. */
  29677. getInputType( /*builder*/ ) {
  29678. return `${this.scope}Array`;
  29679. }
  29680. /**
  29681. * This method can be used to access elements via an index node.
  29682. *
  29683. * @param {IndexNode} indexNode - indexNode.
  29684. * @return {WorkgroupInfoElementNode} A reference to an element.
  29685. */
  29686. element( indexNode ) {
  29687. return new WorkgroupInfoElementNode( this, indexNode );
  29688. }
  29689. generate( builder ) {
  29690. const name = ( this.name !== '' ) ? this.name : `${this.scope}Array_${this.id}`;
  29691. return builder.getScopedArray( name, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  29692. }
  29693. }
  29694. /**
  29695. * TSL function for creating a workgroup info node.
  29696. * Creates a new 'workgroup' scoped array buffer.
  29697. *
  29698. * @tsl
  29699. * @function
  29700. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  29701. * @param {number} [count=0] - The number of elements in the buffer.
  29702. * @returns {WorkgroupInfoNode}
  29703. */
  29704. const workgroupArray = ( type, count ) => new WorkgroupInfoNode( 'Workgroup', type, count );
  29705. /**
  29706. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  29707. * within a shader. In an atomic function, any modification to an atomic variable will
  29708. * occur as an indivisible step with a defined order relative to other modifications.
  29709. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  29710. * atomic operations will not interfere with each other.
  29711. *
  29712. * This node can only be used with a WebGPU backend.
  29713. *
  29714. * @augments Node
  29715. */
  29716. class AtomicFunctionNode extends Node {
  29717. static get type() {
  29718. return 'AtomicFunctionNode';
  29719. }
  29720. /**
  29721. * Constructs a new atomic function node.
  29722. *
  29723. * @param {string} method - The signature of the atomic function to construct.
  29724. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29725. * @param {Node} valueNode - The value that mutates the atomic variable.
  29726. */
  29727. constructor( method, pointerNode, valueNode ) {
  29728. super( 'uint' );
  29729. /**
  29730. * The signature of the atomic function to construct.
  29731. *
  29732. * @type {string}
  29733. */
  29734. this.method = method;
  29735. /**
  29736. * An atomic variable or element of an atomic buffer.
  29737. *
  29738. * @type {Node}
  29739. */
  29740. this.pointerNode = pointerNode;
  29741. /**
  29742. * A value that modifies the atomic variable.
  29743. *
  29744. * @type {Node}
  29745. */
  29746. this.valueNode = valueNode;
  29747. /**
  29748. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  29749. *
  29750. * @type {boolean}
  29751. * @default true
  29752. */
  29753. this.parents = true;
  29754. }
  29755. /**
  29756. * Overwrites the default implementation to return the type of
  29757. * the pointer node.
  29758. *
  29759. * @param {NodeBuilder} builder - The current node builder.
  29760. * @return {string} The input type.
  29761. */
  29762. getInputType( builder ) {
  29763. return this.pointerNode.getNodeType( builder );
  29764. }
  29765. /**
  29766. * Overwritten since the node type is inferred from the input type.
  29767. *
  29768. * @param {NodeBuilder} builder - The current node builder.
  29769. * @return {string} The node type.
  29770. */
  29771. getNodeType( builder ) {
  29772. return this.getInputType( builder );
  29773. }
  29774. generate( builder ) {
  29775. const properties = builder.getNodeProperties( this );
  29776. const parents = properties.parents;
  29777. const method = this.method;
  29778. const type = this.getNodeType( builder );
  29779. const inputType = this.getInputType( builder );
  29780. const a = this.pointerNode;
  29781. const b = this.valueNode;
  29782. const params = [];
  29783. params.push( `&${ a.build( builder, inputType ) }` );
  29784. if ( b !== null ) {
  29785. params.push( b.build( builder, inputType ) );
  29786. }
  29787. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  29788. const isVoid = parents ? ( parents.length === 1 && parents[ 0 ].isStackNode === true ) : false;
  29789. if ( isVoid ) {
  29790. builder.addLineFlowCode( methodSnippet, this );
  29791. } else {
  29792. if ( properties.constNode === undefined ) {
  29793. properties.constNode = expression( methodSnippet, type ).toConst();
  29794. }
  29795. return properties.constNode.build( builder );
  29796. }
  29797. }
  29798. }
  29799. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  29800. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  29801. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  29802. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  29803. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  29804. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  29805. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  29806. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  29807. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  29808. /**
  29809. * TSL function for creating an atomic function node.
  29810. *
  29811. * @tsl
  29812. * @function
  29813. * @param {string} method - The signature of the atomic function to construct.
  29814. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29815. * @param {Node} valueNode - The value that mutates the atomic variable.
  29816. * @returns {AtomicFunctionNode}
  29817. */
  29818. const atomicNode = nodeProxy( AtomicFunctionNode );
  29819. /**
  29820. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  29821. *
  29822. * @tsl
  29823. * @function
  29824. * @param {string} method - The signature of the atomic function to construct.
  29825. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29826. * @param {Node} valueNode - The value that mutates the atomic variable.
  29827. * @returns {AtomicFunctionNode}
  29828. */
  29829. const atomicFunc = ( method, pointerNode, valueNode ) => {
  29830. return atomicNode( method, pointerNode, valueNode ).toStack();
  29831. };
  29832. /**
  29833. * Loads the value stored in the atomic variable.
  29834. *
  29835. * @tsl
  29836. * @function
  29837. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29838. * @returns {AtomicFunctionNode}
  29839. */
  29840. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  29841. /**
  29842. * Stores a value in the atomic variable.
  29843. *
  29844. * @tsl
  29845. * @function
  29846. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29847. * @param {Node} valueNode - The value that mutates the atomic variable.
  29848. * @returns {AtomicFunctionNode}
  29849. */
  29850. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  29851. /**
  29852. * Increments the value stored in the atomic variable.
  29853. *
  29854. * @tsl
  29855. * @function
  29856. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29857. * @param {Node} valueNode - The value that mutates the atomic variable.
  29858. * @returns {AtomicFunctionNode}
  29859. */
  29860. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  29861. /**
  29862. * Decrements the value stored in the atomic variable.
  29863. *
  29864. * @tsl
  29865. * @function
  29866. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29867. * @param {Node} valueNode - The value that mutates the atomic variable.
  29868. * @returns {AtomicFunctionNode}
  29869. */
  29870. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  29871. /**
  29872. * Stores in an atomic variable the maximum between its current value and a parameter.
  29873. *
  29874. * @tsl
  29875. * @function
  29876. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29877. * @param {Node} valueNode - The value that mutates the atomic variable.
  29878. * @returns {AtomicFunctionNode}
  29879. */
  29880. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  29881. /**
  29882. * Stores in an atomic variable the minimum between its current value and a parameter.
  29883. *
  29884. * @tsl
  29885. * @function
  29886. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29887. * @param {Node} valueNode - The value that mutates the atomic variable.
  29888. * @returns {AtomicFunctionNode}
  29889. */
  29890. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  29891. /**
  29892. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  29893. *
  29894. * @tsl
  29895. * @function
  29896. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29897. * @param {Node} valueNode - The value that mutates the atomic variable.
  29898. * @returns {AtomicFunctionNode}
  29899. */
  29900. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  29901. /**
  29902. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  29903. *
  29904. * @tsl
  29905. * @function
  29906. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29907. * @param {Node} valueNode - The value that mutates the atomic variable.
  29908. * @returns {AtomicFunctionNode}
  29909. */
  29910. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  29911. /**
  29912. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  29913. *
  29914. * @tsl
  29915. * @function
  29916. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29917. * @param {Node} valueNode - The value that mutates the atomic variable.
  29918. * @returns {AtomicFunctionNode}
  29919. */
  29920. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  29921. /**
  29922. * This class represents a set of built in WGSL shader functions that sync
  29923. * synchronously execute an operation across a subgroup, or 'warp', of compute
  29924. * or fragment shader invocations within a workgroup. Typically, these functions
  29925. * will synchronously execute an operation using data from all active invocations
  29926. * within the subgroup, then broadcast that result to all active invocations. In
  29927. * other graphics APIs, subgroup functions are also referred to as wave intrinsics
  29928. * (DirectX/HLSL) or warp intrinsics (CUDA).
  29929. *
  29930. * @augments TempNode
  29931. */
  29932. class SubgroupFunctionNode extends TempNode {
  29933. static get type() {
  29934. return 'SubgroupFunctionNode';
  29935. }
  29936. /**
  29937. * Constructs a new function node.
  29938. *
  29939. * @param {string} method - The subgroup/wave intrinsic method to construct.
  29940. * @param {Node} [aNode=null] - The method's first argument.
  29941. * @param {Node} [bNode=null] - The method's second argument.
  29942. */
  29943. constructor( method, aNode = null, bNode = null ) {
  29944. super();
  29945. /**
  29946. * The subgroup/wave intrinsic method to construct.
  29947. *
  29948. * @type {string}
  29949. */
  29950. this.method = method;
  29951. /**
  29952. * The method's first argument.
  29953. *
  29954. * @type {Node}
  29955. */
  29956. this.aNode = aNode;
  29957. /**
  29958. * The method's second argument.
  29959. *
  29960. * @type {Node}
  29961. */
  29962. this.bNode = bNode;
  29963. }
  29964. getInputType( builder ) {
  29965. const aType = this.aNode ? this.aNode.getNodeType( builder ) : null;
  29966. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  29967. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  29968. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  29969. if ( aLen > bLen ) {
  29970. return aType;
  29971. } else {
  29972. return bType;
  29973. }
  29974. }
  29975. getNodeType( builder ) {
  29976. const method = this.method;
  29977. if ( method === SubgroupFunctionNode.SUBGROUP_ELECT ) {
  29978. return 'bool';
  29979. } else if ( method === SubgroupFunctionNode.SUBGROUP_BALLOT ) {
  29980. return 'uvec4';
  29981. } else {
  29982. return this.getInputType( builder );
  29983. }
  29984. }
  29985. generate( builder, output ) {
  29986. const method = this.method;
  29987. const type = this.getNodeType( builder );
  29988. const inputType = this.getInputType( builder );
  29989. const a = this.aNode;
  29990. const b = this.bNode;
  29991. const params = [];
  29992. if (
  29993. method === SubgroupFunctionNode.SUBGROUP_BROADCAST ||
  29994. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE ||
  29995. method === SubgroupFunctionNode.QUAD_BROADCAST
  29996. ) {
  29997. const bType = b.getNodeType( builder );
  29998. params.push(
  29999. a.build( builder, type ),
  30000. b.build( builder, bType === 'float' ? 'int' : type )
  30001. );
  30002. } else if (
  30003. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ||
  30004. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ||
  30005. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP
  30006. ) {
  30007. params.push(
  30008. a.build( builder, type ),
  30009. b.build( builder, 'uint' )
  30010. );
  30011. } else {
  30012. if ( a !== null ) params.push( a.build( builder, inputType ) );
  30013. if ( b !== null ) params.push( b.build( builder, inputType ) );
  30014. }
  30015. const paramsString = params.length === 0 ? '()' : `( ${params.join( ', ' )} )`;
  30016. return builder.format( `${ builder.getMethod( method, type ) }${paramsString}`, type, output );
  30017. }
  30018. serialize( data ) {
  30019. super.serialize( data );
  30020. data.method = this.method;
  30021. }
  30022. deserialize( data ) {
  30023. super.deserialize( data );
  30024. this.method = data.method;
  30025. }
  30026. }
  30027. // 0 inputs
  30028. SubgroupFunctionNode.SUBGROUP_ELECT = 'subgroupElect';
  30029. // 1 input
  30030. SubgroupFunctionNode.SUBGROUP_BALLOT = 'subgroupBallot';
  30031. SubgroupFunctionNode.SUBGROUP_ADD = 'subgroupAdd';
  30032. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD = 'subgroupInclusiveAdd';
  30033. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND = 'subgroupExclusiveAdd';
  30034. SubgroupFunctionNode.SUBGROUP_MUL = 'subgroupMul';
  30035. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL = 'subgroupInclusiveMul';
  30036. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL = 'subgroupExclusiveMul';
  30037. SubgroupFunctionNode.SUBGROUP_AND = 'subgroupAnd';
  30038. SubgroupFunctionNode.SUBGROUP_OR = 'subgroupOr';
  30039. SubgroupFunctionNode.SUBGROUP_XOR = 'subgroupXor';
  30040. SubgroupFunctionNode.SUBGROUP_MIN = 'subgroupMin';
  30041. SubgroupFunctionNode.SUBGROUP_MAX = 'subgroupMax';
  30042. SubgroupFunctionNode.SUBGROUP_ALL = 'subgroupAll';
  30043. SubgroupFunctionNode.SUBGROUP_ANY = 'subgroupAny';
  30044. SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST = 'subgroupBroadcastFirst';
  30045. SubgroupFunctionNode.QUAD_SWAP_X = 'quadSwapX';
  30046. SubgroupFunctionNode.QUAD_SWAP_Y = 'quadSwapY';
  30047. SubgroupFunctionNode.QUAD_SWAP_DIAGONAL = 'quadSwapDiagonal';
  30048. // 2 inputs
  30049. SubgroupFunctionNode.SUBGROUP_BROADCAST = 'subgroupBroadcast';
  30050. SubgroupFunctionNode.SUBGROUP_SHUFFLE = 'subgroupShuffle';
  30051. SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR = 'subgroupShuffleXor';
  30052. SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP = 'subgroupShuffleUp';
  30053. SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN = 'subgroupShuffleDown';
  30054. SubgroupFunctionNode.QUAD_BROADCAST = 'quadBroadcast';
  30055. /**
  30056. * Returns true if this invocation has the lowest subgroup_invocation_id
  30057. * among active invocations in the subgroup.
  30058. *
  30059. * @tsl
  30060. * @method
  30061. * @return {bool} The result of the computation.
  30062. */
  30063. const subgroupElect = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ELECT ).setParameterLength( 0 );
  30064. /**
  30065. * Returns a set of bitfields where the bit corresponding to subgroup_invocation_id
  30066. * is 1 if pred is true for that active invocation and 0 otherwise.
  30067. *
  30068. * @tsl
  30069. * @method
  30070. * @param {bool} pred - A boolean that sets the bit corresponding to the invocations subgroup invocation id.
  30071. * @return {vec4<u32>}- A bitfield corresponding to the pred value of each subgroup invocation.
  30072. */
  30073. const subgroupBallot = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BALLOT ).setParameterLength( 1 );
  30074. /**
  30075. * A reduction that adds e among all active invocations and returns that result.
  30076. *
  30077. * @tsl
  30078. * @method
  30079. * @param {number} e - The value provided to the reduction by the current invocation.
  30080. * @return {number} The accumulated result of the reduction operation.
  30081. */
  30082. const subgroupAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ADD ).setParameterLength( 1 );
  30083. /**
  30084. * An inclusive scan returning the sum of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  30085. *
  30086. * @tsl
  30087. * @method
  30088. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  30089. * @return {number} The accumulated result of the inclusive scan operation.
  30090. */
  30091. const subgroupInclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD ).setParameterLength( 1 );
  30092. /**
  30093. * An exclusive scan that returns the sum of e for all active invocations with subgroup_invocation_id less than this invocation.
  30094. *
  30095. * @tsl
  30096. * @method
  30097. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  30098. * @return {number} The accumulated result of the exclusive scan operation.
  30099. */
  30100. const subgroupExclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND ).setParameterLength( 1 );
  30101. /**
  30102. * A reduction that multiplies e among all active invocations and returns that result.
  30103. *
  30104. * @tsl
  30105. * @method
  30106. * @param {number} e - The value provided to the reduction by the current invocation.
  30107. * @return {number} The accumulated result of the reduction operation.
  30108. */
  30109. const subgroupMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MUL ).setParameterLength( 1 );
  30110. /**
  30111. * An inclusive scan returning the product of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  30112. *
  30113. * @tsl
  30114. * @method
  30115. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  30116. * @return {number} The accumulated result of the inclusive scan operation.
  30117. */
  30118. const subgroupInclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL ).setParameterLength( 1 );
  30119. /**
  30120. * An exclusive scan that returns the product of e for all active invocations with subgroup_invocation_id less than this invocation.
  30121. *
  30122. * @tsl
  30123. * @method
  30124. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  30125. * @return {number} The accumulated result of the exclusive scan operation.
  30126. */
  30127. const subgroupExclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL ).setParameterLength( 1 );
  30128. /**
  30129. * A reduction that performs a bitwise and of e among all active invocations and returns that result.
  30130. *
  30131. * @tsl
  30132. * @method
  30133. * @param {number} e - The value provided to the reduction by the current invocation.
  30134. * @return {number} The result of the reduction operation.
  30135. */
  30136. const subgroupAnd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_AND ).setParameterLength( 1 );
  30137. /**
  30138. * A reduction that performs a bitwise or of e among all active invocations and returns that result.
  30139. *
  30140. * @tsl
  30141. * @method
  30142. * @param {number} e - The value provided to the reduction by the current invocation.
  30143. * @return {number} The result of the reduction operation.
  30144. */
  30145. const subgroupOr = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_OR ).setParameterLength( 1 );
  30146. /**
  30147. * A reduction that performs a bitwise xor of e among all active invocations and returns that result.
  30148. *
  30149. * @tsl
  30150. * @method
  30151. * @param {number} e - The value provided to the reduction by the current invocation.
  30152. * @return {number} The result of the reduction operation.
  30153. */
  30154. const subgroupXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_XOR ).setParameterLength( 1 );
  30155. /**
  30156. * A reduction that performs a min of e among all active invocations and returns that result.
  30157. *
  30158. * @tsl
  30159. * @method
  30160. * @param {number} e - The value provided to the reduction by the current invocation.
  30161. * @return {number} The result of the reduction operation.
  30162. */
  30163. const subgroupMin = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MIN ).setParameterLength( 1 );
  30164. /**
  30165. * A reduction that performs a max of e among all active invocations and returns that result.
  30166. *
  30167. * @tsl
  30168. * @method
  30169. * @param {number} e - The value provided to the reduction by the current invocation.
  30170. * @return {number} The result of the reduction operation.
  30171. */
  30172. const subgroupMax = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MAX ).setParameterLength( 1 );
  30173. /**
  30174. * Returns true if e is true for all active invocations in the subgroup.
  30175. *
  30176. * @tsl
  30177. * @method
  30178. * @return {bool} The result of the computation.
  30179. */
  30180. const subgroupAll = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ALL ).setParameterLength( 0 );
  30181. /**
  30182. * Returns true if e is true for any active invocation in the subgroup
  30183. *
  30184. * @tsl
  30185. * @method
  30186. * @return {bool} The result of the computation.
  30187. */
  30188. const subgroupAny = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ANY ).setParameterLength( 0 );
  30189. /**
  30190. * Broadcasts e from the active invocation with the lowest subgroup_invocation_id in the subgroup to all other active invocations.
  30191. *
  30192. * @tsl
  30193. * @method
  30194. * @param {number} e - The value to broadcast from the lowest subgroup invocation.
  30195. * @param {number} id - The subgroup invocation to broadcast from.
  30196. * @return {number} The broadcast value.
  30197. */
  30198. const subgroupBroadcastFirst = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST ).setParameterLength( 2 );
  30199. /**
  30200. * Swaps e between invocations in the quad in the X direction.
  30201. *
  30202. * @tsl
  30203. * @method
  30204. * @param {number} e - The value to swap from the current invocation.
  30205. * @return {number} The value received from the swap operation.
  30206. */
  30207. const quadSwapX = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_X ).setParameterLength( 1 );
  30208. /**
  30209. * Swaps e between invocations in the quad in the Y direction.
  30210. *
  30211. * @tsl
  30212. * @method
  30213. * @param {number} e - The value to swap from the current invocation.
  30214. * @return {number} The value received from the swap operation.
  30215. */
  30216. const quadSwapY = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_Y ).setParameterLength( 1 );
  30217. /**
  30218. * Swaps e between invocations in the quad diagonally.
  30219. *
  30220. * @tsl
  30221. * @method
  30222. * @param {number} e - The value to swap from the current invocation.
  30223. * @return {number} The value received from the swap operation.
  30224. */
  30225. const quadSwapDiagonal = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_DIAGONAL ).setParameterLength( 1 );
  30226. /**
  30227. * Broadcasts e from the invocation whose subgroup_invocation_id matches id, to all active invocations.
  30228. *
  30229. * @tsl
  30230. * @method
  30231. * @param {number} e - The value to broadcast from subgroup invocation 'id'.
  30232. * @param {number} id - The subgroup invocation to broadcast from.
  30233. * @return {number} The broadcast value.
  30234. */
  30235. const subgroupBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST ).setParameterLength( 2 );
  30236. /**
  30237. * Returns v from the active invocation whose subgroup_invocation_id matches id
  30238. *
  30239. * @tsl
  30240. * @method
  30241. * @param {number} v - The value to return from subgroup invocation id^mask.
  30242. * @param {number} id - The subgroup invocation which returns the value v.
  30243. * @return {number} The broadcast value.
  30244. */
  30245. const subgroupShuffle = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE ).setParameterLength( 2 );
  30246. /**
  30247. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id ^ mask.
  30248. *
  30249. * @tsl
  30250. * @method
  30251. * @param {number} v - The value to return from subgroup invocation id^mask.
  30252. * @param {number} mask - A bitmask that determines the target invocation via a XOR operation.
  30253. * @return {number} The broadcast value.
  30254. */
  30255. const subgroupShuffleXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ).setParameterLength( 2 );
  30256. /**
  30257. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id - delta
  30258. *
  30259. * @tsl
  30260. * @method
  30261. * @param {number} v - The value to return from subgroup invocation id^mask.
  30262. * @param {number} delta - A value that offsets the current in.
  30263. * @return {number} The broadcast value.
  30264. */
  30265. const subgroupShuffleUp = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP ).setParameterLength( 2 );
  30266. /**
  30267. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id + delta
  30268. *
  30269. * @tsl
  30270. * @method
  30271. * @param {number} v - The value to return from subgroup invocation id^mask.
  30272. * @param {number} delta - A value that offsets the current subgroup invocation.
  30273. * @return {number} The broadcast value.
  30274. */
  30275. const subgroupShuffleDown = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ).setParameterLength( 2 );
  30276. /**
  30277. * Broadcasts e from the quad invocation with id equal to id.
  30278. *
  30279. * @tsl
  30280. * @method
  30281. * @param {number} e - The value to broadcast.
  30282. * @return {number} The broadcast value.
  30283. */
  30284. const quadBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_BROADCAST ).setParameterLength( 1 );
  30285. let uniformsLib;
  30286. function getLightData( light ) {
  30287. uniformsLib = uniformsLib || new WeakMap();
  30288. let uniforms = uniformsLib.get( light );
  30289. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  30290. return uniforms;
  30291. }
  30292. /**
  30293. * TSL function for getting a shadow matrix uniform node for the given light.
  30294. *
  30295. * @tsl
  30296. * @function
  30297. * @param {Light} light -The light source.
  30298. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  30299. */
  30300. function lightShadowMatrix( light ) {
  30301. const data = getLightData( light );
  30302. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  30303. // normally, shadow matrices are updated in ShadowNode. However, if the shadow matrix is used outside
  30304. // of shadow rendering (like in ProjectorLightNode), the shadow matrix still requires an update
  30305. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  30306. if ( light.shadow.camera.coordinateSystem !== frame.camera.coordinateSystem ) {
  30307. light.shadow.camera.coordinateSystem = frame.camera.coordinateSystem;
  30308. light.shadow.camera.updateProjectionMatrix();
  30309. }
  30310. light.shadow.updateMatrices( light );
  30311. }
  30312. return light.shadow.matrix;
  30313. } ) );
  30314. }
  30315. /**
  30316. * TSL function for getting projected uv coordinates for the given light.
  30317. * Relevant when using maps with spot lights.
  30318. *
  30319. * @tsl
  30320. * @function
  30321. * @param {Light} light -The light source.
  30322. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  30323. * @returns {Node<vec3>} The projected uvs.
  30324. */
  30325. function lightProjectionUV( light, position = positionWorld ) {
  30326. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  30327. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  30328. return projectionUV;
  30329. }
  30330. /**
  30331. * TSL function for getting the position in world space for the given light.
  30332. *
  30333. * @tsl
  30334. * @function
  30335. * @param {Light} light -The light source.
  30336. * @returns {UniformNode<vec3>} The light's position in world space.
  30337. */
  30338. function lightPosition( light ) {
  30339. const data = getLightData( light );
  30340. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  30341. }
  30342. /**
  30343. * TSL function for getting the light target position in world space for the given light.
  30344. *
  30345. * @tsl
  30346. * @function
  30347. * @param {Light} light -The light source.
  30348. * @returns {UniformNode<vec3>} The light target position in world space.
  30349. */
  30350. function lightTargetPosition( light ) {
  30351. const data = getLightData( light );
  30352. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  30353. }
  30354. /**
  30355. * TSL function for getting the position in view space for the given light.
  30356. *
  30357. * @tsl
  30358. * @function
  30359. * @param {Light} light - The light source.
  30360. * @returns {UniformNode<vec3>} The light's position in view space.
  30361. */
  30362. function lightViewPosition( light ) {
  30363. const data = getLightData( light );
  30364. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  30365. self.value = self.value || new Vector3();
  30366. self.value.setFromMatrixPosition( light.matrixWorld );
  30367. self.value.applyMatrix4( camera.matrixWorldInverse );
  30368. } ) );
  30369. }
  30370. /**
  30371. * TSL function for getting the light target direction for the given light.
  30372. *
  30373. * @tsl
  30374. * @function
  30375. * @param {Light} light -The light source.
  30376. * @returns {Node<vec3>} The light's target direction.
  30377. */
  30378. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  30379. const sortLights = ( lights ) => {
  30380. return lights.sort( ( a, b ) => a.id - b.id );
  30381. };
  30382. const getLightNodeById = ( id, lightNodes ) => {
  30383. for ( const lightNode of lightNodes ) {
  30384. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  30385. return lightNode;
  30386. }
  30387. }
  30388. return null;
  30389. };
  30390. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  30391. const _hashData = [];
  30392. /**
  30393. * This node represents the scene's lighting and manages the lighting model's life cycle
  30394. * for the current build 3D object. It is responsible for computing the total outgoing
  30395. * light in a given lighting context.
  30396. *
  30397. * @augments Node
  30398. */
  30399. class LightsNode extends Node {
  30400. static get type() {
  30401. return 'LightsNode';
  30402. }
  30403. /**
  30404. * Constructs a new lights node.
  30405. */
  30406. constructor() {
  30407. super( 'vec3' );
  30408. /**
  30409. * A node representing the total diffuse light.
  30410. *
  30411. * @type {Node<vec3>}
  30412. */
  30413. this.totalDiffuseNode = property( 'vec3', 'totalDiffuse' );
  30414. /**
  30415. * A node representing the total specular light.
  30416. *
  30417. * @type {Node<vec3>}
  30418. */
  30419. this.totalSpecularNode = property( 'vec3', 'totalSpecular' );
  30420. /**
  30421. * A node representing the outgoing light.
  30422. *
  30423. * @type {Node<vec3>}
  30424. */
  30425. this.outgoingLightNode = property( 'vec3', 'outgoingLight' );
  30426. /**
  30427. * An array representing the lights in the scene.
  30428. *
  30429. * @private
  30430. * @type {Array<Light>}
  30431. */
  30432. this._lights = [];
  30433. /**
  30434. * For each light in the scene, this node will create a
  30435. * corresponding light node.
  30436. *
  30437. * @private
  30438. * @type {?Array<LightingNode>}
  30439. * @default null
  30440. */
  30441. this._lightNodes = null;
  30442. /**
  30443. * A hash for identifying the current light nodes setup.
  30444. *
  30445. * @private
  30446. * @type {?string}
  30447. * @default null
  30448. */
  30449. this._lightNodesHash = null;
  30450. /**
  30451. * `LightsNode` sets this property to `true` by default.
  30452. *
  30453. * @type {boolean}
  30454. * @default true
  30455. */
  30456. this.global = true;
  30457. }
  30458. /**
  30459. * Overwrites the default {@link Node#customCacheKey} implementation by including
  30460. * light data into the cache key.
  30461. *
  30462. * @return {number} The custom cache key.
  30463. */
  30464. customCacheKey() {
  30465. const lights = this._lights;
  30466. for ( let i = 0; i < lights.length; i ++ ) {
  30467. const light = lights[ i ];
  30468. _hashData.push( light.id );
  30469. _hashData.push( light.castShadow ? 1 : 0 );
  30470. if ( light.isSpotLight === true ) {
  30471. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  30472. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  30473. _hashData.push( hashMap, hashColorNode );
  30474. }
  30475. }
  30476. const cacheKey = hashArray( _hashData );
  30477. _hashData.length = 0;
  30478. return cacheKey;
  30479. }
  30480. /**
  30481. * Computes a hash value for identifying the current light nodes setup.
  30482. *
  30483. * @param {NodeBuilder} builder - A reference to the current node builder.
  30484. * @return {string} The computed hash.
  30485. */
  30486. getHash( builder ) {
  30487. if ( this._lightNodesHash === null ) {
  30488. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  30489. const hash = [];
  30490. for ( const lightNode of this._lightNodes ) {
  30491. hash.push( lightNode.getHash() );
  30492. }
  30493. this._lightNodesHash = 'lights-' + hash.join( ',' );
  30494. }
  30495. return this._lightNodesHash;
  30496. }
  30497. analyze( builder ) {
  30498. const properties = builder.getNodeProperties( this );
  30499. for ( const node of properties.nodes ) {
  30500. node.build( builder );
  30501. }
  30502. properties.outputNode.build( builder );
  30503. }
  30504. /**
  30505. * Creates lighting nodes for each scene light. This makes it possible to further
  30506. * process lights in the node system.
  30507. *
  30508. * @param {NodeBuilder} builder - A reference to the current node builder.
  30509. */
  30510. setupLightsNode( builder ) {
  30511. const lightNodes = [];
  30512. const previousLightNodes = this._lightNodes;
  30513. const lights = sortLights( this._lights );
  30514. const nodeLibrary = builder.renderer.library;
  30515. for ( const light of lights ) {
  30516. if ( light.isNode ) {
  30517. lightNodes.push( nodeObject( light ) );
  30518. } else {
  30519. let lightNode = null;
  30520. if ( previousLightNodes !== null ) {
  30521. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  30522. }
  30523. if ( lightNode === null ) {
  30524. // find the corresponding node type for a given light
  30525. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  30526. if ( lightNodeClass === null ) {
  30527. warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  30528. continue;
  30529. }
  30530. let lightNode = null;
  30531. if ( ! _lightsNodeRef.has( light ) ) {
  30532. lightNode = new lightNodeClass( light );
  30533. _lightsNodeRef.set( light, lightNode );
  30534. } else {
  30535. lightNode = _lightsNodeRef.get( light );
  30536. }
  30537. lightNodes.push( lightNode );
  30538. }
  30539. }
  30540. }
  30541. this._lightNodes = lightNodes;
  30542. }
  30543. /**
  30544. * Sets up a direct light in the lighting model.
  30545. *
  30546. * @param {Object} builder - The builder object containing the context and stack.
  30547. * @param {Object} lightNode - The light node.
  30548. * @param {Object} lightData - The light object containing color and direction properties.
  30549. */
  30550. setupDirectLight( builder, lightNode, lightData ) {
  30551. const { lightingModel, reflectedLight } = builder.context;
  30552. lightingModel.direct( {
  30553. ...lightData,
  30554. lightNode,
  30555. reflectedLight
  30556. }, builder );
  30557. }
  30558. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  30559. const { lightingModel, reflectedLight } = builder.context;
  30560. lightingModel.directRectArea( {
  30561. ...lightData,
  30562. lightNode,
  30563. reflectedLight
  30564. }, builder );
  30565. }
  30566. /**
  30567. * Setups the internal lights by building all respective
  30568. * light nodes.
  30569. *
  30570. * @param {NodeBuilder} builder - A reference to the current node builder.
  30571. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  30572. */
  30573. setupLights( builder, lightNodes ) {
  30574. for ( const lightNode of lightNodes ) {
  30575. lightNode.build( builder );
  30576. }
  30577. }
  30578. getLightNodes( builder ) {
  30579. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  30580. return this._lightNodes;
  30581. }
  30582. /**
  30583. * The implementation makes sure that for each light in the scene
  30584. * there is a corresponding light node. By building the light nodes
  30585. * and evaluating the lighting model the outgoing light is computed.
  30586. *
  30587. * @param {NodeBuilder} builder - A reference to the current node builder.
  30588. * @return {Node<vec3>} A node representing the outgoing light.
  30589. */
  30590. setup( builder ) {
  30591. const currentLightsNode = builder.lightsNode;
  30592. builder.lightsNode = this;
  30593. //
  30594. let outgoingLightNode = this.outgoingLightNode;
  30595. const context = builder.context;
  30596. const lightingModel = context.lightingModel;
  30597. const properties = builder.getNodeProperties( this );
  30598. if ( lightingModel ) {
  30599. const { totalDiffuseNode, totalSpecularNode } = this;
  30600. context.outgoingLight = outgoingLightNode;
  30601. const stack = builder.addStack();
  30602. //
  30603. properties.nodes = stack.nodes;
  30604. //
  30605. lightingModel.start( builder );
  30606. //
  30607. const { backdrop, backdropAlpha } = context;
  30608. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  30609. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  30610. if ( backdrop !== null ) {
  30611. if ( backdropAlpha !== null ) {
  30612. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  30613. } else {
  30614. totalDiffuse = vec3( backdrop );
  30615. }
  30616. }
  30617. totalDiffuseNode.assign( totalDiffuse );
  30618. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  30619. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  30620. //
  30621. lightingModel.finish( builder );
  30622. //
  30623. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  30624. } else {
  30625. properties.nodes = [];
  30626. }
  30627. //
  30628. builder.lightsNode = currentLightsNode;
  30629. return outgoingLightNode;
  30630. }
  30631. /**
  30632. * Configures this node with an array of lights.
  30633. *
  30634. * @param {Array<Light>} lights - An array of lights.
  30635. * @return {LightsNode} A reference to this node.
  30636. */
  30637. setLights( lights ) {
  30638. this._lights = lights;
  30639. this._lightNodes = null;
  30640. this._lightNodesHash = null;
  30641. return this;
  30642. }
  30643. /**
  30644. * Returns an array of the scene's lights.
  30645. *
  30646. * @return {Array<Light>} The scene's lights.
  30647. */
  30648. getLights() {
  30649. return this._lights;
  30650. }
  30651. /**
  30652. * Whether the scene has lights or not.
  30653. *
  30654. * @type {boolean}
  30655. */
  30656. get hasLights() {
  30657. return this._lights.length > 0;
  30658. }
  30659. }
  30660. /**
  30661. * TSL function for creating an instance of `LightsNode` and configuring
  30662. * it with the given array of lights.
  30663. *
  30664. * @tsl
  30665. * @function
  30666. * @param {Array<Light>} lights - An array of lights.
  30667. * @return {LightsNode} The created lights node.
  30668. */
  30669. const lights = ( lights = [] ) => new LightsNode().setLights( lights );
  30670. /**
  30671. * Base class for all shadow nodes.
  30672. *
  30673. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  30674. * Lighting nodes might share the same shadow node type or use specific ones depending on
  30675. * their requirements.
  30676. *
  30677. * @augments Node
  30678. */
  30679. class ShadowBaseNode extends Node {
  30680. static get type() {
  30681. return 'ShadowBaseNode';
  30682. }
  30683. /**
  30684. * Constructs a new shadow base node.
  30685. *
  30686. * @param {Light} light - The shadow casting light.
  30687. */
  30688. constructor( light ) {
  30689. super();
  30690. /**
  30691. * The shadow casting light.
  30692. *
  30693. * @type {Light}
  30694. */
  30695. this.light = light;
  30696. /**
  30697. * Overwritten since shadows are updated by default per render.
  30698. *
  30699. * @type {string}
  30700. * @default 'render'
  30701. */
  30702. this.updateBeforeType = NodeUpdateType.RENDER;
  30703. /**
  30704. * This flag can be used for type testing.
  30705. *
  30706. * @type {boolean}
  30707. * @readonly
  30708. * @default true
  30709. */
  30710. this.isShadowBaseNode = true;
  30711. }
  30712. /**
  30713. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  30714. *
  30715. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  30716. */
  30717. setupShadowPosition( { context, material } ) {
  30718. // Use assign inside an Fn()
  30719. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  30720. }
  30721. }
  30722. /**
  30723. * TSL object that represents the vertex position in world space during the shadow pass.
  30724. *
  30725. * @tsl
  30726. * @type {Node<vec3>}
  30727. */
  30728. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  30729. /**
  30730. * Saves the state of the given renderer and stores it into the given state object.
  30731. *
  30732. * If not state object is provided, the function creates one.
  30733. *
  30734. * @private
  30735. * @function
  30736. * @param {Renderer} renderer - The renderer.
  30737. * @param {Object} [state={}] - The state.
  30738. * @return {Object} The state.
  30739. */
  30740. function saveRendererState( renderer, state = {} ) {
  30741. state.toneMapping = renderer.toneMapping;
  30742. state.toneMappingExposure = renderer.toneMappingExposure;
  30743. state.outputColorSpace = renderer.outputColorSpace;
  30744. state.renderTarget = renderer.getRenderTarget();
  30745. state.activeCubeFace = renderer.getActiveCubeFace();
  30746. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  30747. state.renderObjectFunction = renderer.getRenderObjectFunction();
  30748. state.pixelRatio = renderer.getPixelRatio();
  30749. state.mrt = renderer.getMRT();
  30750. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  30751. state.clearAlpha = renderer.getClearAlpha();
  30752. state.autoClear = renderer.autoClear;
  30753. state.scissorTest = renderer.getScissorTest();
  30754. return state;
  30755. }
  30756. /**
  30757. * Saves the state of the given renderer and stores it into the given state object.
  30758. * Besides, the function also resets the state of the renderer to its default values.
  30759. *
  30760. * If not state object is provided, the function creates one.
  30761. *
  30762. * @private
  30763. * @function
  30764. * @param {Renderer} renderer - The renderer.
  30765. * @param {Object} [state={}] - The state.
  30766. * @return {Object} The state.
  30767. */
  30768. function resetRendererState( renderer, state ) {
  30769. state = saveRendererState( renderer, state );
  30770. renderer.setMRT( null );
  30771. renderer.setRenderObjectFunction( null );
  30772. renderer.setClearColor( 0x000000, 1 );
  30773. renderer.autoClear = true;
  30774. return state;
  30775. }
  30776. /**
  30777. * Restores the state of the given renderer from the given state object.
  30778. *
  30779. * @private
  30780. * @function
  30781. * @param {Renderer} renderer - The renderer.
  30782. * @param {Object} state - The state to restore.
  30783. */
  30784. function restoreRendererState( renderer, state ) {
  30785. renderer.toneMapping = state.toneMapping;
  30786. renderer.toneMappingExposure = state.toneMappingExposure;
  30787. renderer.outputColorSpace = state.outputColorSpace;
  30788. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  30789. renderer.setRenderObjectFunction( state.renderObjectFunction );
  30790. renderer.setPixelRatio( state.pixelRatio );
  30791. renderer.setMRT( state.mrt );
  30792. renderer.setClearColor( state.clearColor, state.clearAlpha );
  30793. renderer.autoClear = state.autoClear;
  30794. renderer.setScissorTest( state.scissorTest );
  30795. }
  30796. /**
  30797. * Saves the state of the given scene and stores it into the given state object.
  30798. *
  30799. * If not state object is provided, the function creates one.
  30800. *
  30801. * @private
  30802. * @function
  30803. * @param {Scene} scene - The scene.
  30804. * @param {Object} [state={}] - The state.
  30805. * @return {Object} The state.
  30806. */
  30807. function saveSceneState( scene, state = {} ) {
  30808. state.background = scene.background;
  30809. state.backgroundNode = scene.backgroundNode;
  30810. state.overrideMaterial = scene.overrideMaterial;
  30811. return state;
  30812. }
  30813. /**
  30814. * Saves the state of the given scene and stores it into the given state object.
  30815. * Besides, the function also resets the state of the scene to its default values.
  30816. *
  30817. * If not state object is provided, the function creates one.
  30818. *
  30819. * @private
  30820. * @function
  30821. * @param {Scene} scene - The scene.
  30822. * @param {Object} [state={}] - The state.
  30823. * @return {Object} The state.
  30824. */
  30825. function resetSceneState( scene, state ) {
  30826. state = saveSceneState( scene, state );
  30827. scene.background = null;
  30828. scene.backgroundNode = null;
  30829. scene.overrideMaterial = null;
  30830. return state;
  30831. }
  30832. /**
  30833. * Restores the state of the given scene from the given state object.
  30834. *
  30835. * @private
  30836. * @function
  30837. * @param {Scene} scene - The scene.
  30838. * @param {Object} state - The state to restore.
  30839. */
  30840. function restoreSceneState( scene, state ) {
  30841. scene.background = state.background;
  30842. scene.backgroundNode = state.backgroundNode;
  30843. scene.overrideMaterial = state.overrideMaterial;
  30844. }
  30845. /**
  30846. * Saves the state of the given renderer and scene and stores it into the given state object.
  30847. *
  30848. * If not state object is provided, the function creates one.
  30849. *
  30850. * @private
  30851. * @function
  30852. * @param {Renderer} renderer - The renderer.
  30853. * @param {Scene} scene - The scene.
  30854. * @param {Object} [state={}] - The state.
  30855. * @return {Object} The state.
  30856. */
  30857. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  30858. state = saveRendererState( renderer, state );
  30859. state = saveSceneState( scene, state );
  30860. return state;
  30861. }
  30862. /**
  30863. * Saves the state of the given renderer and scene and stores it into the given state object.
  30864. * Besides, the function also resets the state of the renderer and scene to its default values.
  30865. *
  30866. * If not state object is provided, the function creates one.
  30867. *
  30868. * @private
  30869. * @function
  30870. * @param {Renderer} renderer - The renderer.
  30871. * @param {Scene} scene - The scene.
  30872. * @param {Object} [state={}] - The state.
  30873. * @return {Object} The state.
  30874. */
  30875. function resetRendererAndSceneState( renderer, scene, state ) {
  30876. state = resetRendererState( renderer, state );
  30877. state = resetSceneState( scene, state );
  30878. return state;
  30879. }
  30880. /**
  30881. * Restores the state of the given renderer and scene from the given state object.
  30882. *
  30883. * @private
  30884. * @function
  30885. * @param {Renderer} renderer - The renderer.
  30886. * @param {Scene} scene - The scene.
  30887. * @param {Object} state - The state to restore.
  30888. */
  30889. function restoreRendererAndSceneState( renderer, scene, state ) {
  30890. restoreRendererState( renderer, state );
  30891. restoreSceneState( scene, state );
  30892. }
  30893. var RendererUtils = /*#__PURE__*/Object.freeze({
  30894. __proto__: null,
  30895. resetRendererAndSceneState: resetRendererAndSceneState,
  30896. resetRendererState: resetRendererState,
  30897. resetSceneState: resetSceneState,
  30898. restoreRendererAndSceneState: restoreRendererAndSceneState,
  30899. restoreRendererState: restoreRendererState,
  30900. restoreSceneState: restoreSceneState,
  30901. saveRendererAndSceneState: saveRendererAndSceneState,
  30902. saveRendererState: saveRendererState,
  30903. saveSceneState: saveSceneState
  30904. });
  30905. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  30906. /**
  30907. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  30908. * with a binary `[0,1]` result.
  30909. *
  30910. * @method
  30911. * @param {Object} inputs - The input parameter object.
  30912. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30913. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30914. * @return {Node<float>} The filtering result.
  30915. */
  30916. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  30917. let basic = texture( depthTexture, shadowCoord.xy ).setName( 't_basic' );
  30918. if ( depthTexture.isArrayTexture ) {
  30919. basic = basic.depth( depthLayer );
  30920. }
  30921. return basic.compare( shadowCoord.z );
  30922. } );
  30923. /**
  30924. * A shadow filtering function performing PCF filtering with Vogel disk sampling and IGN.
  30925. *
  30926. * Uses 5 samples distributed via Vogel disk pattern, rotated per-pixel using Interleaved
  30927. * Gradient Noise (IGN) to break up banding artifacts. Combined with hardware PCF (4-tap
  30928. * filtering per sample), this effectively provides 20 filtered taps with better distribution.
  30929. *
  30930. * @method
  30931. * @param {Object} inputs - The input parameter object.
  30932. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30933. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30934. * @param {LightShadow} inputs.shadow - The light shadow.
  30935. * @return {Node<float>} The filtering result.
  30936. */
  30937. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  30938. const depthCompare = ( uv, compare ) => {
  30939. let depth = texture( depthTexture, uv );
  30940. if ( depthTexture.isArrayTexture ) {
  30941. depth = depth.depth( depthLayer );
  30942. }
  30943. return depth.compare( compare );
  30944. };
  30945. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  30946. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  30947. const texelSize = vec2( 1 ).div( mapSize );
  30948. const radiusScaled = radius.mul( texelSize.x );
  30949. // Use IGN to rotate sampling pattern per pixel (phi = IGN * 2π)
  30950. const phi = interleavedGradientNoise( screenCoordinate.xy ).mul( 6.28318530718 );
  30951. // 5 samples using Vogel disk distribution
  30952. return add(
  30953. depthCompare( shadowCoord.xy.add( vogelDiskSample( 0, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  30954. depthCompare( shadowCoord.xy.add( vogelDiskSample( 1, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  30955. depthCompare( shadowCoord.xy.add( vogelDiskSample( 2, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  30956. depthCompare( shadowCoord.xy.add( vogelDiskSample( 3, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  30957. depthCompare( shadowCoord.xy.add( vogelDiskSample( 4, 5, phi ).mul( radiusScaled ) ), shadowCoord.z )
  30958. ).mul( 1 / 5 );
  30959. } );
  30960. /**
  30961. * A shadow filtering function performing PCF soft filtering.
  30962. *
  30963. * @method
  30964. * @param {Object} inputs - The input parameter object.
  30965. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30966. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30967. * @param {LightShadow} inputs.shadow - The light shadow.
  30968. * @return {Node<float>} The filtering result.
  30969. */
  30970. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  30971. const depthCompare = ( uv, compare ) => {
  30972. let depth = texture( depthTexture, uv );
  30973. if ( depthTexture.isArrayTexture ) {
  30974. depth = depth.depth( depthLayer );
  30975. }
  30976. return depth.compare( compare );
  30977. };
  30978. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  30979. const texelSize = vec2( 1 ).div( mapSize );
  30980. const dx = texelSize.x;
  30981. const dy = texelSize.y;
  30982. const uv = shadowCoord.xy;
  30983. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  30984. uv.subAssign( f.mul( texelSize ) );
  30985. return add(
  30986. depthCompare( uv, shadowCoord.z ),
  30987. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  30988. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  30989. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  30990. mix(
  30991. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  30992. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  30993. f.x
  30994. ),
  30995. mix(
  30996. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  30997. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  30998. f.x
  30999. ),
  31000. mix(
  31001. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  31002. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  31003. f.y
  31004. ),
  31005. mix(
  31006. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  31007. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  31008. f.y
  31009. ),
  31010. mix(
  31011. mix(
  31012. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  31013. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  31014. f.x
  31015. ),
  31016. mix(
  31017. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  31018. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  31019. f.x
  31020. ),
  31021. f.y
  31022. )
  31023. ).mul( 1 / 9 );
  31024. } );
  31025. /**
  31026. * A shadow filtering function performing VSM filtering.
  31027. *
  31028. * @method
  31029. * @param {Object} inputs - The input parameter object.
  31030. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31031. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  31032. * @return {Node<float>} The filtering result.
  31033. */
  31034. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  31035. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  31036. if ( depthTexture.isArrayTexture ) {
  31037. distribution = distribution.depth( depthLayer );
  31038. }
  31039. distribution = distribution.rg;
  31040. const mean = distribution.x;
  31041. const variance = max$1( 0.0000001, distribution.y.mul( distribution.y ) );
  31042. const hardShadow = step( shadowCoord.z, mean );
  31043. // Early return if fully lit
  31044. If( hardShadow.equal( 1.0 ), () => {
  31045. return float( 1.0 );
  31046. } );
  31047. // Distance from mean
  31048. const d = shadowCoord.z.sub( mean );
  31049. // Chebyshev's inequality for upper bound on probability
  31050. let p_max = variance.div( variance.add( d.mul( d ) ) );
  31051. // Reduce light bleeding by remapping [amount, 1] to [0, 1]
  31052. p_max = clamp( sub( p_max, 0.3 ).div( 0.65 ) );
  31053. return max$1( hardShadow, p_max );
  31054. } );
  31055. //
  31056. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  31057. let dist = positionWorld.sub( position ).length();
  31058. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  31059. dist = dist.saturate(); // clamp to [ 0, 1 ]
  31060. return dist;
  31061. } );
  31062. const linearShadowDistance = ( light ) => {
  31063. const camera = light.shadow.camera;
  31064. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  31065. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  31066. const referencePosition = objectPosition( light );
  31067. return linearDistance( referencePosition, nearDistance, farDistance );
  31068. };
  31069. /**
  31070. * Retrieves or creates a shadow material for the given light source.
  31071. *
  31072. * This function checks if a shadow material already exists for the provided light.
  31073. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  31074. * in the `shadowMaterialLib` for future use.
  31075. *
  31076. * @tsl
  31077. * @function
  31078. * @param {Light} light - The light source for which the shadow material is needed.
  31079. * If the light is a point light, a depth node is calculated
  31080. * using the linear shadow distance.
  31081. * @returns {NodeMaterial} The shadow material associated with the given light.
  31082. */
  31083. const getShadowMaterial = ( light ) => {
  31084. let material = shadowMaterialLib.get( light );
  31085. if ( material === undefined ) {
  31086. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  31087. material = new NodeMaterial();
  31088. material.colorNode = vec4( 0, 0, 0, 1 );
  31089. material.depthNode = depthNode;
  31090. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  31091. material.name = 'ShadowMaterial';
  31092. material.fog = false;
  31093. shadowMaterialLib.set( light, material );
  31094. }
  31095. return material;
  31096. };
  31097. /**
  31098. * Disposes the shadow material for the given light source.
  31099. *
  31100. * @param {Light} light - The light source.
  31101. */
  31102. const disposeShadowMaterial = ( light ) => {
  31103. const material = shadowMaterialLib.get( light );
  31104. if ( material !== undefined ) {
  31105. material.dispose();
  31106. shadowMaterialLib.delete( light );
  31107. }
  31108. };
  31109. //
  31110. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  31111. const _shadowRenderObjectKeys = [];
  31112. /**
  31113. * Creates a function to render shadow objects in a scene.
  31114. *
  31115. * @tsl
  31116. * @function
  31117. * @param {Renderer} renderer - The renderer.
  31118. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  31119. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  31120. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  31121. * @return {shadowRenderObjectFunction} A function that renders shadow objects.
  31122. */
  31123. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  31124. _shadowRenderObjectKeys[ 0 ] = renderer;
  31125. _shadowRenderObjectKeys[ 1 ] = shadow;
  31126. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  31127. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  31128. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  31129. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  31130. if ( useVelocity ) {
  31131. getDataFromObject( object ).useVelocity = true;
  31132. }
  31133. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  31134. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  31135. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  31136. }
  31137. };
  31138. renderObjectFunction.shadowType = shadowType;
  31139. renderObjectFunction.useVelocity = useVelocity;
  31140. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  31141. }
  31142. _shadowRenderObjectKeys[ 0 ] = null;
  31143. _shadowRenderObjectKeys[ 1 ] = null;
  31144. return renderObjectFunction;
  31145. };
  31146. /**
  31147. * Represents the shader code for the first VSM render pass.
  31148. *
  31149. * @private
  31150. * @method
  31151. * @param {Object} inputs - The input parameter object.
  31152. * @param {Node<float>} inputs.samples - The number of samples
  31153. * @param {Node<float>} inputs.radius - The radius.
  31154. * @param {Node<float>} inputs.size - The size.
  31155. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  31156. * @return {Node<vec2>} The VSM output.
  31157. */
  31158. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  31159. const mean = float( 0 ).toVar( 'meanVertical' );
  31160. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  31161. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  31162. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  31163. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  31164. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  31165. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  31166. if ( shadowPass.value.isArrayTexture ) {
  31167. depth = depth.depth( depthLayer );
  31168. }
  31169. depth = depth.x;
  31170. mean.addAssign( depth );
  31171. squaredMean.addAssign( depth.mul( depth ) );
  31172. } );
  31173. mean.divAssign( samples );
  31174. squaredMean.divAssign( samples );
  31175. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ).max( 0 ) );
  31176. return vec2( mean, std_dev );
  31177. } );
  31178. /**
  31179. * Represents the shader code for the second VSM render pass.
  31180. *
  31181. * @private
  31182. * @method
  31183. * @param {Object} inputs - The input parameter object.
  31184. * @param {Node<float>} inputs.samples - The number of samples
  31185. * @param {Node<float>} inputs.radius - The radius.
  31186. * @param {Node<float>} inputs.size - The size.
  31187. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  31188. * @return {Node<vec2>} The VSM output.
  31189. */
  31190. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  31191. const mean = float( 0 ).toVar( 'meanHorizontal' );
  31192. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  31193. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  31194. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  31195. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  31196. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  31197. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  31198. if ( shadowPass.value.isArrayTexture ) {
  31199. distribution = distribution.depth( depthLayer );
  31200. }
  31201. mean.addAssign( distribution.x );
  31202. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  31203. } );
  31204. mean.divAssign( samples );
  31205. squaredMean.divAssign( samples );
  31206. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ).max( 0 ) );
  31207. return vec2( mean, std_dev );
  31208. } );
  31209. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  31210. //
  31211. let _rendererState;
  31212. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  31213. /**
  31214. * Represents the default shadow implementation for lighting nodes.
  31215. *
  31216. * @augments ShadowBaseNode
  31217. */
  31218. class ShadowNode extends ShadowBaseNode {
  31219. static get type() {
  31220. return 'ShadowNode';
  31221. }
  31222. /**
  31223. * Constructs a new shadow node.
  31224. *
  31225. * @param {Light} light - The shadow casting light.
  31226. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  31227. */
  31228. constructor( light, shadow = null ) {
  31229. super( light );
  31230. /**
  31231. * The light shadow which defines the properties light's
  31232. * shadow.
  31233. *
  31234. * @type {?LightShadow}
  31235. * @default null
  31236. */
  31237. this.shadow = shadow || light.shadow;
  31238. /**
  31239. * A reference to the shadow map which is a render target.
  31240. *
  31241. * @type {?RenderTarget}
  31242. * @default null
  31243. */
  31244. this.shadowMap = null;
  31245. /**
  31246. * Only relevant for VSM shadows. Render target for the
  31247. * first VSM render pass.
  31248. *
  31249. * @type {?RenderTarget}
  31250. * @default null
  31251. */
  31252. this.vsmShadowMapVertical = null;
  31253. /**
  31254. * Only relevant for VSM shadows. Render target for the
  31255. * second VSM render pass.
  31256. *
  31257. * @type {?RenderTarget}
  31258. * @default null
  31259. */
  31260. this.vsmShadowMapHorizontal = null;
  31261. /**
  31262. * Only relevant for VSM shadows. Node material which
  31263. * is used to render the first VSM pass.
  31264. *
  31265. * @type {?NodeMaterial}
  31266. * @default null
  31267. */
  31268. this.vsmMaterialVertical = null;
  31269. /**
  31270. * Only relevant for VSM shadows. Node material which
  31271. * is used to render the second VSM pass.
  31272. *
  31273. * @type {?NodeMaterial}
  31274. * @default null
  31275. */
  31276. this.vsmMaterialHorizontal = null;
  31277. /**
  31278. * A reference to the output node which defines the
  31279. * final result of this shadow node.
  31280. *
  31281. * @type {?Node}
  31282. * @private
  31283. * @default null
  31284. */
  31285. this._node = null;
  31286. /**
  31287. * The current shadow map type of this shadow node.
  31288. *
  31289. * @type {?number}
  31290. * @private
  31291. * @default null
  31292. */
  31293. this._currentShadowType = null;
  31294. /**
  31295. * A Weak Map holding the current frame ID per camera. Used
  31296. * to control the update of shadow maps.
  31297. *
  31298. * @type {WeakMap<Camera,number>}
  31299. * @private
  31300. */
  31301. this._cameraFrameId = new WeakMap();
  31302. /**
  31303. * This flag can be used for type testing.
  31304. *
  31305. * @type {boolean}
  31306. * @readonly
  31307. * @default true
  31308. */
  31309. this.isShadowNode = true;
  31310. /**
  31311. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  31312. *
  31313. * @type {number}
  31314. * @readonly
  31315. * @default true
  31316. */
  31317. this.depthLayer = 0;
  31318. }
  31319. /**
  31320. * Setups the shadow filtering.
  31321. *
  31322. * @param {NodeBuilder} builder - A reference to the current node builder.
  31323. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  31324. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  31325. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31326. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  31327. * @param {LightShadow} inputs.shadow - The light shadow.
  31328. * @return {Node<float>} The result node of the shadow filtering.
  31329. */
  31330. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  31331. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  31332. .and( shadowCoord.x.lessThanEqual( 1 ) )
  31333. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  31334. .and( shadowCoord.y.lessThanEqual( 1 ) )
  31335. .and( shadowCoord.z.lessThanEqual( 1 ) );
  31336. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  31337. return frustumTest.select( shadowNode, float( 1 ) );
  31338. }
  31339. /**
  31340. * Setups the shadow coordinates.
  31341. *
  31342. * @param {NodeBuilder} builder - A reference to the current node builder.
  31343. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  31344. * @return {Node<vec3>} The shadow coordinates.
  31345. */
  31346. setupShadowCoord( builder, shadowPosition ) {
  31347. const { shadow } = this;
  31348. const { renderer } = builder;
  31349. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  31350. let shadowCoord = shadowPosition;
  31351. let coordZ;
  31352. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  31353. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  31354. coordZ = shadowCoord.z;
  31355. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  31356. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  31357. }
  31358. } else {
  31359. const w = shadowCoord.w;
  31360. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  31361. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  31362. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  31363. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  31364. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  31365. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  31366. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  31367. }
  31368. shadowCoord = vec3(
  31369. shadowCoord.x,
  31370. shadowCoord.y.oneMinus(), // follow webgpu standards
  31371. coordZ.add( bias )
  31372. );
  31373. return shadowCoord;
  31374. }
  31375. /**
  31376. * Returns the shadow filtering function for the given shadow type.
  31377. *
  31378. * @param {number} type - The shadow type.
  31379. * @return {Function} The filtering function.
  31380. */
  31381. getShadowFilterFn( type ) {
  31382. return _shadowFilterLib[ type ];
  31383. }
  31384. setupRenderTarget( shadow, builder ) {
  31385. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  31386. depthTexture.name = 'ShadowDepthTexture';
  31387. depthTexture.compareFunction = LessCompare;
  31388. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  31389. shadowMap.texture.name = 'ShadowMap';
  31390. shadowMap.texture.type = shadow.mapType;
  31391. shadowMap.depthTexture = depthTexture;
  31392. return { shadowMap, depthTexture };
  31393. }
  31394. /**
  31395. * Setups the shadow output node.
  31396. *
  31397. * @param {NodeBuilder} builder - A reference to the current node builder.
  31398. * @return {Node<vec3>} The shadow output node.
  31399. */
  31400. setupShadow( builder ) {
  31401. const { renderer, camera } = builder;
  31402. const { light, shadow } = this;
  31403. const shadowMapType = renderer.shadowMap.type;
  31404. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  31405. shadow.camera.coordinateSystem = camera.coordinateSystem;
  31406. shadow.camera.updateProjectionMatrix();
  31407. // VSM
  31408. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  31409. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  31410. if ( shadowMap.depth > 1 ) {
  31411. if ( ! shadowMap._vsmShadowMapVertical ) {
  31412. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  31413. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  31414. }
  31415. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  31416. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  31417. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  31418. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  31419. }
  31420. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  31421. } else {
  31422. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  31423. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  31424. }
  31425. let shadowPassVertical = texture( depthTexture );
  31426. if ( depthTexture.isArrayTexture ) {
  31427. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  31428. }
  31429. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  31430. if ( depthTexture.isArrayTexture ) {
  31431. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  31432. }
  31433. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  31434. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  31435. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  31436. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  31437. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  31438. material.name = 'VSMVertical';
  31439. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  31440. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  31441. material.name = 'VSMHorizontal';
  31442. }
  31443. //
  31444. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  31445. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  31446. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( normalWorld.mul( normalBias ) ) );
  31447. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  31448. //
  31449. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  31450. if ( filterFn === null ) {
  31451. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  31452. }
  31453. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  31454. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  31455. let shadowColor;
  31456. if ( shadowMap.texture.isCubeTexture ) {
  31457. // For cube shadow maps (point lights), use cubeTexture with vec3 coordinates
  31458. shadowColor = cubeTexture( shadowMap.texture, shadowCoord.xyz );
  31459. } else {
  31460. shadowColor = texture( shadowMap.texture, shadowCoord );
  31461. if ( depthTexture.isArrayTexture ) {
  31462. shadowColor = shadowColor.depth( this.depthLayer );
  31463. }
  31464. }
  31465. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  31466. this.shadowMap = shadowMap;
  31467. this.shadow.map = shadowMap;
  31468. // Shadow Output + Inspector
  31469. const inspectName = `${ this.light.type } Shadow [ ${ this.light.name || 'ID: ' + this.light.id } ]`;
  31470. return shadowOutput.toInspector( `${ inspectName } / Color`, () => {
  31471. if ( this.shadowMap.texture.isCubeTexture ) {
  31472. return cubeTexture( this.shadowMap.texture );
  31473. }
  31474. return texture( this.shadowMap.texture );
  31475. } ).toInspector( `${ inspectName } / Depth`, () => {
  31476. // TODO: Use linear depth
  31477. if ( this.shadowMap.texture.isCubeTexture ) {
  31478. return cubeTexture( this.shadowMap.texture ).r.oneMinus();
  31479. }
  31480. return textureLoad( this.shadowMap.depthTexture, uv$1().mul( textureSize( texture( this.shadowMap.depthTexture ) ) ) ).r.oneMinus();
  31481. } );
  31482. }
  31483. /**
  31484. * The implementation performs the setup of the output node. An output is only
  31485. * produces if shadow mapping is globally enabled in the renderer.
  31486. *
  31487. * @param {NodeBuilder} builder - A reference to the current node builder.
  31488. * @return {ShaderCallNodeInternal} The output node.
  31489. */
  31490. setup( builder ) {
  31491. if ( builder.renderer.shadowMap.enabled === false ) return;
  31492. return Fn( () => {
  31493. const currentShadowType = builder.renderer.shadowMap.type;
  31494. if ( this._currentShadowType !== currentShadowType ) {
  31495. this._reset();
  31496. this._node = null;
  31497. }
  31498. let node = this._node;
  31499. this.setupShadowPosition( builder );
  31500. if ( node === null ) {
  31501. this._node = node = this.setupShadow( builder );
  31502. this._currentShadowType = currentShadowType;
  31503. }
  31504. if ( builder.material.shadowNode ) { // @deprecated, r171
  31505. warn( 'NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  31506. }
  31507. if ( builder.material.receivedShadowNode ) {
  31508. node = builder.material.receivedShadowNode( node );
  31509. }
  31510. return node;
  31511. } )();
  31512. }
  31513. /**
  31514. * Renders the shadow. The logic of this function could be included
  31515. * into {@link ShadowNode#updateShadow} however more specialized shadow
  31516. * nodes might require a custom shadow map rendering. By having a
  31517. * dedicated method, it's easier to overwrite the default behavior.
  31518. *
  31519. * @param {NodeFrame} frame - A reference to the current node frame.
  31520. */
  31521. renderShadow( frame ) {
  31522. const { shadow, shadowMap, light } = this;
  31523. const { renderer, scene } = frame;
  31524. shadow.updateMatrices( light );
  31525. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  31526. const currentSceneName = scene.name;
  31527. scene.name = `Shadow Map [ ${ light.name || 'ID: ' + light.id } ]`;
  31528. renderer.render( scene, shadow.camera );
  31529. scene.name = currentSceneName;
  31530. }
  31531. /**
  31532. * Updates the shadow.
  31533. *
  31534. * @param {NodeFrame} frame - A reference to the current node frame.
  31535. */
  31536. updateShadow( frame ) {
  31537. const { shadowMap, light, shadow } = this;
  31538. const { renderer, scene, camera } = frame;
  31539. const shadowType = renderer.shadowMap.type;
  31540. const depthVersion = shadowMap.depthTexture.version;
  31541. this._depthVersionCached = depthVersion;
  31542. const _shadowCameraLayer = shadow.camera.layers.mask;
  31543. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  31544. shadow.camera.layers.mask = camera.layers.mask;
  31545. }
  31546. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  31547. const currentMRT = renderer.getMRT();
  31548. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  31549. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  31550. scene.overrideMaterial = getShadowMaterial( light );
  31551. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  31552. renderer.setClearColor( 0x000000, 0 );
  31553. renderer.setRenderTarget( shadowMap );
  31554. this.renderShadow( frame );
  31555. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  31556. // vsm blur pass
  31557. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  31558. this.vsmPass( renderer );
  31559. }
  31560. shadow.camera.layers.mask = _shadowCameraLayer;
  31561. restoreRendererAndSceneState( renderer, scene, _rendererState );
  31562. }
  31563. /**
  31564. * For VSM additional render passes are required.
  31565. *
  31566. * @param {Renderer} renderer - A reference to the current renderer.
  31567. */
  31568. vsmPass( renderer ) {
  31569. const { shadow } = this;
  31570. const depth = this.shadowMap.depth;
  31571. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  31572. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  31573. renderer.setRenderTarget( this.vsmShadowMapVertical );
  31574. _quadMesh.material = this.vsmMaterialVertical;
  31575. _quadMesh.render( renderer );
  31576. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  31577. _quadMesh.material = this.vsmMaterialHorizontal;
  31578. _quadMesh.render( renderer );
  31579. }
  31580. /**
  31581. * Frees the internal resources of this shadow node.
  31582. */
  31583. dispose() {
  31584. this._reset();
  31585. super.dispose();
  31586. }
  31587. /**
  31588. * Resets the resouce state of this shadow node.
  31589. *
  31590. * @private
  31591. */
  31592. _reset() {
  31593. this._currentShadowType = null;
  31594. disposeShadowMaterial( this.light );
  31595. if ( this.shadowMap ) {
  31596. this.shadowMap.dispose();
  31597. this.shadowMap = null;
  31598. }
  31599. if ( this.vsmShadowMapVertical !== null ) {
  31600. this.vsmShadowMapVertical.dispose();
  31601. this.vsmShadowMapVertical = null;
  31602. this.vsmMaterialVertical.dispose();
  31603. this.vsmMaterialVertical = null;
  31604. }
  31605. if ( this.vsmShadowMapHorizontal !== null ) {
  31606. this.vsmShadowMapHorizontal.dispose();
  31607. this.vsmShadowMapHorizontal = null;
  31608. this.vsmMaterialHorizontal.dispose();
  31609. this.vsmMaterialHorizontal = null;
  31610. }
  31611. }
  31612. /**
  31613. * The implementation performs the update of the shadow map if necessary.
  31614. *
  31615. * @param {NodeFrame} frame - A reference to the current node frame.
  31616. */
  31617. updateBefore( frame ) {
  31618. const { shadow } = this;
  31619. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  31620. if ( needsUpdate ) {
  31621. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  31622. needsUpdate = false;
  31623. }
  31624. this._cameraFrameId[ frame.camera ] = frame.frameId;
  31625. }
  31626. if ( needsUpdate ) {
  31627. this.updateShadow( frame );
  31628. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  31629. shadow.needsUpdate = false;
  31630. }
  31631. }
  31632. }
  31633. }
  31634. /**
  31635. * Shadow Render Object Function.
  31636. *
  31637. * @function shadowRenderObjectFunction
  31638. * @param {Object3D} object - The 3D object to render.
  31639. * @param {Scene} scene - The scene containing the object.
  31640. * @param {Camera} _camera - The camera used for rendering.
  31641. * @param {BufferGeometry} geometry - The geometry of the object.
  31642. * @param {Material} material - The material of the object.
  31643. * @param {Group} group - The group the object belongs to.
  31644. * @param {...any} params - Additional parameters for rendering.
  31645. */
  31646. /**
  31647. * TSL function for creating an instance of `ShadowNode`.
  31648. *
  31649. * @tsl
  31650. * @function
  31651. * @param {Light} light - The shadow casting light.
  31652. * @param {?LightShadow} [shadow] - The light shadow.
  31653. * @return {ShadowNode} The created shadow node.
  31654. */
  31655. const shadow = ( light, shadow ) => new ShadowNode( light, shadow );
  31656. const _clearColor$1 = /*@__PURE__*/ new Color();
  31657. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  31658. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  31659. const _lookTarget = /*@__PURE__*/ new Vector3();
  31660. // Cube map face directions and up vectors for point light shadows
  31661. // Face order: +X, -X, +Y, -Y, +Z, -Z
  31662. // WebGPU coordinate system - Y faces swapped to match texture sampling convention
  31663. const _cubeDirectionsWebGPU = [
  31664. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ),
  31665. /*@__PURE__*/ new Vector3( 0, 1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  31666. ];
  31667. const _cubeUpsWebGPU = [
  31668. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, -1 ),
  31669. /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  31670. ];
  31671. // WebGL coordinate system - standard OpenGL convention
  31672. const _cubeDirectionsWebGL = [
  31673. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, 1, 0 ),
  31674. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  31675. ];
  31676. const _cubeUpsWebGL = [
  31677. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ),
  31678. /*@__PURE__*/ new Vector3( 0, 0, -1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  31679. ];
  31680. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp } ) => {
  31681. return cubeTexture( depthTexture, bd3D ).compare( dp );
  31682. } );
  31683. /**
  31684. * A shadow filtering function for point lights using Vogel disk sampling and IGN.
  31685. *
  31686. * Uses 5 samples distributed via Vogel disk pattern in tangent space around the
  31687. * sample direction, rotated per-pixel using Interleaved Gradient Noise (IGN).
  31688. *
  31689. * @method
  31690. * @param {Object} inputs - The input parameter object.
  31691. * @param {CubeDepthTexture} inputs.depthTexture - A reference to the shadow cube map.
  31692. * @param {Node<vec3>} inputs.bd3D - The normalized direction from light to fragment.
  31693. * @param {Node<float>} inputs.dp - The depth value to compare against.
  31694. * @param {LightShadow} inputs.shadow - The light shadow.
  31695. * @return {Node<float>} The filtering result.
  31696. */
  31697. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, shadow } ) => {
  31698. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  31699. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  31700. const texelSize = radius.div( mapSize.x );
  31701. // Build a tangent-space coordinate system for applying offsets
  31702. const absDir = abs( bd3D );
  31703. const tangent = normalize( cross( bd3D, absDir.x.greaterThan( absDir.z ).select( vec3( 0, 1, 0 ), vec3( 1, 0, 0 ) ) ) );
  31704. const bitangent = cross( bd3D, tangent );
  31705. // Use IGN to rotate sampling pattern per pixel (phi = IGN * 2π)
  31706. const phi = interleavedGradientNoise( screenCoordinate.xy ).mul( 6.28318530718 );
  31707. // 5 samples using Vogel disk distribution in tangent space
  31708. const sample0 = vogelDiskSample( 0, 5, phi );
  31709. const sample1 = vogelDiskSample( 1, 5, phi );
  31710. const sample2 = vogelDiskSample( 2, 5, phi );
  31711. const sample3 = vogelDiskSample( 3, 5, phi );
  31712. const sample4 = vogelDiskSample( 4, 5, phi );
  31713. return cubeTexture( depthTexture, bd3D.add( tangent.mul( sample0.x ).add( bitangent.mul( sample0.y ) ).mul( texelSize ) ) ).compare( dp )
  31714. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample1.x ).add( bitangent.mul( sample1.y ) ).mul( texelSize ) ) ).compare( dp ) )
  31715. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample2.x ).add( bitangent.mul( sample2.y ) ).mul( texelSize ) ) ).compare( dp ) )
  31716. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample3.x ).add( bitangent.mul( sample3.y ) ).mul( texelSize ) ) ).compare( dp ) )
  31717. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample4.x ).add( bitangent.mul( sample4.y ) ).mul( texelSize ) ) ).compare( dp ) )
  31718. .mul( 1.0 / 5.0 );
  31719. } );
  31720. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  31721. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  31722. // the vector from the light to the world-space position of the fragment.
  31723. const lightToPosition = shadowCoord.xyz.toVar();
  31724. const lightToPositionLength = lightToPosition.length();
  31725. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  31726. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  31727. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  31728. const result = float( 1.0 ).toVar();
  31729. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  31730. // dp = normalized distance from light to fragment position
  31731. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  31732. dp.addAssign( bias );
  31733. // bd3D = base direction 3D (direction from light to fragment)
  31734. const bd3D = lightToPosition.normalize();
  31735. // percentage-closer filtering using cube texture sampling
  31736. result.assign( filterFn( { depthTexture, bd3D, dp, shadow } ) );
  31737. } );
  31738. return result;
  31739. } );
  31740. /**
  31741. * Represents the shadow implementation for point light nodes.
  31742. *
  31743. * @augments ShadowNode
  31744. */
  31745. class PointShadowNode extends ShadowNode {
  31746. static get type() {
  31747. return 'PointShadowNode';
  31748. }
  31749. /**
  31750. * Constructs a new point shadow node.
  31751. *
  31752. * @param {PointLight} light - The shadow casting point light.
  31753. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  31754. */
  31755. constructor( light, shadow = null ) {
  31756. super( light, shadow );
  31757. }
  31758. /**
  31759. * Overwrites the default implementation to return point light shadow specific
  31760. * filtering functions.
  31761. *
  31762. * @param {number} type - The shadow type.
  31763. * @return {Function} The filtering function.
  31764. */
  31765. getShadowFilterFn( type ) {
  31766. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  31767. }
  31768. /**
  31769. * Overwrites the default implementation so the unaltered shadow position is used.
  31770. *
  31771. * @param {NodeBuilder} builder - A reference to the current node builder.
  31772. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  31773. * @return {Node<vec3>} The shadow coordinates.
  31774. */
  31775. setupShadowCoord( builder, shadowPosition ) {
  31776. return shadowPosition;
  31777. }
  31778. /**
  31779. * Overwrites the default implementation to only use point light specific
  31780. * shadow filter functions.
  31781. *
  31782. * @param {NodeBuilder} builder - A reference to the current node builder.
  31783. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  31784. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  31785. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's depth texture.
  31786. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  31787. * @param {LightShadow} inputs.shadow - The light shadow.
  31788. * @return {Node<float>} The result node of the shadow filtering.
  31789. */
  31790. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  31791. return pointShadowFilter( { filterFn, depthTexture, shadowCoord, shadow } );
  31792. }
  31793. /**
  31794. * Overwrites the default implementation to create a CubeRenderTarget with CubeDepthTexture.
  31795. *
  31796. * @param {LightShadow} shadow - The light shadow object.
  31797. * @param {NodeBuilder} builder - A reference to the current node builder.
  31798. * @return {Object} An object containing the shadow map and depth texture.
  31799. */
  31800. setupRenderTarget( shadow, builder ) {
  31801. const depthTexture = new CubeDepthTexture( shadow.mapSize.width );
  31802. depthTexture.name = 'PointShadowDepthTexture';
  31803. depthTexture.compareFunction = LessCompare;
  31804. const shadowMap = builder.createCubeRenderTarget( shadow.mapSize.width );
  31805. shadowMap.texture.name = 'PointShadowMap';
  31806. shadowMap.depthTexture = depthTexture;
  31807. return { shadowMap, depthTexture };
  31808. }
  31809. /**
  31810. * Overwrites the default implementation with point light specific
  31811. * rendering code.
  31812. *
  31813. * @param {NodeFrame} frame - A reference to the current node frame.
  31814. */
  31815. renderShadow( frame ) {
  31816. const { shadow, shadowMap, light } = this;
  31817. const { renderer, scene } = frame;
  31818. const camera = shadow.camera;
  31819. const shadowMatrix = shadow.matrix;
  31820. // Select cube directions/ups based on coordinate system
  31821. const isWebGPU = renderer.coordinateSystem === WebGPUCoordinateSystem;
  31822. const cubeDirections = isWebGPU ? _cubeDirectionsWebGPU : _cubeDirectionsWebGL;
  31823. const cubeUps = isWebGPU ? _cubeUpsWebGPU : _cubeUpsWebGL;
  31824. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.width );
  31825. //
  31826. const previousAutoClear = renderer.autoClear;
  31827. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  31828. const previousClearAlpha = renderer.getClearAlpha();
  31829. renderer.autoClear = false;
  31830. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  31831. // Render each cube face
  31832. for ( let face = 0; face < 6; face ++ ) {
  31833. // Set render target to the specific cube face
  31834. renderer.setRenderTarget( shadowMap, face );
  31835. renderer.clear();
  31836. // Update shadow camera matrices for this face
  31837. const far = light.distance || camera.far;
  31838. if ( far !== camera.far ) {
  31839. camera.far = far;
  31840. camera.updateProjectionMatrix();
  31841. }
  31842. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  31843. camera.position.copy( _lightPositionWorld );
  31844. _lookTarget.copy( camera.position );
  31845. _lookTarget.add( cubeDirections[ face ] );
  31846. camera.up.copy( cubeUps[ face ] );
  31847. camera.lookAt( _lookTarget );
  31848. camera.updateMatrixWorld();
  31849. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  31850. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  31851. shadow._frustum.setFromProjectionMatrix( _projScreenMatrix$1, camera.coordinateSystem, camera.reversedDepth );
  31852. //
  31853. const currentSceneName = scene.name;
  31854. scene.name = `Point Light Shadow [ ${ light.name || 'ID: ' + light.id } ] - Face ${ face + 1 }`;
  31855. renderer.render( scene, camera );
  31856. scene.name = currentSceneName;
  31857. }
  31858. //
  31859. renderer.autoClear = previousAutoClear;
  31860. renderer.setClearColor( previousClearColor, previousClearAlpha );
  31861. }
  31862. }
  31863. /**
  31864. * TSL function for creating an instance of `PointShadowNode`.
  31865. *
  31866. * @tsl
  31867. * @function
  31868. * @param {PointLight} light - The shadow casting point light.
  31869. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  31870. * @return {PointShadowNode} The created point shadow node.
  31871. */
  31872. const pointShadow = ( light, shadow ) => new PointShadowNode( light, shadow );
  31873. /**
  31874. * Base class for analytic light nodes.
  31875. *
  31876. * @augments LightingNode
  31877. */
  31878. class AnalyticLightNode extends LightingNode {
  31879. static get type() {
  31880. return 'AnalyticLightNode';
  31881. }
  31882. /**
  31883. * Constructs a new analytic light node.
  31884. *
  31885. * @param {?Light} [light=null] - The light source.
  31886. */
  31887. constructor( light = null ) {
  31888. super();
  31889. /**
  31890. * The light source.
  31891. *
  31892. * @type {?Light}
  31893. * @default null
  31894. */
  31895. this.light = light;
  31896. /**
  31897. * The light's color value.
  31898. *
  31899. * @type {Color}
  31900. */
  31901. this.color = new Color();
  31902. /**
  31903. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  31904. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  31905. *
  31906. * @type {Node}
  31907. */
  31908. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  31909. /**
  31910. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  31911. * The final color node is represented by a different node when using shadows.
  31912. *
  31913. * @type {?Node}
  31914. * @default null
  31915. */
  31916. this.baseColorNode = null;
  31917. /**
  31918. * Represents the light's shadow.
  31919. *
  31920. * @type {?ShadowNode}
  31921. * @default null
  31922. */
  31923. this.shadowNode = null;
  31924. /**
  31925. * Represents the light's shadow color.
  31926. *
  31927. * @type {?Node}
  31928. * @default null
  31929. */
  31930. this.shadowColorNode = null;
  31931. /**
  31932. * This flag can be used for type testing.
  31933. *
  31934. * @type {boolean}
  31935. * @readonly
  31936. * @default true
  31937. */
  31938. this.isAnalyticLightNode = true;
  31939. /**
  31940. * Overwritten since analytic light nodes are updated
  31941. * once per frame.
  31942. *
  31943. * @type {string}
  31944. * @default 'frame'
  31945. */
  31946. this.updateType = NodeUpdateType.FRAME;
  31947. if ( light && light.shadow ) {
  31948. this._shadowDisposeListener = () => {
  31949. this.disposeShadow();
  31950. };
  31951. light.addEventListener( 'dispose', this._shadowDisposeListener );
  31952. }
  31953. }
  31954. dispose() {
  31955. if ( this._shadowDisposeListener ) {
  31956. this.light.removeEventListener( 'dispose', this._shadowDisposeListener );
  31957. }
  31958. super.dispose();
  31959. }
  31960. /**
  31961. * Frees internal resources related to shadows.
  31962. */
  31963. disposeShadow() {
  31964. if ( this.shadowNode !== null ) {
  31965. this.shadowNode.dispose();
  31966. this.shadowNode = null;
  31967. }
  31968. this.shadowColorNode = null;
  31969. if ( this.baseColorNode !== null ) {
  31970. this.colorNode = this.baseColorNode;
  31971. this.baseColorNode = null;
  31972. }
  31973. }
  31974. getHash() {
  31975. return this.light.uuid;
  31976. }
  31977. /**
  31978. * Returns a node representing a direction vector which points from the current
  31979. * position in view space to the light's position in view space.
  31980. *
  31981. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  31982. * @return {Node<vec3>} The light vector node.
  31983. */
  31984. getLightVector( builder ) {
  31985. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  31986. }
  31987. /**
  31988. * Sets up the direct lighting for the analytic light node.
  31989. *
  31990. * @abstract
  31991. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  31992. * @return {Object|undefined} The direct light data (color and direction).
  31993. */
  31994. setupDirect( /*builder*/ ) { }
  31995. /**
  31996. * Sets up the direct rect area lighting for the analytic light node.
  31997. *
  31998. * @abstract
  31999. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  32000. * @return {Object|undefined} The direct rect area light data.
  32001. */
  32002. setupDirectRectArea( /*builder*/ ) { }
  32003. /**
  32004. * Setups the shadow node for this light. The method exists so concrete light classes
  32005. * can setup different types of shadow nodes.
  32006. *
  32007. * @return {ShadowNode} The created shadow node.
  32008. */
  32009. setupShadowNode() {
  32010. return shadow( this.light );
  32011. }
  32012. /**
  32013. * Setups the shadow for this light. This method is only executed if the light
  32014. * cast shadows and the current build object receives shadows. It incorporates
  32015. * shadows into the lighting computation.
  32016. *
  32017. * @param {NodeBuilder} builder - The current node builder.
  32018. */
  32019. setupShadow( builder ) {
  32020. const { renderer } = builder;
  32021. if ( renderer.shadowMap.enabled === false ) return;
  32022. let shadowColorNode = this.shadowColorNode;
  32023. if ( shadowColorNode === null ) {
  32024. const customShadowNode = this.light.shadow.shadowNode;
  32025. let shadowNode;
  32026. if ( customShadowNode !== undefined ) {
  32027. shadowNode = nodeObject( customShadowNode );
  32028. } else {
  32029. shadowNode = this.setupShadowNode();
  32030. }
  32031. this.shadowNode = shadowNode;
  32032. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  32033. this.baseColorNode = this.colorNode;
  32034. }
  32035. //
  32036. if ( builder.context.getShadow ) {
  32037. shadowColorNode = builder.context.getShadow( this, builder );
  32038. }
  32039. this.colorNode = shadowColorNode;
  32040. }
  32041. /**
  32042. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  32043. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  32044. * invocate the respective interface methods.
  32045. *
  32046. * @param {NodeBuilder} builder - The current node builder.
  32047. */
  32048. setup( builder ) {
  32049. this.colorNode = this.baseColorNode || this.colorNode;
  32050. if ( this.light.castShadow ) {
  32051. if ( builder.object.receiveShadow ) {
  32052. this.setupShadow( builder );
  32053. }
  32054. } else if ( this.shadowNode !== null ) {
  32055. this.shadowNode.dispose();
  32056. this.shadowNode = null;
  32057. this.shadowColorNode = null;
  32058. }
  32059. const directLightData = this.setupDirect( builder );
  32060. const directRectAreaLightData = this.setupDirectRectArea( builder );
  32061. if ( directLightData ) {
  32062. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  32063. }
  32064. if ( directRectAreaLightData ) {
  32065. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  32066. }
  32067. }
  32068. /**
  32069. * The update method is used to update light uniforms per frame.
  32070. * Potentially overwritten in concrete light nodes to update light
  32071. * specific uniforms.
  32072. *
  32073. * @param {NodeFrame} frame - A reference to the current node frame.
  32074. */
  32075. update( /*frame*/ ) {
  32076. const { light } = this;
  32077. this.color.copy( light.color ).multiplyScalar( light.intensity );
  32078. }
  32079. }
  32080. /**
  32081. * Represents a `discard` shader operation in TSL.
  32082. *
  32083. * @method
  32084. * @param {Object} inputs - The input parameter object.
  32085. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  32086. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  32087. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  32088. * @return {Node<float>} The distance falloff.
  32089. */
  32090. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  32091. // based upon Frostbite 3 Moving to Physically-based Rendering
  32092. // page 32, equation 26: E[window1]
  32093. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  32094. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  32095. return cutoffDistance.greaterThan( 0 ).select(
  32096. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  32097. distanceFalloff
  32098. );
  32099. } ); // validated
  32100. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  32101. const lightDirection = lightVector.normalize();
  32102. const lightDistance = lightVector.length();
  32103. const attenuation = getDistanceAttenuation( {
  32104. lightDistance,
  32105. cutoffDistance,
  32106. decayExponent
  32107. } );
  32108. const lightColor = color.mul( attenuation );
  32109. return { lightDirection, lightColor };
  32110. };
  32111. /**
  32112. * Module for representing point lights as nodes.
  32113. *
  32114. * @augments AnalyticLightNode
  32115. */
  32116. class PointLightNode extends AnalyticLightNode {
  32117. static get type() {
  32118. return 'PointLightNode';
  32119. }
  32120. /**
  32121. * Constructs a new point light node.
  32122. *
  32123. * @param {?PointLight} [light=null] - The point light source.
  32124. */
  32125. constructor( light = null ) {
  32126. super( light );
  32127. /**
  32128. * Uniform node representing the cutoff distance.
  32129. *
  32130. * @type {UniformNode<float>}
  32131. */
  32132. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  32133. /**
  32134. * Uniform node representing the decay exponent.
  32135. *
  32136. * @type {UniformNode<float>}
  32137. */
  32138. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  32139. }
  32140. /**
  32141. * Overwritten to updated point light specific uniforms.
  32142. *
  32143. * @param {NodeFrame} frame - A reference to the current node frame.
  32144. */
  32145. update( frame ) {
  32146. const { light } = this;
  32147. super.update( frame );
  32148. this.cutoffDistanceNode.value = light.distance;
  32149. this.decayExponentNode.value = light.decay;
  32150. }
  32151. /**
  32152. * Overwritten to setup point light specific shadow.
  32153. *
  32154. * @return {PointShadowNode}
  32155. */
  32156. setupShadowNode() {
  32157. return pointShadow( this.light );
  32158. }
  32159. setupDirect( builder ) {
  32160. return directPointLight( {
  32161. color: this.colorNode,
  32162. lightVector: this.getLightVector( builder ),
  32163. cutoffDistance: this.cutoffDistanceNode,
  32164. decayExponent: this.decayExponentNode
  32165. } );
  32166. }
  32167. }
  32168. /**
  32169. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  32170. *
  32171. * @tsl
  32172. * @function
  32173. * @param {Node<vec2>} coord - The uv coordinates.
  32174. * @return {Node<float>} The result data.
  32175. */
  32176. const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => {
  32177. const uv = coord.mul( 2.0 );
  32178. const cx = uv.x.floor();
  32179. const cy = uv.y.floor();
  32180. const result = cx.add( cy ).mod( 2.0 );
  32181. return result.sign();
  32182. } );
  32183. /**
  32184. * Generates a circle based on the uv coordinates.
  32185. *
  32186. * @tsl
  32187. * @function
  32188. * @param {Node<vec2>} coord - The uv to generate the circle.
  32189. * @return {Node<float>} The circle shape.
  32190. */
  32191. const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => {
  32192. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  32193. let alpha;
  32194. if ( material.alphaToCoverage && renderer.currentSamples > 0 ) {
  32195. const dlen = float( len2.fwidth() ).toVar();
  32196. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  32197. } else {
  32198. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  32199. }
  32200. return alpha;
  32201. } );
  32202. // Three.js Transpiler
  32203. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  32204. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  32205. const f = float( f_immutable ).toVar();
  32206. const t = float( t_immutable ).toVar();
  32207. const b = bool( b_immutable ).toVar();
  32208. return select( b, t, f );
  32209. } ).setLayout( {
  32210. name: 'mx_select',
  32211. type: 'float',
  32212. inputs: [
  32213. { name: 'b', type: 'bool' },
  32214. { name: 't', type: 'float' },
  32215. { name: 'f', type: 'float' }
  32216. ]
  32217. } );
  32218. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  32219. const b = bool( b_immutable ).toVar();
  32220. const val = float( val_immutable ).toVar();
  32221. return select( b, val.negate(), val );
  32222. } ).setLayout( {
  32223. name: 'mx_negate_if',
  32224. type: 'float',
  32225. inputs: [
  32226. { name: 'val', type: 'float' },
  32227. { name: 'b', type: 'bool' }
  32228. ]
  32229. } );
  32230. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  32231. const x = float( x_immutable ).toVar();
  32232. return int( floor( x ) );
  32233. } ).setLayout( {
  32234. name: 'mx_floor',
  32235. type: 'int',
  32236. inputs: [
  32237. { name: 'x', type: 'float' }
  32238. ]
  32239. } );
  32240. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  32241. const x = float( x_immutable ).toVar();
  32242. i.assign( mx_floor( x ) );
  32243. return x.sub( float( i ) );
  32244. } );
  32245. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  32246. const t = float( t_immutable ).toVar();
  32247. const s = float( s_immutable ).toVar();
  32248. const v3 = float( v3_immutable ).toVar();
  32249. const v2 = float( v2_immutable ).toVar();
  32250. const v1 = float( v1_immutable ).toVar();
  32251. const v0 = float( v0_immutable ).toVar();
  32252. const s1 = float( sub( 1.0, s ) ).toVar();
  32253. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  32254. } ).setLayout( {
  32255. name: 'mx_bilerp_0',
  32256. type: 'float',
  32257. inputs: [
  32258. { name: 'v0', type: 'float' },
  32259. { name: 'v1', type: 'float' },
  32260. { name: 'v2', type: 'float' },
  32261. { name: 'v3', type: 'float' },
  32262. { name: 's', type: 'float' },
  32263. { name: 't', type: 'float' }
  32264. ]
  32265. } );
  32266. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  32267. const t = float( t_immutable ).toVar();
  32268. const s = float( s_immutable ).toVar();
  32269. const v3 = vec3( v3_immutable ).toVar();
  32270. const v2 = vec3( v2_immutable ).toVar();
  32271. const v1 = vec3( v1_immutable ).toVar();
  32272. const v0 = vec3( v0_immutable ).toVar();
  32273. const s1 = float( sub( 1.0, s ) ).toVar();
  32274. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  32275. } ).setLayout( {
  32276. name: 'mx_bilerp_1',
  32277. type: 'vec3',
  32278. inputs: [
  32279. { name: 'v0', type: 'vec3' },
  32280. { name: 'v1', type: 'vec3' },
  32281. { name: 'v2', type: 'vec3' },
  32282. { name: 'v3', type: 'vec3' },
  32283. { name: 's', type: 'float' },
  32284. { name: 't', type: 'float' }
  32285. ]
  32286. } );
  32287. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  32288. 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 ] ) => {
  32289. const r = float( r_immutable ).toVar();
  32290. const t = float( t_immutable ).toVar();
  32291. const s = float( s_immutable ).toVar();
  32292. const v7 = float( v7_immutable ).toVar();
  32293. const v6 = float( v6_immutable ).toVar();
  32294. const v5 = float( v5_immutable ).toVar();
  32295. const v4 = float( v4_immutable ).toVar();
  32296. const v3 = float( v3_immutable ).toVar();
  32297. const v2 = float( v2_immutable ).toVar();
  32298. const v1 = float( v1_immutable ).toVar();
  32299. const v0 = float( v0_immutable ).toVar();
  32300. const s1 = float( sub( 1.0, s ) ).toVar();
  32301. const t1 = float( sub( 1.0, t ) ).toVar();
  32302. const r1 = float( sub( 1.0, r ) ).toVar();
  32303. 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 ) ) ) ) ) );
  32304. } ).setLayout( {
  32305. name: 'mx_trilerp_0',
  32306. type: 'float',
  32307. inputs: [
  32308. { name: 'v0', type: 'float' },
  32309. { name: 'v1', type: 'float' },
  32310. { name: 'v2', type: 'float' },
  32311. { name: 'v3', type: 'float' },
  32312. { name: 'v4', type: 'float' },
  32313. { name: 'v5', type: 'float' },
  32314. { name: 'v6', type: 'float' },
  32315. { name: 'v7', type: 'float' },
  32316. { name: 's', type: 'float' },
  32317. { name: 't', type: 'float' },
  32318. { name: 'r', type: 'float' }
  32319. ]
  32320. } );
  32321. 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 ] ) => {
  32322. const r = float( r_immutable ).toVar();
  32323. const t = float( t_immutable ).toVar();
  32324. const s = float( s_immutable ).toVar();
  32325. const v7 = vec3( v7_immutable ).toVar();
  32326. const v6 = vec3( v6_immutable ).toVar();
  32327. const v5 = vec3( v5_immutable ).toVar();
  32328. const v4 = vec3( v4_immutable ).toVar();
  32329. const v3 = vec3( v3_immutable ).toVar();
  32330. const v2 = vec3( v2_immutable ).toVar();
  32331. const v1 = vec3( v1_immutable ).toVar();
  32332. const v0 = vec3( v0_immutable ).toVar();
  32333. const s1 = float( sub( 1.0, s ) ).toVar();
  32334. const t1 = float( sub( 1.0, t ) ).toVar();
  32335. const r1 = float( sub( 1.0, r ) ).toVar();
  32336. 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 ) ) ) ) ) );
  32337. } ).setLayout( {
  32338. name: 'mx_trilerp_1',
  32339. type: 'vec3',
  32340. inputs: [
  32341. { name: 'v0', type: 'vec3' },
  32342. { name: 'v1', type: 'vec3' },
  32343. { name: 'v2', type: 'vec3' },
  32344. { name: 'v3', type: 'vec3' },
  32345. { name: 'v4', type: 'vec3' },
  32346. { name: 'v5', type: 'vec3' },
  32347. { name: 'v6', type: 'vec3' },
  32348. { name: 'v7', type: 'vec3' },
  32349. { name: 's', type: 'float' },
  32350. { name: 't', type: 'float' },
  32351. { name: 'r', type: 'float' }
  32352. ]
  32353. } );
  32354. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  32355. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  32356. const y = float( y_immutable ).toVar();
  32357. const x = float( x_immutable ).toVar();
  32358. const hash = uint( hash_immutable ).toVar();
  32359. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  32360. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  32361. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  32362. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  32363. } ).setLayout( {
  32364. name: 'mx_gradient_float_0',
  32365. type: 'float',
  32366. inputs: [
  32367. { name: 'hash', type: 'uint' },
  32368. { name: 'x', type: 'float' },
  32369. { name: 'y', type: 'float' }
  32370. ]
  32371. } );
  32372. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  32373. const z = float( z_immutable ).toVar();
  32374. const y = float( y_immutable ).toVar();
  32375. const x = float( x_immutable ).toVar();
  32376. const hash = uint( hash_immutable ).toVar();
  32377. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  32378. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  32379. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  32380. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  32381. } ).setLayout( {
  32382. name: 'mx_gradient_float_1',
  32383. type: 'float',
  32384. inputs: [
  32385. { name: 'hash', type: 'uint' },
  32386. { name: 'x', type: 'float' },
  32387. { name: 'y', type: 'float' },
  32388. { name: 'z', type: 'float' }
  32389. ]
  32390. } );
  32391. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  32392. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  32393. const y = float( y_immutable ).toVar();
  32394. const x = float( x_immutable ).toVar();
  32395. const hash = uvec3( hash_immutable ).toVar();
  32396. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  32397. } ).setLayout( {
  32398. name: 'mx_gradient_vec3_0',
  32399. type: 'vec3',
  32400. inputs: [
  32401. { name: 'hash', type: 'uvec3' },
  32402. { name: 'x', type: 'float' },
  32403. { name: 'y', type: 'float' }
  32404. ]
  32405. } );
  32406. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  32407. const z = float( z_immutable ).toVar();
  32408. const y = float( y_immutable ).toVar();
  32409. const x = float( x_immutable ).toVar();
  32410. const hash = uvec3( hash_immutable ).toVar();
  32411. 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 ) );
  32412. } ).setLayout( {
  32413. name: 'mx_gradient_vec3_1',
  32414. type: 'vec3',
  32415. inputs: [
  32416. { name: 'hash', type: 'uvec3' },
  32417. { name: 'x', type: 'float' },
  32418. { name: 'y', type: 'float' },
  32419. { name: 'z', type: 'float' }
  32420. ]
  32421. } );
  32422. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  32423. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32424. const v = float( v_immutable ).toVar();
  32425. return mul( 0.6616, v );
  32426. } ).setLayout( {
  32427. name: 'mx_gradient_scale2d_0',
  32428. type: 'float',
  32429. inputs: [
  32430. { name: 'v', type: 'float' }
  32431. ]
  32432. } );
  32433. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32434. const v = float( v_immutable ).toVar();
  32435. return mul( 0.9820, v );
  32436. } ).setLayout( {
  32437. name: 'mx_gradient_scale3d_0',
  32438. type: 'float',
  32439. inputs: [
  32440. { name: 'v', type: 'float' }
  32441. ]
  32442. } );
  32443. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32444. const v = vec3( v_immutable ).toVar();
  32445. return mul( 0.6616, v );
  32446. } ).setLayout( {
  32447. name: 'mx_gradient_scale2d_1',
  32448. type: 'vec3',
  32449. inputs: [
  32450. { name: 'v', type: 'vec3' }
  32451. ]
  32452. } );
  32453. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  32454. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32455. const v = vec3( v_immutable ).toVar();
  32456. return mul( 0.9820, v );
  32457. } ).setLayout( {
  32458. name: 'mx_gradient_scale3d_1',
  32459. type: 'vec3',
  32460. inputs: [
  32461. { name: 'v', type: 'vec3' }
  32462. ]
  32463. } );
  32464. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  32465. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  32466. const k = int( k_immutable ).toVar();
  32467. const x = uint( x_immutable ).toVar();
  32468. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  32469. } ).setLayout( {
  32470. name: 'mx_rotl32',
  32471. type: 'uint',
  32472. inputs: [
  32473. { name: 'x', type: 'uint' },
  32474. { name: 'k', type: 'int' }
  32475. ]
  32476. } );
  32477. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  32478. a.subAssign( c );
  32479. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  32480. c.addAssign( b );
  32481. b.subAssign( a );
  32482. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  32483. a.addAssign( c );
  32484. c.subAssign( b );
  32485. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  32486. b.addAssign( a );
  32487. a.subAssign( c );
  32488. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  32489. c.addAssign( b );
  32490. b.subAssign( a );
  32491. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  32492. a.addAssign( c );
  32493. c.subAssign( b );
  32494. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  32495. b.addAssign( a );
  32496. } );
  32497. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  32498. const c = uint( c_immutable ).toVar();
  32499. const b = uint( b_immutable ).toVar();
  32500. const a = uint( a_immutable ).toVar();
  32501. c.bitXorAssign( b );
  32502. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  32503. a.bitXorAssign( c );
  32504. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  32505. b.bitXorAssign( a );
  32506. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  32507. c.bitXorAssign( b );
  32508. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  32509. a.bitXorAssign( c );
  32510. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  32511. b.bitXorAssign( a );
  32512. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  32513. c.bitXorAssign( b );
  32514. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  32515. return c;
  32516. } ).setLayout( {
  32517. name: 'mx_bjfinal',
  32518. type: 'uint',
  32519. inputs: [
  32520. { name: 'a', type: 'uint' },
  32521. { name: 'b', type: 'uint' },
  32522. { name: 'c', type: 'uint' }
  32523. ]
  32524. } );
  32525. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  32526. const bits = uint( bits_immutable ).toVar();
  32527. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  32528. } ).setLayout( {
  32529. name: 'mx_bits_to_01',
  32530. type: 'float',
  32531. inputs: [
  32532. { name: 'bits', type: 'uint' }
  32533. ]
  32534. } );
  32535. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  32536. const t = float( t_immutable ).toVar();
  32537. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  32538. } ).setLayout( {
  32539. name: 'mx_fade',
  32540. type: 'float',
  32541. inputs: [
  32542. { name: 't', type: 'float' }
  32543. ]
  32544. } );
  32545. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  32546. const x = int( x_immutable ).toVar();
  32547. const len = uint( uint( 1 ) ).toVar();
  32548. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  32549. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  32550. } ).setLayout( {
  32551. name: 'mx_hash_int_0',
  32552. type: 'uint',
  32553. inputs: [
  32554. { name: 'x', type: 'int' }
  32555. ]
  32556. } );
  32557. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  32558. const y = int( y_immutable ).toVar();
  32559. const x = int( x_immutable ).toVar();
  32560. const len = uint( uint( 2 ) ).toVar();
  32561. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32562. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32563. a.addAssign( uint( x ) );
  32564. b.addAssign( uint( y ) );
  32565. return mx_bjfinal( a, b, c );
  32566. } ).setLayout( {
  32567. name: 'mx_hash_int_1',
  32568. type: 'uint',
  32569. inputs: [
  32570. { name: 'x', type: 'int' },
  32571. { name: 'y', type: 'int' }
  32572. ]
  32573. } );
  32574. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  32575. const z = int( z_immutable ).toVar();
  32576. const y = int( y_immutable ).toVar();
  32577. const x = int( x_immutable ).toVar();
  32578. const len = uint( uint( 3 ) ).toVar();
  32579. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32580. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32581. a.addAssign( uint( x ) );
  32582. b.addAssign( uint( y ) );
  32583. c.addAssign( uint( z ) );
  32584. return mx_bjfinal( a, b, c );
  32585. } ).setLayout( {
  32586. name: 'mx_hash_int_2',
  32587. type: 'uint',
  32588. inputs: [
  32589. { name: 'x', type: 'int' },
  32590. { name: 'y', type: 'int' },
  32591. { name: 'z', type: 'int' }
  32592. ]
  32593. } );
  32594. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  32595. const xx = int( xx_immutable ).toVar();
  32596. const z = int( z_immutable ).toVar();
  32597. const y = int( y_immutable ).toVar();
  32598. const x = int( x_immutable ).toVar();
  32599. const len = uint( uint( 4 ) ).toVar();
  32600. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32601. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32602. a.addAssign( uint( x ) );
  32603. b.addAssign( uint( y ) );
  32604. c.addAssign( uint( z ) );
  32605. mx_bjmix( a, b, c );
  32606. a.addAssign( uint( xx ) );
  32607. return mx_bjfinal( a, b, c );
  32608. } ).setLayout( {
  32609. name: 'mx_hash_int_3',
  32610. type: 'uint',
  32611. inputs: [
  32612. { name: 'x', type: 'int' },
  32613. { name: 'y', type: 'int' },
  32614. { name: 'z', type: 'int' },
  32615. { name: 'xx', type: 'int' }
  32616. ]
  32617. } );
  32618. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  32619. const yy = int( yy_immutable ).toVar();
  32620. const xx = int( xx_immutable ).toVar();
  32621. const z = int( z_immutable ).toVar();
  32622. const y = int( y_immutable ).toVar();
  32623. const x = int( x_immutable ).toVar();
  32624. const len = uint( uint( 5 ) ).toVar();
  32625. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32626. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32627. a.addAssign( uint( x ) );
  32628. b.addAssign( uint( y ) );
  32629. c.addAssign( uint( z ) );
  32630. mx_bjmix( a, b, c );
  32631. a.addAssign( uint( xx ) );
  32632. b.addAssign( uint( yy ) );
  32633. return mx_bjfinal( a, b, c );
  32634. } ).setLayout( {
  32635. name: 'mx_hash_int_4',
  32636. type: 'uint',
  32637. inputs: [
  32638. { name: 'x', type: 'int' },
  32639. { name: 'y', type: 'int' },
  32640. { name: 'z', type: 'int' },
  32641. { name: 'xx', type: 'int' },
  32642. { name: 'yy', type: 'int' }
  32643. ]
  32644. } );
  32645. 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 ] );
  32646. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  32647. const y = int( y_immutable ).toVar();
  32648. const x = int( x_immutable ).toVar();
  32649. const h = uint( mx_hash_int( x, y ) ).toVar();
  32650. const result = uvec3().toVar();
  32651. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  32652. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  32653. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  32654. return result;
  32655. } ).setLayout( {
  32656. name: 'mx_hash_vec3_0',
  32657. type: 'uvec3',
  32658. inputs: [
  32659. { name: 'x', type: 'int' },
  32660. { name: 'y', type: 'int' }
  32661. ]
  32662. } );
  32663. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  32664. const z = int( z_immutable ).toVar();
  32665. const y = int( y_immutable ).toVar();
  32666. const x = int( x_immutable ).toVar();
  32667. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  32668. const result = uvec3().toVar();
  32669. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  32670. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  32671. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  32672. return result;
  32673. } ).setLayout( {
  32674. name: 'mx_hash_vec3_1',
  32675. type: 'uvec3',
  32676. inputs: [
  32677. { name: 'x', type: 'int' },
  32678. { name: 'y', type: 'int' },
  32679. { name: 'z', type: 'int' }
  32680. ]
  32681. } );
  32682. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  32683. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32684. const p = vec2( p_immutable ).toVar();
  32685. const X = int().toVar(), Y = int().toVar();
  32686. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32687. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32688. const u = float( mx_fade( fx ) ).toVar();
  32689. const v = float( mx_fade( fy ) ).toVar();
  32690. 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();
  32691. return mx_gradient_scale2d( result );
  32692. } ).setLayout( {
  32693. name: 'mx_perlin_noise_float_0',
  32694. type: 'float',
  32695. inputs: [
  32696. { name: 'p', type: 'vec2' }
  32697. ]
  32698. } );
  32699. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32700. const p = vec3( p_immutable ).toVar();
  32701. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32702. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32703. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32704. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  32705. const u = float( mx_fade( fx ) ).toVar();
  32706. const v = float( mx_fade( fy ) ).toVar();
  32707. const w = float( mx_fade( fz ) ).toVar();
  32708. 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();
  32709. return mx_gradient_scale3d( result );
  32710. } ).setLayout( {
  32711. name: 'mx_perlin_noise_float_1',
  32712. type: 'float',
  32713. inputs: [
  32714. { name: 'p', type: 'vec3' }
  32715. ]
  32716. } );
  32717. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  32718. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32719. const p = vec2( p_immutable ).toVar();
  32720. const X = int().toVar(), Y = int().toVar();
  32721. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32722. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32723. const u = float( mx_fade( fx ) ).toVar();
  32724. const v = float( mx_fade( fy ) ).toVar();
  32725. 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();
  32726. return mx_gradient_scale2d( result );
  32727. } ).setLayout( {
  32728. name: 'mx_perlin_noise_vec3_0',
  32729. type: 'vec3',
  32730. inputs: [
  32731. { name: 'p', type: 'vec2' }
  32732. ]
  32733. } );
  32734. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32735. const p = vec3( p_immutable ).toVar();
  32736. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32737. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32738. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32739. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  32740. const u = float( mx_fade( fx ) ).toVar();
  32741. const v = float( mx_fade( fy ) ).toVar();
  32742. const w = float( mx_fade( fz ) ).toVar();
  32743. 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();
  32744. return mx_gradient_scale3d( result );
  32745. } ).setLayout( {
  32746. name: 'mx_perlin_noise_vec3_1',
  32747. type: 'vec3',
  32748. inputs: [
  32749. { name: 'p', type: 'vec3' }
  32750. ]
  32751. } );
  32752. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  32753. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32754. const p = float( p_immutable ).toVar();
  32755. const ix = int( mx_floor( p ) ).toVar();
  32756. return mx_bits_to_01( mx_hash_int( ix ) );
  32757. } ).setLayout( {
  32758. name: 'mx_cell_noise_float_0',
  32759. type: 'float',
  32760. inputs: [
  32761. { name: 'p', type: 'float' }
  32762. ]
  32763. } );
  32764. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32765. const p = vec2( p_immutable ).toVar();
  32766. const ix = int( mx_floor( p.x ) ).toVar();
  32767. const iy = int( mx_floor( p.y ) ).toVar();
  32768. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  32769. } ).setLayout( {
  32770. name: 'mx_cell_noise_float_1',
  32771. type: 'float',
  32772. inputs: [
  32773. { name: 'p', type: 'vec2' }
  32774. ]
  32775. } );
  32776. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32777. const p = vec3( p_immutable ).toVar();
  32778. const ix = int( mx_floor( p.x ) ).toVar();
  32779. const iy = int( mx_floor( p.y ) ).toVar();
  32780. const iz = int( mx_floor( p.z ) ).toVar();
  32781. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  32782. } ).setLayout( {
  32783. name: 'mx_cell_noise_float_2',
  32784. type: 'float',
  32785. inputs: [
  32786. { name: 'p', type: 'vec3' }
  32787. ]
  32788. } );
  32789. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32790. const p = vec4( p_immutable ).toVar();
  32791. const ix = int( mx_floor( p.x ) ).toVar();
  32792. const iy = int( mx_floor( p.y ) ).toVar();
  32793. const iz = int( mx_floor( p.z ) ).toVar();
  32794. const iw = int( mx_floor( p.w ) ).toVar();
  32795. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  32796. } ).setLayout( {
  32797. name: 'mx_cell_noise_float_3',
  32798. type: 'float',
  32799. inputs: [
  32800. { name: 'p', type: 'vec4' }
  32801. ]
  32802. } );
  32803. 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 ] );
  32804. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32805. const p = float( p_immutable ).toVar();
  32806. const ix = int( mx_floor( p ) ).toVar();
  32807. 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 ) ) ) );
  32808. } ).setLayout( {
  32809. name: 'mx_cell_noise_vec3_0',
  32810. type: 'vec3',
  32811. inputs: [
  32812. { name: 'p', type: 'float' }
  32813. ]
  32814. } );
  32815. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32816. const p = vec2( p_immutable ).toVar();
  32817. const ix = int( mx_floor( p.x ) ).toVar();
  32818. const iy = int( mx_floor( p.y ) ).toVar();
  32819. 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 ) ) ) );
  32820. } ).setLayout( {
  32821. name: 'mx_cell_noise_vec3_1',
  32822. type: 'vec3',
  32823. inputs: [
  32824. { name: 'p', type: 'vec2' }
  32825. ]
  32826. } );
  32827. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32828. const p = vec3( p_immutable ).toVar();
  32829. const ix = int( mx_floor( p.x ) ).toVar();
  32830. const iy = int( mx_floor( p.y ) ).toVar();
  32831. const iz = int( mx_floor( p.z ) ).toVar();
  32832. 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 ) ) ) );
  32833. } ).setLayout( {
  32834. name: 'mx_cell_noise_vec3_2',
  32835. type: 'vec3',
  32836. inputs: [
  32837. { name: 'p', type: 'vec3' }
  32838. ]
  32839. } );
  32840. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32841. const p = vec4( p_immutable ).toVar();
  32842. const ix = int( mx_floor( p.x ) ).toVar();
  32843. const iy = int( mx_floor( p.y ) ).toVar();
  32844. const iz = int( mx_floor( p.z ) ).toVar();
  32845. const iw = int( mx_floor( p.w ) ).toVar();
  32846. 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 ) ) ) );
  32847. } ).setLayout( {
  32848. name: 'mx_cell_noise_vec3_3',
  32849. type: 'vec3',
  32850. inputs: [
  32851. { name: 'p', type: 'vec4' }
  32852. ]
  32853. } );
  32854. 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 ] );
  32855. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32856. const diminish = float( diminish_immutable ).toVar();
  32857. const lacunarity = float( lacunarity_immutable ).toVar();
  32858. const octaves = int( octaves_immutable ).toVar();
  32859. const p = vec3( p_immutable ).toVar();
  32860. const result = float( 0.0 ).toVar();
  32861. const amplitude = float( 1.0 ).toVar();
  32862. Loop( octaves, () => {
  32863. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  32864. amplitude.mulAssign( diminish );
  32865. p.mulAssign( lacunarity );
  32866. } );
  32867. return result;
  32868. } ).setLayout( {
  32869. name: 'mx_fractal_noise_float',
  32870. type: 'float',
  32871. inputs: [
  32872. { name: 'p', type: 'vec3' },
  32873. { name: 'octaves', type: 'int' },
  32874. { name: 'lacunarity', type: 'float' },
  32875. { name: 'diminish', type: 'float' }
  32876. ]
  32877. } );
  32878. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32879. const diminish = float( diminish_immutable ).toVar();
  32880. const lacunarity = float( lacunarity_immutable ).toVar();
  32881. const octaves = int( octaves_immutable ).toVar();
  32882. const p = vec3( p_immutable ).toVar();
  32883. const result = vec3( 0.0 ).toVar();
  32884. const amplitude = float( 1.0 ).toVar();
  32885. Loop( octaves, () => {
  32886. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  32887. amplitude.mulAssign( diminish );
  32888. p.mulAssign( lacunarity );
  32889. } );
  32890. return result;
  32891. } ).setLayout( {
  32892. name: 'mx_fractal_noise_vec3',
  32893. type: 'vec3',
  32894. inputs: [
  32895. { name: 'p', type: 'vec3' },
  32896. { name: 'octaves', type: 'int' },
  32897. { name: 'lacunarity', type: 'float' },
  32898. { name: 'diminish', type: 'float' }
  32899. ]
  32900. } );
  32901. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32902. const diminish = float( diminish_immutable ).toVar();
  32903. const lacunarity = float( lacunarity_immutable ).toVar();
  32904. const octaves = int( octaves_immutable ).toVar();
  32905. const p = vec3( p_immutable ).toVar();
  32906. 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 ) );
  32907. } ).setLayout( {
  32908. name: 'mx_fractal_noise_vec2',
  32909. type: 'vec2',
  32910. inputs: [
  32911. { name: 'p', type: 'vec3' },
  32912. { name: 'octaves', type: 'int' },
  32913. { name: 'lacunarity', type: 'float' },
  32914. { name: 'diminish', type: 'float' }
  32915. ]
  32916. } );
  32917. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32918. const diminish = float( diminish_immutable ).toVar();
  32919. const lacunarity = float( lacunarity_immutable ).toVar();
  32920. const octaves = int( octaves_immutable ).toVar();
  32921. const p = vec3( p_immutable ).toVar();
  32922. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  32923. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  32924. return vec4( c, f );
  32925. } ).setLayout( {
  32926. name: 'mx_fractal_noise_vec4',
  32927. type: 'vec4',
  32928. inputs: [
  32929. { name: 'p', type: 'vec3' },
  32930. { name: 'octaves', type: 'int' },
  32931. { name: 'lacunarity', type: 'float' },
  32932. { name: 'diminish', type: 'float' }
  32933. ]
  32934. } );
  32935. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  32936. const metric = int( metric_immutable ).toVar();
  32937. const jitter = float( jitter_immutable ).toVar();
  32938. const yoff = int( yoff_immutable ).toVar();
  32939. const xoff = int( xoff_immutable ).toVar();
  32940. const y = int( y_immutable ).toVar();
  32941. const x = int( x_immutable ).toVar();
  32942. const p = vec2( p_immutable ).toVar();
  32943. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  32944. const off = vec2( tmp.x, tmp.y ).toVar();
  32945. off.subAssign( 0.5 );
  32946. off.mulAssign( jitter );
  32947. off.addAssign( 0.5 );
  32948. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  32949. const diff = vec2( cellpos.sub( p ) ).toVar();
  32950. If( metric.equal( int( 2 ) ), () => {
  32951. return abs( diff.x ).add( abs( diff.y ) );
  32952. } );
  32953. If( metric.equal( int( 3 ) ), () => {
  32954. return max$1( abs( diff.x ), abs( diff.y ) );
  32955. } );
  32956. return dot( diff, diff );
  32957. } ).setLayout( {
  32958. name: 'mx_worley_distance_0',
  32959. type: 'float',
  32960. inputs: [
  32961. { name: 'p', type: 'vec2' },
  32962. { name: 'x', type: 'int' },
  32963. { name: 'y', type: 'int' },
  32964. { name: 'xoff', type: 'int' },
  32965. { name: 'yoff', type: 'int' },
  32966. { name: 'jitter', type: 'float' },
  32967. { name: 'metric', type: 'int' }
  32968. ]
  32969. } );
  32970. 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 ] ) => {
  32971. const metric = int( metric_immutable ).toVar();
  32972. const jitter = float( jitter_immutable ).toVar();
  32973. const zoff = int( zoff_immutable ).toVar();
  32974. const yoff = int( yoff_immutable ).toVar();
  32975. const xoff = int( xoff_immutable ).toVar();
  32976. const z = int( z_immutable ).toVar();
  32977. const y = int( y_immutable ).toVar();
  32978. const x = int( x_immutable ).toVar();
  32979. const p = vec3( p_immutable ).toVar();
  32980. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  32981. off.subAssign( 0.5 );
  32982. off.mulAssign( jitter );
  32983. off.addAssign( 0.5 );
  32984. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  32985. const diff = vec3( cellpos.sub( p ) ).toVar();
  32986. If( metric.equal( int( 2 ) ), () => {
  32987. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  32988. } );
  32989. If( metric.equal( int( 3 ) ), () => {
  32990. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  32991. } );
  32992. return dot( diff, diff );
  32993. } ).setLayout( {
  32994. name: 'mx_worley_distance_1',
  32995. type: 'float',
  32996. inputs: [
  32997. { name: 'p', type: 'vec3' },
  32998. { name: 'x', type: 'int' },
  32999. { name: 'y', type: 'int' },
  33000. { name: 'z', type: 'int' },
  33001. { name: 'xoff', type: 'int' },
  33002. { name: 'yoff', type: 'int' },
  33003. { name: 'zoff', type: 'int' },
  33004. { name: 'jitter', type: 'float' },
  33005. { name: 'metric', type: 'int' }
  33006. ]
  33007. } );
  33008. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  33009. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33010. const metric = int( metric_immutable ).toVar();
  33011. const jitter = float( jitter_immutable ).toVar();
  33012. const p = vec2( p_immutable ).toVar();
  33013. const X = int().toVar(), Y = int().toVar();
  33014. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  33015. const sqdist = float( 1e6 ).toVar();
  33016. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33017. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33018. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  33019. sqdist.assign( min$1( sqdist, dist ) );
  33020. } );
  33021. } );
  33022. If( metric.equal( int( 0 ) ), () => {
  33023. sqdist.assign( sqrt( sqdist ) );
  33024. } );
  33025. return sqdist;
  33026. } ).setLayout( {
  33027. name: 'mx_worley_noise_float_0',
  33028. type: 'float',
  33029. inputs: [
  33030. { name: 'p', type: 'vec2' },
  33031. { name: 'jitter', type: 'float' },
  33032. { name: 'metric', type: 'int' }
  33033. ]
  33034. } );
  33035. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33036. const metric = int( metric_immutable ).toVar();
  33037. const jitter = float( jitter_immutable ).toVar();
  33038. const p = vec2( p_immutable ).toVar();
  33039. const X = int().toVar(), Y = int().toVar();
  33040. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  33041. const sqdist = vec2( 1e6, 1e6 ).toVar();
  33042. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33043. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33044. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  33045. If( dist.lessThan( sqdist.x ), () => {
  33046. sqdist.y.assign( sqdist.x );
  33047. sqdist.x.assign( dist );
  33048. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33049. sqdist.y.assign( dist );
  33050. } );
  33051. } );
  33052. } );
  33053. If( metric.equal( int( 0 ) ), () => {
  33054. sqdist.assign( sqrt( sqdist ) );
  33055. } );
  33056. return sqdist;
  33057. } ).setLayout( {
  33058. name: 'mx_worley_noise_vec2_0',
  33059. type: 'vec2',
  33060. inputs: [
  33061. { name: 'p', type: 'vec2' },
  33062. { name: 'jitter', type: 'float' },
  33063. { name: 'metric', type: 'int' }
  33064. ]
  33065. } );
  33066. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33067. const metric = int( metric_immutable ).toVar();
  33068. const jitter = float( jitter_immutable ).toVar();
  33069. const p = vec2( p_immutable ).toVar();
  33070. const X = int().toVar(), Y = int().toVar();
  33071. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  33072. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  33073. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33074. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33075. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  33076. If( dist.lessThan( sqdist.x ), () => {
  33077. sqdist.z.assign( sqdist.y );
  33078. sqdist.y.assign( sqdist.x );
  33079. sqdist.x.assign( dist );
  33080. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33081. sqdist.z.assign( sqdist.y );
  33082. sqdist.y.assign( dist );
  33083. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  33084. sqdist.z.assign( dist );
  33085. } );
  33086. } );
  33087. } );
  33088. If( metric.equal( int( 0 ) ), () => {
  33089. sqdist.assign( sqrt( sqdist ) );
  33090. } );
  33091. return sqdist;
  33092. } ).setLayout( {
  33093. name: 'mx_worley_noise_vec3_0',
  33094. type: 'vec3',
  33095. inputs: [
  33096. { name: 'p', type: 'vec2' },
  33097. { name: 'jitter', type: 'float' },
  33098. { name: 'metric', type: 'int' }
  33099. ]
  33100. } );
  33101. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33102. const metric = int( metric_immutable ).toVar();
  33103. const jitter = float( jitter_immutable ).toVar();
  33104. const p = vec3( p_immutable ).toVar();
  33105. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33106. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  33107. const sqdist = float( 1e6 ).toVar();
  33108. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33109. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33110. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  33111. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  33112. sqdist.assign( min$1( sqdist, dist ) );
  33113. } );
  33114. } );
  33115. } );
  33116. If( metric.equal( int( 0 ) ), () => {
  33117. sqdist.assign( sqrt( sqdist ) );
  33118. } );
  33119. return sqdist;
  33120. } ).setLayout( {
  33121. name: 'mx_worley_noise_float_1',
  33122. type: 'float',
  33123. inputs: [
  33124. { name: 'p', type: 'vec3' },
  33125. { name: 'jitter', type: 'float' },
  33126. { name: 'metric', type: 'int' }
  33127. ]
  33128. } );
  33129. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  33130. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33131. const metric = int( metric_immutable ).toVar();
  33132. const jitter = float( jitter_immutable ).toVar();
  33133. const p = vec3( p_immutable ).toVar();
  33134. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33135. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  33136. const sqdist = vec2( 1e6, 1e6 ).toVar();
  33137. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33138. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33139. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  33140. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  33141. If( dist.lessThan( sqdist.x ), () => {
  33142. sqdist.y.assign( sqdist.x );
  33143. sqdist.x.assign( dist );
  33144. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33145. sqdist.y.assign( dist );
  33146. } );
  33147. } );
  33148. } );
  33149. } );
  33150. If( metric.equal( int( 0 ) ), () => {
  33151. sqdist.assign( sqrt( sqdist ) );
  33152. } );
  33153. return sqdist;
  33154. } ).setLayout( {
  33155. name: 'mx_worley_noise_vec2_1',
  33156. type: 'vec2',
  33157. inputs: [
  33158. { name: 'p', type: 'vec3' },
  33159. { name: 'jitter', type: 'float' },
  33160. { name: 'metric', type: 'int' }
  33161. ]
  33162. } );
  33163. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  33164. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33165. const metric = int( metric_immutable ).toVar();
  33166. const jitter = float( jitter_immutable ).toVar();
  33167. const p = vec3( p_immutable ).toVar();
  33168. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33169. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  33170. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  33171. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33172. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33173. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  33174. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  33175. If( dist.lessThan( sqdist.x ), () => {
  33176. sqdist.z.assign( sqdist.y );
  33177. sqdist.y.assign( sqdist.x );
  33178. sqdist.x.assign( dist );
  33179. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33180. sqdist.z.assign( sqdist.y );
  33181. sqdist.y.assign( dist );
  33182. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  33183. sqdist.z.assign( dist );
  33184. } );
  33185. } );
  33186. } );
  33187. } );
  33188. If( metric.equal( int( 0 ) ), () => {
  33189. sqdist.assign( sqrt( sqdist ) );
  33190. } );
  33191. return sqdist;
  33192. } ).setLayout( {
  33193. name: 'mx_worley_noise_vec3_1',
  33194. type: 'vec3',
  33195. inputs: [
  33196. { name: 'p', type: 'vec3' },
  33197. { name: 'jitter', type: 'float' },
  33198. { name: 'metric', type: 'int' }
  33199. ]
  33200. } );
  33201. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  33202. // Unified Noise 2D
  33203. const mx_unifiednoise2d$1 = /*@__PURE__*/ Fn( ( [
  33204. noiseType_immutable, texcoord_immutable, freq_immutable, offset_immutable,
  33205. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  33206. octaves_immutable, lacunarity_immutable, diminish_immutable
  33207. ] ) => {
  33208. const noiseType = int( noiseType_immutable ).toVar();
  33209. const texcoord = vec2( texcoord_immutable ).toVar();
  33210. const freq = vec2( freq_immutable ).toVar();
  33211. const offset = vec2( offset_immutable ).toVar();
  33212. const jitter = float( jitter_immutable ).toVar();
  33213. const outmin = float( outmin_immutable ).toVar();
  33214. const outmax = float( outmax_immutable ).toVar();
  33215. const clampoutput = bool( clampoutput_immutable ).toVar();
  33216. const octaves = int( octaves_immutable ).toVar();
  33217. const lacunarity = float( lacunarity_immutable ).toVar();
  33218. const diminish = float( diminish_immutable ).toVar();
  33219. // Compute input position
  33220. const p = texcoord.mul( freq ).add( offset );
  33221. const result = float( 0.0 ).toVar();
  33222. // Perlin
  33223. If( noiseType.equal( int( 0 ) ), () => {
  33224. result.assign( mx_perlin_noise_vec3( p ) );
  33225. } );
  33226. // Cell
  33227. If( noiseType.equal( int( 1 ) ), () => {
  33228. result.assign( mx_cell_noise_vec3( p ) );
  33229. } );
  33230. // Worley (metric=0 = euclidean)
  33231. If( noiseType.equal( int( 2 ) ), () => {
  33232. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  33233. } );
  33234. // Fractal (use vec3(p, 0.0) for 2D input)
  33235. If( noiseType.equal( int( 3 ) ), () => {
  33236. result.assign( mx_fractal_noise_vec3$1( vec3( p, 0.0 ), octaves, lacunarity, diminish ) );
  33237. } );
  33238. // Remap output to [outmin, outmax]
  33239. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  33240. // Clamp if requested
  33241. If( clampoutput, () => {
  33242. result.assign( clamp( result, outmin, outmax ) );
  33243. } );
  33244. return result;
  33245. } ).setLayout( {
  33246. name: 'mx_unifiednoise2d',
  33247. type: 'float',
  33248. inputs: [
  33249. { name: 'noiseType', type: 'int' },
  33250. { name: 'texcoord', type: 'vec2' },
  33251. { name: 'freq', type: 'vec2' },
  33252. { name: 'offset', type: 'vec2' },
  33253. { name: 'jitter', type: 'float' },
  33254. { name: 'outmin', type: 'float' },
  33255. { name: 'outmax', type: 'float' },
  33256. { name: 'clampoutput', type: 'bool' },
  33257. { name: 'octaves', type: 'int' },
  33258. { name: 'lacunarity', type: 'float' },
  33259. { name: 'diminish', type: 'float' }
  33260. ]
  33261. } );
  33262. // Unified Noise 3D
  33263. const mx_unifiednoise3d$1 = /*@__PURE__*/ Fn( ( [
  33264. noiseType_immutable, position_immutable, freq_immutable, offset_immutable,
  33265. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  33266. octaves_immutable, lacunarity_immutable, diminish_immutable
  33267. ] ) => {
  33268. const noiseType = int( noiseType_immutable ).toVar();
  33269. const position = vec3( position_immutable ).toVar();
  33270. const freq = vec3( freq_immutable ).toVar();
  33271. const offset = vec3( offset_immutable ).toVar();
  33272. const jitter = float( jitter_immutable ).toVar();
  33273. const outmin = float( outmin_immutable ).toVar();
  33274. const outmax = float( outmax_immutable ).toVar();
  33275. const clampoutput = bool( clampoutput_immutable ).toVar();
  33276. const octaves = int( octaves_immutable ).toVar();
  33277. const lacunarity = float( lacunarity_immutable ).toVar();
  33278. const diminish = float( diminish_immutable ).toVar();
  33279. // Compute input position
  33280. const p = position.mul( freq ).add( offset );
  33281. const result = float( 0.0 ).toVar();
  33282. // Perlin
  33283. If( noiseType.equal( int( 0 ) ), () => {
  33284. result.assign( mx_perlin_noise_vec3( p ) );
  33285. } );
  33286. // Cell
  33287. If( noiseType.equal( int( 1 ) ), () => {
  33288. result.assign( mx_cell_noise_vec3( p ) );
  33289. } );
  33290. // Worley (metric=0 = euclidean)
  33291. If( noiseType.equal( int( 2 ) ), () => {
  33292. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  33293. } );
  33294. // Fractal
  33295. If( noiseType.equal( int( 3 ) ), () => {
  33296. result.assign( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) );
  33297. } );
  33298. // Remap output to [outmin, outmax]
  33299. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  33300. // Clamp if requested
  33301. If( clampoutput, () => {
  33302. result.assign( clamp( result, outmin, outmax ) );
  33303. } );
  33304. return result;
  33305. } ).setLayout( {
  33306. name: 'mx_unifiednoise3d',
  33307. type: 'float',
  33308. inputs: [
  33309. { name: 'noiseType', type: 'int' },
  33310. { name: 'position', type: 'vec3' },
  33311. { name: 'freq', type: 'vec3' },
  33312. { name: 'offset', type: 'vec3' },
  33313. { name: 'jitter', type: 'float' },
  33314. { name: 'outmin', type: 'float' },
  33315. { name: 'outmax', type: 'float' },
  33316. { name: 'clampoutput', type: 'bool' },
  33317. { name: 'octaves', type: 'int' },
  33318. { name: 'lacunarity', type: 'float' },
  33319. { name: 'diminish', type: 'float' }
  33320. ]
  33321. } );
  33322. // Three.js Transpiler
  33323. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  33324. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  33325. const s = hsv.y;
  33326. const v = hsv.z;
  33327. const result = vec3().toVar();
  33328. If( s.lessThan( 0.0001 ), () => {
  33329. result.assign( vec3( v, v, v ) );
  33330. } ).Else( () => {
  33331. let h = hsv.x;
  33332. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  33333. const hi = int( trunc( h ) );
  33334. const f = h.sub( float( hi ) );
  33335. const p = v.mul( s.oneMinus() );
  33336. const q = v.mul( s.mul( f ).oneMinus() );
  33337. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  33338. If( hi.equal( int( 0 ) ), () => {
  33339. result.assign( vec3( v, t, p ) );
  33340. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  33341. result.assign( vec3( q, v, p ) );
  33342. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  33343. result.assign( vec3( p, v, t ) );
  33344. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  33345. result.assign( vec3( p, q, v ) );
  33346. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  33347. result.assign( vec3( t, p, v ) );
  33348. } ).Else( () => {
  33349. result.assign( vec3( v, p, q ) );
  33350. } );
  33351. } );
  33352. return result;
  33353. } ).setLayout( {
  33354. name: 'mx_hsvtorgb',
  33355. type: 'vec3',
  33356. inputs: [
  33357. { name: 'hsv', type: 'vec3' }
  33358. ]
  33359. } );
  33360. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  33361. const c = vec3( c_immutable ).toVar();
  33362. const r = float( c.x ).toVar();
  33363. const g = float( c.y ).toVar();
  33364. const b = float( c.z ).toVar();
  33365. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  33366. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  33367. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  33368. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  33369. v.assign( maxcomp );
  33370. If( maxcomp.greaterThan( 0.0 ), () => {
  33371. s.assign( delta.div( maxcomp ) );
  33372. } ).Else( () => {
  33373. s.assign( 0.0 );
  33374. } );
  33375. If( s.lessThanEqual( 0.0 ), () => {
  33376. h.assign( 0.0 );
  33377. } ).Else( () => {
  33378. If( r.greaterThanEqual( maxcomp ), () => {
  33379. h.assign( g.sub( b ).div( delta ) );
  33380. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  33381. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  33382. } ).Else( () => {
  33383. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  33384. } );
  33385. h.mulAssign( 1.0 / 6.0 );
  33386. If( h.lessThan( 0.0 ), () => {
  33387. h.addAssign( 1.0 );
  33388. } );
  33389. } );
  33390. return vec3( h, s, v );
  33391. } ).setLayout( {
  33392. name: 'mx_rgbtohsv',
  33393. type: 'vec3',
  33394. inputs: [
  33395. { name: 'c', type: 'vec3' }
  33396. ]
  33397. } );
  33398. // Three.js Transpiler
  33399. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  33400. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  33401. const color = vec3( color_immutable ).toVar();
  33402. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  33403. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  33404. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  33405. return mix( linSeg, powSeg, isAbove );
  33406. } ).setLayout( {
  33407. name: 'mx_srgb_texture_to_lin_rec709',
  33408. type: 'vec3',
  33409. inputs: [
  33410. { name: 'color', type: 'vec3' }
  33411. ]
  33412. } );
  33413. const mx_aastep = ( threshold, value ) => {
  33414. threshold = float( threshold );
  33415. value = float( value );
  33416. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  33417. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  33418. };
  33419. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  33420. const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' );
  33421. const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' );
  33422. // Bilinear ramp: interpolate between four corners (tl, tr, bl, br) using texcoord.x and texcoord.y
  33423. const mx_ramp4 = (
  33424. valuetl, valuetr, valuebl, valuebr, texcoord = uv$1()
  33425. ) => {
  33426. const u = texcoord.x.clamp();
  33427. const v = texcoord.y.clamp();
  33428. const top = mix( valuetl, valuetr, u );
  33429. const bottom = mix( valuebl, valuebr, u );
  33430. return mix( top, bottom, v );
  33431. };
  33432. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  33433. const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' );
  33434. const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' );
  33435. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  33436. const mx_safepower = ( in1, in2 = 1 ) => {
  33437. in1 = float( in1 );
  33438. return in1.abs().pow( in2 ).mul( in1.sign() );
  33439. };
  33440. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  33441. const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33442. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33443. const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33444. const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => {
  33445. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  33446. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  33447. return noise_vec4.mul( amplitude ).add( pivot );
  33448. };
  33449. 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 );
  33450. 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 );
  33451. const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33452. const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33453. const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33454. const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  33455. 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 );
  33456. 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 );
  33457. 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 );
  33458. 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 );
  33459. // === Moved from MaterialXLoader.js ===
  33460. // Math ops
  33461. const mx_add = ( in1, in2 = float( 0 ) ) => add( in1, in2 );
  33462. const mx_subtract = ( in1, in2 = float( 0 ) ) => sub( in1, in2 );
  33463. const mx_multiply = ( in1, in2 = float( 1 ) ) => mul( in1, in2 );
  33464. const mx_divide = ( in1, in2 = float( 1 ) ) => div( in1, in2 );
  33465. const mx_modulo = ( in1, in2 = float( 1 ) ) => mod( in1, in2 );
  33466. const mx_power = ( in1, in2 = float( 1 ) ) => pow( in1, in2 );
  33467. const mx_atan2 = ( in1 = float( 0 ), in2 = float( 1 ) ) => atan( in1, in2 );
  33468. const mx_timer = () => time;
  33469. const mx_frame = () => frameId;
  33470. const mx_invert = ( in1, amount = float( 1 ) ) => sub( amount, in1 );
  33471. const mx_ifgreater = ( value1, value2, in1, in2 ) => value1.greaterThan( value2 ).mix( in1, in2 );
  33472. const mx_ifgreatereq = ( value1, value2, in1, in2 ) => value1.greaterThanEqual( value2 ).mix( in1, in2 );
  33473. const mx_ifequal = ( value1, value2, in1, in2 ) => value1.equal( value2 ).mix( in1, in2 );
  33474. // Enhanced separate node to support multi-output referencing (outx, outy, outz, outw)
  33475. const mx_separate = ( in1, channelOrOut = null ) => {
  33476. if ( typeof channelOrOut === 'string' ) {
  33477. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  33478. const c = channelOrOut.replace( /^out/, '' ).toLowerCase();
  33479. if ( map[ c ] !== undefined ) return in1.element( map[ c ] );
  33480. }
  33481. if ( typeof channelOrOut === 'number' ) {
  33482. return in1.element( channelOrOut );
  33483. }
  33484. if ( typeof channelOrOut === 'string' && channelOrOut.length === 1 ) {
  33485. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  33486. if ( map[ channelOrOut ] !== undefined ) return in1.element( map[ channelOrOut ] );
  33487. }
  33488. return in1;
  33489. };
  33490. const mx_place2d = (
  33491. texcoord, pivot = vec2( 0.5, 0.5 ), scale = vec2( 1, 1 ), rotate = float( 0 ), offset = vec2( 0, 0 )/*, operationorder = int( 0 )*/
  33492. ) => {
  33493. let uv = texcoord;
  33494. if ( pivot ) uv = uv.sub( pivot );
  33495. if ( scale ) uv = uv.mul( scale );
  33496. if ( rotate ) {
  33497. const rad = rotate.mul( Math.PI / 180.0 );
  33498. const cosR = rad.cos();
  33499. const sinR = rad.sin();
  33500. uv = vec2(
  33501. uv.x.mul( cosR ).sub( uv.y.mul( sinR ) ),
  33502. uv.x.mul( sinR ).add( uv.y.mul( cosR ) )
  33503. );
  33504. }
  33505. if ( pivot ) uv = uv.add( pivot );
  33506. if ( offset ) uv = uv.add( offset );
  33507. return uv;
  33508. };
  33509. const mx_rotate2d = ( input, amount ) => {
  33510. input = vec2( input );
  33511. amount = float( amount );
  33512. const radians = amount.mul( Math.PI / 180.0 );
  33513. return rotate( input, radians );
  33514. };
  33515. const mx_rotate3d = ( input, amount, axis ) => {
  33516. input = vec3( input );
  33517. amount = float( amount );
  33518. axis = vec3( axis );
  33519. const radians = amount.mul( Math.PI / 180.0 );
  33520. const nAxis = axis.normalize();
  33521. const cosA = radians.cos();
  33522. const sinA = radians.sin();
  33523. const oneMinusCosA = float( 1 ).sub( cosA );
  33524. const rot =
  33525. input.mul( cosA )
  33526. .add( nAxis.cross( input ).mul( sinA ) )
  33527. .add( nAxis.mul( nAxis.dot( input ) ).mul( oneMinusCosA ) );
  33528. return rot;
  33529. };
  33530. const mx_heighttonormal = ( input, scale/*, texcoord*/ ) => {
  33531. input = vec3( input );
  33532. scale = float( scale );
  33533. return bumpMap( input, scale );
  33534. };
  33535. /**
  33536. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  33537. *
  33538. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  33539. *
  33540. * ```js
  33541. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  33542. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  33543. * ```
  33544. *
  33545. * @tsl
  33546. * @function
  33547. * @param {Node<vec3>} normal - The normal to correct.
  33548. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  33549. * @param {Node<vec3>} cubePos - The cube position.
  33550. * @return {Node<vec3>} The parallax corrected normal.
  33551. */
  33552. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  33553. const nDir = normalize( normal ).toVar();
  33554. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  33555. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  33556. const rbminmax = vec3().toVar();
  33557. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  33558. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  33559. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  33560. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  33561. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  33562. return boxIntersection.sub( cubePos );
  33563. } );
  33564. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  33565. // normal is assumed to have unit length
  33566. const x = normal.x, y = normal.y, z = normal.z;
  33567. // band 0
  33568. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  33569. // band 1
  33570. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  33571. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  33572. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  33573. // band 2
  33574. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  33575. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  33576. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  33577. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  33578. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  33579. return result;
  33580. } );
  33581. // constants
  33582. var TSL = /*#__PURE__*/Object.freeze({
  33583. __proto__: null,
  33584. BRDF_GGX: BRDF_GGX,
  33585. BRDF_Lambert: BRDF_Lambert,
  33586. BasicPointShadowFilter: BasicPointShadowFilter,
  33587. BasicShadowFilter: BasicShadowFilter,
  33588. Break: Break,
  33589. Const: Const,
  33590. Continue: Continue,
  33591. DFGLUT: DFGLUT,
  33592. D_GGX: D_GGX,
  33593. Discard: Discard,
  33594. EPSILON: EPSILON,
  33595. F_Schlick: F_Schlick,
  33596. Fn: Fn,
  33597. HALF_PI: HALF_PI,
  33598. INFINITY: INFINITY,
  33599. If: If,
  33600. Loop: Loop,
  33601. NodeAccess: NodeAccess,
  33602. NodeShaderStage: NodeShaderStage,
  33603. NodeType: NodeType,
  33604. NodeUpdateType: NodeUpdateType,
  33605. OnBeforeMaterialUpdate: OnBeforeMaterialUpdate,
  33606. OnBeforeObjectUpdate: OnBeforeObjectUpdate,
  33607. OnMaterialUpdate: OnMaterialUpdate,
  33608. OnObjectUpdate: OnObjectUpdate,
  33609. PCFShadowFilter: PCFShadowFilter,
  33610. PCFSoftShadowFilter: PCFSoftShadowFilter,
  33611. PI: PI,
  33612. PI2: PI2,
  33613. PointShadowFilter: PointShadowFilter,
  33614. Return: Return,
  33615. Schlick_to_F0: Schlick_to_F0,
  33616. ScriptableNodeResources: ScriptableNodeResources,
  33617. ShaderNode: ShaderNode,
  33618. Stack: Stack,
  33619. Switch: Switch,
  33620. TBNViewMatrix: TBNViewMatrix,
  33621. TWO_PI: TWO_PI,
  33622. VSMShadowFilter: VSMShadowFilter,
  33623. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  33624. Var: Var,
  33625. VarIntent: VarIntent,
  33626. abs: abs,
  33627. acesFilmicToneMapping: acesFilmicToneMapping,
  33628. acos: acos,
  33629. add: add,
  33630. addMethodChaining: addMethodChaining,
  33631. addNodeElement: addNodeElement,
  33632. agxToneMapping: agxToneMapping,
  33633. all: all,
  33634. alphaT: alphaT,
  33635. and: and,
  33636. anisotropy: anisotropy,
  33637. anisotropyB: anisotropyB,
  33638. anisotropyT: anisotropyT,
  33639. any: any,
  33640. append: append,
  33641. array: array,
  33642. arrayBuffer: arrayBuffer,
  33643. asin: asin,
  33644. assign: assign,
  33645. atan: atan,
  33646. atan2: atan2,
  33647. atomicAdd: atomicAdd,
  33648. atomicAnd: atomicAnd,
  33649. atomicFunc: atomicFunc,
  33650. atomicLoad: atomicLoad,
  33651. atomicMax: atomicMax,
  33652. atomicMin: atomicMin,
  33653. atomicOr: atomicOr,
  33654. atomicStore: atomicStore,
  33655. atomicSub: atomicSub,
  33656. atomicXor: atomicXor,
  33657. attenuationColor: attenuationColor,
  33658. attenuationDistance: attenuationDistance,
  33659. attribute: attribute,
  33660. attributeArray: attributeArray,
  33661. backgroundBlurriness: backgroundBlurriness,
  33662. backgroundIntensity: backgroundIntensity,
  33663. backgroundRotation: backgroundRotation,
  33664. batch: batch,
  33665. bentNormalView: bentNormalView,
  33666. billboarding: billboarding,
  33667. bitAnd: bitAnd,
  33668. bitNot: bitNot,
  33669. bitOr: bitOr,
  33670. bitXor: bitXor,
  33671. bitangentGeometry: bitangentGeometry,
  33672. bitangentLocal: bitangentLocal,
  33673. bitangentView: bitangentView,
  33674. bitangentWorld: bitangentWorld,
  33675. bitcast: bitcast,
  33676. blendBurn: blendBurn,
  33677. blendColor: blendColor,
  33678. blendDodge: blendDodge,
  33679. blendOverlay: blendOverlay,
  33680. blendScreen: blendScreen,
  33681. blur: blur,
  33682. bool: bool,
  33683. buffer: buffer,
  33684. bufferAttribute: bufferAttribute,
  33685. builtin: builtin,
  33686. builtinAOContext: builtinAOContext,
  33687. builtinShadowContext: builtinShadowContext,
  33688. bumpMap: bumpMap,
  33689. burn: burn,
  33690. bvec2: bvec2,
  33691. bvec3: bvec3,
  33692. bvec4: bvec4,
  33693. bypass: bypass,
  33694. cache: cache,
  33695. call: call,
  33696. cameraFar: cameraFar,
  33697. cameraIndex: cameraIndex,
  33698. cameraNear: cameraNear,
  33699. cameraNormalMatrix: cameraNormalMatrix,
  33700. cameraPosition: cameraPosition,
  33701. cameraProjectionMatrix: cameraProjectionMatrix,
  33702. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  33703. cameraViewMatrix: cameraViewMatrix,
  33704. cameraViewport: cameraViewport,
  33705. cameraWorldMatrix: cameraWorldMatrix,
  33706. cbrt: cbrt,
  33707. cdl: cdl,
  33708. ceil: ceil,
  33709. checker: checker,
  33710. cineonToneMapping: cineonToneMapping,
  33711. clamp: clamp,
  33712. clearcoat: clearcoat,
  33713. clearcoatNormalView: clearcoatNormalView,
  33714. clearcoatRoughness: clearcoatRoughness,
  33715. code: code,
  33716. color: color,
  33717. colorSpaceToWorking: colorSpaceToWorking,
  33718. colorToDirection: colorToDirection,
  33719. compute: compute,
  33720. computeKernel: computeKernel,
  33721. computeSkinning: computeSkinning,
  33722. context: context,
  33723. convert: convert,
  33724. convertColorSpace: convertColorSpace,
  33725. convertToTexture: convertToTexture,
  33726. cos: cos,
  33727. countLeadingZeros: countLeadingZeros,
  33728. countOneBits: countOneBits,
  33729. countTrailingZeros: countTrailingZeros,
  33730. cross: cross,
  33731. cubeTexture: cubeTexture,
  33732. cubeTextureBase: cubeTextureBase,
  33733. dFdx: dFdx,
  33734. dFdy: dFdy,
  33735. dashSize: dashSize,
  33736. debug: debug,
  33737. decrement: decrement,
  33738. decrementBefore: decrementBefore,
  33739. defaultBuildStages: defaultBuildStages,
  33740. defaultShaderStages: defaultShaderStages,
  33741. defined: defined,
  33742. degrees: degrees,
  33743. deltaTime: deltaTime,
  33744. densityFog: densityFog,
  33745. densityFogFactor: densityFogFactor,
  33746. depth: depth,
  33747. depthPass: depthPass,
  33748. determinant: determinant,
  33749. difference: difference,
  33750. diffuseColor: diffuseColor,
  33751. diffuseContribution: diffuseContribution,
  33752. directPointLight: directPointLight,
  33753. directionToColor: directionToColor,
  33754. directionToFaceDirection: directionToFaceDirection,
  33755. dispersion: dispersion,
  33756. disposeShadowMaterial: disposeShadowMaterial,
  33757. distance: distance,
  33758. div: div,
  33759. dodge: dodge,
  33760. dot: dot,
  33761. drawIndex: drawIndex,
  33762. dynamicBufferAttribute: dynamicBufferAttribute,
  33763. element: element,
  33764. emissive: emissive,
  33765. equal: equal,
  33766. equals: equals,
  33767. equirectUV: equirectUV,
  33768. exp: exp,
  33769. exp2: exp2,
  33770. expression: expression,
  33771. faceDirection: faceDirection,
  33772. faceForward: faceForward,
  33773. faceforward: faceforward,
  33774. float: float,
  33775. floatBitsToInt: floatBitsToInt,
  33776. floatBitsToUint: floatBitsToUint,
  33777. floor: floor,
  33778. fog: fog,
  33779. fract: fract,
  33780. frameGroup: frameGroup,
  33781. frameId: frameId,
  33782. frontFacing: frontFacing,
  33783. fwidth: fwidth,
  33784. gain: gain,
  33785. gapSize: gapSize,
  33786. getConstNodeType: getConstNodeType,
  33787. getCurrentStack: getCurrentStack,
  33788. getDirection: getDirection,
  33789. getDistanceAttenuation: getDistanceAttenuation,
  33790. getGeometryRoughness: getGeometryRoughness,
  33791. getNormalFromDepth: getNormalFromDepth,
  33792. getParallaxCorrectNormal: getParallaxCorrectNormal,
  33793. getRoughness: getRoughness,
  33794. getScreenPosition: getScreenPosition,
  33795. getShIrradianceAt: getShIrradianceAt,
  33796. getShadowMaterial: getShadowMaterial,
  33797. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  33798. getTextureIndex: getTextureIndex,
  33799. getViewPosition: getViewPosition,
  33800. ggxConvolution: ggxConvolution,
  33801. globalId: globalId,
  33802. glsl: glsl,
  33803. glslFn: glslFn,
  33804. grayscale: grayscale,
  33805. greaterThan: greaterThan,
  33806. greaterThanEqual: greaterThanEqual,
  33807. hash: hash,
  33808. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  33809. highpModelViewMatrix: highpModelViewMatrix,
  33810. hue: hue,
  33811. increment: increment,
  33812. incrementBefore: incrementBefore,
  33813. inspector: inspector,
  33814. instance: instance,
  33815. instanceIndex: instanceIndex,
  33816. instancedArray: instancedArray,
  33817. instancedBufferAttribute: instancedBufferAttribute,
  33818. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  33819. instancedMesh: instancedMesh,
  33820. int: int,
  33821. intBitsToFloat: intBitsToFloat,
  33822. interleavedGradientNoise: interleavedGradientNoise,
  33823. inverse: inverse,
  33824. inverseSqrt: inverseSqrt,
  33825. inversesqrt: inversesqrt,
  33826. invocationLocalIndex: invocationLocalIndex,
  33827. invocationSubgroupIndex: invocationSubgroupIndex,
  33828. ior: ior,
  33829. iridescence: iridescence,
  33830. iridescenceIOR: iridescenceIOR,
  33831. iridescenceThickness: iridescenceThickness,
  33832. isolate: isolate,
  33833. ivec2: ivec2,
  33834. ivec3: ivec3,
  33835. ivec4: ivec4,
  33836. js: js,
  33837. label: label,
  33838. length: length,
  33839. lengthSq: lengthSq,
  33840. lessThan: lessThan,
  33841. lessThanEqual: lessThanEqual,
  33842. lightPosition: lightPosition,
  33843. lightProjectionUV: lightProjectionUV,
  33844. lightShadowMatrix: lightShadowMatrix,
  33845. lightTargetDirection: lightTargetDirection,
  33846. lightTargetPosition: lightTargetPosition,
  33847. lightViewPosition: lightViewPosition,
  33848. lightingContext: lightingContext,
  33849. lights: lights,
  33850. linearDepth: linearDepth,
  33851. linearToneMapping: linearToneMapping,
  33852. localId: localId,
  33853. log: log,
  33854. log2: log2,
  33855. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  33856. luminance: luminance,
  33857. mat2: mat2,
  33858. mat3: mat3,
  33859. mat4: mat4,
  33860. matcapUV: matcapUV,
  33861. materialAO: materialAO,
  33862. materialAlphaTest: materialAlphaTest,
  33863. materialAnisotropy: materialAnisotropy,
  33864. materialAnisotropyVector: materialAnisotropyVector,
  33865. materialAttenuationColor: materialAttenuationColor,
  33866. materialAttenuationDistance: materialAttenuationDistance,
  33867. materialClearcoat: materialClearcoat,
  33868. materialClearcoatNormal: materialClearcoatNormal,
  33869. materialClearcoatRoughness: materialClearcoatRoughness,
  33870. materialColor: materialColor,
  33871. materialDispersion: materialDispersion,
  33872. materialEmissive: materialEmissive,
  33873. materialEnvIntensity: materialEnvIntensity,
  33874. materialEnvRotation: materialEnvRotation,
  33875. materialIOR: materialIOR,
  33876. materialIridescence: materialIridescence,
  33877. materialIridescenceIOR: materialIridescenceIOR,
  33878. materialIridescenceThickness: materialIridescenceThickness,
  33879. materialLightMap: materialLightMap,
  33880. materialLineDashOffset: materialLineDashOffset,
  33881. materialLineDashSize: materialLineDashSize,
  33882. materialLineGapSize: materialLineGapSize,
  33883. materialLineScale: materialLineScale,
  33884. materialLineWidth: materialLineWidth,
  33885. materialMetalness: materialMetalness,
  33886. materialNormal: materialNormal,
  33887. materialOpacity: materialOpacity,
  33888. materialPointSize: materialPointSize,
  33889. materialReference: materialReference,
  33890. materialReflectivity: materialReflectivity,
  33891. materialRefractionRatio: materialRefractionRatio,
  33892. materialRotation: materialRotation,
  33893. materialRoughness: materialRoughness,
  33894. materialSheen: materialSheen,
  33895. materialSheenRoughness: materialSheenRoughness,
  33896. materialShininess: materialShininess,
  33897. materialSpecular: materialSpecular,
  33898. materialSpecularColor: materialSpecularColor,
  33899. materialSpecularIntensity: materialSpecularIntensity,
  33900. materialSpecularStrength: materialSpecularStrength,
  33901. materialThickness: materialThickness,
  33902. materialTransmission: materialTransmission,
  33903. max: max$1,
  33904. maxMipLevel: maxMipLevel,
  33905. mediumpModelViewMatrix: mediumpModelViewMatrix,
  33906. metalness: metalness,
  33907. min: min$1,
  33908. mix: mix,
  33909. mixElement: mixElement,
  33910. mod: mod,
  33911. modInt: modInt,
  33912. modelDirection: modelDirection,
  33913. modelNormalMatrix: modelNormalMatrix,
  33914. modelPosition: modelPosition,
  33915. modelRadius: modelRadius,
  33916. modelScale: modelScale,
  33917. modelViewMatrix: modelViewMatrix,
  33918. modelViewPosition: modelViewPosition,
  33919. modelViewProjection: modelViewProjection,
  33920. modelWorldMatrix: modelWorldMatrix,
  33921. modelWorldMatrixInverse: modelWorldMatrixInverse,
  33922. morphReference: morphReference,
  33923. mrt: mrt,
  33924. mul: mul,
  33925. mx_aastep: mx_aastep,
  33926. mx_add: mx_add,
  33927. mx_atan2: mx_atan2,
  33928. mx_cell_noise_float: mx_cell_noise_float,
  33929. mx_contrast: mx_contrast,
  33930. mx_divide: mx_divide,
  33931. mx_fractal_noise_float: mx_fractal_noise_float,
  33932. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  33933. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  33934. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  33935. mx_frame: mx_frame,
  33936. mx_heighttonormal: mx_heighttonormal,
  33937. mx_hsvtorgb: mx_hsvtorgb,
  33938. mx_ifequal: mx_ifequal,
  33939. mx_ifgreater: mx_ifgreater,
  33940. mx_ifgreatereq: mx_ifgreatereq,
  33941. mx_invert: mx_invert,
  33942. mx_modulo: mx_modulo,
  33943. mx_multiply: mx_multiply,
  33944. mx_noise_float: mx_noise_float,
  33945. mx_noise_vec3: mx_noise_vec3,
  33946. mx_noise_vec4: mx_noise_vec4,
  33947. mx_place2d: mx_place2d,
  33948. mx_power: mx_power,
  33949. mx_ramp4: mx_ramp4,
  33950. mx_ramplr: mx_ramplr,
  33951. mx_ramptb: mx_ramptb,
  33952. mx_rgbtohsv: mx_rgbtohsv,
  33953. mx_rotate2d: mx_rotate2d,
  33954. mx_rotate3d: mx_rotate3d,
  33955. mx_safepower: mx_safepower,
  33956. mx_separate: mx_separate,
  33957. mx_splitlr: mx_splitlr,
  33958. mx_splittb: mx_splittb,
  33959. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  33960. mx_subtract: mx_subtract,
  33961. mx_timer: mx_timer,
  33962. mx_transform_uv: mx_transform_uv,
  33963. mx_unifiednoise2d: mx_unifiednoise2d,
  33964. mx_unifiednoise3d: mx_unifiednoise3d,
  33965. mx_worley_noise_float: mx_worley_noise_float,
  33966. mx_worley_noise_vec2: mx_worley_noise_vec2,
  33967. mx_worley_noise_vec3: mx_worley_noise_vec3,
  33968. negate: negate,
  33969. neutralToneMapping: neutralToneMapping,
  33970. nodeArray: nodeArray,
  33971. nodeImmutable: nodeImmutable,
  33972. nodeObject: nodeObject,
  33973. nodeObjectIntent: nodeObjectIntent,
  33974. nodeObjects: nodeObjects,
  33975. nodeProxy: nodeProxy,
  33976. nodeProxyIntent: nodeProxyIntent,
  33977. normalFlat: normalFlat,
  33978. normalGeometry: normalGeometry,
  33979. normalLocal: normalLocal,
  33980. normalMap: normalMap,
  33981. normalView: normalView,
  33982. normalViewGeometry: normalViewGeometry,
  33983. normalWorld: normalWorld,
  33984. normalWorldGeometry: normalWorldGeometry,
  33985. normalize: normalize,
  33986. not: not,
  33987. notEqual: notEqual,
  33988. numWorkgroups: numWorkgroups,
  33989. objectDirection: objectDirection,
  33990. objectGroup: objectGroup,
  33991. objectPosition: objectPosition,
  33992. objectRadius: objectRadius,
  33993. objectScale: objectScale,
  33994. objectViewPosition: objectViewPosition,
  33995. objectWorldMatrix: objectWorldMatrix,
  33996. oneMinus: oneMinus,
  33997. or: or,
  33998. orthographicDepthToViewZ: orthographicDepthToViewZ,
  33999. oscSawtooth: oscSawtooth,
  34000. oscSine: oscSine,
  34001. oscSquare: oscSquare,
  34002. oscTriangle: oscTriangle,
  34003. output: output,
  34004. outputStruct: outputStruct,
  34005. overlay: overlay,
  34006. overloadingFn: overloadingFn,
  34007. packHalf2x16: packHalf2x16,
  34008. packSnorm2x16: packSnorm2x16,
  34009. packUnorm2x16: packUnorm2x16,
  34010. parabola: parabola,
  34011. parallaxDirection: parallaxDirection,
  34012. parallaxUV: parallaxUV,
  34013. parameter: parameter,
  34014. pass: pass,
  34015. passTexture: passTexture,
  34016. pcurve: pcurve,
  34017. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  34018. pmremTexture: pmremTexture,
  34019. pointShadow: pointShadow,
  34020. pointUV: pointUV,
  34021. pointWidth: pointWidth,
  34022. positionGeometry: positionGeometry,
  34023. positionLocal: positionLocal,
  34024. positionPrevious: positionPrevious,
  34025. positionView: positionView,
  34026. positionViewDirection: positionViewDirection,
  34027. positionWorld: positionWorld,
  34028. positionWorldDirection: positionWorldDirection,
  34029. posterize: posterize,
  34030. pow: pow,
  34031. pow2: pow2,
  34032. pow3: pow3,
  34033. pow4: pow4,
  34034. premultiplyAlpha: premultiplyAlpha,
  34035. property: property,
  34036. quadBroadcast: quadBroadcast,
  34037. quadSwapDiagonal: quadSwapDiagonal,
  34038. quadSwapX: quadSwapX,
  34039. quadSwapY: quadSwapY,
  34040. radians: radians,
  34041. rand: rand,
  34042. range: range,
  34043. rangeFog: rangeFog,
  34044. rangeFogFactor: rangeFogFactor,
  34045. reciprocal: reciprocal,
  34046. reference: reference,
  34047. referenceBuffer: referenceBuffer,
  34048. reflect: reflect,
  34049. reflectVector: reflectVector,
  34050. reflectView: reflectView,
  34051. reflector: reflector,
  34052. refract: refract,
  34053. refractVector: refractVector,
  34054. refractView: refractView,
  34055. reinhardToneMapping: reinhardToneMapping,
  34056. remap: remap,
  34057. remapClamp: remapClamp,
  34058. renderGroup: renderGroup,
  34059. renderOutput: renderOutput,
  34060. rendererReference: rendererReference,
  34061. replaceDefaultUV: replaceDefaultUV,
  34062. rotate: rotate,
  34063. rotateUV: rotateUV,
  34064. roughness: roughness,
  34065. round: round,
  34066. rtt: rtt,
  34067. sRGBTransferEOTF: sRGBTransferEOTF,
  34068. sRGBTransferOETF: sRGBTransferOETF,
  34069. sample: sample,
  34070. sampler: sampler,
  34071. samplerComparison: samplerComparison,
  34072. saturate: saturate,
  34073. saturation: saturation,
  34074. screen: screen,
  34075. screenCoordinate: screenCoordinate,
  34076. screenDPR: screenDPR,
  34077. screenSize: screenSize,
  34078. screenUV: screenUV,
  34079. scriptable: scriptable,
  34080. scriptableValue: scriptableValue,
  34081. select: select,
  34082. setCurrentStack: setCurrentStack,
  34083. setName: setName,
  34084. shaderStages: shaderStages,
  34085. shadow: shadow,
  34086. shadowPositionWorld: shadowPositionWorld,
  34087. shapeCircle: shapeCircle,
  34088. sharedUniformGroup: sharedUniformGroup,
  34089. sheen: sheen,
  34090. sheenRoughness: sheenRoughness,
  34091. shiftLeft: shiftLeft,
  34092. shiftRight: shiftRight,
  34093. shininess: shininess,
  34094. sign: sign,
  34095. sin: sin,
  34096. sinc: sinc,
  34097. skinning: skinning,
  34098. smoothstep: smoothstep,
  34099. smoothstepElement: smoothstepElement,
  34100. specularColor: specularColor,
  34101. specularColorBlended: specularColorBlended,
  34102. specularF90: specularF90,
  34103. spherizeUV: spherizeUV,
  34104. split: split,
  34105. spritesheetUV: spritesheetUV,
  34106. sqrt: sqrt,
  34107. stack: stack,
  34108. step: step,
  34109. stepElement: stepElement,
  34110. storage: storage,
  34111. storageBarrier: storageBarrier,
  34112. storageObject: storageObject,
  34113. storageTexture: storageTexture,
  34114. string: string,
  34115. struct: struct,
  34116. sub: sub,
  34117. subBuild: subBuild,
  34118. subgroupAdd: subgroupAdd,
  34119. subgroupAll: subgroupAll,
  34120. subgroupAnd: subgroupAnd,
  34121. subgroupAny: subgroupAny,
  34122. subgroupBallot: subgroupBallot,
  34123. subgroupBroadcast: subgroupBroadcast,
  34124. subgroupBroadcastFirst: subgroupBroadcastFirst,
  34125. subgroupElect: subgroupElect,
  34126. subgroupExclusiveAdd: subgroupExclusiveAdd,
  34127. subgroupExclusiveMul: subgroupExclusiveMul,
  34128. subgroupInclusiveAdd: subgroupInclusiveAdd,
  34129. subgroupInclusiveMul: subgroupInclusiveMul,
  34130. subgroupIndex: subgroupIndex,
  34131. subgroupMax: subgroupMax,
  34132. subgroupMin: subgroupMin,
  34133. subgroupMul: subgroupMul,
  34134. subgroupOr: subgroupOr,
  34135. subgroupShuffle: subgroupShuffle,
  34136. subgroupShuffleDown: subgroupShuffleDown,
  34137. subgroupShuffleUp: subgroupShuffleUp,
  34138. subgroupShuffleXor: subgroupShuffleXor,
  34139. subgroupSize: subgroupSize,
  34140. subgroupXor: subgroupXor,
  34141. tan: tan,
  34142. tangentGeometry: tangentGeometry,
  34143. tangentLocal: tangentLocal,
  34144. tangentView: tangentView,
  34145. tangentWorld: tangentWorld,
  34146. texture: texture,
  34147. texture3D: texture3D,
  34148. texture3DLevel: texture3DLevel,
  34149. texture3DLoad: texture3DLoad,
  34150. textureBarrier: textureBarrier,
  34151. textureBicubic: textureBicubic,
  34152. textureBicubicLevel: textureBicubicLevel,
  34153. textureCubeUV: textureCubeUV,
  34154. textureLevel: textureLevel,
  34155. textureLoad: textureLoad,
  34156. textureSize: textureSize,
  34157. textureStore: textureStore,
  34158. thickness: thickness,
  34159. time: time,
  34160. toneMapping: toneMapping,
  34161. toneMappingExposure: toneMappingExposure,
  34162. toonOutlinePass: toonOutlinePass,
  34163. transformDirection: transformDirection,
  34164. transformNormal: transformNormal,
  34165. transformNormalToView: transformNormalToView,
  34166. transformedClearcoatNormalView: transformedClearcoatNormalView,
  34167. transformedNormalView: transformedNormalView,
  34168. transformedNormalWorld: transformedNormalWorld,
  34169. transmission: transmission,
  34170. transpose: transpose,
  34171. triNoise3D: triNoise3D,
  34172. triplanarTexture: triplanarTexture,
  34173. triplanarTextures: triplanarTextures,
  34174. trunc: trunc,
  34175. uint: uint,
  34176. uintBitsToFloat: uintBitsToFloat,
  34177. uniform: uniform,
  34178. uniformArray: uniformArray,
  34179. uniformCubeTexture: uniformCubeTexture,
  34180. uniformFlow: uniformFlow,
  34181. uniformGroup: uniformGroup,
  34182. uniformTexture: uniformTexture,
  34183. unpackHalf2x16: unpackHalf2x16,
  34184. unpackNormal: unpackNormal,
  34185. unpackSnorm2x16: unpackSnorm2x16,
  34186. unpackUnorm2x16: unpackUnorm2x16,
  34187. unpremultiplyAlpha: unpremultiplyAlpha,
  34188. userData: userData,
  34189. uv: uv$1,
  34190. uvec2: uvec2,
  34191. uvec3: uvec3,
  34192. uvec4: uvec4,
  34193. varying: varying,
  34194. varyingProperty: varyingProperty,
  34195. vec2: vec2,
  34196. vec3: vec3,
  34197. vec4: vec4,
  34198. vectorComponents: vectorComponents,
  34199. velocity: velocity,
  34200. vertexColor: vertexColor,
  34201. vertexIndex: vertexIndex,
  34202. vertexStage: vertexStage,
  34203. vibrance: vibrance,
  34204. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  34205. viewZToOrthographicDepth: viewZToOrthographicDepth,
  34206. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  34207. viewport: viewport,
  34208. viewportCoordinate: viewportCoordinate,
  34209. viewportDepthTexture: viewportDepthTexture,
  34210. viewportLinearDepth: viewportLinearDepth,
  34211. viewportMipTexture: viewportMipTexture,
  34212. viewportResolution: viewportResolution,
  34213. viewportSafeUV: viewportSafeUV,
  34214. viewportSharedTexture: viewportSharedTexture,
  34215. viewportSize: viewportSize,
  34216. viewportTexture: viewportTexture,
  34217. viewportUV: viewportUV,
  34218. vogelDiskSample: vogelDiskSample,
  34219. wgsl: wgsl,
  34220. wgslFn: wgslFn,
  34221. workgroupArray: workgroupArray,
  34222. workgroupBarrier: workgroupBarrier,
  34223. workgroupId: workgroupId,
  34224. workingToColorSpace: workingToColorSpace,
  34225. xor: xor
  34226. });
  34227. const _clearColor = /*@__PURE__*/ new Color4();
  34228. /**
  34229. * This renderer module manages the background.
  34230. *
  34231. * @private
  34232. * @augments DataMap
  34233. */
  34234. class Background extends DataMap {
  34235. /**
  34236. * Constructs a new background management component.
  34237. *
  34238. * @param {Renderer} renderer - The renderer.
  34239. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  34240. */
  34241. constructor( renderer, nodes ) {
  34242. super();
  34243. /**
  34244. * The renderer.
  34245. *
  34246. * @type {Renderer}
  34247. */
  34248. this.renderer = renderer;
  34249. /**
  34250. * Renderer component for managing nodes related logic.
  34251. *
  34252. * @type {Nodes}
  34253. */
  34254. this.nodes = nodes;
  34255. }
  34256. /**
  34257. * Updates the background for the given scene. Depending on how `Scene.background`
  34258. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  34259. * or add a mesh to the render list for rendering the background as a textured plane
  34260. * or skybox.
  34261. *
  34262. * @param {Scene} scene - The scene.
  34263. * @param {RenderList} renderList - The current render list.
  34264. * @param {RenderContext} renderContext - The current render context.
  34265. */
  34266. update( scene, renderList, renderContext ) {
  34267. const renderer = this.renderer;
  34268. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  34269. let forceClear = false;
  34270. if ( background === null ) {
  34271. // no background settings, use clear color configuration from the renderer
  34272. renderer._clearColor.getRGB( _clearColor );
  34273. _clearColor.a = renderer._clearColor.a;
  34274. } else if ( background.isColor === true ) {
  34275. // background is an opaque color
  34276. background.getRGB( _clearColor );
  34277. _clearColor.a = 1;
  34278. forceClear = true;
  34279. } else if ( background.isNode === true ) {
  34280. const sceneData = this.get( scene );
  34281. const backgroundNode = background;
  34282. _clearColor.copy( renderer._clearColor );
  34283. let backgroundMesh = sceneData.backgroundMesh;
  34284. if ( backgroundMesh === undefined ) {
  34285. const backgroundMeshNode = vec4( backgroundNode ).mul( backgroundIntensity ).context( {
  34286. // @TODO: Add Texture2D support using node context
  34287. getUV: () => backgroundRotation.mul( normalWorldGeometry ),
  34288. getTextureLevel: () => backgroundBlurriness
  34289. } );
  34290. // when using orthographic cameras, we must scale the skybox sphere
  34291. // up to exceed the dimensions of the camera's viewing box.
  34292. const isOrtho = cameraProjectionMatrix.element( 3 ).element( 3 ).equal( 1.0 );
  34293. // calculate the orthographic scale
  34294. // projectionMatrix[1][1] is (1 / top). Invert it to get the height and multiply by 3.0
  34295. // (an arbitrary safety factor) to ensure the skybox is large enough to cover the corners
  34296. // of the rectangular screen
  34297. const orthoScale = div( 1.0, cameraProjectionMatrix.element( 1 ).element( 1 ) ).mul( 3.0 );
  34298. // compute vertex position
  34299. const modifiedPosition = isOrtho.select( positionLocal.mul( orthoScale ), positionLocal );
  34300. let viewProj = cameraProjectionMatrix.mul( modelViewMatrix.mul( vec4( modifiedPosition, 1.0 ) ) );
  34301. // force background to far plane so it does not occlude objects
  34302. viewProj = viewProj.setZ( viewProj.w );
  34303. const nodeMaterial = new NodeMaterial();
  34304. nodeMaterial.name = 'Background.material';
  34305. nodeMaterial.side = BackSide;
  34306. nodeMaterial.depthTest = false;
  34307. nodeMaterial.depthWrite = false;
  34308. nodeMaterial.allowOverride = false;
  34309. nodeMaterial.fog = false;
  34310. nodeMaterial.lights = false;
  34311. nodeMaterial.vertexNode = viewProj;
  34312. nodeMaterial.colorNode = backgroundMeshNode;
  34313. sceneData.backgroundMeshNode = backgroundMeshNode;
  34314. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  34315. backgroundMesh.frustumCulled = false;
  34316. backgroundMesh.name = 'Background.mesh';
  34317. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  34318. this.matrixWorld.copyPosition( camera.matrixWorld );
  34319. };
  34320. function onBackgroundDispose() {
  34321. background.removeEventListener( 'dispose', onBackgroundDispose );
  34322. backgroundMesh.material.dispose();
  34323. backgroundMesh.geometry.dispose();
  34324. }
  34325. background.addEventListener( 'dispose', onBackgroundDispose );
  34326. }
  34327. const backgroundCacheKey = backgroundNode.getCacheKey();
  34328. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  34329. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  34330. sceneData.backgroundMeshNode.needsUpdate = true;
  34331. backgroundMesh.material.needsUpdate = true;
  34332. sceneData.backgroundCacheKey = backgroundCacheKey;
  34333. }
  34334. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  34335. } else {
  34336. error( 'Renderer: Unsupported background configuration.', background );
  34337. }
  34338. //
  34339. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  34340. if ( environmentBlendMode === 'additive' ) {
  34341. _clearColor.set( 0, 0, 0, 1 );
  34342. } else if ( environmentBlendMode === 'alpha-blend' ) {
  34343. _clearColor.set( 0, 0, 0, 0 );
  34344. }
  34345. //
  34346. if ( renderer.autoClear === true || forceClear === true ) {
  34347. const clearColorValue = renderContext.clearColorValue;
  34348. clearColorValue.r = _clearColor.r;
  34349. clearColorValue.g = _clearColor.g;
  34350. clearColorValue.b = _clearColor.b;
  34351. clearColorValue.a = _clearColor.a;
  34352. // premultiply alpha
  34353. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  34354. clearColorValue.r *= clearColorValue.a;
  34355. clearColorValue.g *= clearColorValue.a;
  34356. clearColorValue.b *= clearColorValue.a;
  34357. }
  34358. //
  34359. renderContext.depthClearValue = renderer._clearDepth;
  34360. renderContext.stencilClearValue = renderer._clearStencil;
  34361. renderContext.clearColor = renderer.autoClearColor === true;
  34362. renderContext.clearDepth = renderer.autoClearDepth === true;
  34363. renderContext.clearStencil = renderer.autoClearStencil === true;
  34364. } else {
  34365. renderContext.clearColor = false;
  34366. renderContext.clearDepth = false;
  34367. renderContext.clearStencil = false;
  34368. }
  34369. }
  34370. }
  34371. let _id$7 = 0;
  34372. /**
  34373. * A bind group represents a collection of bindings and thus a collection
  34374. * or resources. Bind groups are assigned to pipelines to provide them
  34375. * with the required resources (like uniform buffers or textures).
  34376. *
  34377. * @private
  34378. */
  34379. class BindGroup {
  34380. /**
  34381. * Constructs a new bind group.
  34382. *
  34383. * @param {string} name - The bind group's name.
  34384. * @param {Array<Binding>} bindings - An array of bindings.
  34385. * @param {number} index - The group index.
  34386. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  34387. */
  34388. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  34389. /**
  34390. * The bind group's name.
  34391. *
  34392. * @type {string}
  34393. */
  34394. this.name = name;
  34395. /**
  34396. * An array of bindings.
  34397. *
  34398. * @type {Array<Binding>}
  34399. */
  34400. this.bindings = bindings;
  34401. /**
  34402. * The group index.
  34403. *
  34404. * @type {number}
  34405. */
  34406. this.index = index;
  34407. /**
  34408. * An array of reference bindings.
  34409. *
  34410. * @type {Array<Binding>}
  34411. */
  34412. this.bindingsReference = bindingsReference;
  34413. /**
  34414. * The group's ID.
  34415. *
  34416. * @type {number}
  34417. */
  34418. this.id = _id$7 ++;
  34419. }
  34420. }
  34421. /**
  34422. * This module represents the state of a node builder after it was
  34423. * used to build the nodes for a render object. The state holds the
  34424. * results of the build for further processing in the renderer.
  34425. *
  34426. * Render objects with identical cache keys share the same node builder state.
  34427. *
  34428. * @private
  34429. */
  34430. class NodeBuilderState {
  34431. /**
  34432. * Constructs a new node builder state.
  34433. *
  34434. * @param {string} vertexShader - The native vertex shader code.
  34435. * @param {string} fragmentShader - The native fragment shader code.
  34436. * @param {string} computeShader - The native compute shader code.
  34437. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  34438. * @param {Array<BindGroup>} bindings - An array of bind groups.
  34439. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  34440. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  34441. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  34442. * @param {NodeMaterialObserver} observer - A node material observer.
  34443. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  34444. */
  34445. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  34446. /**
  34447. * The native vertex shader code.
  34448. *
  34449. * @type {string}
  34450. */
  34451. this.vertexShader = vertexShader;
  34452. /**
  34453. * The native fragment shader code.
  34454. *
  34455. * @type {string}
  34456. */
  34457. this.fragmentShader = fragmentShader;
  34458. /**
  34459. * The native compute shader code.
  34460. *
  34461. * @type {string}
  34462. */
  34463. this.computeShader = computeShader;
  34464. /**
  34465. * An array with transform attribute objects.
  34466. * Only relevant when using compute shaders with WebGL 2.
  34467. *
  34468. * @type {Array<Object>}
  34469. */
  34470. this.transforms = transforms;
  34471. /**
  34472. * An array of node attributes representing
  34473. * the attributes of the shaders.
  34474. *
  34475. * @type {Array<NodeAttribute>}
  34476. */
  34477. this.nodeAttributes = nodeAttributes;
  34478. /**
  34479. * An array of bind groups representing the uniform or storage
  34480. * buffers, texture or samplers of the shader.
  34481. *
  34482. * @type {Array<BindGroup>}
  34483. */
  34484. this.bindings = bindings;
  34485. /**
  34486. * An array of nodes that implement their `update()` method.
  34487. *
  34488. * @type {Array<Node>}
  34489. */
  34490. this.updateNodes = updateNodes;
  34491. /**
  34492. * An array of nodes that implement their `updateBefore()` method.
  34493. *
  34494. * @type {Array<Node>}
  34495. */
  34496. this.updateBeforeNodes = updateBeforeNodes;
  34497. /**
  34498. * An array of nodes that implement their `updateAfter()` method.
  34499. *
  34500. * @type {Array<Node>}
  34501. */
  34502. this.updateAfterNodes = updateAfterNodes;
  34503. /**
  34504. * A node material observer.
  34505. *
  34506. * @type {NodeMaterialObserver}
  34507. */
  34508. this.observer = observer;
  34509. /**
  34510. * How often this state is used by render objects.
  34511. *
  34512. * @type {number}
  34513. */
  34514. this.usedTimes = 0;
  34515. }
  34516. /**
  34517. * This method is used to create a array of bind groups based
  34518. * on the existing bind groups of this state. Shared groups are
  34519. * not cloned.
  34520. *
  34521. * @return {Array<BindGroup>} A array of bind groups.
  34522. */
  34523. createBindings() {
  34524. const bindings = [];
  34525. for ( const instanceGroup of this.bindings ) {
  34526. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  34527. if ( shared !== true ) {
  34528. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup.bindingsReference );
  34529. bindings.push( bindingsGroup );
  34530. for ( const instanceBinding of instanceGroup.bindings ) {
  34531. bindingsGroup.bindings.push( instanceBinding.clone() );
  34532. }
  34533. } else {
  34534. bindings.push( instanceGroup );
  34535. }
  34536. }
  34537. return bindings;
  34538. }
  34539. }
  34540. /**
  34541. * {@link NodeBuilder} is going to create instances of this class during the build process
  34542. * of nodes. They represent the final shader attributes that are going to be generated
  34543. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  34544. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  34545. */
  34546. class NodeAttribute {
  34547. /**
  34548. * Constructs a new node attribute.
  34549. *
  34550. * @param {string} name - The name of the attribute.
  34551. * @param {string} type - The type of the attribute.
  34552. * @param {?Node} node - An optional reference to the node.
  34553. */
  34554. constructor( name, type, node = null ) {
  34555. /**
  34556. * This flag can be used for type testing.
  34557. *
  34558. * @type {boolean}
  34559. * @readonly
  34560. * @default true
  34561. */
  34562. this.isNodeAttribute = true;
  34563. /**
  34564. * The name of the attribute.
  34565. *
  34566. * @type {string}
  34567. */
  34568. this.name = name;
  34569. /**
  34570. * The type of the attribute.
  34571. *
  34572. * @type {string}
  34573. */
  34574. this.type = type;
  34575. /**
  34576. * An optional reference to the node.
  34577. *
  34578. * @type {?Node}
  34579. * @default null
  34580. */
  34581. this.node = node;
  34582. }
  34583. }
  34584. /**
  34585. * {@link NodeBuilder} is going to create instances of this class during the build process
  34586. * of nodes. They represent the final shader uniforms that are going to be generated
  34587. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  34588. * for this purpose.
  34589. */
  34590. class NodeUniform {
  34591. /**
  34592. * Constructs a new node uniform.
  34593. *
  34594. * @param {string} name - The name of the uniform.
  34595. * @param {string} type - The type of the uniform.
  34596. * @param {UniformNode} node - An reference to the node.
  34597. */
  34598. constructor( name, type, node ) {
  34599. /**
  34600. * This flag can be used for type testing.
  34601. *
  34602. * @type {boolean}
  34603. * @readonly
  34604. * @default true
  34605. */
  34606. this.isNodeUniform = true;
  34607. /**
  34608. * The name of the uniform.
  34609. *
  34610. * @type {string}
  34611. */
  34612. this.name = name;
  34613. /**
  34614. * The type of the uniform.
  34615. *
  34616. * @type {string}
  34617. */
  34618. this.type = type;
  34619. /**
  34620. * An reference to the node.
  34621. *
  34622. * @type {UniformNode}
  34623. */
  34624. this.node = node;
  34625. }
  34626. /**
  34627. * The value of the uniform node.
  34628. *
  34629. * @type {any}
  34630. */
  34631. get value() {
  34632. return this.node.value;
  34633. }
  34634. set value( val ) {
  34635. this.node.value = val;
  34636. }
  34637. /**
  34638. * The id of the uniform node.
  34639. *
  34640. * @type {number}
  34641. */
  34642. get id() {
  34643. return this.node.id;
  34644. }
  34645. /**
  34646. * The uniform node's group.
  34647. *
  34648. * @type {UniformGroupNode}
  34649. */
  34650. get groupNode() {
  34651. return this.node.groupNode;
  34652. }
  34653. }
  34654. /**
  34655. * {@link NodeBuilder} is going to create instances of this class during the build process
  34656. * of nodes. They represent the final shader variables that are going to be generated
  34657. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  34658. * this purpose.
  34659. */
  34660. class NodeVar {
  34661. /**
  34662. * Constructs a new node variable.
  34663. *
  34664. * @param {string} name - The name of the variable.
  34665. * @param {string} type - The type of the variable.
  34666. * @param {boolean} [readOnly=false] - The read-only flag.
  34667. * @param {?number} [count=null] - The size.
  34668. */
  34669. constructor( name, type, readOnly = false, count = null ) {
  34670. /**
  34671. * This flag can be used for type testing.
  34672. *
  34673. * @type {boolean}
  34674. * @readonly
  34675. * @default true
  34676. */
  34677. this.isNodeVar = true;
  34678. /**
  34679. * The name of the variable.
  34680. *
  34681. * @type {string}
  34682. */
  34683. this.name = name;
  34684. /**
  34685. * The type of the variable.
  34686. *
  34687. * @type {string}
  34688. */
  34689. this.type = type;
  34690. /**
  34691. * The read-only flag.
  34692. *
  34693. * @type {boolean}
  34694. */
  34695. this.readOnly = readOnly;
  34696. /**
  34697. * The size.
  34698. *
  34699. * @type {?number}
  34700. */
  34701. this.count = count;
  34702. }
  34703. }
  34704. /**
  34705. * {@link NodeBuilder} is going to create instances of this class during the build process
  34706. * of nodes. They represent the final shader varyings that are going to be generated
  34707. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  34708. * this purpose.
  34709. *
  34710. * @augments NodeVar
  34711. */
  34712. class NodeVarying extends NodeVar {
  34713. /**
  34714. * Constructs a new node varying.
  34715. *
  34716. * @param {string} name - The name of the varying.
  34717. * @param {string} type - The type of the varying.
  34718. * @param {?string} interpolationType - The interpolation type of the varying.
  34719. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  34720. */
  34721. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  34722. super( name, type );
  34723. /**
  34724. * Whether this varying requires interpolation or not. This property can be used
  34725. * to check if the varying can be optimized for a variable.
  34726. *
  34727. * @type {boolean}
  34728. * @default false
  34729. */
  34730. this.needsInterpolation = false;
  34731. /**
  34732. * This flag can be used for type testing.
  34733. *
  34734. * @type {boolean}
  34735. * @readonly
  34736. * @default true
  34737. */
  34738. this.isNodeVarying = true;
  34739. /**
  34740. * The interpolation type of the varying data.
  34741. *
  34742. * @type {?string}
  34743. * @default null
  34744. */
  34745. this.interpolationType = interpolationType;
  34746. /**
  34747. * The interpolation sampling type of varying data.
  34748. *
  34749. * @type {?string}
  34750. * @default null
  34751. */
  34752. this.interpolationSampling = interpolationSampling;
  34753. }
  34754. }
  34755. /**
  34756. * {@link NodeBuilder} is going to create instances of this class during the build process
  34757. * of nodes. They represent user-defined, native shader code portions that are going to be
  34758. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  34759. * for this purpose.
  34760. */
  34761. class NodeCode {
  34762. /**
  34763. * Constructs a new code node.
  34764. *
  34765. * @param {string} name - The name of the code.
  34766. * @param {string} type - The node type.
  34767. * @param {string} [code=''] - The native shader code.
  34768. */
  34769. constructor( name, type, code = '' ) {
  34770. /**
  34771. * The name of the code.
  34772. *
  34773. * @type {string}
  34774. */
  34775. this.name = name;
  34776. /**
  34777. * The node type.
  34778. *
  34779. * @type {string}
  34780. */
  34781. this.type = type;
  34782. /**
  34783. * The native shader code.
  34784. *
  34785. * @type {string}
  34786. * @default ''
  34787. */
  34788. this.code = code;
  34789. Object.defineProperty( this, 'isNodeCode', { value: true } );
  34790. }
  34791. }
  34792. let _id$6 = 0;
  34793. /**
  34794. * This utility class is used in {@link NodeBuilder} as an internal
  34795. * cache data structure for node data.
  34796. */
  34797. class NodeCache {
  34798. /**
  34799. * Constructs a new node cache.
  34800. *
  34801. * @param {?NodeCache} parent - A reference to a parent cache.
  34802. */
  34803. constructor( parent = null ) {
  34804. /**
  34805. * The id of the cache.
  34806. *
  34807. * @type {number}
  34808. * @readonly
  34809. */
  34810. this.id = _id$6 ++;
  34811. /**
  34812. * A weak map for managing node data.
  34813. *
  34814. * @type {WeakMap<Node, Object>}
  34815. */
  34816. this.nodesData = new WeakMap();
  34817. /**
  34818. * Reference to a parent node cache.
  34819. *
  34820. * @type {?NodeCache}
  34821. * @default null
  34822. */
  34823. this.parent = parent;
  34824. }
  34825. /**
  34826. * Returns the data for the given node.
  34827. *
  34828. * @param {Node} node - The node.
  34829. * @return {?Object} The data for the node.
  34830. */
  34831. getData( node ) {
  34832. let data = this.nodesData.get( node );
  34833. if ( data === undefined && this.parent !== null ) {
  34834. data = this.parent.getData( node );
  34835. }
  34836. return data;
  34837. }
  34838. /**
  34839. * Sets the data for a given node.
  34840. *
  34841. * @param {Node} node - The node.
  34842. * @param {Object} data - The data that should be cached.
  34843. */
  34844. setData( node, data ) {
  34845. this.nodesData.set( node, data );
  34846. }
  34847. }
  34848. class StructType {
  34849. constructor( name, members ) {
  34850. this.name = name;
  34851. this.members = members;
  34852. this.output = false;
  34853. }
  34854. }
  34855. /**
  34856. * Abstract base class for uniforms.
  34857. *
  34858. * @abstract
  34859. * @private
  34860. */
  34861. class Uniform {
  34862. /**
  34863. * Constructs a new uniform.
  34864. *
  34865. * @param {string} name - The uniform's name.
  34866. * @param {any} value - The uniform's value.
  34867. */
  34868. constructor( name, value ) {
  34869. /**
  34870. * The uniform's name.
  34871. *
  34872. * @type {string}
  34873. */
  34874. this.name = name;
  34875. /**
  34876. * The uniform's value.
  34877. *
  34878. * @type {any}
  34879. */
  34880. this.value = value;
  34881. /**
  34882. * Used to build the uniform buffer according to the STD140 layout.
  34883. * Derived uniforms will set this property to a data type specific
  34884. * value.
  34885. *
  34886. * @type {number}
  34887. */
  34888. this.boundary = 0;
  34889. /**
  34890. * The item size. Derived uniforms will set this property to a data
  34891. * type specific value.
  34892. *
  34893. * @type {number}
  34894. */
  34895. this.itemSize = 0;
  34896. /**
  34897. * This property is set by {@link UniformsGroup} and marks
  34898. * the start position in the uniform buffer.
  34899. *
  34900. * @type {number}
  34901. */
  34902. this.offset = 0;
  34903. }
  34904. /**
  34905. * Sets the uniform's value.
  34906. *
  34907. * @param {any} value - The value to set.
  34908. */
  34909. setValue( value ) {
  34910. this.value = value;
  34911. }
  34912. /**
  34913. * Returns the uniform's value.
  34914. *
  34915. * @return {any} The value.
  34916. */
  34917. getValue() {
  34918. return this.value;
  34919. }
  34920. }
  34921. /**
  34922. * Represents a Number uniform.
  34923. *
  34924. * @private
  34925. * @augments Uniform
  34926. */
  34927. class NumberUniform extends Uniform {
  34928. /**
  34929. * Constructs a new Number uniform.
  34930. *
  34931. * @param {string} name - The uniform's name.
  34932. * @param {number} value - The uniform's value.
  34933. */
  34934. constructor( name, value = 0 ) {
  34935. super( name, value );
  34936. /**
  34937. * This flag can be used for type testing.
  34938. *
  34939. * @type {boolean}
  34940. * @readonly
  34941. * @default true
  34942. */
  34943. this.isNumberUniform = true;
  34944. this.boundary = 4;
  34945. this.itemSize = 1;
  34946. }
  34947. }
  34948. /**
  34949. * Represents a Vector2 uniform.
  34950. *
  34951. * @private
  34952. * @augments Uniform
  34953. */
  34954. class Vector2Uniform extends Uniform {
  34955. /**
  34956. * Constructs a new Number uniform.
  34957. *
  34958. * @param {string} name - The uniform's name.
  34959. * @param {Vector2} value - The uniform's value.
  34960. */
  34961. constructor( name, value = new Vector2() ) {
  34962. super( name, value );
  34963. /**
  34964. * This flag can be used for type testing.
  34965. *
  34966. * @type {boolean}
  34967. * @readonly
  34968. * @default true
  34969. */
  34970. this.isVector2Uniform = true;
  34971. this.boundary = 8;
  34972. this.itemSize = 2;
  34973. }
  34974. }
  34975. /**
  34976. * Represents a Vector3 uniform.
  34977. *
  34978. * @private
  34979. * @augments Uniform
  34980. */
  34981. class Vector3Uniform extends Uniform {
  34982. /**
  34983. * Constructs a new Number uniform.
  34984. *
  34985. * @param {string} name - The uniform's name.
  34986. * @param {Vector3} value - The uniform's value.
  34987. */
  34988. constructor( name, value = new Vector3() ) {
  34989. super( name, value );
  34990. /**
  34991. * This flag can be used for type testing.
  34992. *
  34993. * @type {boolean}
  34994. * @readonly
  34995. * @default true
  34996. */
  34997. this.isVector3Uniform = true;
  34998. this.boundary = 16;
  34999. this.itemSize = 3;
  35000. }
  35001. }
  35002. /**
  35003. * Represents a Vector4 uniform.
  35004. *
  35005. * @private
  35006. * @augments Uniform
  35007. */
  35008. class Vector4Uniform extends Uniform {
  35009. /**
  35010. * Constructs a new Number uniform.
  35011. *
  35012. * @param {string} name - The uniform's name.
  35013. * @param {Vector4} value - The uniform's value.
  35014. */
  35015. constructor( name, value = new Vector4() ) {
  35016. super( name, value );
  35017. /**
  35018. * This flag can be used for type testing.
  35019. *
  35020. * @type {boolean}
  35021. * @readonly
  35022. * @default true
  35023. */
  35024. this.isVector4Uniform = true;
  35025. this.boundary = 16;
  35026. this.itemSize = 4;
  35027. }
  35028. }
  35029. /**
  35030. * Represents a Color uniform.
  35031. *
  35032. * @private
  35033. * @augments Uniform
  35034. */
  35035. class ColorUniform extends Uniform {
  35036. /**
  35037. * Constructs a new Number uniform.
  35038. *
  35039. * @param {string} name - The uniform's name.
  35040. * @param {Color} value - The uniform's value.
  35041. */
  35042. constructor( name, value = new Color() ) {
  35043. super( name, value );
  35044. /**
  35045. * This flag can be used for type testing.
  35046. *
  35047. * @type {boolean}
  35048. * @readonly
  35049. * @default true
  35050. */
  35051. this.isColorUniform = true;
  35052. this.boundary = 16;
  35053. this.itemSize = 3;
  35054. }
  35055. }
  35056. /**
  35057. * Represents a Matrix2 uniform.
  35058. *
  35059. * @private
  35060. * @augments Uniform
  35061. */
  35062. class Matrix2Uniform extends Uniform {
  35063. /**
  35064. * Constructs a new Number uniform.
  35065. *
  35066. * @param {string} name - The uniform's name.
  35067. * @param {Matrix2} value - The uniform's value.
  35068. */
  35069. constructor( name, value = new Matrix2() ) {
  35070. super( name, value );
  35071. /**
  35072. * This flag can be used for type testing.
  35073. *
  35074. * @type {boolean}
  35075. * @readonly
  35076. * @default true
  35077. */
  35078. this.isMatrix2Uniform = true;
  35079. this.boundary = 8;
  35080. this.itemSize = 4;
  35081. }
  35082. }
  35083. /**
  35084. * Represents a Matrix3 uniform.
  35085. *
  35086. * @private
  35087. * @augments Uniform
  35088. */
  35089. class Matrix3Uniform extends Uniform {
  35090. /**
  35091. * Constructs a new Number uniform.
  35092. *
  35093. * @param {string} name - The uniform's name.
  35094. * @param {Matrix3} value - The uniform's value.
  35095. */
  35096. constructor( name, value = new Matrix3() ) {
  35097. super( name, value );
  35098. /**
  35099. * This flag can be used for type testing.
  35100. *
  35101. * @type {boolean}
  35102. * @readonly
  35103. * @default true
  35104. */
  35105. this.isMatrix3Uniform = true;
  35106. this.boundary = 48;
  35107. this.itemSize = 12;
  35108. }
  35109. }
  35110. /**
  35111. * Represents a Matrix4 uniform.
  35112. *
  35113. * @private
  35114. * @augments Uniform
  35115. */
  35116. class Matrix4Uniform extends Uniform {
  35117. /**
  35118. * Constructs a new Number uniform.
  35119. *
  35120. * @param {string} name - The uniform's name.
  35121. * @param {Matrix4} value - The uniform's value.
  35122. */
  35123. constructor( name, value = new Matrix4() ) {
  35124. super( name, value );
  35125. /**
  35126. * This flag can be used for type testing.
  35127. *
  35128. * @type {boolean}
  35129. * @readonly
  35130. * @default true
  35131. */
  35132. this.isMatrix4Uniform = true;
  35133. this.boundary = 64;
  35134. this.itemSize = 16;
  35135. }
  35136. }
  35137. /**
  35138. * A special form of Number uniform binding type.
  35139. * It's value is managed by a node object.
  35140. *
  35141. * @private
  35142. * @augments NumberUniform
  35143. */
  35144. class NumberNodeUniform extends NumberUniform {
  35145. /**
  35146. * Constructs a new node-based Number uniform.
  35147. *
  35148. * @param {NodeUniform} nodeUniform - The node uniform.
  35149. */
  35150. constructor( nodeUniform ) {
  35151. super( nodeUniform.name, nodeUniform.value );
  35152. /**
  35153. * The node uniform.
  35154. *
  35155. * @type {NodeUniform}
  35156. */
  35157. this.nodeUniform = nodeUniform;
  35158. }
  35159. /**
  35160. * Overwritten to return the value of the node uniform.
  35161. *
  35162. * @return {number} The value.
  35163. */
  35164. getValue() {
  35165. return this.nodeUniform.value;
  35166. }
  35167. /**
  35168. * Returns the node uniform data type.
  35169. *
  35170. * @return {string} The data type.
  35171. */
  35172. getType() {
  35173. return this.nodeUniform.type;
  35174. }
  35175. }
  35176. /**
  35177. * A special form of Vector2 uniform binding type.
  35178. * It's value is managed by a node object.
  35179. *
  35180. * @private
  35181. * @augments Vector2Uniform
  35182. */
  35183. class Vector2NodeUniform extends Vector2Uniform {
  35184. /**
  35185. * Constructs a new node-based Vector2 uniform.
  35186. *
  35187. * @param {NodeUniform} nodeUniform - The node uniform.
  35188. */
  35189. constructor( nodeUniform ) {
  35190. super( nodeUniform.name, nodeUniform.value );
  35191. /**
  35192. * The node uniform.
  35193. *
  35194. * @type {NodeUniform}
  35195. */
  35196. this.nodeUniform = nodeUniform;
  35197. }
  35198. /**
  35199. * Overwritten to return the value of the node uniform.
  35200. *
  35201. * @return {Vector2} The value.
  35202. */
  35203. getValue() {
  35204. return this.nodeUniform.value;
  35205. }
  35206. /**
  35207. * Returns the node uniform data type.
  35208. *
  35209. * @return {string} The data type.
  35210. */
  35211. getType() {
  35212. return this.nodeUniform.type;
  35213. }
  35214. }
  35215. /**
  35216. * A special form of Vector3 uniform binding type.
  35217. * It's value is managed by a node object.
  35218. *
  35219. * @private
  35220. * @augments Vector3Uniform
  35221. */
  35222. class Vector3NodeUniform extends Vector3Uniform {
  35223. /**
  35224. * Constructs a new node-based Vector3 uniform.
  35225. *
  35226. * @param {NodeUniform} nodeUniform - The node uniform.
  35227. */
  35228. constructor( nodeUniform ) {
  35229. super( nodeUniform.name, nodeUniform.value );
  35230. /**
  35231. * The node uniform.
  35232. *
  35233. * @type {NodeUniform}
  35234. */
  35235. this.nodeUniform = nodeUniform;
  35236. }
  35237. /**
  35238. * Overwritten to return the value of the node uniform.
  35239. *
  35240. * @return {Vector3} The value.
  35241. */
  35242. getValue() {
  35243. return this.nodeUniform.value;
  35244. }
  35245. /**
  35246. * Returns the node uniform data type.
  35247. *
  35248. * @return {string} The data type.
  35249. */
  35250. getType() {
  35251. return this.nodeUniform.type;
  35252. }
  35253. }
  35254. /**
  35255. * A special form of Vector4 uniform binding type.
  35256. * It's value is managed by a node object.
  35257. *
  35258. * @private
  35259. * @augments Vector4Uniform
  35260. */
  35261. class Vector4NodeUniform extends Vector4Uniform {
  35262. /**
  35263. * Constructs a new node-based Vector4 uniform.
  35264. *
  35265. * @param {NodeUniform} nodeUniform - The node uniform.
  35266. */
  35267. constructor( nodeUniform ) {
  35268. super( nodeUniform.name, nodeUniform.value );
  35269. /**
  35270. * The node uniform.
  35271. *
  35272. * @type {NodeUniform}
  35273. */
  35274. this.nodeUniform = nodeUniform;
  35275. }
  35276. /**
  35277. * Overwritten to return the value of the node uniform.
  35278. *
  35279. * @return {Vector4} The value.
  35280. */
  35281. getValue() {
  35282. return this.nodeUniform.value;
  35283. }
  35284. /**
  35285. * Returns the node uniform data type.
  35286. *
  35287. * @return {string} The data type.
  35288. */
  35289. getType() {
  35290. return this.nodeUniform.type;
  35291. }
  35292. }
  35293. /**
  35294. * A special form of Color uniform binding type.
  35295. * It's value is managed by a node object.
  35296. *
  35297. * @private
  35298. * @augments ColorUniform
  35299. */
  35300. class ColorNodeUniform extends ColorUniform {
  35301. /**
  35302. * Constructs a new node-based Color uniform.
  35303. *
  35304. * @param {NodeUniform} nodeUniform - The node uniform.
  35305. */
  35306. constructor( nodeUniform ) {
  35307. super( nodeUniform.name, nodeUniform.value );
  35308. /**
  35309. * The node uniform.
  35310. *
  35311. * @type {NodeUniform}
  35312. */
  35313. this.nodeUniform = nodeUniform;
  35314. }
  35315. /**
  35316. * Overwritten to return the value of the node uniform.
  35317. *
  35318. * @return {Color} The value.
  35319. */
  35320. getValue() {
  35321. return this.nodeUniform.value;
  35322. }
  35323. /**
  35324. * Returns the node uniform data type.
  35325. *
  35326. * @return {string} The data type.
  35327. */
  35328. getType() {
  35329. return this.nodeUniform.type;
  35330. }
  35331. }
  35332. /**
  35333. * A special form of Matrix2 uniform binding type.
  35334. * It's value is managed by a node object.
  35335. *
  35336. * @private
  35337. * @augments Matrix2Uniform
  35338. */
  35339. class Matrix2NodeUniform extends Matrix2Uniform {
  35340. /**
  35341. * Constructs a new node-based Matrix2 uniform.
  35342. *
  35343. * @param {NodeUniform} nodeUniform - The node uniform.
  35344. */
  35345. constructor( nodeUniform ) {
  35346. super( nodeUniform.name, nodeUniform.value );
  35347. /**
  35348. * The node uniform.
  35349. *
  35350. * @type {NodeUniform}
  35351. */
  35352. this.nodeUniform = nodeUniform;
  35353. }
  35354. /**
  35355. * Overwritten to return the value of the node uniform.
  35356. *
  35357. * @return {Matrix2} The value.
  35358. */
  35359. getValue() {
  35360. return this.nodeUniform.value;
  35361. }
  35362. /**
  35363. * Returns the node uniform data type.
  35364. *
  35365. * @return {string} The data type.
  35366. */
  35367. getType() {
  35368. return this.nodeUniform.type;
  35369. }
  35370. }
  35371. /**
  35372. * A special form of Matrix3 uniform binding type.
  35373. * It's value is managed by a node object.
  35374. *
  35375. * @private
  35376. * @augments Matrix3Uniform
  35377. */
  35378. class Matrix3NodeUniform extends Matrix3Uniform {
  35379. /**
  35380. * Constructs a new node-based Matrix3 uniform.
  35381. *
  35382. * @param {NodeUniform} nodeUniform - The node uniform.
  35383. */
  35384. constructor( nodeUniform ) {
  35385. super( nodeUniform.name, nodeUniform.value );
  35386. /**
  35387. * The node uniform.
  35388. *
  35389. * @type {NodeUniform}
  35390. */
  35391. this.nodeUniform = nodeUniform;
  35392. }
  35393. /**
  35394. * Overwritten to return the value of the node uniform.
  35395. *
  35396. * @return {Matrix3} The value.
  35397. */
  35398. getValue() {
  35399. return this.nodeUniform.value;
  35400. }
  35401. /**
  35402. * Returns the node uniform data type.
  35403. *
  35404. * @return {string} The data type.
  35405. */
  35406. getType() {
  35407. return this.nodeUniform.type;
  35408. }
  35409. }
  35410. /**
  35411. * A special form of Matrix4 uniform binding type.
  35412. * It's value is managed by a node object.
  35413. *
  35414. * @private
  35415. * @augments Matrix4Uniform
  35416. */
  35417. class Matrix4NodeUniform extends Matrix4Uniform {
  35418. /**
  35419. * Constructs a new node-based Matrix4 uniform.
  35420. *
  35421. * @param {NodeUniform} nodeUniform - The node uniform.
  35422. */
  35423. constructor( nodeUniform ) {
  35424. super( nodeUniform.name, nodeUniform.value );
  35425. /**
  35426. * The node uniform.
  35427. *
  35428. * @type {NodeUniform}
  35429. */
  35430. this.nodeUniform = nodeUniform;
  35431. }
  35432. /**
  35433. * Overwritten to return the value of the node uniform.
  35434. *
  35435. * @return {Matrix4} The value.
  35436. */
  35437. getValue() {
  35438. return this.nodeUniform.value;
  35439. }
  35440. /**
  35441. * Returns the node uniform data type.
  35442. *
  35443. * @return {string} The data type.
  35444. */
  35445. getType() {
  35446. return this.nodeUniform.type;
  35447. }
  35448. }
  35449. let _id$5 = 0;
  35450. const sharedNodeData = new WeakMap();
  35451. const rendererCache = new WeakMap();
  35452. const typeFromArray = new Map( [
  35453. [ Int8Array, 'int' ],
  35454. [ Int16Array, 'int' ],
  35455. [ Int32Array, 'int' ],
  35456. [ Uint8Array, 'uint' ],
  35457. [ Uint16Array, 'uint' ],
  35458. [ Uint32Array, 'uint' ],
  35459. [ Float32Array, 'float' ]
  35460. ] );
  35461. const toFloat = ( value ) => {
  35462. if ( /e/g.test( value ) ) {
  35463. return String( value ).replace( /\+/g, '' );
  35464. } else {
  35465. value = Number( value );
  35466. return value + ( value % 1 ? '' : '.0' );
  35467. }
  35468. };
  35469. /**
  35470. * Base class for builders which generate a shader program based
  35471. * on a 3D object and its node material definition.
  35472. */
  35473. class NodeBuilder {
  35474. /**
  35475. * Constructs a new node builder.
  35476. *
  35477. * @param {Object3D} object - The 3D object.
  35478. * @param {Renderer} renderer - The current renderer.
  35479. * @param {NodeParser} parser - A reference to a node parser.
  35480. */
  35481. constructor( object, renderer, parser ) {
  35482. /**
  35483. * The 3D object.
  35484. *
  35485. * @type {Object3D}
  35486. */
  35487. this.object = object;
  35488. /**
  35489. * The material of the 3D object.
  35490. *
  35491. * @type {?Material}
  35492. */
  35493. this.material = ( object && object.material ) || null;
  35494. /**
  35495. * The geometry of the 3D object.
  35496. *
  35497. * @type {?BufferGeometry}
  35498. */
  35499. this.geometry = ( object && object.geometry ) || null;
  35500. /**
  35501. * The current renderer.
  35502. *
  35503. * @type {Renderer}
  35504. */
  35505. this.renderer = renderer;
  35506. /**
  35507. * A reference to a node parser.
  35508. *
  35509. * @type {NodeParser}
  35510. */
  35511. this.parser = parser;
  35512. /**
  35513. * The scene the 3D object belongs to.
  35514. *
  35515. * @type {?Scene}
  35516. * @default null
  35517. */
  35518. this.scene = null;
  35519. /**
  35520. * The camera the 3D object is rendered with.
  35521. *
  35522. * @type {?Camera}
  35523. * @default null
  35524. */
  35525. this.camera = null;
  35526. /**
  35527. * A list of all nodes the builder is processing
  35528. * for this 3D object.
  35529. *
  35530. * @type {Array<Node>}
  35531. */
  35532. this.nodes = [];
  35533. /**
  35534. * A list of all sequential nodes.
  35535. *
  35536. * @type {Array<Node>}
  35537. */
  35538. this.sequentialNodes = [];
  35539. /**
  35540. * A list of all nodes which {@link Node#update} method should be executed.
  35541. *
  35542. * @type {Array<Node>}
  35543. */
  35544. this.updateNodes = [];
  35545. /**
  35546. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  35547. *
  35548. * @type {Array<Node>}
  35549. */
  35550. this.updateBeforeNodes = [];
  35551. /**
  35552. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  35553. *
  35554. * @type {Array<Node>}
  35555. */
  35556. this.updateAfterNodes = [];
  35557. /**
  35558. * A dictionary that assigns each node to a unique hash.
  35559. *
  35560. * @type {Object<number,Node>}
  35561. */
  35562. this.hashNodes = {};
  35563. /**
  35564. * A reference to a node material observer.
  35565. *
  35566. * @type {?NodeMaterialObserver}
  35567. * @default null
  35568. */
  35569. this.observer = null;
  35570. /**
  35571. * A reference to the current lights node.
  35572. *
  35573. * @type {?LightsNode}
  35574. * @default null
  35575. */
  35576. this.lightsNode = null;
  35577. /**
  35578. * A reference to the current environment node.
  35579. *
  35580. * @type {?Node}
  35581. * @default null
  35582. */
  35583. this.environmentNode = null;
  35584. /**
  35585. * A reference to the current fog node.
  35586. *
  35587. * @type {?Node}
  35588. * @default null
  35589. */
  35590. this.fogNode = null;
  35591. /**
  35592. * The current clipping context.
  35593. *
  35594. * @type {?ClippingContext}
  35595. */
  35596. this.clippingContext = null;
  35597. /**
  35598. * The generated vertex shader.
  35599. *
  35600. * @type {?string}
  35601. */
  35602. this.vertexShader = null;
  35603. /**
  35604. * The generated fragment shader.
  35605. *
  35606. * @type {?string}
  35607. */
  35608. this.fragmentShader = null;
  35609. /**
  35610. * The generated compute shader.
  35611. *
  35612. * @type {?string}
  35613. */
  35614. this.computeShader = null;
  35615. /**
  35616. * Nodes used in the primary flow of code generation.
  35617. *
  35618. * @type {Object<string,Array<Node>>}
  35619. */
  35620. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  35621. /**
  35622. * Nodes code from `.flowNodes`.
  35623. *
  35624. * @type {Object<string,string>}
  35625. */
  35626. this.flowCode = { vertex: '', fragment: '', compute: '' };
  35627. /**
  35628. * This dictionary holds the node uniforms of the builder.
  35629. * The uniforms are maintained in an array for each shader stage.
  35630. *
  35631. * @type {Object}
  35632. */
  35633. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  35634. /**
  35635. * This dictionary holds the output structs of the builder.
  35636. * The structs are maintained in an array for each shader stage.
  35637. *
  35638. * @type {Object}
  35639. */
  35640. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  35641. /**
  35642. * This dictionary holds the types of the builder.
  35643. *
  35644. * @type {Object}
  35645. */
  35646. this.types = { vertex: [], fragment: [], compute: [], index: 0 };
  35647. /**
  35648. * This dictionary holds the bindings for each shader stage.
  35649. *
  35650. * @type {Object}
  35651. */
  35652. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  35653. /**
  35654. * This dictionary maintains the binding indices per bind group.
  35655. *
  35656. * @type {Object}
  35657. */
  35658. this.bindingsIndexes = {};
  35659. /**
  35660. * Reference to the array of bind groups.
  35661. *
  35662. * @type {?Array<BindGroup>}
  35663. */
  35664. this.bindGroups = null;
  35665. /**
  35666. * This array holds the node attributes of this builder
  35667. * created via {@link AttributeNode}.
  35668. *
  35669. * @type {Array<NodeAttribute>}
  35670. */
  35671. this.attributes = [];
  35672. /**
  35673. * This array holds the node attributes of this builder
  35674. * created via {@link BufferAttributeNode}.
  35675. *
  35676. * @type {Array<NodeAttribute>}
  35677. */
  35678. this.bufferAttributes = [];
  35679. /**
  35680. * This array holds the node varyings of this builder.
  35681. *
  35682. * @type {Array<NodeVarying>}
  35683. */
  35684. this.varyings = [];
  35685. /**
  35686. * This dictionary holds the (native) node codes of this builder.
  35687. * The codes are maintained in an array for each shader stage.
  35688. *
  35689. * @type {Object<string,Array<NodeCode>>}
  35690. */
  35691. this.codes = {};
  35692. /**
  35693. * This dictionary holds the node variables of this builder.
  35694. * The variables are maintained in an array for each shader stage.
  35695. * This dictionary is also used to count the number of variables
  35696. * according to their type (const, vars).
  35697. *
  35698. * @type {Object<string,Array<NodeVar>|number>}
  35699. */
  35700. this.vars = {};
  35701. /**
  35702. * This dictionary holds the declarations for each shader stage.
  35703. *
  35704. * @type {Object}
  35705. */
  35706. this.declarations = {};
  35707. /**
  35708. * Current code flow.
  35709. * All code generated in this stack will be stored in `.flow`.
  35710. *
  35711. * @type {{code: string}}
  35712. */
  35713. this.flow = { code: '' };
  35714. /**
  35715. * A chain of nodes.
  35716. * Used to check recursive calls in node-graph.
  35717. *
  35718. * @type {Array<Node>}
  35719. */
  35720. this.chaining = [];
  35721. /**
  35722. * The current stack.
  35723. * This reflects the current process in the code block hierarchy,
  35724. * it is useful to know if the current process is inside a conditional for example.
  35725. *
  35726. * @type {StackNode}
  35727. */
  35728. this.stack = stack();
  35729. /**
  35730. * List of stack nodes.
  35731. * The current stack hierarchy is stored in an array.
  35732. *
  35733. * @type {Array<StackNode>}
  35734. */
  35735. this.stacks = [];
  35736. /**
  35737. * A tab value. Used for shader string generation.
  35738. *
  35739. * @type {string}
  35740. * @default '\t'
  35741. */
  35742. this.tab = '\t';
  35743. /**
  35744. * Reference to the current function node.
  35745. *
  35746. * @type {?FunctionNode}
  35747. * @default null
  35748. */
  35749. this.currentFunctionNode = null;
  35750. /**
  35751. * The builder's context.
  35752. *
  35753. * @type {Object}
  35754. */
  35755. this.context = {
  35756. material: this.material
  35757. };
  35758. /**
  35759. * The builder's cache.
  35760. *
  35761. * @type {NodeCache}
  35762. */
  35763. this.cache = new NodeCache();
  35764. /**
  35765. * Since the {@link NodeBuilder#cache} might be temporarily
  35766. * overwritten by other caches, this member retains the reference
  35767. * to the builder's own cache.
  35768. *
  35769. * @type {NodeCache}
  35770. * @default this.cache
  35771. */
  35772. this.globalCache = this.cache;
  35773. this.flowsData = new WeakMap();
  35774. /**
  35775. * The current shader stage.
  35776. *
  35777. * @type {?('vertex'|'fragment'|'compute'|'any')}
  35778. */
  35779. this.shaderStage = null;
  35780. /**
  35781. * The current build stage.
  35782. *
  35783. * @type {?('setup'|'analyze'|'generate')}
  35784. */
  35785. this.buildStage = null;
  35786. /**
  35787. * The sub-build layers.
  35788. *
  35789. * @type {Array<SubBuildNode>}
  35790. * @default []
  35791. */
  35792. this.subBuildLayers = [];
  35793. /**
  35794. * The active stack nodes.
  35795. *
  35796. * @type {Array<StackNode>}
  35797. */
  35798. this.activeStacks = [];
  35799. /**
  35800. * The current sub-build TSL function(Fn).
  35801. *
  35802. * @type {?string}
  35803. * @default null
  35804. */
  35805. this.subBuildFn = null;
  35806. /**
  35807. * The current TSL function(Fn) call node.
  35808. *
  35809. * @type {?Node}
  35810. * @default null
  35811. */
  35812. this.fnCall = null;
  35813. Object.defineProperty( this, 'id', { value: _id$5 ++ } );
  35814. }
  35815. /**
  35816. * Whether the material is opaque or not.
  35817. *
  35818. * @return {boolean} Whether the material is opaque or not.
  35819. */
  35820. isOpaque() {
  35821. const material = this.material;
  35822. return material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false;
  35823. }
  35824. /**
  35825. * Returns the bind groups of the current renderer.
  35826. *
  35827. * @return {ChainMap} The cache.
  35828. */
  35829. getBindGroupsCache() {
  35830. let bindGroupsCache = rendererCache.get( this.renderer );
  35831. if ( bindGroupsCache === undefined ) {
  35832. bindGroupsCache = new ChainMap();
  35833. rendererCache.set( this.renderer, bindGroupsCache );
  35834. }
  35835. return bindGroupsCache;
  35836. }
  35837. /**
  35838. * Factory method for creating an instance of {@link RenderTarget} with the given
  35839. * dimensions and options.
  35840. *
  35841. * @param {number} width - The width of the render target.
  35842. * @param {number} height - The height of the render target.
  35843. * @param {Object} options - The options of the render target.
  35844. * @return {RenderTarget} The render target.
  35845. */
  35846. createRenderTarget( width, height, options ) {
  35847. return new RenderTarget( width, height, options );
  35848. }
  35849. /**
  35850. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  35851. * dimensions and options.
  35852. *
  35853. * @param {number} size - The size of the cube render target.
  35854. * @param {Object} options - The options of the cube render target.
  35855. * @return {CubeRenderTarget} The cube render target.
  35856. */
  35857. createCubeRenderTarget( size, options ) {
  35858. return new CubeRenderTarget( size, options );
  35859. }
  35860. /**
  35861. * Whether the given node is included in the internal array of nodes or not.
  35862. *
  35863. * @param {Node} node - The node to test.
  35864. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  35865. */
  35866. includes( node ) {
  35867. return this.nodes.includes( node );
  35868. }
  35869. /**
  35870. * Returns the output struct name which is required by
  35871. * {@link OutputStructNode}.
  35872. *
  35873. * @abstract
  35874. * @return {string} The name of the output struct.
  35875. */
  35876. getOutputStructName() {}
  35877. /**
  35878. * Returns a bind group for the given group name and binding.
  35879. *
  35880. * @private
  35881. * @param {string} groupName - The group name.
  35882. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  35883. * @return {BindGroup} The bind group
  35884. */
  35885. _getBindGroup( groupName, bindings ) {
  35886. const bindGroupsCache = this.getBindGroupsCache();
  35887. //
  35888. const bindingsArray = [];
  35889. let sharedGroup = true;
  35890. for ( const binding of bindings ) {
  35891. bindingsArray.push( binding );
  35892. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  35893. }
  35894. //
  35895. let bindGroup;
  35896. if ( sharedGroup ) {
  35897. bindGroup = bindGroupsCache.get( bindingsArray );
  35898. if ( bindGroup === undefined ) {
  35899. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  35900. bindGroupsCache.set( bindingsArray, bindGroup );
  35901. }
  35902. } else {
  35903. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  35904. }
  35905. return bindGroup;
  35906. }
  35907. /**
  35908. * Returns an array of node uniform groups for the given group name and shader stage.
  35909. *
  35910. * @param {string} groupName - The group name.
  35911. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35912. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  35913. */
  35914. getBindGroupArray( groupName, shaderStage ) {
  35915. const bindings = this.bindings[ shaderStage ];
  35916. let bindGroup = bindings[ groupName ];
  35917. if ( bindGroup === undefined ) {
  35918. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  35919. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  35920. }
  35921. bindings[ groupName ] = bindGroup = [];
  35922. }
  35923. return bindGroup;
  35924. }
  35925. /**
  35926. * Returns a list bindings of all shader stages separated by groups.
  35927. *
  35928. * @return {Array<BindGroup>} The list of bindings.
  35929. */
  35930. getBindings() {
  35931. let bindingsGroups = this.bindGroups;
  35932. if ( bindingsGroups === null ) {
  35933. const groups = {};
  35934. const bindings = this.bindings;
  35935. for ( const shaderStage of shaderStages ) {
  35936. for ( const groupName in bindings[ shaderStage ] ) {
  35937. const uniforms = bindings[ shaderStage ][ groupName ];
  35938. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  35939. groupUniforms.push( ...uniforms );
  35940. }
  35941. }
  35942. bindingsGroups = [];
  35943. for ( const groupName in groups ) {
  35944. const group = groups[ groupName ];
  35945. const bindingsGroup = this._getBindGroup( groupName, group );
  35946. bindingsGroups.push( bindingsGroup );
  35947. }
  35948. this.bindGroups = bindingsGroups;
  35949. }
  35950. return bindingsGroups;
  35951. }
  35952. /**
  35953. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  35954. */
  35955. sortBindingGroups() {
  35956. const bindingsGroups = this.getBindings();
  35957. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  35958. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  35959. const bindingGroup = bindingsGroups[ i ];
  35960. this.bindingsIndexes[ bindingGroup.name ].group = i;
  35961. bindingGroup.index = i;
  35962. }
  35963. }
  35964. /**
  35965. * The builder maintains each node in a hash-based dictionary.
  35966. * This method sets the given node (value) with the given hash (key) into this dictionary.
  35967. *
  35968. * @param {Node} node - The node to add.
  35969. * @param {number} hash - The hash of the node.
  35970. */
  35971. setHashNode( node, hash ) {
  35972. this.hashNodes[ hash ] = node;
  35973. }
  35974. /**
  35975. * Adds a node to this builder.
  35976. *
  35977. * @param {Node} node - The node to add.
  35978. */
  35979. addNode( node ) {
  35980. if ( this.nodes.includes( node ) === false ) {
  35981. this.nodes.push( node );
  35982. this.setHashNode( node, node.getHash( this ) );
  35983. }
  35984. }
  35985. /**
  35986. * It is used to add Nodes that will be used as FRAME and RENDER events,
  35987. * and need to follow a certain sequence in the calls to work correctly.
  35988. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  35989. *
  35990. * @param {Node} node - The node to add.
  35991. */
  35992. addSequentialNode( node ) {
  35993. if ( this.sequentialNodes.includes( node ) === false ) {
  35994. this.sequentialNodes.push( node );
  35995. }
  35996. }
  35997. /**
  35998. * Checks the update types of nodes
  35999. */
  36000. buildUpdateNodes() {
  36001. for ( const node of this.nodes ) {
  36002. const updateType = node.getUpdateType();
  36003. if ( updateType !== NodeUpdateType.NONE ) {
  36004. this.updateNodes.push( node );
  36005. }
  36006. }
  36007. for ( const node of this.sequentialNodes ) {
  36008. const updateBeforeType = node.getUpdateBeforeType();
  36009. const updateAfterType = node.getUpdateAfterType();
  36010. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  36011. this.updateBeforeNodes.push( node );
  36012. }
  36013. if ( updateAfterType !== NodeUpdateType.NONE ) {
  36014. this.updateAfterNodes.push( node );
  36015. }
  36016. }
  36017. }
  36018. /**
  36019. * A reference the current node which is the
  36020. * last node in the chain of nodes.
  36021. *
  36022. * @type {Node}
  36023. */
  36024. get currentNode() {
  36025. return this.chaining[ this.chaining.length - 1 ];
  36026. }
  36027. /**
  36028. * Whether the given texture is filtered or not.
  36029. *
  36030. * @param {Texture} texture - The texture to check.
  36031. * @return {boolean} Whether the given texture is filtered or not.
  36032. */
  36033. isFilteredTexture( texture ) {
  36034. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  36035. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  36036. }
  36037. /**
  36038. * Adds the given node to the internal node chain.
  36039. * This is used to check recursive calls in node-graph.
  36040. *
  36041. * @param {Node} node - The node to add.
  36042. */
  36043. addChain( node ) {
  36044. /*
  36045. if ( this.chaining.indexOf( node ) !== - 1 ) {
  36046. warn( 'Recursive node: ', node );
  36047. }
  36048. */
  36049. this.chaining.push( node );
  36050. }
  36051. /**
  36052. * Removes the given node from the internal node chain.
  36053. *
  36054. * @param {Node} node - The node to remove.
  36055. */
  36056. removeChain( node ) {
  36057. const lastChain = this.chaining.pop();
  36058. if ( lastChain !== node ) {
  36059. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  36060. }
  36061. }
  36062. /**
  36063. * Returns the native shader method name for a given generic name. E.g.
  36064. * the method name `textureDimensions` matches the WGSL name but must be
  36065. * resolved to `textureSize` in GLSL.
  36066. *
  36067. * @abstract
  36068. * @param {string} method - The method name to resolve.
  36069. * @return {string} The resolved method name.
  36070. */
  36071. getMethod( method ) {
  36072. return method;
  36073. }
  36074. /**
  36075. * Returns the native snippet for a ternary operation. E.g. GLSL would output
  36076. * a ternary op as `cond ? x : y` whereas WGSL would output it as `select(y, x, cond)`
  36077. *
  36078. * @abstract
  36079. * @param {string} condSnippet - The condition determining which expression gets resolved.
  36080. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  36081. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  36082. * @return {string} The resolved method name.
  36083. */
  36084. getTernary( /* condSnippet, ifSnippet, elseSnippet*/ ) {
  36085. return null;
  36086. }
  36087. /**
  36088. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  36089. *
  36090. * @param {number} hash - The hash of the node.
  36091. * @return {Node} The found node.
  36092. */
  36093. getNodeFromHash( hash ) {
  36094. return this.hashNodes[ hash ];
  36095. }
  36096. /**
  36097. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  36098. *
  36099. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  36100. * @param {Node} node - The node to add.
  36101. * @return {Node} The node.
  36102. */
  36103. addFlow( shaderStage, node ) {
  36104. this.flowNodes[ shaderStage ].push( node );
  36105. return node;
  36106. }
  36107. /**
  36108. * Sets builder's context.
  36109. *
  36110. * @param {Object} context - The context to set.
  36111. */
  36112. setContext( context ) {
  36113. this.context = context;
  36114. }
  36115. /**
  36116. * Returns the builder's current context.
  36117. *
  36118. * @return {Object} The builder's current context.
  36119. */
  36120. getContext() {
  36121. return this.context;
  36122. }
  36123. /**
  36124. * Adds context data to the builder's current context.
  36125. *
  36126. * @param {Object} context - The context to add.
  36127. * @return {Object} The previous context.
  36128. */
  36129. addContext( context ) {
  36130. const previousContext = this.getContext();
  36131. this.setContext( { ...this.context, ...context } );
  36132. return previousContext;
  36133. }
  36134. /**
  36135. * Gets a context used in shader construction that can be shared across different materials.
  36136. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  36137. *
  36138. * @return {Object} The builder's current context without material.
  36139. */
  36140. getSharedContext() {
  36141. const context = { ...this.context };
  36142. delete context.material;
  36143. delete context.getUV;
  36144. delete context.getOutput;
  36145. delete context.getTextureLevel;
  36146. delete context.getAO;
  36147. delete context.getShadow;
  36148. return context;
  36149. }
  36150. /**
  36151. * Sets builder's cache.
  36152. *
  36153. * @param {NodeCache} cache - The cache to set.
  36154. */
  36155. setCache( cache ) {
  36156. this.cache = cache;
  36157. }
  36158. /**
  36159. * Returns the builder's current cache.
  36160. *
  36161. * @return {NodeCache} The builder's current cache.
  36162. */
  36163. getCache() {
  36164. return this.cache;
  36165. }
  36166. /**
  36167. * Returns a cache for the given node.
  36168. *
  36169. * @param {Node} node - The node.
  36170. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  36171. * @return {NodeCache} The cache.
  36172. */
  36173. getCacheFromNode( node, parent = true ) {
  36174. const data = this.getDataFromNode( node );
  36175. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  36176. return data.cache;
  36177. }
  36178. /**
  36179. * Whether the requested feature is available or not.
  36180. *
  36181. * @abstract
  36182. * @param {string} name - The requested feature.
  36183. * @return {boolean} Whether the requested feature is supported or not.
  36184. */
  36185. isAvailable( /*name*/ ) {
  36186. return false;
  36187. }
  36188. /**
  36189. * Returns the vertexIndex input variable as a native shader string.
  36190. *
  36191. * @abstract
  36192. * @return {string} The instanceIndex shader string.
  36193. */
  36194. getVertexIndex() {
  36195. warn( 'Abstract function.' );
  36196. }
  36197. /**
  36198. * Contextually returns either the vertex stage instance index builtin
  36199. * or the linearized index of an compute invocation within a grid of workgroups.
  36200. *
  36201. * @abstract
  36202. * @return {string} The instanceIndex shader string.
  36203. */
  36204. getInstanceIndex() {
  36205. warn( 'Abstract function.' );
  36206. }
  36207. /**
  36208. * Returns the drawIndex input variable as a native shader string.
  36209. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  36210. *
  36211. * @abstract
  36212. * @return {?string} The drawIndex shader string.
  36213. */
  36214. getDrawIndex() {
  36215. warn( 'Abstract function.' );
  36216. }
  36217. /**
  36218. * Returns the frontFacing input variable as a native shader string.
  36219. *
  36220. * @abstract
  36221. * @return {string} The frontFacing shader string.
  36222. */
  36223. getFrontFacing() {
  36224. warn( 'Abstract function.' );
  36225. }
  36226. /**
  36227. * Returns the fragCoord input variable as a native shader string.
  36228. *
  36229. * @abstract
  36230. * @return {string} The fragCoord shader string.
  36231. */
  36232. getFragCoord() {
  36233. warn( 'Abstract function.' );
  36234. }
  36235. /**
  36236. * Whether to flip texture data along its vertical axis or not. WebGL needs
  36237. * this method evaluate to `true`, WebGPU to `false`.
  36238. *
  36239. * @abstract
  36240. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  36241. */
  36242. isFlipY() {
  36243. return false;
  36244. }
  36245. /**
  36246. * Calling this method increases the usage count for the given node by one.
  36247. *
  36248. * @param {Node} node - The node to increase the usage count for.
  36249. * @return {number} The updated usage count.
  36250. */
  36251. increaseUsage( node ) {
  36252. const nodeData = this.getDataFromNode( node );
  36253. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  36254. return nodeData.usageCount;
  36255. }
  36256. /**
  36257. * Generates a texture sample shader string for the given texture data.
  36258. *
  36259. * @abstract
  36260. * @param {Texture} texture - The texture.
  36261. * @param {string} textureProperty - The texture property name.
  36262. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  36263. * @return {string} The generated shader string.
  36264. */
  36265. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  36266. warn( 'Abstract function.' );
  36267. }
  36268. /**
  36269. * Generates a texture LOD shader string for the given texture data.
  36270. *
  36271. * @abstract
  36272. * @param {Texture} texture - The texture.
  36273. * @param {string} textureProperty - The texture property name.
  36274. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  36275. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  36276. * @param {string} levelSnippet - Snippet defining the mip level.
  36277. * @return {string} The generated shader string.
  36278. */
  36279. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  36280. warn( 'Abstract function.' );
  36281. }
  36282. /**
  36283. * Generates the array declaration string.
  36284. *
  36285. * @param {string} type - The type.
  36286. * @param {?number} [count] - The count.
  36287. * @return {string} The generated value as a shader string.
  36288. */
  36289. generateArrayDeclaration( type, count ) {
  36290. return this.getType( type ) + '[ ' + count + ' ]';
  36291. }
  36292. /**
  36293. * Generates the array shader string for the given type and value.
  36294. *
  36295. * @param {string} type - The type.
  36296. * @param {?number} [count] - The count.
  36297. * @param {?Array<Node>} [values=null] - The default values.
  36298. * @return {string} The generated value as a shader string.
  36299. */
  36300. generateArray( type, count, values = null ) {
  36301. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  36302. for ( let i = 0; i < count; i ++ ) {
  36303. const value = values ? values[ i ] : null;
  36304. if ( value !== null ) {
  36305. snippet += value.build( this, type );
  36306. } else {
  36307. snippet += this.generateConst( type );
  36308. }
  36309. if ( i < count - 1 ) snippet += ', ';
  36310. }
  36311. snippet += ' )';
  36312. return snippet;
  36313. }
  36314. /**
  36315. * Generates the struct shader string.
  36316. *
  36317. * @param {string} type - The type.
  36318. * @param {Array<Object>} [membersLayout] - The count.
  36319. * @param {?Array<Node>} [values=null] - The default values.
  36320. * @return {string} The generated value as a shader string.
  36321. */
  36322. generateStruct( type, membersLayout, values = null ) {
  36323. const snippets = [];
  36324. for ( const member of membersLayout ) {
  36325. const { name, type } = member;
  36326. if ( values && values[ name ] && values[ name ].isNode ) {
  36327. snippets.push( values[ name ].build( this, type ) );
  36328. } else {
  36329. snippets.push( this.generateConst( type ) );
  36330. }
  36331. }
  36332. return type + '( ' + snippets.join( ', ' ) + ' )';
  36333. }
  36334. /**
  36335. * Generates the shader string for the given type and value.
  36336. *
  36337. * @param {string} type - The type.
  36338. * @param {?any} [value=null] - The value.
  36339. * @return {string} The generated value as a shader string.
  36340. */
  36341. generateConst( type, value = null ) {
  36342. if ( value === null ) {
  36343. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  36344. else if ( type === 'bool' ) value = false;
  36345. else if ( type === 'color' ) value = new Color();
  36346. else if ( type === 'vec2' || type === 'uvec2' || type === 'ivec2' ) value = new Vector2();
  36347. else if ( type === 'vec3' || type === 'uvec3' || type === 'ivec3' ) value = new Vector3();
  36348. else if ( type === 'vec4' || type === 'uvec4' || type === 'ivec4' ) value = new Vector4();
  36349. }
  36350. if ( type === 'float' ) return toFloat( value );
  36351. if ( type === 'int' ) return `${ Math.round( value ) }`;
  36352. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  36353. if ( type === 'bool' ) return value ? 'true' : 'false';
  36354. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  36355. const typeLength = this.getTypeLength( type );
  36356. const componentType = this.getComponentType( type );
  36357. const generateConst = value => this.generateConst( componentType, value );
  36358. if ( typeLength === 2 ) {
  36359. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  36360. } else if ( typeLength === 3 ) {
  36361. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  36362. } else if ( typeLength === 4 && type !== 'mat2' ) {
  36363. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  36364. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  36365. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  36366. } else if ( typeLength > 4 ) {
  36367. return `${ this.getType( type ) }()`;
  36368. }
  36369. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  36370. }
  36371. /**
  36372. * It might be necessary to convert certain data types to different ones
  36373. * so this method can be used to hide the conversion.
  36374. *
  36375. * @param {string} type - The type.
  36376. * @return {string} The updated type.
  36377. */
  36378. getType( type ) {
  36379. if ( type === 'color' ) return 'vec3';
  36380. return type;
  36381. }
  36382. /**
  36383. * Whether the given attribute name is defined in the geometry or not.
  36384. *
  36385. * @param {string} name - The attribute name.
  36386. * @return {boolean} Whether the given attribute name is defined in the geometry.
  36387. */
  36388. hasGeometryAttribute( name ) {
  36389. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  36390. }
  36391. /**
  36392. * Returns a node attribute for the given name and type.
  36393. *
  36394. * @param {string} name - The attribute's name.
  36395. * @param {string} type - The attribute's type.
  36396. * @return {NodeAttribute} The node attribute.
  36397. */
  36398. getAttribute( name, type ) {
  36399. const attributes = this.attributes;
  36400. // find attribute
  36401. for ( const attribute of attributes ) {
  36402. if ( attribute.name === name ) {
  36403. return attribute;
  36404. }
  36405. }
  36406. // create a new if no exist
  36407. const attribute = new NodeAttribute( name, type );
  36408. this.registerDeclaration( attribute );
  36409. attributes.push( attribute );
  36410. return attribute;
  36411. }
  36412. /**
  36413. * Returns for the given node and shader stage the property name for the shader.
  36414. *
  36415. * @param {Node} node - The node.
  36416. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36417. * @return {string} The property name.
  36418. */
  36419. getPropertyName( node/*, shaderStage*/ ) {
  36420. return node.name;
  36421. }
  36422. /**
  36423. * Whether the given type is a vector type or not.
  36424. *
  36425. * @param {string} type - The type to check.
  36426. * @return {boolean} Whether the given type is a vector type or not.
  36427. */
  36428. isVector( type ) {
  36429. return /vec\d/.test( type );
  36430. }
  36431. /**
  36432. * Whether the given type is a matrix type or not.
  36433. *
  36434. * @param {string} type - The type to check.
  36435. * @return {boolean} Whether the given type is a matrix type or not.
  36436. */
  36437. isMatrix( type ) {
  36438. return /mat\d/.test( type );
  36439. }
  36440. /**
  36441. * Whether the given type is a reference type or not.
  36442. *
  36443. * @param {string} type - The type to check.
  36444. * @return {boolean} Whether the given type is a reference type or not.
  36445. */
  36446. isReference( type ) {
  36447. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  36448. }
  36449. /**
  36450. * Checks if the given texture requires a manual conversion to the working color space.
  36451. *
  36452. * @abstract
  36453. * @param {Texture} texture - The texture to check.
  36454. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  36455. */
  36456. needsToWorkingColorSpace( /*texture*/ ) {
  36457. return false;
  36458. }
  36459. /**
  36460. * Returns the component type of a given texture.
  36461. *
  36462. * @param {Texture} texture - The texture.
  36463. * @return {string} The component type.
  36464. */
  36465. getComponentTypeFromTexture( texture ) {
  36466. const type = texture.type;
  36467. if ( texture.isDataTexture ) {
  36468. if ( type === IntType ) return 'int';
  36469. if ( type === UnsignedIntType ) return 'uint';
  36470. }
  36471. return 'float';
  36472. }
  36473. /**
  36474. * Returns the element type for a given type.
  36475. *
  36476. * @param {string} type - The type.
  36477. * @return {string} The element type.
  36478. */
  36479. getElementType( type ) {
  36480. if ( type === 'mat2' ) return 'vec2';
  36481. if ( type === 'mat3' ) return 'vec3';
  36482. if ( type === 'mat4' ) return 'vec4';
  36483. return this.getComponentType( type );
  36484. }
  36485. /**
  36486. * Returns the component type for a given type.
  36487. *
  36488. * @param {string} type - The type.
  36489. * @return {string} The component type.
  36490. */
  36491. getComponentType( type ) {
  36492. type = this.getVectorType( type );
  36493. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  36494. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  36495. if ( componentType === null ) return null;
  36496. if ( componentType[ 1 ] === 'b' ) return 'bool';
  36497. if ( componentType[ 1 ] === 'i' ) return 'int';
  36498. if ( componentType[ 1 ] === 'u' ) return 'uint';
  36499. return 'float';
  36500. }
  36501. /**
  36502. * Returns the vector type for a given type.
  36503. *
  36504. * @param {string} type - The type.
  36505. * @return {string} The vector type.
  36506. */
  36507. getVectorType( type ) {
  36508. if ( type === 'color' ) return 'vec3';
  36509. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  36510. return type;
  36511. }
  36512. /**
  36513. * Returns the data type for the given the length and component type.
  36514. *
  36515. * @param {number} length - The length.
  36516. * @param {string} [componentType='float'] - The component type.
  36517. * @return {string} The type.
  36518. */
  36519. getTypeFromLength( length, componentType = 'float' ) {
  36520. if ( length === 1 ) return componentType;
  36521. let baseType = getTypeFromLength( length );
  36522. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  36523. // fix edge case for mat2x2 being same size as vec4
  36524. if ( /mat2/.test( componentType ) === true ) {
  36525. baseType = baseType.replace( 'vec', 'mat' );
  36526. }
  36527. return prefix + baseType;
  36528. }
  36529. /**
  36530. * Returns the type for a given typed array.
  36531. *
  36532. * @param {TypedArray} array - The typed array.
  36533. * @return {string} The type.
  36534. */
  36535. getTypeFromArray( array ) {
  36536. return typeFromArray.get( array.constructor );
  36537. }
  36538. /**
  36539. * Returns the type is an integer type.
  36540. *
  36541. * @param {string} type - The type.
  36542. * @return {boolean} Whether the type is an integer type or not.
  36543. */
  36544. isInteger( type ) {
  36545. return /int|uint|(i|u)vec/.test( type );
  36546. }
  36547. /**
  36548. * Returns the type for a given buffer attribute.
  36549. *
  36550. * @param {BufferAttribute} attribute - The buffer attribute.
  36551. * @return {string} The type.
  36552. */
  36553. getTypeFromAttribute( attribute ) {
  36554. let dataAttribute = attribute;
  36555. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  36556. const array = dataAttribute.array;
  36557. const itemSize = attribute.itemSize;
  36558. const normalized = attribute.normalized;
  36559. let arrayType;
  36560. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  36561. arrayType = this.getTypeFromArray( array );
  36562. }
  36563. return this.getTypeFromLength( itemSize, arrayType );
  36564. }
  36565. /**
  36566. * Returns the length for the given data type.
  36567. *
  36568. * @param {string} type - The data type.
  36569. * @return {number} The length.
  36570. */
  36571. getTypeLength( type ) {
  36572. const vecType = this.getVectorType( type );
  36573. const vecNum = /vec([2-4])/.exec( vecType );
  36574. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  36575. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  36576. if ( /mat2/.test( type ) === true ) return 4;
  36577. if ( /mat3/.test( type ) === true ) return 9;
  36578. if ( /mat4/.test( type ) === true ) return 16;
  36579. return 0;
  36580. }
  36581. /**
  36582. * Returns the vector type for a given matrix type.
  36583. *
  36584. * @param {string} type - The matrix type.
  36585. * @return {string} The vector type.
  36586. */
  36587. getVectorFromMatrix( type ) {
  36588. return type.replace( 'mat', 'vec' );
  36589. }
  36590. /**
  36591. * For a given type this method changes the component type to the
  36592. * given value. E.g. `vec4` should be changed to the new component type
  36593. * `uint` which results in `uvec4`.
  36594. *
  36595. * @param {string} type - The type.
  36596. * @param {string} newComponentType - The new component type.
  36597. * @return {string} The new type.
  36598. */
  36599. changeComponentType( type, newComponentType ) {
  36600. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  36601. }
  36602. /**
  36603. * Returns the integer type pendant for the given type.
  36604. *
  36605. * @param {string} type - The type.
  36606. * @return {string} The integer type.
  36607. */
  36608. getIntegerType( type ) {
  36609. const componentType = this.getComponentType( type );
  36610. if ( componentType === 'int' || componentType === 'uint' ) return type;
  36611. return this.changeComponentType( type, 'int' );
  36612. }
  36613. /**
  36614. * Adds an active stack to the internal stack.
  36615. *
  36616. * @param {StackNode} stack - The stack node to add.
  36617. */
  36618. setActiveStack( stack ) {
  36619. this.activeStacks.push( stack );
  36620. }
  36621. /**
  36622. * Removes the active stack from the internal stack.
  36623. *
  36624. * @param {StackNode} stack - The stack node to remove.
  36625. */
  36626. removeActiveStack( stack ) {
  36627. if ( this.activeStacks[ this.activeStacks.length - 1 ] === stack ) {
  36628. this.activeStacks.pop();
  36629. } else {
  36630. throw new Error( 'NodeBuilder: Invalid active stack removal.' );
  36631. }
  36632. }
  36633. /**
  36634. * Returns the active stack.
  36635. *
  36636. * @return {StackNode} The active stack.
  36637. */
  36638. getActiveStack() {
  36639. return this.activeStacks[ this.activeStacks.length - 1 ];
  36640. }
  36641. /**
  36642. * Returns the base stack.
  36643. *
  36644. * @return {StackNode} The base stack.
  36645. */
  36646. getBaseStack() {
  36647. return this.activeStacks[ 0 ];
  36648. }
  36649. /**
  36650. * Adds a stack node to the internal stack.
  36651. *
  36652. * @return {StackNode} The added stack node.
  36653. */
  36654. addStack() {
  36655. this.stack = stack( this.stack );
  36656. const previousStack = getCurrentStack();
  36657. this.stacks.push( previousStack );
  36658. setCurrentStack( this.stack );
  36659. return this.stack;
  36660. }
  36661. /**
  36662. * Removes the last stack node from the internal stack.
  36663. *
  36664. * @return {StackNode} The removed stack node.
  36665. */
  36666. removeStack() {
  36667. const lastStack = this.stack;
  36668. for ( const node of lastStack.nodes ) {
  36669. const nodeData = this.getDataFromNode( node );
  36670. nodeData.stack = lastStack;
  36671. }
  36672. this.stack = lastStack.parent;
  36673. setCurrentStack( this.stacks.pop() );
  36674. return lastStack;
  36675. }
  36676. /**
  36677. * The builder maintains (cached) data for each node during the building process. This method
  36678. * can be used to get these data for a specific shader stage and cache.
  36679. *
  36680. * @param {Node} node - The node to get the data for.
  36681. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36682. * @param {?NodeCache} cache - An optional cache.
  36683. * @return {Object} The node data.
  36684. */
  36685. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  36686. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  36687. let nodeData = cache.getData( node );
  36688. if ( nodeData === undefined ) {
  36689. nodeData = {};
  36690. cache.setData( node, nodeData );
  36691. }
  36692. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  36693. //
  36694. let data = nodeData[ shaderStage ];
  36695. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  36696. const subBuild = this.getClosestSubBuild( subBuilds );
  36697. if ( subBuild ) {
  36698. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  36699. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  36700. data.subBuilds = subBuilds;
  36701. }
  36702. return data;
  36703. }
  36704. /**
  36705. * Returns the properties for the given node and shader stage.
  36706. *
  36707. * Properties are typically used within a build stage to reference a node's
  36708. * child node or nodes manually assigned to the properties in a separate build stage.
  36709. * A typical usage pattern for defining nodes manually would be assigning dependency nodes
  36710. * to the current node's properties in the setup stage and building those properties in the generate stage.
  36711. *
  36712. * @param {Node} node - The node to get the properties for.
  36713. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  36714. * @return {Object} The node properties.
  36715. */
  36716. getNodeProperties( node, shaderStage = 'any' ) {
  36717. const nodeData = this.getDataFromNode( node, shaderStage );
  36718. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  36719. }
  36720. /**
  36721. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  36722. *
  36723. * @param {BufferAttributeNode} node - The buffer attribute node.
  36724. * @param {string} type - The node type.
  36725. * @return {NodeAttribute} The node attribute.
  36726. */
  36727. getBufferAttributeFromNode( node, type ) {
  36728. const nodeData = this.getDataFromNode( node, 'vertex' );
  36729. let bufferAttribute = nodeData.bufferAttribute;
  36730. if ( bufferAttribute === undefined ) {
  36731. const index = this.uniforms.index ++;
  36732. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  36733. this.bufferAttributes.push( bufferAttribute );
  36734. nodeData.bufferAttribute = bufferAttribute;
  36735. }
  36736. return bufferAttribute;
  36737. }
  36738. /**
  36739. * Returns an instance of {@link StructType} for the given struct name and shader stage
  36740. * or null if not found.
  36741. *
  36742. * @param {string} name - The name of the struct.
  36743. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36744. * @return {?StructType} The struct type or null if not found.
  36745. */
  36746. getStructTypeNode( name, shaderStage = this.shaderStage ) {
  36747. return this.types[ shaderStage ][ name ] || null;
  36748. }
  36749. /**
  36750. * Returns an instance of {@link StructType} for the given output struct node.
  36751. *
  36752. * @param {OutputStructNode} node - The output struct node.
  36753. * @param {Array<Object>} membersLayout - The output struct types.
  36754. * @param {?string} [name=null] - The name of the struct.
  36755. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36756. * @return {StructType} The struct type attribute.
  36757. */
  36758. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  36759. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  36760. let structType = nodeData.structType;
  36761. if ( structType === undefined ) {
  36762. const index = this.structs.index ++;
  36763. if ( name === null ) name = 'StructType' + index;
  36764. structType = new StructType( name, membersLayout );
  36765. this.structs[ shaderStage ].push( structType );
  36766. this.types[ shaderStage ][ name ] = node;
  36767. nodeData.structType = structType;
  36768. }
  36769. return structType;
  36770. }
  36771. /**
  36772. * Returns an instance of {@link StructType} for the given output struct node.
  36773. *
  36774. * @param {OutputStructNode} node - The output struct node.
  36775. * @param {Array<Object>} membersLayout - The output struct types.
  36776. * @return {StructType} The struct type attribute.
  36777. */
  36778. getOutputStructTypeFromNode( node, membersLayout ) {
  36779. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  36780. structType.output = true;
  36781. return structType;
  36782. }
  36783. /**
  36784. * Returns an instance of {@link NodeUniform} for the given uniform node.
  36785. *
  36786. * @param {UniformNode} node - The uniform node.
  36787. * @param {string} type - The uniform type.
  36788. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36789. * @param {?string} name - The name of the uniform.
  36790. * @return {NodeUniform} The node uniform.
  36791. */
  36792. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  36793. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  36794. let nodeUniform = nodeData.uniform;
  36795. if ( nodeUniform === undefined ) {
  36796. const index = this.uniforms.index ++;
  36797. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  36798. this.uniforms[ shaderStage ].push( nodeUniform );
  36799. this.registerDeclaration( nodeUniform );
  36800. nodeData.uniform = nodeUniform;
  36801. }
  36802. return nodeUniform;
  36803. }
  36804. /**
  36805. * Returns an instance of {@link NodeVar} for the given variable node.
  36806. *
  36807. * @param {VarNode} node - The variable node.
  36808. * @param {?string} name - The variable's name.
  36809. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  36810. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36811. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  36812. *
  36813. * @return {NodeVar} The node variable.
  36814. */
  36815. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  36816. const nodeData = this.getDataFromNode( node, shaderStage );
  36817. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  36818. let nodeVar = nodeData[ subBuildVariable ];
  36819. if ( nodeVar === undefined ) {
  36820. const idNS = readOnly ? '_const' : '_var';
  36821. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  36822. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  36823. if ( name === null ) {
  36824. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  36825. this.vars[ idNS ] ++;
  36826. }
  36827. //
  36828. if ( subBuildVariable !== 'variable' ) {
  36829. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  36830. }
  36831. //
  36832. const count = node.getArrayCount( this );
  36833. nodeVar = new NodeVar( name, type, readOnly, count );
  36834. if ( ! readOnly ) {
  36835. vars.push( nodeVar );
  36836. }
  36837. this.registerDeclaration( nodeVar );
  36838. nodeData[ subBuildVariable ] = nodeVar;
  36839. }
  36840. return nodeVar;
  36841. }
  36842. /**
  36843. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  36844. *
  36845. * @param {Node} node - The varying node.
  36846. * @return {boolean} Returns true if deterministic.
  36847. */
  36848. isDeterministic( node ) {
  36849. if ( node.isMathNode ) {
  36850. return this.isDeterministic( node.aNode ) &&
  36851. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  36852. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  36853. } else if ( node.isOperatorNode ) {
  36854. return this.isDeterministic( node.aNode ) &&
  36855. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  36856. } else if ( node.isArrayNode ) {
  36857. if ( node.values !== null ) {
  36858. for ( const n of node.values ) {
  36859. if ( ! this.isDeterministic( n ) ) {
  36860. return false;
  36861. }
  36862. }
  36863. }
  36864. return true;
  36865. } else if ( node.isConstNode ) {
  36866. return true;
  36867. }
  36868. return false;
  36869. }
  36870. /**
  36871. * Returns an instance of {@link NodeVarying} for the given varying node.
  36872. *
  36873. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  36874. * @param {?string} name - The varying's name.
  36875. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  36876. * @param {?string} interpolationType - The interpolation type of the varying.
  36877. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  36878. * @return {NodeVar} The node varying.
  36879. */
  36880. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  36881. const nodeData = this.getDataFromNode( node, 'any' );
  36882. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  36883. let nodeVarying = nodeData[ subBuildVarying ];
  36884. if ( nodeVarying === undefined ) {
  36885. const varyings = this.varyings;
  36886. const index = varyings.length;
  36887. if ( name === null ) name = 'nodeVarying' + index;
  36888. //
  36889. if ( subBuildVarying !== 'varying' ) {
  36890. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  36891. }
  36892. //
  36893. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  36894. varyings.push( nodeVarying );
  36895. this.registerDeclaration( nodeVarying );
  36896. nodeData[ subBuildVarying ] = nodeVarying;
  36897. }
  36898. return nodeVarying;
  36899. }
  36900. /**
  36901. * Registers a node declaration in the current shader stage.
  36902. *
  36903. * @param {Object} node - The node to be registered.
  36904. */
  36905. registerDeclaration( node ) {
  36906. const shaderStage = this.shaderStage;
  36907. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  36908. const property = this.getPropertyName( node );
  36909. let index = 1;
  36910. let name = property;
  36911. // Automatically renames the property if the name is already in use.
  36912. while ( declarations[ name ] !== undefined ) {
  36913. name = property + '_' + index ++;
  36914. }
  36915. if ( index > 1 ) {
  36916. node.name = name;
  36917. warn( `TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  36918. }
  36919. declarations[ name ] = node;
  36920. }
  36921. /**
  36922. * Returns an instance of {@link NodeCode} for the given code node.
  36923. *
  36924. * @param {CodeNode} node - The code node.
  36925. * @param {string} type - The node type.
  36926. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36927. * @return {NodeCode} The node code.
  36928. */
  36929. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  36930. const nodeData = this.getDataFromNode( node );
  36931. let nodeCode = nodeData.code;
  36932. if ( nodeCode === undefined ) {
  36933. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  36934. const index = codes.length;
  36935. nodeCode = new NodeCode( 'nodeCode' + index, type );
  36936. codes.push( nodeCode );
  36937. nodeData.code = nodeCode;
  36938. }
  36939. return nodeCode;
  36940. }
  36941. /**
  36942. * Adds a code flow based on the code-block hierarchy.
  36943. * This is used so that code-blocks like If,Else create their variables locally if the Node
  36944. * is only used inside one of these conditionals in the current shader stage.
  36945. *
  36946. * @param {Node} node - The node to add.
  36947. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  36948. */
  36949. addFlowCodeHierarchy( node, nodeBlock ) {
  36950. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  36951. let needsFlowCode = true;
  36952. let nodeBlockHierarchy = nodeBlock;
  36953. while ( nodeBlockHierarchy ) {
  36954. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  36955. needsFlowCode = false;
  36956. break;
  36957. }
  36958. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  36959. }
  36960. if ( needsFlowCode ) {
  36961. for ( const flowCode of flowCodes ) {
  36962. this.addLineFlowCode( flowCode );
  36963. }
  36964. }
  36965. }
  36966. /**
  36967. * Add a inline-code to the current flow code-block.
  36968. *
  36969. * @param {Node} node - The node to add.
  36970. * @param {string} code - The code to add.
  36971. * @param {Node} nodeBlock - Current ConditionalNode
  36972. */
  36973. addLineFlowCodeBlock( node, code, nodeBlock ) {
  36974. const nodeData = this.getDataFromNode( node );
  36975. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  36976. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  36977. flowCodes.push( code );
  36978. codeBlock.set( nodeBlock, true );
  36979. }
  36980. /**
  36981. * Add a inline-code to the current flow.
  36982. *
  36983. * @param {string} code - The code to add.
  36984. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  36985. * @return {NodeBuilder} A reference to this node builder.
  36986. */
  36987. addLineFlowCode( code, node = null ) {
  36988. if ( code === '' ) return this;
  36989. if ( node !== null && this.context.nodeBlock ) {
  36990. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  36991. }
  36992. code = this.tab + code;
  36993. if ( ! /;\s*$/.test( code ) ) {
  36994. code = code + ';\n';
  36995. }
  36996. this.flow.code += code;
  36997. return this;
  36998. }
  36999. /**
  37000. * Adds a code to the current code flow.
  37001. *
  37002. * @param {string} code - Shader code.
  37003. * @return {NodeBuilder} A reference to this node builder.
  37004. */
  37005. addFlowCode( code ) {
  37006. this.flow.code += code;
  37007. return this;
  37008. }
  37009. /**
  37010. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  37011. * Typically used in codes with If,Else.
  37012. *
  37013. * @return {NodeBuilder} A reference to this node builder.
  37014. */
  37015. addFlowTab() {
  37016. this.tab += '\t';
  37017. return this;
  37018. }
  37019. /**
  37020. * Removes a tab.
  37021. *
  37022. * @return {NodeBuilder} A reference to this node builder.
  37023. */
  37024. removeFlowTab() {
  37025. this.tab = this.tab.slice( 0, -1 );
  37026. return this;
  37027. }
  37028. /**
  37029. * Gets the current flow data based on a Node.
  37030. *
  37031. * @param {Node} node - Node that the flow was started.
  37032. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37033. * @return {Object} The flow data.
  37034. */
  37035. getFlowData( node/*, shaderStage*/ ) {
  37036. return this.flowsData.get( node );
  37037. }
  37038. /**
  37039. * Executes the node flow based on a root node to generate the final shader code.
  37040. *
  37041. * @param {Node} node - The node to execute.
  37042. * @return {Object} The code flow.
  37043. */
  37044. flowNode( node ) {
  37045. const output = node.getNodeType( this );
  37046. const flowData = this.flowChildNode( node, output );
  37047. this.flowsData.set( node, flowData );
  37048. return flowData;
  37049. }
  37050. /**
  37051. * Includes a node in the current function node.
  37052. *
  37053. * @param {Node} node - The node to include.
  37054. * @returns {void}
  37055. */
  37056. addInclude( node ) {
  37057. if ( this.currentFunctionNode !== null ) {
  37058. this.currentFunctionNode.includes.push( node );
  37059. }
  37060. }
  37061. /**
  37062. * Returns the native shader operator name for a given generic name.
  37063. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  37064. *
  37065. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  37066. * @return {FunctionNode} The build function node.
  37067. */
  37068. buildFunctionNode( shaderNode ) {
  37069. const fn = new FunctionNode();
  37070. const previous = this.currentFunctionNode;
  37071. this.currentFunctionNode = fn;
  37072. fn.code = this.buildFunctionCode( shaderNode );
  37073. this.currentFunctionNode = previous;
  37074. return fn;
  37075. }
  37076. /**
  37077. * Generates a code flow based on a TSL function: Fn().
  37078. *
  37079. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  37080. * @return {Object}
  37081. */
  37082. flowShaderNode( shaderNode ) {
  37083. const layout = shaderNode.layout;
  37084. const inputs = {
  37085. [ Symbol.iterator ]() {
  37086. let index = 0;
  37087. const values = Object.values( this );
  37088. return {
  37089. next: () => ( {
  37090. value: values[ index ],
  37091. done: index ++ >= values.length
  37092. } )
  37093. };
  37094. }
  37095. };
  37096. for ( const input of layout.inputs ) {
  37097. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  37098. }
  37099. //
  37100. shaderNode.layout = null;
  37101. const callNode = shaderNode.call( inputs );
  37102. const flowData = this.flowStagesNode( callNode, layout.type );
  37103. shaderNode.layout = layout;
  37104. return flowData;
  37105. }
  37106. /**
  37107. * Executes the node in a specific build stage.
  37108. *
  37109. * This function can be used to arbitrarily execute the specified build stage
  37110. * outside of the standard build process. For instance, if a node's type depends
  37111. * on properties created by the 'setup' stage, then flowBuildStage(node, 'setup')
  37112. * can be used to execute the setup build stage and access its generated nodes
  37113. * before the standard build process begins.
  37114. *
  37115. * @param {Node} node - The node to execute.
  37116. * @param {string} buildStage - The build stage to execute the node in.
  37117. * @param {?(Node|string)} [output=null] - Expected output type. For example 'vec3'.
  37118. * @return {?(Node|string)} The result of the node build.
  37119. */
  37120. flowBuildStage( node, buildStage, output = null ) {
  37121. const previousBuildStage = this.getBuildStage();
  37122. this.setBuildStage( buildStage );
  37123. const result = node.build( this, output );
  37124. this.setBuildStage( previousBuildStage );
  37125. return result;
  37126. }
  37127. /**
  37128. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  37129. *
  37130. * @param {Node} node - The node to execute.
  37131. * @param {?string} output - Expected output type. For example 'vec3'.
  37132. * @return {Object}
  37133. */
  37134. flowStagesNode( node, output = null ) {
  37135. const previousFlow = this.flow;
  37136. const previousVars = this.vars;
  37137. const previousDeclarations = this.declarations;
  37138. const previousCache = this.cache;
  37139. const previousBuildStage = this.buildStage;
  37140. const previousStack = this.stack;
  37141. const flow = {
  37142. code: ''
  37143. };
  37144. this.flow = flow;
  37145. this.vars = {};
  37146. this.declarations = {};
  37147. this.cache = new NodeCache();
  37148. this.stack = stack();
  37149. for ( const buildStage of defaultBuildStages ) {
  37150. this.setBuildStage( buildStage );
  37151. flow.result = node.build( this, output );
  37152. }
  37153. flow.vars = this.getVars( this.shaderStage );
  37154. this.flow = previousFlow;
  37155. this.vars = previousVars;
  37156. this.declarations = previousDeclarations;
  37157. this.cache = previousCache;
  37158. this.stack = previousStack;
  37159. this.setBuildStage( previousBuildStage );
  37160. return flow;
  37161. }
  37162. /**
  37163. * Returns the native shader operator name for a given generic name.
  37164. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  37165. *
  37166. * @abstract
  37167. * @param {string} op - The operator name to resolve.
  37168. * @return {?string} The resolved operator name.
  37169. */
  37170. getFunctionOperator( /* op */ ) {
  37171. return null;
  37172. }
  37173. /**
  37174. * Builds the given shader node.
  37175. *
  37176. * @abstract
  37177. * @param {ShaderNodeInternal} shaderNode - The shader node.
  37178. * @return {string} The function code.
  37179. */
  37180. buildFunctionCode( /* shaderNode */ ) {
  37181. warn( 'Abstract function.' );
  37182. }
  37183. /**
  37184. * Generates a code flow based on a child Node.
  37185. *
  37186. * @param {Node} node - The node to execute.
  37187. * @param {?string} output - Expected output type. For example 'vec3'.
  37188. * @return {Object} The code flow.
  37189. */
  37190. flowChildNode( node, output = null ) {
  37191. const previousFlow = this.flow;
  37192. const flow = {
  37193. code: ''
  37194. };
  37195. this.flow = flow;
  37196. flow.result = node.build( this, output );
  37197. this.flow = previousFlow;
  37198. return flow;
  37199. }
  37200. /**
  37201. * Executes a flow of code in a different stage.
  37202. *
  37203. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  37204. * return the value in fragment-stage even if it is being executed in an input fragment.
  37205. *
  37206. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37207. * @param {Node} node - The node to execute.
  37208. * @param {?string} output - Expected output type. For example 'vec3'.
  37209. * @param {?string} propertyName - The property name to assign the result.
  37210. * @return {?(Object|Node)} The code flow or node.build() result.
  37211. */
  37212. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  37213. const previousTab = this.tab;
  37214. const previousCache = this.cache;
  37215. const previousShaderStage = this.shaderStage;
  37216. const previousContext = this.context;
  37217. this.setShaderStage( shaderStage );
  37218. const context = { ...this.context };
  37219. delete context.nodeBlock;
  37220. this.cache = this.globalCache;
  37221. this.tab = '\t';
  37222. this.context = context;
  37223. let result = null;
  37224. if ( this.buildStage === 'generate' ) {
  37225. const flowData = this.flowChildNode( node, output );
  37226. if ( propertyName !== null ) {
  37227. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  37228. }
  37229. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  37230. result = flowData;
  37231. } else {
  37232. result = node.build( this );
  37233. }
  37234. this.setShaderStage( previousShaderStage );
  37235. this.cache = previousCache;
  37236. this.tab = previousTab;
  37237. this.context = previousContext;
  37238. return result;
  37239. }
  37240. /**
  37241. * Returns an array holding all node attributes of this node builder.
  37242. *
  37243. * @return {Array<NodeAttribute>} The node attributes of this builder.
  37244. */
  37245. getAttributesArray() {
  37246. return this.attributes.concat( this.bufferAttributes );
  37247. }
  37248. /**
  37249. * Returns the attribute definitions as a shader string for the given shader stage.
  37250. *
  37251. * @abstract
  37252. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37253. * @return {string} The attribute code section.
  37254. */
  37255. getAttributes( /*shaderStage*/ ) {
  37256. warn( 'Abstract function.' );
  37257. }
  37258. /**
  37259. * Returns the varying definitions as a shader string for the given shader stage.
  37260. *
  37261. * @abstract
  37262. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37263. * @return {string} The varying code section.
  37264. */
  37265. getVaryings( /*shaderStage*/ ) {
  37266. warn( 'Abstract function.' );
  37267. }
  37268. /**
  37269. * Returns a single variable definition as a shader string for the given variable type and name.
  37270. *
  37271. * @param {string} type - The variable's type.
  37272. * @param {string} name - The variable's name.
  37273. * @param {?number} [count=null] - The array length.
  37274. * @return {string} The shader string.
  37275. */
  37276. getVar( type, name, count = null ) {
  37277. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  37278. }
  37279. /**
  37280. * Returns the variable definitions as a shader string for the given shader stage.
  37281. *
  37282. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37283. * @return {string} The variable code section.
  37284. */
  37285. getVars( shaderStage ) {
  37286. let snippet = '';
  37287. const vars = this.vars[ shaderStage ];
  37288. if ( vars !== undefined ) {
  37289. for ( const variable of vars ) {
  37290. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  37291. }
  37292. }
  37293. return snippet;
  37294. }
  37295. /**
  37296. * Returns the uniform definitions as a shader string for the given shader stage.
  37297. *
  37298. * @abstract
  37299. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37300. * @return {string} The uniform code section.
  37301. */
  37302. getUniforms( /*shaderStage*/ ) {
  37303. warn( 'Abstract function.' );
  37304. }
  37305. /**
  37306. * Returns the native code definitions as a shader string for the given shader stage.
  37307. *
  37308. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37309. * @return {string} The native code section.
  37310. */
  37311. getCodes( shaderStage ) {
  37312. const codes = this.codes[ shaderStage ];
  37313. let code = '';
  37314. if ( codes !== undefined ) {
  37315. for ( const nodeCode of codes ) {
  37316. code += nodeCode.code + '\n';
  37317. }
  37318. }
  37319. return code;
  37320. }
  37321. /**
  37322. * Returns the hash of this node builder.
  37323. *
  37324. * @return {string} The hash.
  37325. */
  37326. getHash() {
  37327. return this.vertexShader + this.fragmentShader + this.computeShader;
  37328. }
  37329. /**
  37330. * Sets the current shader stage.
  37331. *
  37332. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  37333. */
  37334. setShaderStage( shaderStage ) {
  37335. this.shaderStage = shaderStage;
  37336. }
  37337. /**
  37338. * Returns the current shader stage.
  37339. *
  37340. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  37341. */
  37342. getShaderStage() {
  37343. return this.shaderStage;
  37344. }
  37345. /**
  37346. * Sets the current build stage.
  37347. *
  37348. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  37349. */
  37350. setBuildStage( buildStage ) {
  37351. this.buildStage = buildStage;
  37352. }
  37353. /**
  37354. * Returns the current build stage.
  37355. *
  37356. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  37357. */
  37358. getBuildStage() {
  37359. return this.buildStage;
  37360. }
  37361. /**
  37362. * Controls the code build of the shader stages.
  37363. *
  37364. * @abstract
  37365. */
  37366. buildCode() {
  37367. warn( 'Abstract function.' );
  37368. }
  37369. /**
  37370. * Returns the current sub-build layer.
  37371. *
  37372. * @return {SubBuildNode} The current sub-build layers.
  37373. */
  37374. get subBuild() {
  37375. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  37376. }
  37377. /**
  37378. * Adds a sub-build layer to the node builder.
  37379. *
  37380. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  37381. */
  37382. addSubBuild( subBuild ) {
  37383. this.subBuildLayers.push( subBuild );
  37384. }
  37385. /**
  37386. * Removes the last sub-build layer from the node builder.
  37387. *
  37388. * @return {SubBuildNode} The removed sub-build layer.
  37389. */
  37390. removeSubBuild() {
  37391. return this.subBuildLayers.pop();
  37392. }
  37393. /**
  37394. * Returns the closest sub-build layer for the given data.
  37395. *
  37396. * @param {Node|Set<string>|Array<string>} data - The data to get the closest sub-build layer from.
  37397. * @return {?string} The closest sub-build name or null if none found.
  37398. */
  37399. getClosestSubBuild( data ) {
  37400. let subBuilds;
  37401. if ( data && data.isNode ) {
  37402. if ( data.isShaderCallNodeInternal ) {
  37403. subBuilds = data.shaderNode.subBuilds;
  37404. } else if ( data.isStackNode ) {
  37405. subBuilds = [ data.subBuild ];
  37406. } else {
  37407. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  37408. }
  37409. } else if ( data instanceof Set ) {
  37410. subBuilds = [ ...data ];
  37411. } else {
  37412. subBuilds = data;
  37413. }
  37414. if ( ! subBuilds ) return null;
  37415. const subBuildLayers = this.subBuildLayers;
  37416. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  37417. const subBuild = subBuilds[ i ];
  37418. if ( subBuildLayers.includes( subBuild ) ) {
  37419. return subBuild;
  37420. }
  37421. }
  37422. return null;
  37423. }
  37424. /**
  37425. * Returns the output node of a sub-build layer.
  37426. *
  37427. * @param {Node} node - The node to get the output from.
  37428. * @return {string} The output node name.
  37429. */
  37430. getSubBuildOutput( node ) {
  37431. return this.getSubBuildProperty( 'outputNode', node );
  37432. }
  37433. /**
  37434. * Returns the sub-build property name for the given property and node.
  37435. *
  37436. * @param {string} [property=''] - The property name.
  37437. * @param {?Node} [node=null] - The node to get the sub-build from.
  37438. * @return {string} The sub-build property name.
  37439. */
  37440. getSubBuildProperty( property = '', node = null ) {
  37441. let subBuild;
  37442. if ( node !== null ) {
  37443. subBuild = this.getClosestSubBuild( node );
  37444. } else {
  37445. subBuild = this.subBuildFn;
  37446. }
  37447. let result;
  37448. if ( subBuild ) {
  37449. result = property ? ( subBuild + '_' + property ) : subBuild;
  37450. } else {
  37451. result = property;
  37452. }
  37453. return result;
  37454. }
  37455. /**
  37456. * Central build method which controls the build for the given object.
  37457. *
  37458. * @return {NodeBuilder} A reference to this node builder.
  37459. */
  37460. build() {
  37461. const { object, material, renderer } = this;
  37462. if ( material !== null ) {
  37463. let nodeMaterial = renderer.library.fromMaterial( material );
  37464. if ( nodeMaterial === null ) {
  37465. error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  37466. nodeMaterial = new NodeMaterial();
  37467. }
  37468. nodeMaterial.build( this );
  37469. } else {
  37470. this.addFlow( 'compute', object );
  37471. }
  37472. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  37473. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  37474. // generate() -> stage 3: generate shader
  37475. for ( const buildStage of defaultBuildStages ) {
  37476. this.setBuildStage( buildStage );
  37477. if ( this.context.vertex && this.context.vertex.isNode ) {
  37478. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  37479. }
  37480. for ( const shaderStage of shaderStages ) {
  37481. this.setShaderStage( shaderStage );
  37482. const flowNodes = this.flowNodes[ shaderStage ];
  37483. for ( const node of flowNodes ) {
  37484. if ( buildStage === 'generate' ) {
  37485. this.flowNode( node );
  37486. } else {
  37487. node.build( this );
  37488. }
  37489. }
  37490. }
  37491. }
  37492. this.setBuildStage( null );
  37493. this.setShaderStage( null );
  37494. // stage 4: build code for a specific output
  37495. this.buildCode();
  37496. this.buildUpdateNodes();
  37497. return this;
  37498. }
  37499. /**
  37500. * Returns shared data object for the given node.
  37501. *
  37502. * @param {Node} node - The node to get shared data from.
  37503. * @return {Object} The shared data.
  37504. */
  37505. getSharedDataFromNode( node ) {
  37506. let data = sharedNodeData.get( node );
  37507. if ( data === undefined ) {
  37508. data = {};
  37509. }
  37510. return data;
  37511. }
  37512. /**
  37513. * Returns a uniform representation which is later used for UBO generation and rendering.
  37514. *
  37515. * @param {NodeUniform} uniformNode - The uniform node.
  37516. * @param {string} type - The requested type.
  37517. * @return {Uniform} The uniform.
  37518. */
  37519. getNodeUniform( uniformNode, type ) {
  37520. const nodeData = this.getSharedDataFromNode( uniformNode );
  37521. let node = nodeData.cache;
  37522. if ( node === undefined ) {
  37523. if ( type === 'float' || type === 'int' || type === 'uint' ) node = new NumberNodeUniform( uniformNode );
  37524. else if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) node = new Vector2NodeUniform( uniformNode );
  37525. else if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) node = new Vector3NodeUniform( uniformNode );
  37526. else if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) node = new Vector4NodeUniform( uniformNode );
  37527. else if ( type === 'color' ) node = new ColorNodeUniform( uniformNode );
  37528. else if ( type === 'mat2' ) node = new Matrix2NodeUniform( uniformNode );
  37529. else if ( type === 'mat3' ) node = new Matrix3NodeUniform( uniformNode );
  37530. else if ( type === 'mat4' ) node = new Matrix4NodeUniform( uniformNode );
  37531. else {
  37532. throw new Error( `Uniform "${ type }" not implemented.` );
  37533. }
  37534. nodeData.cache = node;
  37535. }
  37536. return node;
  37537. }
  37538. /**
  37539. * Formats the given shader snippet from a given type into another one. E.g.
  37540. * this method might be used to convert a simple float string `"1.0"` into a
  37541. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  37542. *
  37543. * @param {string} snippet - The shader snippet.
  37544. * @param {string} fromType - The source type.
  37545. * @param {string} toType - The target type.
  37546. * @return {string} The updated shader string.
  37547. */
  37548. format( snippet, fromType, toType ) {
  37549. fromType = this.getVectorType( fromType );
  37550. toType = this.getVectorType( toType );
  37551. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  37552. return snippet;
  37553. }
  37554. const fromTypeLength = this.getTypeLength( fromType );
  37555. const toTypeLength = this.getTypeLength( toType );
  37556. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  37557. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  37558. }
  37559. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  37560. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  37561. }
  37562. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  37563. // @TODO: ignore for now
  37564. return snippet;
  37565. }
  37566. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  37567. // @TODO: ignore for now
  37568. return snippet;
  37569. }
  37570. if ( fromTypeLength === toTypeLength ) {
  37571. return `${ this.getType( toType ) }( ${ snippet } )`;
  37572. }
  37573. if ( fromTypeLength > toTypeLength ) {
  37574. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  37575. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  37576. }
  37577. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  37578. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  37579. }
  37580. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  37581. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  37582. }
  37583. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  37584. // convert a number value to vector type, e.g:
  37585. // vec3( 1u ) -> vec3( float( 1u ) )
  37586. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  37587. }
  37588. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  37589. }
  37590. /**
  37591. * Returns a signature with the engine's current revision.
  37592. *
  37593. * @return {string} The signature.
  37594. */
  37595. getSignature() {
  37596. return `// Three.js r${ REVISION } - Node System\n`;
  37597. }
  37598. }
  37599. /**
  37600. * Management class for updating nodes. The module tracks metrics like
  37601. * the elapsed time, delta time, the render and frame ID to correctly
  37602. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  37603. * and {@link Node#updateAfter} depending on the node's configuration.
  37604. */
  37605. class NodeFrame {
  37606. /**
  37607. * Constructs a new node fame.
  37608. */
  37609. constructor() {
  37610. /**
  37611. * The elapsed time in seconds.
  37612. *
  37613. * @type {number}
  37614. * @default 0
  37615. */
  37616. this.time = 0;
  37617. /**
  37618. * The delta time in seconds.
  37619. *
  37620. * @type {number}
  37621. * @default 0
  37622. */
  37623. this.deltaTime = 0;
  37624. /**
  37625. * The frame ID.
  37626. *
  37627. * @type {number}
  37628. * @default 0
  37629. */
  37630. this.frameId = 0;
  37631. /**
  37632. * The render ID.
  37633. *
  37634. * @type {number}
  37635. * @default 0
  37636. */
  37637. this.renderId = 0;
  37638. /**
  37639. * Used to control the {@link Node#update} call.
  37640. *
  37641. * @type {WeakMap<Node, Object>}
  37642. */
  37643. this.updateMap = new WeakMap();
  37644. /**
  37645. * Used to control the {@link Node#updateBefore} call.
  37646. *
  37647. * @type {WeakMap<Node, Object>}
  37648. */
  37649. this.updateBeforeMap = new WeakMap();
  37650. /**
  37651. * Used to control the {@link Node#updateAfter} call.
  37652. *
  37653. * @type {WeakMap<Node, Object>}
  37654. */
  37655. this.updateAfterMap = new WeakMap();
  37656. /**
  37657. * A reference to the current renderer.
  37658. *
  37659. * @type {?Renderer}
  37660. * @default null
  37661. */
  37662. this.renderer = null;
  37663. /**
  37664. * A reference to the current material.
  37665. *
  37666. * @type {?Material}
  37667. * @default null
  37668. */
  37669. this.material = null;
  37670. /**
  37671. * A reference to the current camera.
  37672. *
  37673. * @type {?Camera}
  37674. * @default null
  37675. */
  37676. this.camera = null;
  37677. /**
  37678. * A reference to the current 3D object.
  37679. *
  37680. * @type {?Object3D}
  37681. * @default null
  37682. */
  37683. this.object = null;
  37684. /**
  37685. * A reference to the current scene.
  37686. *
  37687. * @type {?Scene}
  37688. * @default null
  37689. */
  37690. this.scene = null;
  37691. }
  37692. /**
  37693. * Returns a dictionary for a given node and update map which
  37694. * is used to correctly call node update methods per frame or render.
  37695. *
  37696. * @private
  37697. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  37698. * @param {Node} nodeRef - The reference to the current node.
  37699. * @return {Object<string,WeakMap<Object, number>>} The dictionary.
  37700. */
  37701. _getMaps( referenceMap, nodeRef ) {
  37702. let maps = referenceMap.get( nodeRef );
  37703. if ( maps === undefined ) {
  37704. maps = {
  37705. renderId: 0,
  37706. frameId: 0,
  37707. };
  37708. referenceMap.set( nodeRef, maps );
  37709. }
  37710. return maps;
  37711. }
  37712. /**
  37713. * This method executes the {@link Node#updateBefore} for the given node.
  37714. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  37715. * is only executed once per frame, render or object depending on the update
  37716. * type.
  37717. *
  37718. * @param {Node} node - The node that should be updated.
  37719. */
  37720. updateBeforeNode( node ) {
  37721. const updateType = node.getUpdateBeforeType();
  37722. const reference = node.updateReference( this );
  37723. if ( updateType === NodeUpdateType.FRAME ) {
  37724. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  37725. if ( nodeUpdateBeforeMap.frameId !== this.frameId ) {
  37726. const previousFrameId = nodeUpdateBeforeMap.frameId;
  37727. nodeUpdateBeforeMap.frameId = this.frameId;
  37728. if ( node.updateBefore( this ) === false ) {
  37729. nodeUpdateBeforeMap.frameId = previousFrameId;
  37730. }
  37731. }
  37732. } else if ( updateType === NodeUpdateType.RENDER ) {
  37733. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  37734. if ( nodeUpdateBeforeMap.renderId !== this.renderId ) {
  37735. const previousRenderId = nodeUpdateBeforeMap.renderId;
  37736. nodeUpdateBeforeMap.renderId = this.renderId;
  37737. if ( node.updateBefore( this ) === false ) {
  37738. nodeUpdateBeforeMap.renderId = previousRenderId;
  37739. }
  37740. }
  37741. } else if ( updateType === NodeUpdateType.OBJECT ) {
  37742. node.updateBefore( this );
  37743. }
  37744. }
  37745. /**
  37746. * This method executes the {@link Node#updateAfter} for the given node.
  37747. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  37748. * is only executed once per frame, render or object depending on the update
  37749. * type.
  37750. *
  37751. * @param {Node} node - The node that should be updated.
  37752. */
  37753. updateAfterNode( node ) {
  37754. const updateType = node.getUpdateAfterType();
  37755. const reference = node.updateReference( this );
  37756. if ( updateType === NodeUpdateType.FRAME ) {
  37757. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  37758. if ( nodeUpdateAfterMap.frameId !== this.frameId ) {
  37759. if ( node.updateAfter( this ) !== false ) {
  37760. nodeUpdateAfterMap.frameId = this.frameId;
  37761. }
  37762. }
  37763. } else if ( updateType === NodeUpdateType.RENDER ) {
  37764. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  37765. if ( nodeUpdateAfterMap.renderId !== this.renderId ) {
  37766. if ( node.updateAfter( this ) !== false ) {
  37767. nodeUpdateAfterMap.renderId = this.renderId;
  37768. }
  37769. }
  37770. } else if ( updateType === NodeUpdateType.OBJECT ) {
  37771. node.updateAfter( this );
  37772. }
  37773. }
  37774. /**
  37775. * This method executes the {@link Node#update} for the given node.
  37776. * It makes sure {@link Node#updateType} is honored meaning the update
  37777. * is only executed once per frame, render or object depending on the update
  37778. * type.
  37779. *
  37780. * @param {Node} node - The node that should be updated.
  37781. */
  37782. updateNode( node ) {
  37783. const updateType = node.getUpdateType();
  37784. const reference = node.updateReference( this );
  37785. if ( updateType === NodeUpdateType.FRAME ) {
  37786. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  37787. if ( nodeUpdateMap.frameId !== this.frameId ) {
  37788. if ( node.update( this ) !== false ) {
  37789. nodeUpdateMap.frameId = this.frameId;
  37790. }
  37791. }
  37792. } else if ( updateType === NodeUpdateType.RENDER ) {
  37793. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  37794. if ( nodeUpdateMap.renderId !== this.renderId ) {
  37795. if ( node.update( this ) !== false ) {
  37796. nodeUpdateMap.renderId = this.renderId;
  37797. }
  37798. }
  37799. } else if ( updateType === NodeUpdateType.OBJECT ) {
  37800. node.update( this );
  37801. }
  37802. }
  37803. /**
  37804. * Updates the internal state of the node frame. This method is
  37805. * called by the renderer in its internal animation loop.
  37806. */
  37807. update() {
  37808. this.frameId ++;
  37809. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  37810. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  37811. this.lastTime = performance.now();
  37812. this.time += this.deltaTime;
  37813. }
  37814. }
  37815. /**
  37816. * Describes the input of a {@link NodeFunction}.
  37817. */
  37818. class NodeFunctionInput {
  37819. /**
  37820. * Constructs a new node function input.
  37821. *
  37822. * @param {string} type - The input type.
  37823. * @param {string} name - The input name.
  37824. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  37825. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  37826. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  37827. */
  37828. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  37829. /**
  37830. * The input type.
  37831. *
  37832. * @type {string}
  37833. */
  37834. this.type = type;
  37835. /**
  37836. * The input name.
  37837. *
  37838. * @type {string}
  37839. */
  37840. this.name = name;
  37841. /**
  37842. * If the input is an Array, count will be the length.
  37843. *
  37844. * @type {?number}
  37845. * @default null
  37846. */
  37847. this.count = count;
  37848. /**
  37849. *The parameter qualifier (only relevant for GLSL).
  37850. *
  37851. * @type {('in'|'out'|'inout')}
  37852. * @default ''
  37853. */
  37854. this.qualifier = qualifier;
  37855. /**
  37856. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  37857. *
  37858. * @type {boolean}
  37859. * @default false
  37860. */
  37861. this.isConst = isConst;
  37862. }
  37863. }
  37864. NodeFunctionInput.isNodeFunctionInput = true;
  37865. /**
  37866. * Module for representing directional lights as nodes.
  37867. *
  37868. * @augments AnalyticLightNode
  37869. */
  37870. class DirectionalLightNode extends AnalyticLightNode {
  37871. static get type() {
  37872. return 'DirectionalLightNode';
  37873. }
  37874. /**
  37875. * Constructs a new directional light node.
  37876. *
  37877. * @param {?DirectionalLight} [light=null] - The directional light source.
  37878. */
  37879. constructor( light = null ) {
  37880. super( light );
  37881. }
  37882. setupDirect() {
  37883. const lightColor = this.colorNode;
  37884. const lightDirection = lightTargetDirection( this.light );
  37885. return { lightDirection, lightColor };
  37886. }
  37887. }
  37888. const _matrix41 = /*@__PURE__*/ new Matrix4();
  37889. const _matrix42 = /*@__PURE__*/ new Matrix4();
  37890. let _ltcLib = null;
  37891. /**
  37892. * Module for representing rect area lights as nodes.
  37893. *
  37894. * @augments AnalyticLightNode
  37895. */
  37896. class RectAreaLightNode extends AnalyticLightNode {
  37897. static get type() {
  37898. return 'RectAreaLightNode';
  37899. }
  37900. /**
  37901. * Constructs a new rect area light node.
  37902. *
  37903. * @param {?RectAreaLight} [light=null] - The rect area light source.
  37904. */
  37905. constructor( light = null ) {
  37906. super( light );
  37907. /**
  37908. * Uniform node representing the half height of the are light.
  37909. *
  37910. * @type {UniformNode<vec3>}
  37911. */
  37912. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  37913. /**
  37914. * Uniform node representing the half width of the are light.
  37915. *
  37916. * @type {UniformNode<vec3>}
  37917. */
  37918. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  37919. /**
  37920. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  37921. * relies on `viewMatrix` which might vary per render call.
  37922. *
  37923. * @type {string}
  37924. * @default 'render'
  37925. */
  37926. this.updateType = NodeUpdateType.RENDER;
  37927. }
  37928. /**
  37929. * Overwritten to updated rect area light specific uniforms.
  37930. *
  37931. * @param {NodeFrame} frame - A reference to the current node frame.
  37932. */
  37933. update( frame ) {
  37934. super.update( frame );
  37935. const { light } = this;
  37936. const viewMatrix = frame.camera.matrixWorldInverse;
  37937. _matrix42.identity();
  37938. _matrix41.copy( light.matrixWorld );
  37939. _matrix41.premultiply( viewMatrix );
  37940. _matrix42.extractRotation( _matrix41 );
  37941. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  37942. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  37943. this.halfWidth.value.applyMatrix4( _matrix42 );
  37944. this.halfHeight.value.applyMatrix4( _matrix42 );
  37945. }
  37946. setupDirectRectArea( builder ) {
  37947. let ltc_1, ltc_2;
  37948. if ( builder.isAvailable( 'float32Filterable' ) ) {
  37949. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  37950. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  37951. } else {
  37952. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  37953. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  37954. }
  37955. const { colorNode, light } = this;
  37956. const lightPosition = lightViewPosition( light );
  37957. return {
  37958. lightColor: colorNode,
  37959. lightPosition,
  37960. halfWidth: this.halfWidth,
  37961. halfHeight: this.halfHeight,
  37962. ltc_1,
  37963. ltc_2
  37964. };
  37965. }
  37966. /**
  37967. * Used to configure the internal BRDF approximation texture data.
  37968. *
  37969. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  37970. */
  37971. static setLTC( ltc ) {
  37972. _ltcLib = ltc;
  37973. }
  37974. }
  37975. /**
  37976. * Module for representing spot lights as nodes.
  37977. *
  37978. * @augments AnalyticLightNode
  37979. */
  37980. class SpotLightNode extends AnalyticLightNode {
  37981. static get type() {
  37982. return 'SpotLightNode';
  37983. }
  37984. /**
  37985. * Constructs a new spot light node.
  37986. *
  37987. * @param {?SpotLight} [light=null] - The spot light source.
  37988. */
  37989. constructor( light = null ) {
  37990. super( light );
  37991. /**
  37992. * Uniform node representing the cone cosine.
  37993. *
  37994. * @type {UniformNode<float>}
  37995. */
  37996. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  37997. /**
  37998. * Uniform node representing the penumbra cosine.
  37999. *
  38000. * @type {UniformNode<float>}
  38001. */
  38002. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  38003. /**
  38004. * Uniform node representing the cutoff distance.
  38005. *
  38006. * @type {UniformNode<float>}
  38007. */
  38008. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  38009. /**
  38010. * Uniform node representing the decay exponent.
  38011. *
  38012. * @type {UniformNode<float>}
  38013. */
  38014. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  38015. /**
  38016. * Uniform node representing the light color.
  38017. *
  38018. * @type {UniformNode<Color>}
  38019. */
  38020. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  38021. }
  38022. /**
  38023. * Overwritten to updated spot light specific uniforms.
  38024. *
  38025. * @param {NodeFrame} frame - A reference to the current node frame.
  38026. */
  38027. update( frame ) {
  38028. super.update( frame );
  38029. const { light } = this;
  38030. this.coneCosNode.value = Math.cos( light.angle );
  38031. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  38032. this.cutoffDistanceNode.value = light.distance;
  38033. this.decayExponentNode.value = light.decay;
  38034. }
  38035. /**
  38036. * Computes the spot attenuation for the given angle.
  38037. *
  38038. * @param {NodeBuilder} builder - The node builder.
  38039. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  38040. * @return {Node<float>} The spot attenuation.
  38041. */
  38042. getSpotAttenuation( builder, angleCosine ) {
  38043. const { coneCosNode, penumbraCosNode } = this;
  38044. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  38045. }
  38046. getLightCoord( builder ) {
  38047. const properties = builder.getNodeProperties( this );
  38048. let projectionUV = properties.projectionUV;
  38049. if ( projectionUV === undefined ) {
  38050. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  38051. properties.projectionUV = projectionUV;
  38052. }
  38053. return projectionUV;
  38054. }
  38055. setupDirect( builder ) {
  38056. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  38057. const lightVector = this.getLightVector( builder );
  38058. const lightDirection = lightVector.normalize();
  38059. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  38060. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  38061. const lightDistance = lightVector.length();
  38062. const lightAttenuation = getDistanceAttenuation( {
  38063. lightDistance,
  38064. cutoffDistance: cutoffDistanceNode,
  38065. decayExponent: decayExponentNode
  38066. } );
  38067. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  38068. let projected, lightCoord;
  38069. if ( light.colorNode ) {
  38070. lightCoord = this.getLightCoord( builder );
  38071. projected = light.colorNode( lightCoord );
  38072. } else if ( light.map ) {
  38073. lightCoord = this.getLightCoord( builder );
  38074. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  38075. }
  38076. if ( projected ) {
  38077. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  38078. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  38079. }
  38080. return { lightColor, lightDirection };
  38081. }
  38082. }
  38083. /**
  38084. * An IES version of the default spot light node.
  38085. *
  38086. * @augments SpotLightNode
  38087. */
  38088. class IESSpotLightNode extends SpotLightNode {
  38089. static get type() {
  38090. return 'IESSpotLightNode';
  38091. }
  38092. /**
  38093. * Overwrites the default implementation to compute an IES conform spot attenuation.
  38094. *
  38095. * @param {NodeBuilder} builder - The node builder.
  38096. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  38097. * @return {Node<float>} The spot attenuation.
  38098. */
  38099. getSpotAttenuation( builder, angleCosine ) {
  38100. const iesMap = this.light.iesMap;
  38101. let spotAttenuation = null;
  38102. if ( iesMap && iesMap.isTexture === true ) {
  38103. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  38104. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  38105. } else {
  38106. spotAttenuation = super.getSpotAttenuation( angleCosine );
  38107. }
  38108. return spotAttenuation;
  38109. }
  38110. }
  38111. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  38112. const d = p.abs().sub( b );
  38113. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  38114. } );
  38115. /**
  38116. * An implementation of a projector light node.
  38117. *
  38118. * @augments SpotLightNode
  38119. */
  38120. class ProjectorLightNode extends SpotLightNode {
  38121. static get type() {
  38122. return 'ProjectorLightNode';
  38123. }
  38124. update( frame ) {
  38125. super.update( frame );
  38126. const light = this.light;
  38127. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  38128. if ( light.aspect === null ) {
  38129. let aspect = 1;
  38130. if ( light.map !== null ) {
  38131. aspect = light.map.width / light.map.height;
  38132. }
  38133. light.shadow.aspect = aspect;
  38134. } else {
  38135. light.shadow.aspect = light.aspect;
  38136. }
  38137. }
  38138. /**
  38139. * Overwrites the default implementation to compute projection attenuation.
  38140. *
  38141. * @param {NodeBuilder} builder - The node builder.
  38142. * @return {Node<float>} The spot attenuation.
  38143. */
  38144. getSpotAttenuation( builder ) {
  38145. const attenuation = float( 0 );
  38146. const penumbraCos = this.penumbraCosNode;
  38147. // compute the fragment's position in the light's clip space
  38148. const spotLightCoord = lightShadowMatrix( this.light ).mul( builder.context.positionWorld || positionWorld );
  38149. // the sign of w determines whether the current fragment is in front or behind the light.
  38150. // to avoid a back-projection, it's important to only compute an attenuation if w is positive
  38151. If( spotLightCoord.w.greaterThan( 0 ), () => {
  38152. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  38153. const boxDist = sdBox( projectionUV.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  38154. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  38155. attenuation.assign( saturate( boxDist.mul( -2 ).mul( angleFactor ) ) );
  38156. } );
  38157. return attenuation;
  38158. }
  38159. }
  38160. /**
  38161. * Module for representing ambient lights as nodes.
  38162. *
  38163. * @augments AnalyticLightNode
  38164. */
  38165. class AmbientLightNode extends AnalyticLightNode {
  38166. static get type() {
  38167. return 'AmbientLightNode';
  38168. }
  38169. /**
  38170. * Constructs a new ambient light node.
  38171. *
  38172. * @param {?AmbientLight} [light=null] - The ambient light source.
  38173. */
  38174. constructor( light = null ) {
  38175. super( light );
  38176. }
  38177. setup( { context } ) {
  38178. context.irradiance.addAssign( this.colorNode );
  38179. }
  38180. }
  38181. /**
  38182. * Module for representing hemisphere lights as nodes.
  38183. *
  38184. * @augments AnalyticLightNode
  38185. */
  38186. class HemisphereLightNode extends AnalyticLightNode {
  38187. static get type() {
  38188. return 'HemisphereLightNode';
  38189. }
  38190. /**
  38191. * Constructs a new hemisphere light node.
  38192. *
  38193. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  38194. */
  38195. constructor( light = null ) {
  38196. super( light );
  38197. /**
  38198. * Uniform node representing the light's position.
  38199. *
  38200. * @type {UniformNode<vec3>}
  38201. */
  38202. this.lightPositionNode = lightPosition( light );
  38203. /**
  38204. * A node representing the light's direction.
  38205. *
  38206. * @type {Node<vec3>}
  38207. */
  38208. this.lightDirectionNode = this.lightPositionNode.normalize();
  38209. /**
  38210. * Uniform node representing the light's ground color.
  38211. *
  38212. * @type {UniformNode<vec3>}
  38213. */
  38214. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  38215. }
  38216. /**
  38217. * Overwritten to updated hemisphere light specific uniforms.
  38218. *
  38219. * @param {NodeFrame} frame - A reference to the current node frame.
  38220. */
  38221. update( frame ) {
  38222. const { light } = this;
  38223. super.update( frame );
  38224. this.lightPositionNode.object3d = light;
  38225. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  38226. }
  38227. setup( builder ) {
  38228. const { colorNode, groundColorNode, lightDirectionNode } = this;
  38229. const dotNL = normalWorld.dot( lightDirectionNode );
  38230. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  38231. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  38232. builder.context.irradiance.addAssign( irradiance );
  38233. }
  38234. }
  38235. /**
  38236. * Module for representing light probes as nodes.
  38237. *
  38238. * @augments AnalyticLightNode
  38239. */
  38240. class LightProbeNode extends AnalyticLightNode {
  38241. static get type() {
  38242. return 'LightProbeNode';
  38243. }
  38244. /**
  38245. * Constructs a new light probe node.
  38246. *
  38247. * @param {?LightProbe} [light=null] - The light probe.
  38248. */
  38249. constructor( light = null ) {
  38250. super( light );
  38251. const array = [];
  38252. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  38253. /**
  38254. * Light probe represented as a uniform of spherical harmonics.
  38255. *
  38256. * @type {UniformArrayNode}
  38257. */
  38258. this.lightProbe = uniformArray( array );
  38259. }
  38260. /**
  38261. * Overwritten to updated light probe specific uniforms.
  38262. *
  38263. * @param {NodeFrame} frame - A reference to the current node frame.
  38264. */
  38265. update( frame ) {
  38266. const { light } = this;
  38267. super.update( frame );
  38268. //
  38269. for ( let i = 0; i < 9; i ++ ) {
  38270. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  38271. }
  38272. }
  38273. setup( builder ) {
  38274. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  38275. builder.context.irradiance.addAssign( irradiance );
  38276. }
  38277. }
  38278. /**
  38279. * Base class for node parsers. A derived parser must be implemented
  38280. * for each supported native shader language.
  38281. */
  38282. class NodeParser {
  38283. /**
  38284. * The method parses the given native code an returns a node function.
  38285. *
  38286. * @abstract
  38287. * @param {string} source - The native shader code.
  38288. * @return {NodeFunction} A node function.
  38289. */
  38290. parseFunction( /*source*/ ) {
  38291. warn( 'Abstract function.' );
  38292. }
  38293. }
  38294. /**
  38295. * Base class for node functions. A derived module must be implemented
  38296. * for each supported native shader language. Similar to other `Node*` modules,
  38297. * this class is only relevant during the building process and not used
  38298. * in user-level code.
  38299. */
  38300. class NodeFunction {
  38301. /**
  38302. * Constructs a new node function.
  38303. *
  38304. * @param {string} type - The node type. This type is the return type of the node function.
  38305. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  38306. * @param {string} [name=''] - The function's name.
  38307. * @param {string} [precision=''] - The precision qualifier.
  38308. */
  38309. constructor( type, inputs, name = '', precision = '' ) {
  38310. /**
  38311. * The node type. This type is the return type of the node function.
  38312. *
  38313. * @type {string}
  38314. */
  38315. this.type = type;
  38316. /**
  38317. * The function's inputs.
  38318. *
  38319. * @type {Array<NodeFunctionInput>}
  38320. */
  38321. this.inputs = inputs;
  38322. /**
  38323. * The name of the uniform.
  38324. *
  38325. * @type {string}
  38326. * @default ''
  38327. */
  38328. this.name = name;
  38329. /**
  38330. * The precision qualifier.
  38331. *
  38332. * @type {string}
  38333. * @default ''
  38334. */
  38335. this.precision = precision;
  38336. }
  38337. /**
  38338. * This method returns the native code of the node function.
  38339. *
  38340. * @abstract
  38341. * @param {string} name - The function's name.
  38342. * @return {string} A shader code.
  38343. */
  38344. getCode( /*name = this.name*/ ) {
  38345. warn( 'Abstract function.' );
  38346. }
  38347. }
  38348. NodeFunction.isNodeFunction = true;
  38349. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  38350. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  38351. const pragmaMain = '#pragma main';
  38352. const parse$1 = ( source ) => {
  38353. source = source.trim();
  38354. const pragmaMainIndex = source.indexOf( pragmaMain );
  38355. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  38356. const declaration = mainCode.match( declarationRegexp$1 );
  38357. if ( declaration !== null && declaration.length === 5 ) {
  38358. // tokenizer
  38359. const inputsCode = declaration[ 4 ];
  38360. const propsMatches = [];
  38361. let nameMatch = null;
  38362. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  38363. propsMatches.push( nameMatch );
  38364. }
  38365. // parser
  38366. const inputs = [];
  38367. let i = 0;
  38368. while ( i < propsMatches.length ) {
  38369. const isConst = propsMatches[ i ][ 0 ] === 'const';
  38370. if ( isConst === true ) {
  38371. i ++;
  38372. }
  38373. let qualifier = propsMatches[ i ][ 0 ];
  38374. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  38375. i ++;
  38376. } else {
  38377. qualifier = '';
  38378. }
  38379. const type = propsMatches[ i ++ ][ 0 ];
  38380. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  38381. if ( Number.isNaN( count ) === false ) i ++;
  38382. else count = null;
  38383. const name = propsMatches[ i ++ ][ 0 ];
  38384. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  38385. }
  38386. //
  38387. const blockCode = mainCode.substring( declaration[ 0 ].length );
  38388. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  38389. const type = declaration[ 2 ];
  38390. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  38391. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  38392. return {
  38393. type,
  38394. inputs,
  38395. name,
  38396. precision,
  38397. inputsCode,
  38398. blockCode,
  38399. headerCode
  38400. };
  38401. } else {
  38402. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  38403. }
  38404. };
  38405. /**
  38406. * This class represents a GLSL node function.
  38407. *
  38408. * @augments NodeFunction
  38409. */
  38410. class GLSLNodeFunction extends NodeFunction {
  38411. /**
  38412. * Constructs a new GLSL node function.
  38413. *
  38414. * @param {string} source - The GLSL source.
  38415. */
  38416. constructor( source ) {
  38417. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  38418. super( type, inputs, name, precision );
  38419. this.inputsCode = inputsCode;
  38420. this.blockCode = blockCode;
  38421. this.headerCode = headerCode;
  38422. }
  38423. /**
  38424. * This method returns the GLSL code of the node function.
  38425. *
  38426. * @param {string} [name=this.name] - The function's name.
  38427. * @return {string} The shader code.
  38428. */
  38429. getCode( name = this.name ) {
  38430. let code;
  38431. const blockCode = this.blockCode;
  38432. if ( blockCode !== '' ) {
  38433. const { type, inputsCode, headerCode, precision } = this;
  38434. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  38435. if ( precision !== '' ) {
  38436. declarationCode = `${ precision } ${ declarationCode }`;
  38437. }
  38438. code = headerCode + declarationCode + blockCode;
  38439. } else {
  38440. // interface function
  38441. code = '';
  38442. }
  38443. return code;
  38444. }
  38445. }
  38446. /**
  38447. * A GLSL node parser.
  38448. *
  38449. * @augments NodeParser
  38450. */
  38451. class GLSLNodeParser extends NodeParser {
  38452. /**
  38453. * The method parses the given GLSL code an returns a node function.
  38454. *
  38455. * @param {string} source - The GLSL code.
  38456. * @return {GLSLNodeFunction} A node function.
  38457. */
  38458. parseFunction( source ) {
  38459. return new GLSLNodeFunction( source );
  38460. }
  38461. }
  38462. const _outputNodeMap = new WeakMap();
  38463. const _chainKeys$2 = [];
  38464. const _cacheKeyValues = [];
  38465. /**
  38466. * This renderer module manages node-related objects and is the
  38467. * primary interface between the renderer and the node system.
  38468. *
  38469. * @private
  38470. * @augments DataMap
  38471. */
  38472. class Nodes extends DataMap {
  38473. /**
  38474. * Constructs a new nodes management component.
  38475. *
  38476. * @param {Renderer} renderer - The renderer.
  38477. * @param {Backend} backend - The renderer's backend.
  38478. */
  38479. constructor( renderer, backend ) {
  38480. super();
  38481. /**
  38482. * The renderer.
  38483. *
  38484. * @type {Renderer}
  38485. */
  38486. this.renderer = renderer;
  38487. /**
  38488. * The renderer's backend.
  38489. *
  38490. * @type {Backend}
  38491. */
  38492. this.backend = backend;
  38493. /**
  38494. * The node frame.
  38495. *
  38496. * @type {Renderer}
  38497. */
  38498. this.nodeFrame = new NodeFrame();
  38499. /**
  38500. * A cache for managing node builder states.
  38501. *
  38502. * @type {Map<number,NodeBuilderState>}
  38503. */
  38504. this.nodeBuilderCache = new Map();
  38505. /**
  38506. * A cache for managing data cache key data.
  38507. *
  38508. * @type {ChainMap}
  38509. */
  38510. this.callHashCache = new ChainMap();
  38511. /**
  38512. * A cache for managing node uniforms group data.
  38513. *
  38514. * @type {ChainMap}
  38515. */
  38516. this.groupsData = new ChainMap();
  38517. /**
  38518. * A cache for managing node objects of
  38519. * scene properties like fog or environments.
  38520. *
  38521. * @type {Object<string,WeakMap>}
  38522. */
  38523. this.cacheLib = {};
  38524. }
  38525. /**
  38526. * Returns `true` if the given node uniforms group must be updated or not.
  38527. *
  38528. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  38529. * @return {boolean} Whether the node uniforms group requires an update or not.
  38530. */
  38531. updateGroup( nodeUniformsGroup ) {
  38532. const groupNode = nodeUniformsGroup.groupNode;
  38533. const name = groupNode.name;
  38534. // objectGroup is always updated
  38535. if ( name === objectGroup.name ) return true;
  38536. // renderGroup is updated once per render/compute call
  38537. if ( name === renderGroup.name ) {
  38538. const uniformsGroupData = this.get( nodeUniformsGroup );
  38539. const renderId = this.nodeFrame.renderId;
  38540. if ( uniformsGroupData.renderId !== renderId ) {
  38541. uniformsGroupData.renderId = renderId;
  38542. return true;
  38543. }
  38544. return false;
  38545. }
  38546. // frameGroup is updated once per frame
  38547. if ( name === frameGroup.name ) {
  38548. const uniformsGroupData = this.get( nodeUniformsGroup );
  38549. const frameId = this.nodeFrame.frameId;
  38550. if ( uniformsGroupData.frameId !== frameId ) {
  38551. uniformsGroupData.frameId = frameId;
  38552. return true;
  38553. }
  38554. return false;
  38555. }
  38556. // other groups are updated just when groupNode.needsUpdate is true
  38557. _chainKeys$2[ 0 ] = groupNode;
  38558. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  38559. let groupData = this.groupsData.get( _chainKeys$2 );
  38560. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  38561. _chainKeys$2.length = 0;
  38562. if ( groupData.version !== groupNode.version ) {
  38563. groupData.version = groupNode.version;
  38564. return true;
  38565. }
  38566. return false;
  38567. }
  38568. /**
  38569. * Returns the cache key for the given render object.
  38570. *
  38571. * @param {RenderObject} renderObject - The render object.
  38572. * @return {number} The cache key.
  38573. */
  38574. getForRenderCacheKey( renderObject ) {
  38575. return renderObject.initialCacheKey;
  38576. }
  38577. /**
  38578. * Returns a node builder state for the given render object.
  38579. *
  38580. * @param {RenderObject} renderObject - The render object.
  38581. * @return {NodeBuilderState} The node builder state.
  38582. */
  38583. getForRender( renderObject ) {
  38584. const renderObjectData = this.get( renderObject );
  38585. let nodeBuilderState = renderObjectData.nodeBuilderState;
  38586. if ( nodeBuilderState === undefined ) {
  38587. const { nodeBuilderCache } = this;
  38588. const cacheKey = this.getForRenderCacheKey( renderObject );
  38589. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  38590. if ( nodeBuilderState === undefined ) {
  38591. const createNodeBuilder = ( material ) => {
  38592. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  38593. nodeBuilder.scene = renderObject.scene;
  38594. nodeBuilder.material = material;
  38595. nodeBuilder.camera = renderObject.camera;
  38596. nodeBuilder.context.material = material;
  38597. nodeBuilder.lightsNode = renderObject.lightsNode;
  38598. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  38599. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  38600. nodeBuilder.clippingContext = renderObject.clippingContext;
  38601. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  38602. nodeBuilder.enableMultiview();
  38603. }
  38604. return nodeBuilder;
  38605. };
  38606. let nodeBuilder = createNodeBuilder( renderObject.material );
  38607. try {
  38608. nodeBuilder.build();
  38609. } catch ( e ) {
  38610. nodeBuilder = createNodeBuilder( new NodeMaterial() );
  38611. nodeBuilder.build();
  38612. error( 'TSL: ' + e );
  38613. }
  38614. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  38615. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  38616. }
  38617. nodeBuilderState.usedTimes ++;
  38618. renderObjectData.nodeBuilderState = nodeBuilderState;
  38619. }
  38620. return nodeBuilderState;
  38621. }
  38622. /**
  38623. * Deletes the given object from the internal data map
  38624. *
  38625. * @param {any} object - The object to delete.
  38626. * @return {?Object} The deleted dictionary.
  38627. */
  38628. delete( object ) {
  38629. if ( object.isRenderObject ) {
  38630. const nodeBuilderState = this.get( object ).nodeBuilderState;
  38631. nodeBuilderState.usedTimes --;
  38632. if ( nodeBuilderState.usedTimes === 0 ) {
  38633. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  38634. }
  38635. }
  38636. return super.delete( object );
  38637. }
  38638. /**
  38639. * Returns a node builder state for the given compute node.
  38640. *
  38641. * @param {Node} computeNode - The compute node.
  38642. * @return {NodeBuilderState} The node builder state.
  38643. */
  38644. getForCompute( computeNode ) {
  38645. const computeData = this.get( computeNode );
  38646. let nodeBuilderState = computeData.nodeBuilderState;
  38647. if ( nodeBuilderState === undefined ) {
  38648. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  38649. nodeBuilder.build();
  38650. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  38651. computeData.nodeBuilderState = nodeBuilderState;
  38652. }
  38653. return nodeBuilderState;
  38654. }
  38655. /**
  38656. * Creates a node builder state for the given node builder.
  38657. *
  38658. * @private
  38659. * @param {NodeBuilder} nodeBuilder - The node builder.
  38660. * @return {NodeBuilderState} The node builder state.
  38661. */
  38662. _createNodeBuilderState( nodeBuilder ) {
  38663. return new NodeBuilderState(
  38664. nodeBuilder.vertexShader,
  38665. nodeBuilder.fragmentShader,
  38666. nodeBuilder.computeShader,
  38667. nodeBuilder.getAttributesArray(),
  38668. nodeBuilder.getBindings(),
  38669. nodeBuilder.updateNodes,
  38670. nodeBuilder.updateBeforeNodes,
  38671. nodeBuilder.updateAfterNodes,
  38672. nodeBuilder.observer,
  38673. nodeBuilder.transforms
  38674. );
  38675. }
  38676. /**
  38677. * Returns an environment node for the current configured
  38678. * scene environment.
  38679. *
  38680. * @param {Scene} scene - The scene.
  38681. * @return {Node} A node representing the current scene environment.
  38682. */
  38683. getEnvironmentNode( scene ) {
  38684. this.updateEnvironment( scene );
  38685. let environmentNode = null;
  38686. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  38687. environmentNode = scene.environmentNode;
  38688. } else {
  38689. const sceneData = this.get( scene );
  38690. if ( sceneData.environmentNode ) {
  38691. environmentNode = sceneData.environmentNode;
  38692. }
  38693. }
  38694. return environmentNode;
  38695. }
  38696. /**
  38697. * Returns a background node for the current configured
  38698. * scene background.
  38699. *
  38700. * @param {Scene} scene - The scene.
  38701. * @return {Node} A node representing the current scene background.
  38702. */
  38703. getBackgroundNode( scene ) {
  38704. this.updateBackground( scene );
  38705. let backgroundNode = null;
  38706. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  38707. backgroundNode = scene.backgroundNode;
  38708. } else {
  38709. const sceneData = this.get( scene );
  38710. if ( sceneData.backgroundNode ) {
  38711. backgroundNode = sceneData.backgroundNode;
  38712. }
  38713. }
  38714. return backgroundNode;
  38715. }
  38716. /**
  38717. * Returns a fog node for the current configured scene fog.
  38718. *
  38719. * @param {Scene} scene - The scene.
  38720. * @return {Node} A node representing the current scene fog.
  38721. */
  38722. getFogNode( scene ) {
  38723. this.updateFog( scene );
  38724. return scene.fogNode || this.get( scene ).fogNode || null;
  38725. }
  38726. /**
  38727. * Returns a cache key for the given scene and lights node.
  38728. * This key is used by `RenderObject` as a part of the dynamic
  38729. * cache key (a key that must be checked every time the render
  38730. * objects is drawn).
  38731. *
  38732. * @param {Scene} scene - The scene.
  38733. * @param {LightsNode} lightsNode - The lights node.
  38734. * @return {number} The cache key.
  38735. */
  38736. getCacheKey( scene, lightsNode ) {
  38737. _chainKeys$2[ 0 ] = scene;
  38738. _chainKeys$2[ 1 ] = lightsNode;
  38739. const callId = this.renderer.info.calls;
  38740. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  38741. if ( cacheKeyData.callId !== callId ) {
  38742. const environmentNode = this.getEnvironmentNode( scene );
  38743. const fogNode = this.getFogNode( scene );
  38744. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  38745. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  38746. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  38747. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  38748. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  38749. _cacheKeyValues.push( this.renderer.shadowMap.type );
  38750. cacheKeyData.callId = callId;
  38751. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  38752. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  38753. _cacheKeyValues.length = 0;
  38754. }
  38755. _chainKeys$2.length = 0;
  38756. return cacheKeyData.cacheKey;
  38757. }
  38758. /**
  38759. * A boolean that indicates whether tone mapping should be enabled
  38760. * or not.
  38761. *
  38762. * @type {boolean}
  38763. */
  38764. get isToneMappingState() {
  38765. return this.renderer.getRenderTarget() ? false : true;
  38766. }
  38767. /**
  38768. * If a scene background is configured, this method makes sure to
  38769. * represent the background with a corresponding node-based implementation.
  38770. *
  38771. * @param {Scene} scene - The scene.
  38772. */
  38773. updateBackground( scene ) {
  38774. const sceneData = this.get( scene );
  38775. const background = scene.background;
  38776. if ( background ) {
  38777. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  38778. if ( sceneData.background !== background || forceUpdate ) {
  38779. const backgroundNode = this.getCacheNode( 'background', background, () => {
  38780. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  38781. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  38782. return pmremTexture( background );
  38783. } else {
  38784. let envMap;
  38785. if ( background.isCubeTexture === true ) {
  38786. envMap = cubeTexture( background );
  38787. } else {
  38788. envMap = texture( background );
  38789. }
  38790. return cubeMapNode( envMap );
  38791. }
  38792. } else if ( background.isTexture === true ) {
  38793. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  38794. } else if ( background.isColor !== true ) {
  38795. error( 'WebGPUNodes: Unsupported background configuration.', background );
  38796. }
  38797. }, forceUpdate );
  38798. sceneData.backgroundNode = backgroundNode;
  38799. sceneData.background = background;
  38800. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  38801. }
  38802. } else if ( sceneData.backgroundNode ) {
  38803. delete sceneData.backgroundNode;
  38804. delete sceneData.background;
  38805. }
  38806. }
  38807. /**
  38808. * This method is part of the caching of nodes which are used to represents the
  38809. * scene's background, fog or environment.
  38810. *
  38811. * @param {string} type - The type of object to cache.
  38812. * @param {Object} object - The object.
  38813. * @param {Function} callback - A callback that produces a node representation for the given object.
  38814. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  38815. * @return {Node} The node representation.
  38816. */
  38817. getCacheNode( type, object, callback, forceUpdate = false ) {
  38818. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  38819. let node = nodeCache.get( object );
  38820. if ( node === undefined || forceUpdate ) {
  38821. node = callback();
  38822. nodeCache.set( object, node );
  38823. }
  38824. return node;
  38825. }
  38826. /**
  38827. * If a scene fog is configured, this method makes sure to
  38828. * represent the fog with a corresponding node-based implementation.
  38829. *
  38830. * @param {Scene} scene - The scene.
  38831. */
  38832. updateFog( scene ) {
  38833. const sceneData = this.get( scene );
  38834. const sceneFog = scene.fog;
  38835. if ( sceneFog ) {
  38836. if ( sceneData.fog !== sceneFog ) {
  38837. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  38838. if ( sceneFog.isFogExp2 ) {
  38839. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  38840. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  38841. return fog( color, densityFogFactor( density ) );
  38842. } else if ( sceneFog.isFog ) {
  38843. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  38844. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  38845. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  38846. return fog( color, rangeFogFactor( near, far ) );
  38847. } else {
  38848. error( 'Renderer: Unsupported fog configuration.', sceneFog );
  38849. }
  38850. } );
  38851. sceneData.fogNode = fogNode;
  38852. sceneData.fog = sceneFog;
  38853. }
  38854. } else {
  38855. delete sceneData.fogNode;
  38856. delete sceneData.fog;
  38857. }
  38858. }
  38859. /**
  38860. * If a scene environment is configured, this method makes sure to
  38861. * represent the environment with a corresponding node-based implementation.
  38862. *
  38863. * @param {Scene} scene - The scene.
  38864. */
  38865. updateEnvironment( scene ) {
  38866. const sceneData = this.get( scene );
  38867. const environment = scene.environment;
  38868. if ( environment ) {
  38869. if ( sceneData.environment !== environment ) {
  38870. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  38871. if ( environment.isCubeTexture === true ) {
  38872. return cubeTexture( environment );
  38873. } else if ( environment.isTexture === true ) {
  38874. return texture( environment );
  38875. } else {
  38876. error( 'Nodes: Unsupported environment configuration.', environment );
  38877. }
  38878. } );
  38879. sceneData.environmentNode = environmentNode;
  38880. sceneData.environment = environment;
  38881. }
  38882. } else if ( sceneData.environmentNode ) {
  38883. delete sceneData.environmentNode;
  38884. delete sceneData.environment;
  38885. }
  38886. }
  38887. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  38888. const nodeFrame = this.nodeFrame;
  38889. nodeFrame.renderer = renderer;
  38890. nodeFrame.scene = scene;
  38891. nodeFrame.object = object;
  38892. nodeFrame.camera = camera;
  38893. nodeFrame.material = material;
  38894. return nodeFrame;
  38895. }
  38896. getNodeFrameForRender( renderObject ) {
  38897. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  38898. }
  38899. /**
  38900. * Returns the current output cache key.
  38901. *
  38902. * @return {string} The output cache key.
  38903. */
  38904. getOutputCacheKey() {
  38905. const renderer = this.renderer;
  38906. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  38907. }
  38908. /**
  38909. * Checks if the output configuration (tone mapping and color space) for
  38910. * the given target has changed.
  38911. *
  38912. * @param {Texture} outputTarget - The output target.
  38913. * @return {boolean} Whether the output configuration has changed or not.
  38914. */
  38915. hasOutputChange( outputTarget ) {
  38916. const cacheKey = _outputNodeMap.get( outputTarget );
  38917. return cacheKey !== this.getOutputCacheKey();
  38918. }
  38919. /**
  38920. * Returns a node that represents the output configuration (tone mapping and
  38921. * color space) for the current target.
  38922. *
  38923. * @param {Texture} outputTarget - The output target.
  38924. * @return {Node} The output node.
  38925. */
  38926. getOutputNode( outputTarget ) {
  38927. const renderer = this.renderer;
  38928. const cacheKey = this.getOutputCacheKey();
  38929. const output = outputTarget.isArrayTexture ?
  38930. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  38931. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  38932. _outputNodeMap.set( outputTarget, cacheKey );
  38933. return output;
  38934. }
  38935. /**
  38936. * Triggers the call of `updateBefore()` methods
  38937. * for all nodes of the given render object.
  38938. *
  38939. * @param {RenderObject} renderObject - The render object.
  38940. */
  38941. updateBefore( renderObject ) {
  38942. const nodeBuilder = renderObject.getNodeBuilderState();
  38943. for ( const node of nodeBuilder.updateBeforeNodes ) {
  38944. // update frame state for each node
  38945. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  38946. }
  38947. }
  38948. /**
  38949. * Triggers the call of `updateAfter()` methods
  38950. * for all nodes of the given render object.
  38951. *
  38952. * @param {RenderObject} renderObject - The render object.
  38953. */
  38954. updateAfter( renderObject ) {
  38955. const nodeBuilder = renderObject.getNodeBuilderState();
  38956. for ( const node of nodeBuilder.updateAfterNodes ) {
  38957. // update frame state for each node
  38958. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  38959. }
  38960. }
  38961. /**
  38962. * Triggers the call of `update()` methods
  38963. * for all nodes of the given compute node.
  38964. *
  38965. * @param {Node} computeNode - The compute node.
  38966. */
  38967. updateForCompute( computeNode ) {
  38968. const nodeFrame = this.getNodeFrame();
  38969. const nodeBuilder = this.getForCompute( computeNode );
  38970. for ( const node of nodeBuilder.updateNodes ) {
  38971. nodeFrame.updateNode( node );
  38972. }
  38973. }
  38974. /**
  38975. * Triggers the call of `update()` methods
  38976. * for all nodes of the given compute node.
  38977. *
  38978. * @param {RenderObject} renderObject - The render object.
  38979. */
  38980. updateForRender( renderObject ) {
  38981. const nodeFrame = this.getNodeFrameForRender( renderObject );
  38982. const nodeBuilder = renderObject.getNodeBuilderState();
  38983. for ( const node of nodeBuilder.updateNodes ) {
  38984. nodeFrame.updateNode( node );
  38985. }
  38986. }
  38987. /**
  38988. * Returns `true` if the given render object requires a refresh.
  38989. *
  38990. * @param {RenderObject} renderObject - The render object.
  38991. * @return {boolean} Whether the given render object requires a refresh or not.
  38992. */
  38993. needsRefresh( renderObject ) {
  38994. const nodeFrame = this.getNodeFrameForRender( renderObject );
  38995. const monitor = renderObject.getMonitor();
  38996. return monitor.needsRefresh( renderObject, nodeFrame );
  38997. }
  38998. /**
  38999. * Frees the internal resources.
  39000. */
  39001. dispose() {
  39002. super.dispose();
  39003. this.nodeFrame = new NodeFrame();
  39004. this.nodeBuilderCache = new Map();
  39005. this.cacheLib = {};
  39006. }
  39007. }
  39008. const _plane = /*@__PURE__*/ new Plane();
  39009. /**
  39010. * Represents the state that is used to perform clipping via clipping planes.
  39011. * There is a default clipping context for each render context. When the
  39012. * scene holds instances of `ClippingGroup`, there will be a context for each
  39013. * group.
  39014. *
  39015. * @private
  39016. */
  39017. class ClippingContext {
  39018. /**
  39019. * Constructs a new clipping context.
  39020. *
  39021. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  39022. */
  39023. constructor( parentContext = null ) {
  39024. /**
  39025. * The clipping context's version.
  39026. *
  39027. * @type {number}
  39028. * @readonly
  39029. */
  39030. this.version = 0;
  39031. /**
  39032. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  39033. *
  39034. * @type {?boolean}
  39035. * @default null
  39036. */
  39037. this.clipIntersection = null;
  39038. /**
  39039. * The clipping context's cache key.
  39040. *
  39041. * @type {string}
  39042. */
  39043. this.cacheKey = '';
  39044. /**
  39045. * Whether the shadow pass is active or not.
  39046. *
  39047. * @type {boolean}
  39048. * @default false
  39049. */
  39050. this.shadowPass = false;
  39051. /**
  39052. * The view normal matrix.
  39053. *
  39054. * @type {Matrix3}
  39055. */
  39056. this.viewNormalMatrix = new Matrix3();
  39057. /**
  39058. * Internal cache for maintaining clipping contexts.
  39059. *
  39060. * @type {WeakMap<ClippingGroup,ClippingContext>}
  39061. */
  39062. this.clippingGroupContexts = new WeakMap();
  39063. /**
  39064. * The intersection planes.
  39065. *
  39066. * @type {Array<Vector4>}
  39067. */
  39068. this.intersectionPlanes = [];
  39069. /**
  39070. * The intersection planes.
  39071. *
  39072. * @type {Array<Vector4>}
  39073. */
  39074. this.unionPlanes = [];
  39075. /**
  39076. * The version of the clipping context's parent context.
  39077. *
  39078. * @type {?number}
  39079. * @readonly
  39080. */
  39081. this.parentVersion = null;
  39082. if ( parentContext !== null ) {
  39083. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  39084. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  39085. this.shadowPass = parentContext.shadowPass;
  39086. this.viewMatrix = parentContext.viewMatrix;
  39087. }
  39088. }
  39089. /**
  39090. * Projects the given source clipping planes and writes the result into the
  39091. * destination array.
  39092. *
  39093. * @param {Array<Plane>} source - The source clipping planes.
  39094. * @param {Array<Vector4>} destination - The destination.
  39095. * @param {number} offset - The offset.
  39096. */
  39097. projectPlanes( source, destination, offset ) {
  39098. const l = source.length;
  39099. for ( let i = 0; i < l; i ++ ) {
  39100. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  39101. const v = destination[ offset + i ];
  39102. const normal = _plane.normal;
  39103. v.x = - normal.x;
  39104. v.y = - normal.y;
  39105. v.z = - normal.z;
  39106. v.w = _plane.constant;
  39107. }
  39108. }
  39109. /**
  39110. * Updates the root clipping context of a scene.
  39111. *
  39112. * @param {Scene} scene - The scene.
  39113. * @param {Camera} camera - The camera that is used to render the scene.
  39114. */
  39115. updateGlobal( scene, camera ) {
  39116. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  39117. this.viewMatrix = camera.matrixWorldInverse;
  39118. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  39119. }
  39120. /**
  39121. * Updates the clipping context.
  39122. *
  39123. * @param {ClippingContext} parentContext - The parent context.
  39124. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  39125. */
  39126. update( parentContext, clippingGroup ) {
  39127. let update = false;
  39128. if ( parentContext.version !== this.parentVersion ) {
  39129. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  39130. this.unionPlanes = Array.from( parentContext.unionPlanes );
  39131. this.parentVersion = parentContext.version;
  39132. }
  39133. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  39134. this.clipIntersection = clippingGroup.clipIntersection;
  39135. if ( this.clipIntersection ) {
  39136. this.unionPlanes.length = parentContext.unionPlanes.length;
  39137. } else {
  39138. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  39139. }
  39140. }
  39141. const srcClippingPlanes = clippingGroup.clippingPlanes;
  39142. const l = srcClippingPlanes.length;
  39143. let dstClippingPlanes;
  39144. let offset;
  39145. if ( this.clipIntersection ) {
  39146. dstClippingPlanes = this.intersectionPlanes;
  39147. offset = parentContext.intersectionPlanes.length;
  39148. } else {
  39149. dstClippingPlanes = this.unionPlanes;
  39150. offset = parentContext.unionPlanes.length;
  39151. }
  39152. if ( dstClippingPlanes.length !== offset + l ) {
  39153. dstClippingPlanes.length = offset + l;
  39154. for ( let i = 0; i < l; i ++ ) {
  39155. dstClippingPlanes[ offset + i ] = new Vector4();
  39156. }
  39157. update = true;
  39158. }
  39159. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  39160. if ( update ) {
  39161. this.version ++;
  39162. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  39163. }
  39164. }
  39165. /**
  39166. * Returns a clipping context for the given clipping group.
  39167. *
  39168. * @param {ClippingGroup} clippingGroup - The clipping group.
  39169. * @return {ClippingContext} The clipping context.
  39170. */
  39171. getGroupContext( clippingGroup ) {
  39172. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  39173. let context = this.clippingGroupContexts.get( clippingGroup );
  39174. if ( context === undefined ) {
  39175. context = new ClippingContext( this );
  39176. this.clippingGroupContexts.set( clippingGroup, context );
  39177. }
  39178. context.update( this, clippingGroup );
  39179. return context;
  39180. }
  39181. /**
  39182. * The count of union clipping planes.
  39183. *
  39184. * @type {number}
  39185. * @readonly
  39186. */
  39187. get unionClippingCount() {
  39188. return this.unionPlanes.length;
  39189. }
  39190. }
  39191. /**
  39192. * This module is used to represent render bundles inside the renderer
  39193. * for further processing.
  39194. *
  39195. * @private
  39196. */
  39197. class RenderBundle {
  39198. /**
  39199. * Constructs a new bundle group.
  39200. *
  39201. * @param {BundleGroup} bundleGroup - The bundle group.
  39202. * @param {Camera} camera - The camera the bundle group is rendered with.
  39203. */
  39204. constructor( bundleGroup, camera ) {
  39205. this.bundleGroup = bundleGroup;
  39206. this.camera = camera;
  39207. }
  39208. }
  39209. const _chainKeys$1 = [];
  39210. /**
  39211. * This renderer module manages render bundles.
  39212. *
  39213. * @private
  39214. */
  39215. class RenderBundles {
  39216. /**
  39217. * Constructs a new render bundle management component.
  39218. */
  39219. constructor() {
  39220. /**
  39221. * A chain map for maintaining the render bundles.
  39222. *
  39223. * @type {ChainMap}
  39224. */
  39225. this.bundles = new ChainMap();
  39226. }
  39227. /**
  39228. * Returns a render bundle for the given bundle group and camera.
  39229. *
  39230. * @param {BundleGroup} bundleGroup - The bundle group.
  39231. * @param {Camera} camera - The camera the bundle group is rendered with.
  39232. * @return {RenderBundle} The render bundle.
  39233. */
  39234. get( bundleGroup, camera ) {
  39235. const bundles = this.bundles;
  39236. _chainKeys$1[ 0 ] = bundleGroup;
  39237. _chainKeys$1[ 1 ] = camera;
  39238. let bundle = bundles.get( _chainKeys$1 );
  39239. if ( bundle === undefined ) {
  39240. bundle = new RenderBundle( bundleGroup, camera );
  39241. bundles.set( _chainKeys$1, bundle );
  39242. }
  39243. _chainKeys$1.length = 0;
  39244. return bundle;
  39245. }
  39246. /**
  39247. * Frees all internal resources.
  39248. */
  39249. dispose() {
  39250. this.bundles = new ChainMap();
  39251. }
  39252. }
  39253. /**
  39254. * The purpose of a node library is to assign node implementations
  39255. * to existing library features. In `WebGPURenderer` lights, materials
  39256. * which are not based on `NodeMaterial` as well as tone mapping techniques
  39257. * are implemented with node-based modules.
  39258. *
  39259. * @private
  39260. */
  39261. class NodeLibrary {
  39262. /**
  39263. * Constructs a new node library.
  39264. */
  39265. constructor() {
  39266. /**
  39267. * A weak map that maps lights to light nodes.
  39268. *
  39269. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  39270. */
  39271. this.lightNodes = new WeakMap();
  39272. /**
  39273. * A map that maps materials to node materials.
  39274. *
  39275. * @type {Map<string,NodeMaterial.constructor>}
  39276. */
  39277. this.materialNodes = new Map();
  39278. /**
  39279. * A map that maps tone mapping techniques (constants)
  39280. * to tone mapping node functions.
  39281. *
  39282. * @type {Map<number,Function>}
  39283. */
  39284. this.toneMappingNodes = new Map();
  39285. }
  39286. /**
  39287. * Returns a matching node material instance for the given material object.
  39288. *
  39289. * This method also assigns/copies the properties of the given material object
  39290. * to the node material. This is done to make sure the current material
  39291. * configuration carries over to the node version.
  39292. *
  39293. * @param {Material} material - A material.
  39294. * @return {NodeMaterial} The corresponding node material.
  39295. */
  39296. fromMaterial( material ) {
  39297. if ( material.isNodeMaterial ) return material;
  39298. let nodeMaterial = null;
  39299. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  39300. if ( nodeMaterialClass !== null ) {
  39301. nodeMaterial = new nodeMaterialClass();
  39302. for ( const key in material ) {
  39303. nodeMaterial[ key ] = material[ key ];
  39304. }
  39305. }
  39306. return nodeMaterial;
  39307. }
  39308. /**
  39309. * Adds a tone mapping node function for a tone mapping technique (constant).
  39310. *
  39311. * @param {Function} toneMappingNode - The tone mapping node function.
  39312. * @param {number} toneMapping - The tone mapping.
  39313. */
  39314. addToneMapping( toneMappingNode, toneMapping ) {
  39315. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  39316. }
  39317. /**
  39318. * Returns a tone mapping node function for a tone mapping technique (constant).
  39319. *
  39320. * @param {number} toneMapping - The tone mapping.
  39321. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  39322. */
  39323. getToneMappingFunction( toneMapping ) {
  39324. return this.toneMappingNodes.get( toneMapping ) || null;
  39325. }
  39326. /**
  39327. * Returns a node material class definition for a material type.
  39328. *
  39329. * @param {string} materialType - The material type.
  39330. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  39331. */
  39332. getMaterialNodeClass( materialType ) {
  39333. return this.materialNodes.get( materialType ) || null;
  39334. }
  39335. /**
  39336. * Adds a node material class definition for a given material type.
  39337. *
  39338. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  39339. * @param {string} materialClassType - The material type.
  39340. */
  39341. addMaterial( materialNodeClass, materialClassType ) {
  39342. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  39343. }
  39344. /**
  39345. * Returns a light node class definition for a light class definition.
  39346. *
  39347. * @param {Light.constructor} light - The light class definition.
  39348. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  39349. */
  39350. getLightNodeClass( light ) {
  39351. return this.lightNodes.get( light ) || null;
  39352. }
  39353. /**
  39354. * Adds a light node class definition for a given light class definition.
  39355. *
  39356. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  39357. * @param {Light.constructor} lightClass - The light class definition.
  39358. */
  39359. addLight( lightNodeClass, lightClass ) {
  39360. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  39361. }
  39362. /**
  39363. * Adds a node class definition for the given type to the provided type library.
  39364. *
  39365. * @param {Node.constructor} nodeClass - The node class definition.
  39366. * @param {number|string} type - The object type.
  39367. * @param {Map<number|string,Node.constructor>} library - The type library.
  39368. */
  39369. addType( nodeClass, type, library ) {
  39370. if ( library.has( type ) ) {
  39371. warn( `Redefinition of node ${ type }` );
  39372. return;
  39373. }
  39374. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  39375. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  39376. library.set( type, nodeClass );
  39377. }
  39378. /**
  39379. * Adds a node class definition for the given class definition to the provided type library.
  39380. *
  39381. * @param {Node.constructor} nodeClass - The node class definition.
  39382. * @param {Node.constructor} baseClass - The class definition.
  39383. * @param {WeakMap<Node.constructor, Node.constructor>} library - The type library.
  39384. */
  39385. addClass( nodeClass, baseClass, library ) {
  39386. if ( library.has( baseClass ) ) {
  39387. warn( `Redefinition of node ${ baseClass.name }` );
  39388. return;
  39389. }
  39390. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  39391. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  39392. library.set( baseClass, nodeClass );
  39393. }
  39394. }
  39395. const _defaultLights = /*@__PURE__*/ new LightsNode();
  39396. const _chainKeys = [];
  39397. /**
  39398. * This renderer module manages the lights nodes which are unique
  39399. * per scene and camera combination.
  39400. *
  39401. * The lights node itself is later configured in the render list
  39402. * with the actual lights from the scene.
  39403. *
  39404. * @private
  39405. * @augments ChainMap
  39406. */
  39407. class Lighting extends ChainMap {
  39408. /**
  39409. * Constructs a lighting management component.
  39410. */
  39411. constructor() {
  39412. super();
  39413. }
  39414. /**
  39415. * Creates a new lights node for the given array of lights.
  39416. *
  39417. * @param {Array<Light>} lights - The render object.
  39418. * @return {LightsNode} The lights node.
  39419. */
  39420. createNode( lights = [] ) {
  39421. return new LightsNode().setLights( lights );
  39422. }
  39423. /**
  39424. * Returns a lights node for the given scene and camera.
  39425. *
  39426. * @param {Scene} scene - The scene.
  39427. * @param {Camera} camera - The camera.
  39428. * @return {LightsNode} The lights node.
  39429. */
  39430. getNode( scene, camera ) {
  39431. // ignore post-processing
  39432. if ( scene.isQuadMesh ) return _defaultLights;
  39433. _chainKeys[ 0 ] = scene;
  39434. _chainKeys[ 1 ] = camera;
  39435. let node = this.get( _chainKeys );
  39436. if ( node === undefined ) {
  39437. node = this.createNode();
  39438. this.set( _chainKeys, node );
  39439. }
  39440. _chainKeys.length = 0;
  39441. return node;
  39442. }
  39443. }
  39444. /**
  39445. * A special type of render target that is used when rendering
  39446. * with the WebXR Device API.
  39447. *
  39448. * @private
  39449. * @augments RenderTarget
  39450. */
  39451. class XRRenderTarget extends RenderTarget {
  39452. /**
  39453. * Constructs a new XR render target.
  39454. *
  39455. * @param {number} [width=1] - The width of the render target.
  39456. * @param {number} [height=1] - The height of the render target.
  39457. * @param {Object} [options={}] - The configuration options.
  39458. */
  39459. constructor( width = 1, height = 1, options = {} ) {
  39460. super( width, height, options );
  39461. /**
  39462. * This flag can be used for type testing.
  39463. *
  39464. * @type {boolean}
  39465. * @readonly
  39466. * @default true
  39467. */
  39468. this.isXRRenderTarget = true;
  39469. /**
  39470. * Whether the attachments of the render target
  39471. * are defined by external textures. This flag is
  39472. * set to `true` when using the WebXR Layers API.
  39473. *
  39474. * @private
  39475. * @type {boolean}
  39476. * @default false
  39477. */
  39478. this._hasExternalTextures = false;
  39479. /**
  39480. * Whether a depth buffer should automatically be allocated
  39481. * for this XR render target or not.
  39482. *
  39483. * Allocating a depth buffer is the default behavior of XR render
  39484. * targets. However, when using the WebXR Layers API, this flag
  39485. * must be set to `false` when the `ignoreDepthValues` property of
  39486. * the projection layers evaluates to `false`.
  39487. *
  39488. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  39489. *
  39490. * @private
  39491. * @type {boolean}
  39492. * @default true
  39493. */
  39494. this._autoAllocateDepthBuffer = true;
  39495. /**
  39496. * Whether this render target is associated with a XRWebGLLayer.
  39497. *
  39498. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  39499. * this means that you don't have access to its bound color,
  39500. * stencil and depth buffers. We need to handle this framebuffer
  39501. * differently since its textures are always bound.
  39502. *
  39503. * @private
  39504. * @type {boolean}
  39505. * @default false
  39506. * */
  39507. this._isOpaqueFramebuffer = false;
  39508. }
  39509. copy( source ) {
  39510. super.copy( source );
  39511. this._hasExternalTextures = source._hasExternalTextures;
  39512. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  39513. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  39514. return this;
  39515. }
  39516. }
  39517. const _cameraLPos = /*@__PURE__*/ new Vector3();
  39518. const _cameraRPos = /*@__PURE__*/ new Vector3();
  39519. /**
  39520. * The XR manager is built on top of the WebXR Device API to
  39521. * manage XR sessions with `WebGPURenderer`.
  39522. *
  39523. * XR is currently only supported with a WebGL 2 backend.
  39524. *
  39525. * @augments EventDispatcher
  39526. */
  39527. class XRManager extends EventDispatcher {
  39528. /**
  39529. * Constructs a new XR manager.
  39530. *
  39531. * @param {Renderer} renderer - The renderer.
  39532. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  39533. */
  39534. constructor( renderer, multiview = false ) {
  39535. super();
  39536. /**
  39537. * This flag globally enables XR rendering.
  39538. *
  39539. * @type {boolean}
  39540. * @default false
  39541. */
  39542. this.enabled = false;
  39543. /**
  39544. * Whether the XR device is currently presenting or not.
  39545. *
  39546. * @type {boolean}
  39547. * @default false
  39548. * @readonly
  39549. */
  39550. this.isPresenting = false;
  39551. /**
  39552. * Whether the XR camera should automatically be updated or not.
  39553. *
  39554. * @type {boolean}
  39555. * @default true
  39556. */
  39557. this.cameraAutoUpdate = true;
  39558. /**
  39559. * The renderer.
  39560. *
  39561. * @private
  39562. * @type {Renderer}
  39563. */
  39564. this._renderer = renderer;
  39565. // camera
  39566. /**
  39567. * Represents the camera for the left eye.
  39568. *
  39569. * @private
  39570. * @type {PerspectiveCamera}
  39571. */
  39572. this._cameraL = new PerspectiveCamera();
  39573. this._cameraL.viewport = new Vector4();
  39574. /**
  39575. * Represents the camera for the right eye.
  39576. *
  39577. * @private
  39578. * @type {PerspectiveCamera}
  39579. */
  39580. this._cameraR = new PerspectiveCamera();
  39581. this._cameraR.viewport = new Vector4();
  39582. /**
  39583. * A list of cameras used for rendering the XR views.
  39584. *
  39585. * @private
  39586. * @type {Array<Camera>}
  39587. */
  39588. this._cameras = [ this._cameraL, this._cameraR ];
  39589. /**
  39590. * The main XR camera.
  39591. *
  39592. * @private
  39593. * @type {ArrayCamera}
  39594. */
  39595. this._cameraXR = new ArrayCamera();
  39596. /**
  39597. * The current near value of the XR camera.
  39598. *
  39599. * @private
  39600. * @type {?number}
  39601. * @default null
  39602. */
  39603. this._currentDepthNear = null;
  39604. /**
  39605. * The current far value of the XR camera.
  39606. *
  39607. * @private
  39608. * @type {?number}
  39609. * @default null
  39610. */
  39611. this._currentDepthFar = null;
  39612. /**
  39613. * A list of WebXR controllers requested by the application.
  39614. *
  39615. * @private
  39616. * @type {Array<WebXRController>}
  39617. */
  39618. this._controllers = [];
  39619. /**
  39620. * A list of XR input source. Each input source belongs to
  39621. * an instance of WebXRController.
  39622. *
  39623. * @private
  39624. * @type {Array<XRInputSource?>}
  39625. */
  39626. this._controllerInputSources = [];
  39627. /**
  39628. * The XR render target that represents the rendering destination
  39629. * during an active XR session.
  39630. *
  39631. * @private
  39632. * @type {?RenderTarget}
  39633. * @default null
  39634. */
  39635. this._xrRenderTarget = null;
  39636. /**
  39637. * An array holding all the non-projection layers
  39638. *
  39639. * @private
  39640. * @type {Array<Object>}
  39641. * @default []
  39642. */
  39643. this._layers = [];
  39644. /**
  39645. * Whether the XR session uses layers.
  39646. *
  39647. * @private
  39648. * @type {boolean}
  39649. * @default false
  39650. */
  39651. this._sessionUsesLayers = false;
  39652. /**
  39653. * Whether the device supports binding gl objects.
  39654. *
  39655. * @private
  39656. * @type {boolean}
  39657. * @readonly
  39658. */
  39659. this._supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  39660. this._frameBufferTargets = null;
  39661. /**
  39662. * Helper function to create native WebXR Layer.
  39663. *
  39664. * @private
  39665. * @type {Function}
  39666. */
  39667. this._createXRLayer = createXRLayer.bind( this );
  39668. /**
  39669. * The current WebGL context.
  39670. *
  39671. * @private
  39672. * @type {?WebGL2RenderingContext}
  39673. * @default null
  39674. */
  39675. this._gl = null;
  39676. /**
  39677. * The current animation context.
  39678. *
  39679. * @private
  39680. * @type {?Window}
  39681. * @default null
  39682. */
  39683. this._currentAnimationContext = null;
  39684. /**
  39685. * The current animation loop.
  39686. *
  39687. * @private
  39688. * @type {?Function}
  39689. * @default null
  39690. */
  39691. this._currentAnimationLoop = null;
  39692. /**
  39693. * The current pixel ratio.
  39694. *
  39695. * @private
  39696. * @type {?number}
  39697. * @default null
  39698. */
  39699. this._currentPixelRatio = null;
  39700. /**
  39701. * The current size of the renderer's canvas
  39702. * in logical pixel unit.
  39703. *
  39704. * @private
  39705. * @type {Vector2}
  39706. */
  39707. this._currentSize = new Vector2();
  39708. /**
  39709. * The default event listener for handling events inside a XR session.
  39710. *
  39711. * @private
  39712. * @type {Function}
  39713. */
  39714. this._onSessionEvent = onSessionEvent.bind( this );
  39715. /**
  39716. * The event listener for handling the end of a XR session.
  39717. *
  39718. * @private
  39719. * @type {Function}
  39720. */
  39721. this._onSessionEnd = onSessionEnd.bind( this );
  39722. /**
  39723. * The event listener for handling the `inputsourceschange` event.
  39724. *
  39725. * @private
  39726. * @type {Function}
  39727. */
  39728. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  39729. /**
  39730. * The animation loop which is used as a replacement for the default
  39731. * animation loop of the application. It is only used when a XR session
  39732. * is active.
  39733. *
  39734. * @private
  39735. * @type {Function}
  39736. */
  39737. this._onAnimationFrame = onAnimationFrame.bind( this );
  39738. /**
  39739. * The current XR reference space.
  39740. *
  39741. * @private
  39742. * @type {?XRReferenceSpace}
  39743. * @default null
  39744. */
  39745. this._referenceSpace = null;
  39746. /**
  39747. * The current XR reference space type.
  39748. *
  39749. * @private
  39750. * @type {XRReferenceSpaceType}
  39751. * @default 'local-floor'
  39752. */
  39753. this._referenceSpaceType = 'local-floor';
  39754. /**
  39755. * A custom reference space defined by the application.
  39756. *
  39757. * @private
  39758. * @type {?XRReferenceSpace}
  39759. * @default null
  39760. */
  39761. this._customReferenceSpace = null;
  39762. /**
  39763. * The framebuffer scale factor.
  39764. *
  39765. * @private
  39766. * @type {number}
  39767. * @default 1
  39768. */
  39769. this._framebufferScaleFactor = 1;
  39770. /**
  39771. * The foveation factor.
  39772. *
  39773. * @private
  39774. * @type {number}
  39775. * @default 1
  39776. */
  39777. this._foveation = 1.0;
  39778. /**
  39779. * A reference to the current XR session.
  39780. *
  39781. * @private
  39782. * @type {?XRSession}
  39783. * @default null
  39784. */
  39785. this._session = null;
  39786. /**
  39787. * A reference to the current XR base layer.
  39788. *
  39789. * @private
  39790. * @type {?XRWebGLLayer}
  39791. * @default null
  39792. */
  39793. this._glBaseLayer = null;
  39794. /**
  39795. * A reference to the current XR binding.
  39796. *
  39797. * @private
  39798. * @type {?XRWebGLBinding}
  39799. * @default null
  39800. */
  39801. this._glBinding = null;
  39802. /**
  39803. * A reference to the current XR projection layer.
  39804. *
  39805. * @private
  39806. * @type {?XRProjectionLayer}
  39807. * @default null
  39808. */
  39809. this._glProjLayer = null;
  39810. /**
  39811. * A reference to the current XR frame.
  39812. *
  39813. * @private
  39814. * @type {?XRFrame}
  39815. * @default null
  39816. */
  39817. this._xrFrame = null;
  39818. /**
  39819. * Whether the browser supports the APIs necessary to use XRProjectionLayers.
  39820. *
  39821. * Note: this does not represent XRSession explicitly requesting
  39822. * `'layers'` as a feature - see `_sessionUsesLayers` and #30112
  39823. *
  39824. * @private
  39825. * @type {boolean}
  39826. * @readonly
  39827. */
  39828. this._supportsLayers = ( this._supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  39829. /**
  39830. * Whether the usage of multiview has been requested by the application or not.
  39831. *
  39832. * @private
  39833. * @type {boolean}
  39834. * @default false
  39835. * @readonly
  39836. */
  39837. this._useMultiviewIfPossible = multiview;
  39838. /**
  39839. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  39840. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  39841. *
  39842. * @private
  39843. * @type {boolean}
  39844. * @readonly
  39845. */
  39846. this._useMultiview = false;
  39847. }
  39848. /**
  39849. * Returns an instance of `THREE.Group` that represents the transformation
  39850. * of a XR controller in target ray space. The requested controller is defined
  39851. * by the given index.
  39852. *
  39853. * @param {number} index - The index of the XR controller.
  39854. * @return {Group} A group that represents the controller's transformation.
  39855. */
  39856. getController( index ) {
  39857. const controller = this._getController( index );
  39858. return controller.getTargetRaySpace();
  39859. }
  39860. /**
  39861. * Returns an instance of `THREE.Group` that represents the transformation
  39862. * of a XR controller in grip space. The requested controller is defined
  39863. * by the given index.
  39864. *
  39865. * @param {number} index - The index of the XR controller.
  39866. * @return {Group} A group that represents the controller's transformation.
  39867. */
  39868. getControllerGrip( index ) {
  39869. const controller = this._getController( index );
  39870. return controller.getGripSpace();
  39871. }
  39872. /**
  39873. * Returns an instance of `THREE.Group` that represents the transformation
  39874. * of a XR controller in hand space. The requested controller is defined
  39875. * by the given index.
  39876. *
  39877. * @param {number} index - The index of the XR controller.
  39878. * @return {Group} A group that represents the controller's transformation.
  39879. */
  39880. getHand( index ) {
  39881. const controller = this._getController( index );
  39882. return controller.getHandSpace();
  39883. }
  39884. /**
  39885. * Returns the foveation value.
  39886. *
  39887. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  39888. */
  39889. getFoveation() {
  39890. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  39891. return undefined;
  39892. }
  39893. return this._foveation;
  39894. }
  39895. /**
  39896. * Sets the foveation value.
  39897. *
  39898. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  39899. * and `1` means maximum foveation (the edges render at lower resolution).
  39900. */
  39901. setFoveation( foveation ) {
  39902. this._foveation = foveation;
  39903. if ( this._glProjLayer !== null ) {
  39904. this._glProjLayer.fixedFoveation = foveation;
  39905. }
  39906. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  39907. this._glBaseLayer.fixedFoveation = foveation;
  39908. }
  39909. }
  39910. /**
  39911. * Returns the framebuffer scale factor.
  39912. *
  39913. * @return {number} The framebuffer scale factor.
  39914. */
  39915. getFramebufferScaleFactor() {
  39916. return this._framebufferScaleFactor;
  39917. }
  39918. /**
  39919. * Sets the framebuffer scale factor.
  39920. *
  39921. * This method can not be used during a XR session.
  39922. *
  39923. * @param {number} factor - The framebuffer scale factor.
  39924. */
  39925. setFramebufferScaleFactor( factor ) {
  39926. this._framebufferScaleFactor = factor;
  39927. if ( this.isPresenting === true ) {
  39928. warn( 'XRManager: Cannot change framebuffer scale while presenting.' );
  39929. }
  39930. }
  39931. /**
  39932. * Returns the reference space type.
  39933. *
  39934. * @return {XRReferenceSpaceType} The reference space type.
  39935. */
  39936. getReferenceSpaceType() {
  39937. return this._referenceSpaceType;
  39938. }
  39939. /**
  39940. * Sets the reference space type.
  39941. *
  39942. * This method can not be used during a XR session.
  39943. *
  39944. * @param {XRReferenceSpaceType} type - The reference space type.
  39945. */
  39946. setReferenceSpaceType( type ) {
  39947. this._referenceSpaceType = type;
  39948. if ( this.isPresenting === true ) {
  39949. warn( 'XRManager: Cannot change reference space type while presenting.' );
  39950. }
  39951. }
  39952. /**
  39953. * Returns the XR reference space.
  39954. *
  39955. * @return {XRReferenceSpace} The XR reference space.
  39956. */
  39957. getReferenceSpace() {
  39958. return this._customReferenceSpace || this._referenceSpace;
  39959. }
  39960. /**
  39961. * Sets a custom XR reference space.
  39962. *
  39963. * @param {XRReferenceSpace} space - The XR reference space.
  39964. */
  39965. setReferenceSpace( space ) {
  39966. this._customReferenceSpace = space;
  39967. }
  39968. /**
  39969. * Returns the XR camera.
  39970. *
  39971. * @return {ArrayCamera} The XR camera.
  39972. */
  39973. getCamera() {
  39974. return this._cameraXR;
  39975. }
  39976. /**
  39977. * Returns the environment blend mode from the current XR session.
  39978. *
  39979. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  39980. */
  39981. getEnvironmentBlendMode() {
  39982. if ( this._session !== null ) {
  39983. return this._session.environmentBlendMode;
  39984. }
  39985. }
  39986. /**
  39987. * Returns the current XR binding.
  39988. *
  39989. * Creates a new binding if needed and the browser is
  39990. * capable of doing so.
  39991. *
  39992. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  39993. */
  39994. getBinding() {
  39995. if ( this._glBinding === null && this._supportsGlBinding ) {
  39996. this._glBinding = new XRWebGLBinding( this._session, this._gl );
  39997. }
  39998. return this._glBinding;
  39999. }
  40000. /**
  40001. * Returns the current XR frame.
  40002. *
  40003. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  40004. */
  40005. getFrame() {
  40006. return this._xrFrame;
  40007. }
  40008. /**
  40009. * Returns `true` if the engine renders to a multiview target.
  40010. *
  40011. * @return {boolean} Whether the engine renders to a multiview render target or not.
  40012. */
  40013. useMultiview() {
  40014. return this._useMultiview;
  40015. }
  40016. /**
  40017. * This method can be used in XR applications to create a quadratic layer that presents a separate
  40018. * rendered scene.
  40019. *
  40020. * @param {number} width - The width of the layer plane in world units.
  40021. * @param {number} height - The height of the layer plane in world units.
  40022. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  40023. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  40024. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  40025. * @param {number} pixelheight - The height of the layer's render target in pixels.
  40026. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  40027. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  40028. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  40029. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  40030. */
  40031. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  40032. const geometry = new PlaneGeometry( width, height );
  40033. const renderTarget = new XRRenderTarget(
  40034. pixelwidth,
  40035. pixelheight,
  40036. {
  40037. format: RGBAFormat,
  40038. type: UnsignedByteType,
  40039. depthTexture: new DepthTexture(
  40040. pixelwidth,
  40041. pixelheight,
  40042. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  40043. undefined,
  40044. undefined,
  40045. undefined,
  40046. undefined,
  40047. undefined,
  40048. undefined,
  40049. attributes.stencil ? DepthStencilFormat : DepthFormat
  40050. ),
  40051. stencilBuffer: attributes.stencil,
  40052. resolveDepthBuffer: false,
  40053. resolveStencilBuffer: false
  40054. } );
  40055. renderTarget._autoAllocateDepthBuffer = true;
  40056. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  40057. material.map = renderTarget.texture;
  40058. material.map.offset.y = 1;
  40059. material.map.repeat.y = -1;
  40060. const plane = new Mesh( geometry, material );
  40061. plane.position.copy( translation );
  40062. plane.quaternion.copy( quaternion );
  40063. const layer = {
  40064. type: 'quad',
  40065. width: width,
  40066. height: height,
  40067. translation: translation,
  40068. quaternion: quaternion,
  40069. pixelwidth: pixelwidth,
  40070. pixelheight: pixelheight,
  40071. plane: plane,
  40072. material: material,
  40073. rendercall: rendercall,
  40074. renderTarget: renderTarget };
  40075. this._layers.push( layer );
  40076. if ( this._session !== null ) {
  40077. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  40078. layer.plane.material.blending = CustomBlending;
  40079. layer.plane.material.blendEquation = AddEquation;
  40080. layer.plane.material.blendSrc = ZeroFactor;
  40081. layer.plane.material.blendDst = ZeroFactor;
  40082. layer.xrlayer = this._createXRLayer( layer );
  40083. const xrlayers = this._session.renderState.layers;
  40084. xrlayers.unshift( layer.xrlayer );
  40085. this._session.updateRenderState( { layers: xrlayers } );
  40086. } else {
  40087. renderTarget.isXRRenderTarget = false;
  40088. }
  40089. return plane;
  40090. }
  40091. /**
  40092. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  40093. * rendered scene.
  40094. *
  40095. * @param {number} radius - The radius of the cylinder in world units.
  40096. * @param {number} centralAngle - The central angle of the cylinder in radians.
  40097. * @param {number} aspectratio - The aspect ratio.
  40098. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  40099. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  40100. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  40101. * @param {number} pixelheight - The height of the layer's render target in pixels.
  40102. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  40103. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  40104. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  40105. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  40106. */
  40107. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  40108. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  40109. const renderTarget = new XRRenderTarget(
  40110. pixelwidth,
  40111. pixelheight,
  40112. {
  40113. format: RGBAFormat,
  40114. type: UnsignedByteType,
  40115. depthTexture: new DepthTexture(
  40116. pixelwidth,
  40117. pixelheight,
  40118. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  40119. undefined,
  40120. undefined,
  40121. undefined,
  40122. undefined,
  40123. undefined,
  40124. undefined,
  40125. attributes.stencil ? DepthStencilFormat : DepthFormat
  40126. ),
  40127. stencilBuffer: attributes.stencil,
  40128. resolveDepthBuffer: false,
  40129. resolveStencilBuffer: false
  40130. } );
  40131. renderTarget._autoAllocateDepthBuffer = true;
  40132. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  40133. material.map = renderTarget.texture;
  40134. material.map.offset.y = 1;
  40135. material.map.repeat.y = -1;
  40136. const plane = new Mesh( geometry, material );
  40137. plane.position.copy( translation );
  40138. plane.quaternion.copy( quaternion );
  40139. const layer = {
  40140. type: 'cylinder',
  40141. radius: radius,
  40142. centralAngle: centralAngle,
  40143. aspectratio: aspectratio,
  40144. translation: translation,
  40145. quaternion: quaternion,
  40146. pixelwidth: pixelwidth,
  40147. pixelheight: pixelheight,
  40148. plane: plane,
  40149. material: material,
  40150. rendercall: rendercall,
  40151. renderTarget: renderTarget };
  40152. this._layers.push( layer );
  40153. if ( this._session !== null ) {
  40154. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  40155. layer.plane.material.blending = CustomBlending;
  40156. layer.plane.material.blendEquation = AddEquation;
  40157. layer.plane.material.blendSrc = ZeroFactor;
  40158. layer.plane.material.blendDst = ZeroFactor;
  40159. layer.xrlayer = this._createXRLayer( layer );
  40160. const xrlayers = this._session.renderState.layers;
  40161. xrlayers.unshift( layer.xrlayer );
  40162. this._session.updateRenderState( { layers: xrlayers } );
  40163. } else {
  40164. renderTarget.isXRRenderTarget = false;
  40165. }
  40166. return plane;
  40167. }
  40168. /**
  40169. * Renders the XR layers that have been previously added to the scene.
  40170. *
  40171. * This method is usually called in your animation loop before rendering
  40172. * the actual scene via `renderer.render( scene, camera );`.
  40173. */
  40174. renderLayers( ) {
  40175. const translationObject = new Vector3();
  40176. const quaternionObject = new Quaternion();
  40177. const renderer = this._renderer;
  40178. const wasPresenting = this.isPresenting;
  40179. const rendererOutputTarget = renderer.getOutputRenderTarget();
  40180. const rendererFramebufferTarget = renderer._frameBufferTarget;
  40181. this.isPresenting = false;
  40182. const rendererSize = new Vector2();
  40183. renderer.getSize( rendererSize );
  40184. const rendererQuad = renderer._quad;
  40185. for ( const layer of this._layers ) {
  40186. layer.renderTarget.isXRRenderTarget = this._session !== null;
  40187. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  40188. if ( layer.renderTarget.isXRRenderTarget && this._sessionUsesLayers ) {
  40189. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  40190. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  40191. renderer.backend.setXRRenderTargetTextures(
  40192. layer.renderTarget,
  40193. glSubImage.colorTexture,
  40194. undefined );
  40195. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  40196. renderer.setOutputRenderTarget( layer.renderTarget );
  40197. renderer.setRenderTarget( null );
  40198. renderer._frameBufferTarget = null;
  40199. this._frameBufferTargets || ( this._frameBufferTargets = new WeakMap() );
  40200. const { frameBufferTarget, quad } = this._frameBufferTargets.get( layer.renderTarget ) || { frameBufferTarget: null, quad: null };
  40201. if ( ! frameBufferTarget ) {
  40202. renderer._quad = new QuadMesh( new NodeMaterial() );
  40203. this._frameBufferTargets.set( layer.renderTarget, { frameBufferTarget: renderer._getFrameBufferTarget(), quad: renderer._quad } );
  40204. } else {
  40205. renderer._frameBufferTarget = frameBufferTarget;
  40206. renderer._quad = quad;
  40207. }
  40208. layer.rendercall();
  40209. renderer._frameBufferTarget = null;
  40210. } else {
  40211. renderer.setRenderTarget( layer.renderTarget );
  40212. layer.rendercall();
  40213. }
  40214. }
  40215. renderer.setRenderTarget( null );
  40216. renderer.setOutputRenderTarget( rendererOutputTarget );
  40217. renderer._frameBufferTarget = rendererFramebufferTarget;
  40218. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  40219. renderer._quad = rendererQuad;
  40220. this.isPresenting = wasPresenting;
  40221. }
  40222. /**
  40223. * Returns the current XR session.
  40224. *
  40225. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  40226. */
  40227. getSession() {
  40228. return this._session;
  40229. }
  40230. /**
  40231. * After a XR session has been requested usually with one of the `*Button` modules, it
  40232. * is injected into the renderer with this method. This method triggers the start of
  40233. * the actual XR rendering.
  40234. *
  40235. * @async
  40236. * @param {XRSession} session - The XR session to set.
  40237. * @return {Promise} A Promise that resolves when the session has been set.
  40238. */
  40239. async setSession( session ) {
  40240. const renderer = this._renderer;
  40241. const backend = renderer.backend;
  40242. this._gl = renderer.getContext();
  40243. const gl = this._gl;
  40244. const attributes = gl.getContextAttributes();
  40245. this._session = session;
  40246. if ( session !== null ) {
  40247. 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.' );
  40248. session.addEventListener( 'select', this._onSessionEvent );
  40249. session.addEventListener( 'selectstart', this._onSessionEvent );
  40250. session.addEventListener( 'selectend', this._onSessionEvent );
  40251. session.addEventListener( 'squeeze', this._onSessionEvent );
  40252. session.addEventListener( 'squeezestart', this._onSessionEvent );
  40253. session.addEventListener( 'squeezeend', this._onSessionEvent );
  40254. session.addEventListener( 'end', this._onSessionEnd );
  40255. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  40256. await backend.makeXRCompatible();
  40257. this._currentPixelRatio = renderer.getPixelRatio();
  40258. renderer.getSize( this._currentSize );
  40259. this._currentAnimationContext = renderer._animation.getContext();
  40260. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  40261. renderer._animation.stop();
  40262. //
  40263. if ( this._supportsLayers === true ) {
  40264. // default path using XRProjectionLayer
  40265. let depthFormat = null;
  40266. let depthType = null;
  40267. let glDepthFormat = null;
  40268. if ( renderer.depth ) {
  40269. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  40270. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  40271. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  40272. }
  40273. const projectionlayerInit = {
  40274. colorFormat: gl.RGBA8,
  40275. depthFormat: glDepthFormat,
  40276. scaleFactor: this._framebufferScaleFactor,
  40277. clearOnAccess: false
  40278. };
  40279. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  40280. projectionlayerInit.textureType = 'texture-array';
  40281. this._useMultiview = true;
  40282. }
  40283. this._glBinding = this.getBinding();
  40284. const glProjLayer = this._glBinding.createProjectionLayer( projectionlayerInit );
  40285. const layersArray = [ glProjLayer ];
  40286. this._glProjLayer = glProjLayer;
  40287. renderer.setPixelRatio( 1 );
  40288. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  40289. const depth = this._useMultiview ? 2 : 1;
  40290. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  40291. this._xrRenderTarget = new XRRenderTarget(
  40292. glProjLayer.textureWidth,
  40293. glProjLayer.textureHeight,
  40294. {
  40295. format: RGBAFormat,
  40296. type: UnsignedByteType,
  40297. colorSpace: renderer.outputColorSpace,
  40298. depthTexture: depthTexture,
  40299. stencilBuffer: renderer.stencil,
  40300. samples: attributes.antialias ? 4 : 0,
  40301. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  40302. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  40303. depth: this._useMultiview ? 2 : 1,
  40304. multiview: this._useMultiview
  40305. } );
  40306. this._xrRenderTarget._hasExternalTextures = true;
  40307. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  40308. this._sessionUsesLayers = session.enabledFeatures.includes( 'layers' );
  40309. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  40310. if ( this._sessionUsesLayers ) {
  40311. // switch layers to native
  40312. for ( const layer of this._layers ) {
  40313. // change material so it "punches" out a hole to show the XR Layer.
  40314. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  40315. layer.plane.material.blending = CustomBlending;
  40316. layer.plane.material.blendEquation = AddEquation;
  40317. layer.plane.material.blendSrc = ZeroFactor;
  40318. layer.plane.material.blendDst = ZeroFactor;
  40319. layer.xrlayer = this._createXRLayer( layer );
  40320. layersArray.unshift( layer.xrlayer );
  40321. }
  40322. }
  40323. session.updateRenderState( { layers: layersArray } );
  40324. } else {
  40325. // fallback to XRWebGLLayer
  40326. const layerInit = {
  40327. antialias: renderer.currentSamples > 0,
  40328. alpha: true,
  40329. depth: renderer.depth,
  40330. stencil: renderer.stencil,
  40331. framebufferScaleFactor: this.getFramebufferScaleFactor()
  40332. };
  40333. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  40334. this._glBaseLayer = glBaseLayer;
  40335. session.updateRenderState( { baseLayer: glBaseLayer } );
  40336. renderer.setPixelRatio( 1 );
  40337. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  40338. this._xrRenderTarget = new XRRenderTarget(
  40339. glBaseLayer.framebufferWidth,
  40340. glBaseLayer.framebufferHeight,
  40341. {
  40342. format: RGBAFormat,
  40343. type: UnsignedByteType,
  40344. colorSpace: renderer.outputColorSpace,
  40345. stencilBuffer: renderer.stencil,
  40346. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  40347. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  40348. }
  40349. );
  40350. this._xrRenderTarget._isOpaqueFramebuffer = true;
  40351. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  40352. }
  40353. //
  40354. this.setFoveation( this.getFoveation() );
  40355. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  40356. renderer._animation.setContext( session );
  40357. renderer._animation.start();
  40358. this.isPresenting = true;
  40359. this.dispatchEvent( { type: 'sessionstart' } );
  40360. }
  40361. }
  40362. /**
  40363. * This method is called by the renderer per frame and updates the XR camera
  40364. * and it sub cameras based on the given camera. The given camera is the "user"
  40365. * camera created on application level and used for non-XR rendering.
  40366. *
  40367. * @param {PerspectiveCamera} camera - The camera.
  40368. */
  40369. updateCamera( camera ) {
  40370. const session = this._session;
  40371. if ( session === null ) return;
  40372. const depthNear = camera.near;
  40373. const depthFar = camera.far;
  40374. const cameraXR = this._cameraXR;
  40375. const cameraL = this._cameraL;
  40376. const cameraR = this._cameraR;
  40377. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  40378. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  40379. cameraXR.isMultiViewCamera = this._useMultiview;
  40380. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  40381. // Note that the new renderState won't apply until the next frame. See #18320
  40382. session.updateRenderState( {
  40383. depthNear: cameraXR.near,
  40384. depthFar: cameraXR.far
  40385. } );
  40386. this._currentDepthNear = cameraXR.near;
  40387. this._currentDepthFar = cameraXR.far;
  40388. }
  40389. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  40390. cameraXR.layers.mask = camera.layers.mask | 0b110;
  40391. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  40392. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  40393. const parent = camera.parent;
  40394. const cameras = cameraXR.cameras;
  40395. updateCamera( cameraXR, parent );
  40396. for ( let i = 0; i < cameras.length; i ++ ) {
  40397. updateCamera( cameras[ i ], parent );
  40398. }
  40399. // update projection matrix for proper view frustum culling
  40400. if ( cameras.length === 2 ) {
  40401. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  40402. } else {
  40403. // assume single camera setup (AR)
  40404. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  40405. }
  40406. // update user camera and its children
  40407. updateUserCamera( camera, cameraXR, parent );
  40408. }
  40409. /**
  40410. * Returns a WebXR controller for the given controller index.
  40411. *
  40412. * @private
  40413. * @param {number} index - The controller index.
  40414. * @return {WebXRController} The XR controller.
  40415. */
  40416. _getController( index ) {
  40417. let controller = this._controllers[ index ];
  40418. if ( controller === undefined ) {
  40419. controller = new WebXRController();
  40420. this._controllers[ index ] = controller;
  40421. }
  40422. return controller;
  40423. }
  40424. }
  40425. /**
  40426. * Assumes 2 cameras that are parallel and share an X-axis, and that
  40427. * the cameras' projection and world matrices have already been set.
  40428. * And that near and far planes are identical for both cameras.
  40429. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  40430. *
  40431. * @param {ArrayCamera} camera - The camera to update.
  40432. * @param {PerspectiveCamera} cameraL - The left camera.
  40433. * @param {PerspectiveCamera} cameraR - The right camera.
  40434. */
  40435. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  40436. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  40437. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  40438. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  40439. const projL = cameraL.projectionMatrix.elements;
  40440. const projR = cameraR.projectionMatrix.elements;
  40441. // VR systems will have identical far and near planes, and
  40442. // most likely identical top and bottom frustum extents.
  40443. // Use the left camera for these values.
  40444. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  40445. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  40446. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  40447. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  40448. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  40449. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  40450. const left = near * leftFov;
  40451. const right = near * rightFov;
  40452. // Calculate the new camera's position offset from the
  40453. // left camera. xOffset should be roughly half `ipd`.
  40454. const zOffset = ipd / ( - leftFov + rightFov );
  40455. const xOffset = zOffset * - leftFov;
  40456. // TODO: Better way to apply this offset?
  40457. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  40458. camera.translateX( xOffset );
  40459. camera.translateZ( zOffset );
  40460. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  40461. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  40462. // Check if the projection uses an infinite far plane.
  40463. if ( projL[ 10 ] === -1 ) {
  40464. // Use the projection matrix from the left eye.
  40465. // The camera offset is sufficient to include the view volumes
  40466. // of both eyes (assuming symmetric projections).
  40467. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  40468. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  40469. } else {
  40470. // Find the union of the frustum values of the cameras and scale
  40471. // the values so that the near plane's position does not change in world space,
  40472. // although must now be relative to the new union camera.
  40473. const near2 = near + zOffset;
  40474. const far2 = far + zOffset;
  40475. const left2 = left - xOffset;
  40476. const right2 = right + ( ipd - xOffset );
  40477. const top2 = topFov * far / far2 * near2;
  40478. const bottom2 = bottomFov * far / far2 * near2;
  40479. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  40480. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  40481. }
  40482. }
  40483. /**
  40484. * Updates the world matrices for the given camera based on the parent 3D object.
  40485. *
  40486. * @inner
  40487. * @param {Camera} camera - The camera to update.
  40488. * @param {Object3D} parent - The parent 3D object.
  40489. */
  40490. function updateCamera( camera, parent ) {
  40491. if ( parent === null ) {
  40492. camera.matrixWorld.copy( camera.matrix );
  40493. } else {
  40494. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  40495. }
  40496. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  40497. }
  40498. /**
  40499. * Updates the given camera with the transformation of the XR camera and parent object.
  40500. *
  40501. * @inner
  40502. * @param {Camera} camera - The camera to update.
  40503. * @param {ArrayCamera} cameraXR - The XR camera.
  40504. * @param {Object3D} parent - The parent 3D object.
  40505. */
  40506. function updateUserCamera( camera, cameraXR, parent ) {
  40507. if ( parent === null ) {
  40508. camera.matrix.copy( cameraXR.matrixWorld );
  40509. } else {
  40510. camera.matrix.copy( parent.matrixWorld );
  40511. camera.matrix.invert();
  40512. camera.matrix.multiply( cameraXR.matrixWorld );
  40513. }
  40514. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  40515. camera.updateMatrixWorld( true );
  40516. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  40517. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  40518. if ( camera.isPerspectiveCamera ) {
  40519. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  40520. camera.zoom = 1;
  40521. }
  40522. }
  40523. function onSessionEvent( event ) {
  40524. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  40525. if ( controllerIndex === -1 ) {
  40526. return;
  40527. }
  40528. const controller = this._controllers[ controllerIndex ];
  40529. if ( controller !== undefined ) {
  40530. const referenceSpace = this.getReferenceSpace();
  40531. controller.update( event.inputSource, event.frame, referenceSpace );
  40532. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  40533. }
  40534. }
  40535. function onSessionEnd() {
  40536. const session = this._session;
  40537. const renderer = this._renderer;
  40538. session.removeEventListener( 'select', this._onSessionEvent );
  40539. session.removeEventListener( 'selectstart', this._onSessionEvent );
  40540. session.removeEventListener( 'selectend', this._onSessionEvent );
  40541. session.removeEventListener( 'squeeze', this._onSessionEvent );
  40542. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  40543. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  40544. session.removeEventListener( 'end', this._onSessionEnd );
  40545. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  40546. for ( let i = 0; i < this._controllers.length; i ++ ) {
  40547. const inputSource = this._controllerInputSources[ i ];
  40548. if ( inputSource === null ) continue;
  40549. this._controllerInputSources[ i ] = null;
  40550. this._controllers[ i ].disconnect( inputSource );
  40551. }
  40552. this._currentDepthNear = null;
  40553. this._currentDepthFar = null;
  40554. // restore framebuffer/rendering state
  40555. renderer._resetXRState();
  40556. this._session = null;
  40557. this._xrRenderTarget = null;
  40558. this._glBinding = null;
  40559. this._glBaseLayer = null;
  40560. this._glProjLayer = null;
  40561. // switch layers back to emulated
  40562. if ( this._sessionUsesLayers === true ) {
  40563. for ( const layer of this._layers ) {
  40564. // Recreate layer render target to reset state
  40565. layer.renderTarget = new XRRenderTarget(
  40566. layer.pixelwidth,
  40567. layer.pixelheight,
  40568. {
  40569. format: RGBAFormat,
  40570. type: UnsignedByteType,
  40571. depthTexture: new DepthTexture(
  40572. layer.pixelwidth,
  40573. layer.pixelheight,
  40574. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  40575. undefined,
  40576. undefined,
  40577. undefined,
  40578. undefined,
  40579. undefined,
  40580. undefined,
  40581. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  40582. ),
  40583. stencilBuffer: layer.stencilBuffer,
  40584. resolveDepthBuffer: false,
  40585. resolveStencilBuffer: false
  40586. } );
  40587. layer.renderTarget.isXRRenderTarget = false;
  40588. layer.plane.material = layer.material;
  40589. layer.material.map = layer.renderTarget.texture;
  40590. layer.material.map.offset.y = 1;
  40591. layer.material.map.repeat.y = -1;
  40592. delete layer.xrlayer;
  40593. }
  40594. }
  40595. //
  40596. this.isPresenting = false;
  40597. this._useMultiview = false;
  40598. renderer._animation.stop();
  40599. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  40600. renderer._animation.setContext( this._currentAnimationContext );
  40601. renderer._animation.start();
  40602. renderer.setPixelRatio( this._currentPixelRatio );
  40603. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  40604. this.dispatchEvent( { type: 'sessionend' } );
  40605. }
  40606. function onInputSourcesChange( event ) {
  40607. const controllers = this._controllers;
  40608. const controllerInputSources = this._controllerInputSources;
  40609. // Notify disconnected
  40610. for ( let i = 0; i < event.removed.length; i ++ ) {
  40611. const inputSource = event.removed[ i ];
  40612. const index = controllerInputSources.indexOf( inputSource );
  40613. if ( index >= 0 ) {
  40614. controllerInputSources[ index ] = null;
  40615. controllers[ index ].disconnect( inputSource );
  40616. }
  40617. }
  40618. // Notify connected
  40619. for ( let i = 0; i < event.added.length; i ++ ) {
  40620. const inputSource = event.added[ i ];
  40621. let controllerIndex = controllerInputSources.indexOf( inputSource );
  40622. if ( controllerIndex === -1 ) {
  40623. // Assign input source a controller that currently has no input source
  40624. for ( let i = 0; i < controllers.length; i ++ ) {
  40625. if ( i >= controllerInputSources.length ) {
  40626. controllerInputSources.push( inputSource );
  40627. controllerIndex = i;
  40628. break;
  40629. } else if ( controllerInputSources[ i ] === null ) {
  40630. controllerInputSources[ i ] = inputSource;
  40631. controllerIndex = i;
  40632. break;
  40633. }
  40634. }
  40635. // If all controllers do currently receive input we ignore new ones
  40636. if ( controllerIndex === -1 ) break;
  40637. }
  40638. const controller = controllers[ controllerIndex ];
  40639. if ( controller ) {
  40640. controller.connect( inputSource );
  40641. }
  40642. }
  40643. }
  40644. // Creation method for native WebXR layers
  40645. function createXRLayer( layer ) {
  40646. if ( layer.type === 'quad' ) {
  40647. return this._glBinding.createQuadLayer( {
  40648. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  40649. width: layer.width / 2,
  40650. height: layer.height / 2,
  40651. space: this._referenceSpace,
  40652. viewPixelWidth: layer.pixelwidth,
  40653. viewPixelHeight: layer.pixelheight,
  40654. clearOnAccess: false
  40655. } );
  40656. } else {
  40657. return this._glBinding.createCylinderLayer( {
  40658. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  40659. radius: layer.radius,
  40660. centralAngle: layer.centralAngle,
  40661. aspectRatio: layer.aspectRatio,
  40662. space: this._referenceSpace,
  40663. viewPixelWidth: layer.pixelwidth,
  40664. viewPixelHeight: layer.pixelheight,
  40665. clearOnAccess: false
  40666. } );
  40667. }
  40668. }
  40669. // Animation Loop
  40670. function onAnimationFrame( time, frame ) {
  40671. if ( frame === undefined ) return;
  40672. const cameraXR = this._cameraXR;
  40673. const renderer = this._renderer;
  40674. const backend = renderer.backend;
  40675. const glBaseLayer = this._glBaseLayer;
  40676. const referenceSpace = this.getReferenceSpace();
  40677. const pose = frame.getViewerPose( referenceSpace );
  40678. this._xrFrame = frame;
  40679. if ( pose !== null ) {
  40680. const views = pose.views;
  40681. if ( this._glBaseLayer !== null ) {
  40682. backend.setXRTarget( glBaseLayer.framebuffer );
  40683. }
  40684. let cameraXRNeedsUpdate = false;
  40685. // check if it's necessary to rebuild cameraXR's camera list
  40686. if ( views.length !== cameraXR.cameras.length ) {
  40687. cameraXR.cameras.length = 0;
  40688. cameraXRNeedsUpdate = true;
  40689. }
  40690. for ( let i = 0; i < views.length; i ++ ) {
  40691. const view = views[ i ];
  40692. let viewport;
  40693. if ( this._supportsLayers === true ) {
  40694. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  40695. viewport = glSubImage.viewport;
  40696. // For side-by-side projection, we only produce a single texture for both eyes.
  40697. if ( i === 0 ) {
  40698. backend.setXRRenderTargetTextures(
  40699. this._xrRenderTarget,
  40700. glSubImage.colorTexture,
  40701. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  40702. );
  40703. }
  40704. } else {
  40705. viewport = glBaseLayer.getViewport( view );
  40706. }
  40707. let camera = this._cameras[ i ];
  40708. if ( camera === undefined ) {
  40709. camera = new PerspectiveCamera();
  40710. camera.layers.enable( i );
  40711. camera.viewport = new Vector4();
  40712. this._cameras[ i ] = camera;
  40713. }
  40714. camera.matrix.fromArray( view.transform.matrix );
  40715. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  40716. camera.projectionMatrix.fromArray( view.projectionMatrix );
  40717. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  40718. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  40719. if ( i === 0 ) {
  40720. cameraXR.matrix.copy( camera.matrix );
  40721. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  40722. }
  40723. if ( cameraXRNeedsUpdate === true ) {
  40724. cameraXR.cameras.push( camera );
  40725. }
  40726. }
  40727. renderer.setOutputRenderTarget( this._xrRenderTarget );
  40728. }
  40729. //
  40730. for ( let i = 0; i < this._controllers.length; i ++ ) {
  40731. const inputSource = this._controllerInputSources[ i ];
  40732. const controller = this._controllers[ i ];
  40733. if ( inputSource !== null && controller !== undefined ) {
  40734. controller.update( inputSource, frame, referenceSpace );
  40735. }
  40736. }
  40737. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  40738. if ( frame.detectedPlanes ) {
  40739. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  40740. }
  40741. this._xrFrame = null;
  40742. }
  40743. /**
  40744. * CanvasTarget is a class that represents the final output destination of the renderer.
  40745. *
  40746. * @augments EventDispatcher
  40747. */
  40748. class CanvasTarget extends EventDispatcher {
  40749. /**
  40750. * Constructs a new CanvasTarget.
  40751. *
  40752. * @param {HTMLCanvasElement|OffscreenCanvas} domElement - The canvas element to render to.
  40753. */
  40754. constructor( domElement ) {
  40755. super();
  40756. /**
  40757. * A reference to the canvas element the renderer is drawing to.
  40758. * This value of this property will automatically be created by
  40759. * the renderer.
  40760. *
  40761. * @type {HTMLCanvasElement|OffscreenCanvas}
  40762. */
  40763. this.domElement = domElement;
  40764. /**
  40765. * The renderer's pixel ratio.
  40766. *
  40767. * @private
  40768. * @type {number}
  40769. * @default 1
  40770. */
  40771. this._pixelRatio = 1;
  40772. /**
  40773. * The width of the renderer's default framebuffer in logical pixel unit.
  40774. *
  40775. * @private
  40776. * @type {number}
  40777. */
  40778. this._width = this.domElement.width;
  40779. /**
  40780. * The height of the renderer's default framebuffer in logical pixel unit.
  40781. *
  40782. * @private
  40783. * @type {number}
  40784. */
  40785. this._height = this.domElement.height;
  40786. /**
  40787. * The viewport of the renderer in logical pixel unit.
  40788. *
  40789. * @private
  40790. * @type {Vector4}
  40791. */
  40792. this._viewport = new Vector4( 0, 0, this._width, this._height );
  40793. /**
  40794. * The scissor rectangle of the renderer in logical pixel unit.
  40795. *
  40796. * @private
  40797. * @type {Vector4}
  40798. */
  40799. this._scissor = new Vector4( 0, 0, this._width, this._height );
  40800. /**
  40801. * Whether the scissor test should be enabled or not.
  40802. *
  40803. * @private
  40804. * @type {boolean}
  40805. */
  40806. this._scissorTest = false;
  40807. /**
  40808. * The color texture of the default framebuffer.
  40809. *
  40810. * @type {FramebufferTexture}
  40811. */
  40812. this.colorTexture = new FramebufferTexture();
  40813. /**
  40814. * The depth texture of the default framebuffer.
  40815. *
  40816. * @type {DepthTexture}
  40817. */
  40818. this.depthTexture = new DepthTexture();
  40819. }
  40820. /**
  40821. * Returns the pixel ratio.
  40822. *
  40823. * @return {number} The pixel ratio.
  40824. */
  40825. getPixelRatio() {
  40826. return this._pixelRatio;
  40827. }
  40828. /**
  40829. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  40830. *
  40831. * @param {Vector2} target - The method writes the result in this target object.
  40832. * @return {Vector2} The drawing buffer size.
  40833. */
  40834. getDrawingBufferSize( target ) {
  40835. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  40836. }
  40837. /**
  40838. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  40839. *
  40840. * @param {Vector2} target - The method writes the result in this target object.
  40841. * @return {Vector2} The renderer's size in logical pixels.
  40842. */
  40843. getSize( target ) {
  40844. return target.set( this._width, this._height );
  40845. }
  40846. /**
  40847. * Sets the given pixel ratio and resizes the canvas if necessary.
  40848. *
  40849. * @param {number} [value=1] - The pixel ratio.
  40850. */
  40851. setPixelRatio( value = 1 ) {
  40852. if ( this._pixelRatio === value ) return;
  40853. this._pixelRatio = value;
  40854. this.setSize( this._width, this._height, false );
  40855. }
  40856. /**
  40857. * This method allows to define the drawing buffer size by specifying
  40858. * width, height and pixel ratio all at once. The size of the drawing
  40859. * buffer is computed with this formula:
  40860. * ```js
  40861. * size.x = width * pixelRatio;
  40862. * size.y = height * pixelRatio;
  40863. * ```
  40864. *
  40865. * @param {number} width - The width in logical pixels.
  40866. * @param {number} height - The height in logical pixels.
  40867. * @param {number} pixelRatio - The pixel ratio.
  40868. */
  40869. setDrawingBufferSize( width, height, pixelRatio ) {
  40870. // Renderer can't be resized while presenting in XR.
  40871. if ( this.xr && this.xr.isPresenting ) return;
  40872. this._width = width;
  40873. this._height = height;
  40874. this._pixelRatio = pixelRatio;
  40875. this.domElement.width = Math.floor( width * pixelRatio );
  40876. this.domElement.height = Math.floor( height * pixelRatio );
  40877. this.setViewport( 0, 0, width, height );
  40878. this._dispatchResize();
  40879. }
  40880. /**
  40881. * Sets the size of the renderer.
  40882. *
  40883. * @param {number} width - The width in logical pixels.
  40884. * @param {number} height - The height in logical pixels.
  40885. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  40886. */
  40887. setSize( width, height, updateStyle = true ) {
  40888. // Renderer can't be resized while presenting in XR.
  40889. if ( this.xr && this.xr.isPresenting ) return;
  40890. this._width = width;
  40891. this._height = height;
  40892. this.domElement.width = Math.floor( width * this._pixelRatio );
  40893. this.domElement.height = Math.floor( height * this._pixelRatio );
  40894. if ( updateStyle === true ) {
  40895. this.domElement.style.width = width + 'px';
  40896. this.domElement.style.height = height + 'px';
  40897. }
  40898. this.setViewport( 0, 0, width, height );
  40899. this._dispatchResize();
  40900. }
  40901. /**
  40902. * Returns the scissor rectangle.
  40903. *
  40904. * @param {Vector4} target - The method writes the result in this target object.
  40905. * @return {Vector4} The scissor rectangle.
  40906. */
  40907. getScissor( target ) {
  40908. const scissor = this._scissor;
  40909. target.x = scissor.x;
  40910. target.y = scissor.y;
  40911. target.width = scissor.width;
  40912. target.height = scissor.height;
  40913. return target;
  40914. }
  40915. /**
  40916. * Defines the scissor rectangle.
  40917. *
  40918. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  40919. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  40920. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  40921. * @param {number} width - The width of the scissor box in logical pixel unit.
  40922. * @param {number} height - The height of the scissor box in logical pixel unit.
  40923. */
  40924. setScissor( x, y, width, height ) {
  40925. const scissor = this._scissor;
  40926. if ( x.isVector4 ) {
  40927. scissor.copy( x );
  40928. } else {
  40929. scissor.set( x, y, width, height );
  40930. }
  40931. }
  40932. /**
  40933. * Returns the scissor test value.
  40934. *
  40935. * @return {boolean} Whether the scissor test should be enabled or not.
  40936. */
  40937. getScissorTest() {
  40938. return this._scissorTest;
  40939. }
  40940. /**
  40941. * Defines the scissor test.
  40942. *
  40943. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  40944. */
  40945. setScissorTest( boolean ) {
  40946. this._scissorTest = boolean;
  40947. }
  40948. /**
  40949. * Returns the viewport definition.
  40950. *
  40951. * @param {Vector4} target - The method writes the result in this target object.
  40952. * @return {Vector4} The viewport definition.
  40953. */
  40954. getViewport( target ) {
  40955. return target.copy( this._viewport );
  40956. }
  40957. /**
  40958. * Defines the viewport.
  40959. *
  40960. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  40961. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  40962. * @param {number} width - The width of the viewport in logical pixel unit.
  40963. * @param {number} height - The height of the viewport in logical pixel unit.
  40964. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  40965. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  40966. */
  40967. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  40968. const viewport = this._viewport;
  40969. if ( x.isVector4 ) {
  40970. viewport.copy( x );
  40971. } else {
  40972. viewport.set( x, y, width, height );
  40973. }
  40974. viewport.minDepth = minDepth;
  40975. viewport.maxDepth = maxDepth;
  40976. }
  40977. /**
  40978. * Dispatches the resize event.
  40979. *
  40980. * @private
  40981. */
  40982. _dispatchResize() {
  40983. this.dispatchEvent( { type: 'resize' } );
  40984. }
  40985. /**
  40986. * Frees the GPU-related resources allocated by this instance. Call this
  40987. * method whenever this instance is no longer used in your app.
  40988. *
  40989. * @fires RenderTarget#dispose
  40990. */
  40991. dispose() {
  40992. this.dispatchEvent( { type: 'dispose' } );
  40993. }
  40994. }
  40995. const _scene = /*@__PURE__*/ new Scene();
  40996. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  40997. const _screen = /*@__PURE__*/ new Vector4();
  40998. const _frustum = /*@__PURE__*/ new Frustum();
  40999. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  41000. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  41001. const _vector4 = /*@__PURE__*/ new Vector4();
  41002. /**
  41003. * Base class for renderers.
  41004. */
  41005. class Renderer {
  41006. /**
  41007. * Renderer options.
  41008. *
  41009. * @typedef {Object} Renderer~Options
  41010. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  41011. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  41012. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  41013. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  41014. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  41015. * @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
  41016. * to overwrite the default.
  41017. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  41018. * @property {number} [outputBufferType=HalfFloatType] - Defines the type of output buffers. The default `HalfFloatType` is recommend for best
  41019. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  41020. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  41021. */
  41022. /**
  41023. * Constructs a new renderer.
  41024. *
  41025. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  41026. * @param {Renderer~Options} [parameters] - The configuration parameter.
  41027. */
  41028. constructor( backend, parameters = {} ) {
  41029. /**
  41030. * This flag can be used for type testing.
  41031. *
  41032. * @type {boolean}
  41033. * @readonly
  41034. * @default true
  41035. */
  41036. this.isRenderer = true;
  41037. //
  41038. const {
  41039. logarithmicDepthBuffer = false,
  41040. alpha = true,
  41041. depth = true,
  41042. stencil = false,
  41043. antialias = false,
  41044. samples = 0,
  41045. getFallback = null,
  41046. outputBufferType = HalfFloatType,
  41047. multiview = false
  41048. } = parameters;
  41049. /**
  41050. * A reference to the current backend.
  41051. *
  41052. * @type {Backend}
  41053. */
  41054. this.backend = backend;
  41055. /**
  41056. * Whether the renderer should automatically clear the current rendering target
  41057. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  41058. * or the current bound render target (custom framebuffer).
  41059. *
  41060. * @type {boolean}
  41061. * @default true
  41062. */
  41063. this.autoClear = true;
  41064. /**
  41065. * When `autoClear` is set to `true`, this property defines whether the renderer
  41066. * should clear the color buffer.
  41067. *
  41068. * @type {boolean}
  41069. * @default true
  41070. */
  41071. this.autoClearColor = true;
  41072. /**
  41073. * When `autoClear` is set to `true`, this property defines whether the renderer
  41074. * should clear the depth buffer.
  41075. *
  41076. * @type {boolean}
  41077. * @default true
  41078. */
  41079. this.autoClearDepth = true;
  41080. /**
  41081. * When `autoClear` is set to `true`, this property defines whether the renderer
  41082. * should clear the stencil buffer.
  41083. *
  41084. * @type {boolean}
  41085. * @default true
  41086. */
  41087. this.autoClearStencil = true;
  41088. /**
  41089. * Whether the default framebuffer should be transparent or opaque.
  41090. *
  41091. * @type {boolean}
  41092. * @default true
  41093. */
  41094. this.alpha = alpha;
  41095. /**
  41096. * Whether logarithmic depth buffer is enabled or not.
  41097. *
  41098. * @type {boolean}
  41099. * @default false
  41100. */
  41101. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  41102. /**
  41103. * Defines the output color space of the renderer.
  41104. *
  41105. * @type {string}
  41106. * @default SRGBColorSpace
  41107. */
  41108. this.outputColorSpace = SRGBColorSpace;
  41109. /**
  41110. * Defines the tone mapping of the renderer.
  41111. *
  41112. * @type {number}
  41113. * @default NoToneMapping
  41114. */
  41115. this.toneMapping = NoToneMapping;
  41116. /**
  41117. * Defines the tone mapping exposure.
  41118. *
  41119. * @type {number}
  41120. * @default 1
  41121. */
  41122. this.toneMappingExposure = 1.0;
  41123. /**
  41124. * Whether the renderer should sort its render lists or not.
  41125. *
  41126. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  41127. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  41128. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  41129. * e.g. manually determining each object's rendering order.
  41130. *
  41131. * @type {boolean}
  41132. * @default true
  41133. */
  41134. this.sortObjects = true;
  41135. /**
  41136. * Whether the default framebuffer should have a depth buffer or not.
  41137. *
  41138. * @type {boolean}
  41139. * @default true
  41140. */
  41141. this.depth = depth;
  41142. /**
  41143. * Whether the default framebuffer should have a stencil buffer or not.
  41144. *
  41145. * @type {boolean}
  41146. * @default false
  41147. */
  41148. this.stencil = stencil;
  41149. /**
  41150. * Holds a series of statistical information about the GPU memory
  41151. * and the rendering process. Useful for debugging and monitoring.
  41152. *
  41153. * @type {Info}
  41154. */
  41155. this.info = new Info();
  41156. /**
  41157. * A global context node that stores override nodes for specific transformations or calculations.
  41158. * These nodes can be used to replace default behavior in the rendering pipeline.
  41159. *
  41160. * @type {ContextNode}
  41161. * @property {Object} value - The context value object.
  41162. */
  41163. this.contextNode = context();
  41164. /**
  41165. * The node library defines how certain library objects like materials, lights
  41166. * or tone mapping functions are mapped to node types. This is required since
  41167. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  41168. * be part of the scene graph, they are internally represented as nodes for
  41169. * further processing.
  41170. *
  41171. * @type {NodeLibrary}
  41172. */
  41173. this.library = new NodeLibrary();
  41174. /**
  41175. * A map-like data structure for managing lights.
  41176. *
  41177. * @type {Lighting}
  41178. */
  41179. this.lighting = new Lighting();
  41180. // internals
  41181. /**
  41182. * The number of MSAA samples.
  41183. *
  41184. * @private
  41185. * @type {number}
  41186. * @default 0
  41187. */
  41188. this._samples = samples || ( antialias === true ) ? 4 : 0;
  41189. /**
  41190. * OnCanvasTargetResize callback function.
  41191. *
  41192. * @private
  41193. * @type {Function}
  41194. */
  41195. this._onCanvasTargetResize = this._onCanvasTargetResize.bind( this );
  41196. /**
  41197. * The canvas target for rendering.
  41198. *
  41199. * @private
  41200. * @type {CanvasTarget}
  41201. */
  41202. this._canvasTarget = new CanvasTarget( backend.getDomElement() );
  41203. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  41204. this._canvasTarget.isDefaultCanvasTarget = true;
  41205. /**
  41206. * The inspector provides information about the internal renderer state.
  41207. *
  41208. * @private
  41209. * @type {InspectorBase}
  41210. */
  41211. this._inspector = new InspectorBase();
  41212. this._inspector.setRenderer( this );
  41213. /**
  41214. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  41215. *
  41216. * @private
  41217. * @type {?Function}
  41218. */
  41219. this._getFallback = getFallback;
  41220. /**
  41221. * A reference to a renderer module for managing shader attributes.
  41222. *
  41223. * @private
  41224. * @type {?Attributes}
  41225. * @default null
  41226. */
  41227. this._attributes = null;
  41228. /**
  41229. * A reference to a renderer module for managing geometries.
  41230. *
  41231. * @private
  41232. * @type {?Geometries}
  41233. * @default null
  41234. */
  41235. this._geometries = null;
  41236. /**
  41237. * A reference to a renderer module for managing node related logic.
  41238. *
  41239. * @private
  41240. * @type {?Nodes}
  41241. * @default null
  41242. */
  41243. this._nodes = null;
  41244. /**
  41245. * A reference to a renderer module for managing the internal animation loop.
  41246. *
  41247. * @private
  41248. * @type {?Animation}
  41249. * @default null
  41250. */
  41251. this._animation = null;
  41252. /**
  41253. * A reference to a renderer module for managing shader program bindings.
  41254. *
  41255. * @private
  41256. * @type {?Bindings}
  41257. * @default null
  41258. */
  41259. this._bindings = null;
  41260. /**
  41261. * A reference to a renderer module for managing render objects.
  41262. *
  41263. * @private
  41264. * @type {?RenderObjects}
  41265. * @default null
  41266. */
  41267. this._objects = null;
  41268. /**
  41269. * A reference to a renderer module for managing render and compute pipelines.
  41270. *
  41271. * @private
  41272. * @type {?Pipelines}
  41273. * @default null
  41274. */
  41275. this._pipelines = null;
  41276. /**
  41277. * A reference to a renderer module for managing render bundles.
  41278. *
  41279. * @private
  41280. * @type {?RenderBundles}
  41281. * @default null
  41282. */
  41283. this._bundles = null;
  41284. /**
  41285. * A reference to a renderer module for managing render lists.
  41286. *
  41287. * @private
  41288. * @type {?RenderLists}
  41289. * @default null
  41290. */
  41291. this._renderLists = null;
  41292. /**
  41293. * A reference to a renderer module for managing render contexts.
  41294. *
  41295. * @private
  41296. * @type {?RenderContexts}
  41297. * @default null
  41298. */
  41299. this._renderContexts = null;
  41300. /**
  41301. * A reference to a renderer module for managing textures.
  41302. *
  41303. * @private
  41304. * @type {?Textures}
  41305. * @default null
  41306. */
  41307. this._textures = null;
  41308. /**
  41309. * A reference to a renderer module for backgrounds.
  41310. *
  41311. * @private
  41312. * @type {?Background}
  41313. * @default null
  41314. */
  41315. this._background = null;
  41316. /**
  41317. * This fullscreen quad is used for internal render passes
  41318. * like the tone mapping and color space output pass.
  41319. *
  41320. * @private
  41321. * @type {QuadMesh}
  41322. */
  41323. this._quad = new QuadMesh( new NodeMaterial() );
  41324. this._quad.name = 'Output Color Transform';
  41325. this._quad.material.name = 'outputColorTransform';
  41326. /**
  41327. * A reference to the current render context.
  41328. *
  41329. * @private
  41330. * @type {?RenderContext}
  41331. * @default null
  41332. */
  41333. this._currentRenderContext = null;
  41334. /**
  41335. * A custom sort function for the opaque render list.
  41336. *
  41337. * @private
  41338. * @type {?Function}
  41339. * @default null
  41340. */
  41341. this._opaqueSort = null;
  41342. /**
  41343. * A custom sort function for the transparent render list.
  41344. *
  41345. * @private
  41346. * @type {?Function}
  41347. * @default null
  41348. */
  41349. this._transparentSort = null;
  41350. /**
  41351. * The framebuffer target.
  41352. *
  41353. * @private
  41354. * @type {?RenderTarget}
  41355. * @default null
  41356. */
  41357. this._frameBufferTarget = null;
  41358. const alphaClear = this.alpha === true ? 0 : 1;
  41359. /**
  41360. * The clear color value.
  41361. *
  41362. * @private
  41363. * @type {Color4}
  41364. */
  41365. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  41366. /**
  41367. * The clear depth value.
  41368. *
  41369. * @private
  41370. * @type {number}
  41371. * @default 1
  41372. */
  41373. this._clearDepth = 1;
  41374. /**
  41375. * The clear stencil value.
  41376. *
  41377. * @private
  41378. * @type {number}
  41379. * @default 0
  41380. */
  41381. this._clearStencil = 0;
  41382. /**
  41383. * The current render target.
  41384. *
  41385. * @private
  41386. * @type {?RenderTarget}
  41387. * @default null
  41388. */
  41389. this._renderTarget = null;
  41390. /**
  41391. * The active cube face.
  41392. *
  41393. * @private
  41394. * @type {number}
  41395. * @default 0
  41396. */
  41397. this._activeCubeFace = 0;
  41398. /**
  41399. * The active mipmap level.
  41400. *
  41401. * @private
  41402. * @type {number}
  41403. * @default 0
  41404. */
  41405. this._activeMipmapLevel = 0;
  41406. /**
  41407. * The current output render target.
  41408. *
  41409. * @private
  41410. * @type {?RenderTarget}
  41411. * @default null
  41412. */
  41413. this._outputRenderTarget = null;
  41414. /**
  41415. * The MRT setting.
  41416. *
  41417. * @private
  41418. * @type {?MRTNode}
  41419. * @default null
  41420. */
  41421. this._mrt = null;
  41422. /**
  41423. * This function defines how a render object is going
  41424. * to be rendered.
  41425. *
  41426. * @private
  41427. * @type {?Function}
  41428. * @default null
  41429. */
  41430. this._renderObjectFunction = null;
  41431. /**
  41432. * Used to keep track of the current render object function.
  41433. *
  41434. * @private
  41435. * @type {?Function}
  41436. * @default null
  41437. */
  41438. this._currentRenderObjectFunction = null;
  41439. /**
  41440. * Used to keep track of the current render bundle.
  41441. *
  41442. * @private
  41443. * @type {?RenderBundle}
  41444. * @default null
  41445. */
  41446. this._currentRenderBundle = null;
  41447. /**
  41448. * Next to `_renderObjectFunction()`, this function provides another hook
  41449. * for influencing the render process of a render object. It is meant for internal
  41450. * use and only relevant for `compileAsync()` right now. Instead of using
  41451. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  41452. * a different function might be used which performs no draw but just the node
  41453. * and pipeline updates.
  41454. *
  41455. * @private
  41456. * @type {?Function}
  41457. * @default null
  41458. */
  41459. this._handleObjectFunction = this._renderObjectDirect;
  41460. /**
  41461. * Indicates whether the device has been lost or not. In WebGL terms, the device
  41462. * lost is considered as a context lost. When this is set to `true`, rendering
  41463. * isn't possible anymore.
  41464. *
  41465. * @private
  41466. * @type {boolean}
  41467. * @default false
  41468. */
  41469. this._isDeviceLost = false;
  41470. /**
  41471. * A callback function that defines what should happen when a device/context lost occurs.
  41472. *
  41473. * @type {Function}
  41474. */
  41475. this.onDeviceLost = this._onDeviceLost;
  41476. /**
  41477. * Defines the type of output buffers. The default `HalfFloatType` is recommend for
  41478. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  41479. * This will reduce rendering quality though.
  41480. *
  41481. * @private
  41482. * @type {number}
  41483. * @default HalfFloatType
  41484. */
  41485. this._outputBufferType = outputBufferType;
  41486. /**
  41487. * A cache for shadow nodes per material
  41488. *
  41489. * @private
  41490. * @type {WeakMap<Material, Object>}
  41491. */
  41492. this._cacheShadowNodes = new WeakMap();
  41493. /**
  41494. * Whether the renderer has been initialized or not.
  41495. *
  41496. * @private
  41497. * @type {boolean}
  41498. * @default false
  41499. */
  41500. this._initialized = false;
  41501. /**
  41502. * A reference to the promise which initializes the renderer.
  41503. *
  41504. * @private
  41505. * @type {?Promise<this>}
  41506. * @default null
  41507. */
  41508. this._initPromise = null;
  41509. /**
  41510. * An array of compilation promises which are used in `compileAsync()`.
  41511. *
  41512. * @private
  41513. * @type {?Array<Promise>}
  41514. * @default null
  41515. */
  41516. this._compilationPromises = null;
  41517. /**
  41518. * Whether the renderer should render transparent render objects or not.
  41519. *
  41520. * @type {boolean}
  41521. * @default true
  41522. */
  41523. this.transparent = true;
  41524. /**
  41525. * Whether the renderer should render opaque render objects or not.
  41526. *
  41527. * @type {boolean}
  41528. * @default true
  41529. */
  41530. this.opaque = true;
  41531. /**
  41532. * Shadow map configuration
  41533. * @typedef {Object} ShadowMapConfig
  41534. * @property {boolean} enabled - Whether to globally enable shadows or not.
  41535. * @property {number} type - The shadow map type.
  41536. */
  41537. /**
  41538. * The renderer's shadow configuration.
  41539. *
  41540. * @type {ShadowMapConfig}
  41541. */
  41542. this.shadowMap = {
  41543. enabled: false,
  41544. type: PCFShadowMap
  41545. };
  41546. /**
  41547. * XR configuration.
  41548. * @typedef {Object} XRConfig
  41549. * @property {boolean} enabled - Whether to globally enable XR or not.
  41550. */
  41551. /**
  41552. * The renderer's XR manager.
  41553. *
  41554. * @type {XRManager}
  41555. */
  41556. this.xr = new XRManager( this, multiview );
  41557. /**
  41558. * Debug configuration.
  41559. * @typedef {Object} DebugConfig
  41560. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  41561. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  41562. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  41563. */
  41564. /**
  41565. * The renderer's debug configuration.
  41566. *
  41567. * @type {DebugConfig}
  41568. */
  41569. this.debug = {
  41570. checkShaderErrors: true,
  41571. onShaderError: null,
  41572. getShaderAsync: async ( scene, camera, object ) => {
  41573. await this.compileAsync( scene, camera );
  41574. const renderList = this._renderLists.get( scene, camera );
  41575. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget, this._mrt );
  41576. const material = scene.overrideMaterial || object.material;
  41577. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  41578. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  41579. return { fragmentShader, vertexShader };
  41580. }
  41581. };
  41582. }
  41583. /**
  41584. * Initializes the renderer so it is ready for usage.
  41585. *
  41586. * @async
  41587. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  41588. */
  41589. async init() {
  41590. if ( this._initPromise !== null ) {
  41591. return this._initPromise;
  41592. }
  41593. this._initPromise = new Promise( async ( resolve, reject ) => {
  41594. let backend = this.backend;
  41595. try {
  41596. await backend.init( this );
  41597. } catch ( error ) {
  41598. if ( this._getFallback !== null ) {
  41599. // try the fallback
  41600. try {
  41601. this.backend = backend = this._getFallback( error );
  41602. await backend.init( this );
  41603. } catch ( error ) {
  41604. reject( error );
  41605. return;
  41606. }
  41607. } else {
  41608. reject( error );
  41609. return;
  41610. }
  41611. }
  41612. this._nodes = new Nodes( this, backend );
  41613. this._animation = new Animation( this, this._nodes, this.info );
  41614. this._attributes = new Attributes( backend );
  41615. this._background = new Background( this, this._nodes );
  41616. this._geometries = new Geometries( this._attributes, this.info );
  41617. this._textures = new Textures( this, backend, this.info );
  41618. this._pipelines = new Pipelines( backend, this._nodes );
  41619. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  41620. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  41621. this._renderLists = new RenderLists( this.lighting );
  41622. this._bundles = new RenderBundles();
  41623. this._renderContexts = new RenderContexts();
  41624. //
  41625. this._animation.start();
  41626. this._initialized = true;
  41627. //
  41628. this._inspector.init();
  41629. //
  41630. resolve( this );
  41631. } );
  41632. return this._initPromise;
  41633. }
  41634. /**
  41635. * A reference to the canvas element the renderer is drawing to.
  41636. * This value of this property will automatically be created by
  41637. * the renderer.
  41638. *
  41639. * @type {HTMLCanvasElement|OffscreenCanvas}
  41640. */
  41641. get domElement() {
  41642. return this._canvasTarget.domElement;
  41643. }
  41644. /**
  41645. * The coordinate system of the renderer. The value of this property
  41646. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  41647. * `THREE.WebGPUCoordinateSystem`.
  41648. *
  41649. * @readonly
  41650. * @type {number}
  41651. */
  41652. get coordinateSystem() {
  41653. return this.backend.coordinateSystem;
  41654. }
  41655. /**
  41656. * Compiles all materials in the given scene. This can be useful to avoid a
  41657. * phenomenon which is called "shader compilation stutter", which occurs when
  41658. * rendering an object with a new shader for the first time.
  41659. *
  41660. * If you want to add a 3D object to an existing scene, use the third optional
  41661. * parameter for applying the target scene. Note that the (target) scene's lighting
  41662. * and environment must be configured before calling this method.
  41663. *
  41664. * @async
  41665. * @param {Object3D} scene - The scene or 3D object to precompile.
  41666. * @param {Camera} camera - The camera that is used to render the scene.
  41667. * @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.
  41668. * @return {Promise} A Promise that resolves when the compile has been finished.
  41669. */
  41670. async compileAsync( scene, camera, targetScene = null ) {
  41671. if ( this._isDeviceLost === true ) return;
  41672. if ( this._initialized === false ) await this.init();
  41673. // preserve render tree
  41674. const nodeFrame = this._nodes.nodeFrame;
  41675. const previousRenderId = nodeFrame.renderId;
  41676. const previousRenderContext = this._currentRenderContext;
  41677. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  41678. const previousCompilationPromises = this._compilationPromises;
  41679. //
  41680. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  41681. if ( targetScene === null ) targetScene = scene;
  41682. const renderTarget = this._renderTarget;
  41683. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget, this._mrt );
  41684. const activeMipmapLevel = this._activeMipmapLevel;
  41685. const compilationPromises = [];
  41686. this._currentRenderContext = renderContext;
  41687. this._currentRenderObjectFunction = this.renderObject;
  41688. this._handleObjectFunction = this._createObjectPipeline;
  41689. this._compilationPromises = compilationPromises;
  41690. nodeFrame.renderId ++;
  41691. //
  41692. nodeFrame.update();
  41693. //
  41694. renderContext.depth = this.depth;
  41695. renderContext.stencil = this.stencil;
  41696. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  41697. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  41698. //
  41699. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  41700. //
  41701. const renderList = this._renderLists.get( scene, camera );
  41702. renderList.begin();
  41703. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  41704. // include lights from target scene
  41705. if ( targetScene !== scene ) {
  41706. targetScene.traverseVisible( function ( object ) {
  41707. if ( object.isLight && object.layers.test( camera.layers ) ) {
  41708. renderList.pushLight( object );
  41709. }
  41710. } );
  41711. }
  41712. renderList.finish();
  41713. //
  41714. if ( renderTarget !== null ) {
  41715. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  41716. const renderTargetData = this._textures.get( renderTarget );
  41717. renderContext.textures = renderTargetData.textures;
  41718. renderContext.depthTexture = renderTargetData.depthTexture;
  41719. } else {
  41720. renderContext.textures = null;
  41721. renderContext.depthTexture = null;
  41722. }
  41723. //
  41724. this._background.update( sceneRef, renderList, renderContext );
  41725. // process render lists
  41726. const opaqueObjects = renderList.opaque;
  41727. const transparentObjects = renderList.transparent;
  41728. const transparentDoublePassObjects = renderList.transparentDoublePass;
  41729. const lightsNode = renderList.lightsNode;
  41730. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  41731. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  41732. // restore render tree
  41733. nodeFrame.renderId = previousRenderId;
  41734. this._currentRenderContext = previousRenderContext;
  41735. this._currentRenderObjectFunction = previousRenderObjectFunction;
  41736. this._compilationPromises = previousCompilationPromises;
  41737. this._handleObjectFunction = this._renderObjectDirect;
  41738. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  41739. await Promise.all( compilationPromises );
  41740. }
  41741. /**
  41742. * Renders the scene in an async fashion.
  41743. *
  41744. * @async
  41745. * @deprecated
  41746. * @param {Object3D} scene - The scene or 3D object to render.
  41747. * @param {Camera} camera - The camera.
  41748. * @return {Promise} A Promise that resolves when the render has been finished.
  41749. */
  41750. async renderAsync( scene, camera ) {
  41751. warnOnce( 'Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41752. await this.init();
  41753. this.render( scene, camera );
  41754. }
  41755. /**
  41756. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  41757. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  41758. *
  41759. * @async
  41760. * @deprecated
  41761. * @return {Promise} A Promise that resolves when synchronization has been finished.
  41762. */
  41763. async waitForGPU() {
  41764. error( 'Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.' );
  41765. }
  41766. //
  41767. set inspector( value ) {
  41768. if ( this._inspector !== null ) {
  41769. this._inspector.setRenderer( null );
  41770. }
  41771. this._inspector = value;
  41772. this._inspector.setRenderer( this );
  41773. }
  41774. /**
  41775. * The inspector instance. The inspector can be any class that extends from `InspectorBase`.
  41776. *
  41777. * @type {InspectorBase}
  41778. */
  41779. get inspector() {
  41780. return this._inspector;
  41781. }
  41782. /**
  41783. * Enables or disables high precision for model-view and normal-view matrices.
  41784. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  41785. *
  41786. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  41787. *
  41788. * @param {boolean} value - Whether to enable or disable high precision.
  41789. * @type {boolean}
  41790. */
  41791. set highPrecision( value ) {
  41792. const contextNodeData = this.contextNode.value;
  41793. if ( value === true ) {
  41794. contextNodeData.modelViewMatrix = highpModelViewMatrix;
  41795. contextNodeData.modelNormalViewMatrix = highpModelNormalViewMatrix;
  41796. } else if ( this.highPrecision ) {
  41797. delete contextNodeData.modelViewMatrix;
  41798. delete contextNodeData.modelNormalViewMatrix;
  41799. }
  41800. }
  41801. /**
  41802. * Returns whether high precision is enabled or not.
  41803. *
  41804. * @return {boolean} Whether high precision is enabled or not.
  41805. * @type {boolean}
  41806. */
  41807. get highPrecision() {
  41808. const contextNodeData = this.contextNode.value;
  41809. return contextNodeData.modelViewMatrix === highpModelViewMatrix && contextNodeData.modelNormalViewMatrix === highpModelNormalViewMatrix;
  41810. }
  41811. /**
  41812. * Sets the given MRT configuration.
  41813. *
  41814. * @param {MRTNode} mrt - The MRT node to set.
  41815. * @return {Renderer} A reference to this renderer.
  41816. */
  41817. setMRT( mrt ) {
  41818. this._mrt = mrt;
  41819. return this;
  41820. }
  41821. /**
  41822. * Returns the MRT configuration.
  41823. *
  41824. * @return {MRTNode} The MRT configuration.
  41825. */
  41826. getMRT() {
  41827. return this._mrt;
  41828. }
  41829. /**
  41830. * Returns the output buffer type.
  41831. *
  41832. * @return {number} The output buffer type.
  41833. */
  41834. getOutputBufferType() {
  41835. return this._outputBufferType;
  41836. }
  41837. /**
  41838. * Returns the output buffer type.
  41839. *
  41840. * @deprecated since r182. Use `.getOutputBufferType()` instead.
  41841. * @return {number} The output buffer type.
  41842. */
  41843. getColorBufferType() { // @deprecated, r182
  41844. warnOnce( 'Renderer: ".getColorBufferType()" has been renamed to ".getOutputBufferType()".' );
  41845. return this.getOutputBufferType();
  41846. }
  41847. /**
  41848. * Default implementation of the device lost callback.
  41849. *
  41850. * @private
  41851. * @param {Object} info - Information about the context lost.
  41852. */
  41853. _onDeviceLost( info ) {
  41854. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  41855. if ( info.reason ) {
  41856. errorMessage += `\nReason: ${info.reason}`;
  41857. }
  41858. error( errorMessage );
  41859. this._isDeviceLost = true;
  41860. }
  41861. /**
  41862. * Renders the given render bundle.
  41863. *
  41864. * @private
  41865. * @param {Object} bundle - Render bundle data.
  41866. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  41867. * @param {LightsNode} lightsNode - The lights node.
  41868. */
  41869. _renderBundle( bundle, sceneRef, lightsNode ) {
  41870. const { bundleGroup, camera, renderList } = bundle;
  41871. const renderContext = this._currentRenderContext;
  41872. //
  41873. const renderBundle = this._bundles.get( bundleGroup, camera );
  41874. const renderBundleData = this.backend.get( renderBundle );
  41875. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  41876. //
  41877. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  41878. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  41879. renderBundleData.renderContexts.add( renderContext );
  41880. if ( renderBundleNeedsUpdate ) {
  41881. this.backend.beginBundle( renderContext );
  41882. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  41883. renderBundleData.renderObjects = [];
  41884. }
  41885. this._currentRenderBundle = renderBundle;
  41886. const {
  41887. transparentDoublePass: transparentDoublePassObjects,
  41888. transparent: transparentObjects,
  41889. opaque: opaqueObjects
  41890. } = renderList;
  41891. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  41892. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  41893. this._currentRenderBundle = null;
  41894. //
  41895. this.backend.finishBundle( renderContext, renderBundle );
  41896. renderBundleData.version = bundleGroup.version;
  41897. } else {
  41898. const { renderObjects } = renderBundleData;
  41899. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  41900. const renderObject = renderObjects[ i ];
  41901. if ( this._nodes.needsRefresh( renderObject ) ) {
  41902. this._nodes.updateBefore( renderObject );
  41903. this._nodes.updateForRender( renderObject );
  41904. this._bindings.updateForRender( renderObject );
  41905. this._nodes.updateAfter( renderObject );
  41906. }
  41907. }
  41908. }
  41909. this.backend.addBundle( renderContext, renderBundle );
  41910. }
  41911. /**
  41912. * Renders the scene or 3D object with the given camera. This method can only be called
  41913. * if the renderer has been initialized. When using `render()` inside an animation loop,
  41914. * it's guaranteed the renderer will be initialized. The animation loop must be defined
  41915. * with {@link Renderer#setAnimationLoop} though.
  41916. *
  41917. * For all other use cases (like when using on-demand rendering), you must call
  41918. * {@link Renderer#init} before rendering.
  41919. *
  41920. * The target of the method is the default framebuffer (meaning the canvas)
  41921. * or alternatively a render target when specified via `setRenderTarget()`.
  41922. *
  41923. * @param {Object3D} scene - The scene or 3D object to render.
  41924. * @param {Camera} camera - The camera to render the scene with.
  41925. */
  41926. render( scene, camera ) {
  41927. if ( this._initialized === false ) {
  41928. throw new Error( 'Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.' );
  41929. }
  41930. this._renderScene( scene, camera );
  41931. }
  41932. /**
  41933. * Returns whether the renderer has been initialized or not.
  41934. *
  41935. * @readonly
  41936. * @return {boolean} Whether the renderer has been initialized or not.
  41937. */
  41938. get initialized() {
  41939. return this._initialized;
  41940. }
  41941. /**
  41942. * Returns an internal render target which is used when computing the output tone mapping
  41943. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  41944. * pass and not inline to achieve more correct results.
  41945. *
  41946. * @private
  41947. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  41948. */
  41949. _getFrameBufferTarget() {
  41950. const { currentToneMapping, currentColorSpace } = this;
  41951. const useToneMapping = currentToneMapping !== NoToneMapping;
  41952. const useColorSpace = currentColorSpace !== ColorManagement.workingColorSpace;
  41953. if ( useToneMapping === false && useColorSpace === false ) return null;
  41954. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  41955. const { depth, stencil } = this;
  41956. let frameBufferTarget = this._frameBufferTarget;
  41957. if ( frameBufferTarget === null ) {
  41958. frameBufferTarget = new RenderTarget( width, height, {
  41959. depthBuffer: depth,
  41960. stencilBuffer: stencil,
  41961. type: this._outputBufferType,
  41962. format: RGBAFormat,
  41963. colorSpace: ColorManagement.workingColorSpace,
  41964. generateMipmaps: false,
  41965. minFilter: LinearFilter,
  41966. magFilter: LinearFilter,
  41967. samples: this.samples
  41968. } );
  41969. frameBufferTarget.isPostProcessingRenderTarget = true;
  41970. this._frameBufferTarget = frameBufferTarget;
  41971. }
  41972. const outputRenderTarget = this.getOutputRenderTarget();
  41973. frameBufferTarget.depthBuffer = depth;
  41974. frameBufferTarget.stencilBuffer = stencil;
  41975. if ( outputRenderTarget !== null ) {
  41976. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  41977. } else {
  41978. frameBufferTarget.setSize( width, height, 1 );
  41979. }
  41980. const canvasTarget = this._canvasTarget;
  41981. frameBufferTarget.viewport.copy( canvasTarget._viewport );
  41982. frameBufferTarget.scissor.copy( canvasTarget._scissor );
  41983. frameBufferTarget.viewport.multiplyScalar( canvasTarget._pixelRatio );
  41984. frameBufferTarget.scissor.multiplyScalar( canvasTarget._pixelRatio );
  41985. frameBufferTarget.scissorTest = canvasTarget._scissorTest;
  41986. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  41987. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  41988. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  41989. return frameBufferTarget;
  41990. }
  41991. /**
  41992. * Renders the scene or 3D object with the given camera.
  41993. *
  41994. * @private
  41995. * @param {Object3D} scene - The scene or 3D object to render.
  41996. * @param {Camera} camera - The camera to render the scene with.
  41997. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  41998. * @return {RenderContext} The current render context.
  41999. */
  42000. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  42001. if ( this._isDeviceLost === true ) return;
  42002. //
  42003. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  42004. // preserve render tree
  42005. const nodeFrame = this._nodes.nodeFrame;
  42006. const previousRenderId = nodeFrame.renderId;
  42007. const previousRenderContext = this._currentRenderContext;
  42008. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  42009. //
  42010. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  42011. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  42012. const activeCubeFace = this._activeCubeFace;
  42013. const activeMipmapLevel = this._activeMipmapLevel;
  42014. //
  42015. let renderTarget;
  42016. if ( frameBufferTarget !== null ) {
  42017. renderTarget = frameBufferTarget;
  42018. this.setRenderTarget( renderTarget );
  42019. } else {
  42020. renderTarget = outputRenderTarget;
  42021. }
  42022. //
  42023. const renderContext = this._renderContexts.get( scene, camera, renderTarget, this._mrt );
  42024. this._currentRenderContext = renderContext;
  42025. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  42026. //
  42027. this.info.calls ++;
  42028. this.info.render.calls ++;
  42029. this.info.render.frameCalls ++;
  42030. nodeFrame.renderId = this.info.calls;
  42031. //
  42032. this.backend.updateTimeStampUID( renderContext );
  42033. this.inspector.beginRender( this.backend.getTimestampUID( renderContext ), scene, camera, renderTarget );
  42034. //
  42035. const coordinateSystem = this.coordinateSystem;
  42036. const xr = this.xr;
  42037. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  42038. camera.coordinateSystem = coordinateSystem;
  42039. camera.updateProjectionMatrix();
  42040. if ( camera.isArrayCamera ) {
  42041. for ( const subCamera of camera.cameras ) {
  42042. subCamera.coordinateSystem = coordinateSystem;
  42043. subCamera.updateProjectionMatrix();
  42044. }
  42045. }
  42046. }
  42047. //
  42048. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  42049. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  42050. if ( xr.enabled === true && xr.isPresenting === true ) {
  42051. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  42052. camera = xr.getCamera(); // use XR camera for rendering
  42053. }
  42054. //
  42055. const canvasTarget = this._canvasTarget;
  42056. let viewport = canvasTarget._viewport;
  42057. let scissor = canvasTarget._scissor;
  42058. let pixelRatio = canvasTarget._pixelRatio;
  42059. if ( renderTarget !== null ) {
  42060. viewport = renderTarget.viewport;
  42061. scissor = renderTarget.scissor;
  42062. pixelRatio = 1;
  42063. }
  42064. this.getDrawingBufferSize( _drawingBufferSize );
  42065. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  42066. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  42067. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  42068. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  42069. renderContext.viewportValue.width >>= activeMipmapLevel;
  42070. renderContext.viewportValue.height >>= activeMipmapLevel;
  42071. renderContext.viewportValue.minDepth = minDepth;
  42072. renderContext.viewportValue.maxDepth = maxDepth;
  42073. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  42074. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  42075. renderContext.scissor = canvasTarget._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  42076. renderContext.scissorValue.width >>= activeMipmapLevel;
  42077. renderContext.scissorValue.height >>= activeMipmapLevel;
  42078. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  42079. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  42080. //
  42081. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  42082. //
  42083. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  42084. if ( ! camera.isArrayCamera ) {
  42085. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  42086. frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  42087. }
  42088. const renderList = this._renderLists.get( scene, camera );
  42089. renderList.begin();
  42090. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  42091. renderList.finish();
  42092. if ( this.sortObjects === true ) {
  42093. renderList.sort( this._opaqueSort, this._transparentSort );
  42094. }
  42095. //
  42096. if ( renderTarget !== null ) {
  42097. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  42098. const renderTargetData = this._textures.get( renderTarget );
  42099. renderContext.textures = renderTargetData.textures;
  42100. renderContext.depthTexture = renderTargetData.depthTexture;
  42101. renderContext.width = renderTargetData.width;
  42102. renderContext.height = renderTargetData.height;
  42103. renderContext.renderTarget = renderTarget;
  42104. renderContext.depth = renderTarget.depthBuffer;
  42105. renderContext.stencil = renderTarget.stencilBuffer;
  42106. } else {
  42107. renderContext.textures = null;
  42108. renderContext.depthTexture = null;
  42109. renderContext.width = _drawingBufferSize.width;
  42110. renderContext.height = _drawingBufferSize.height;
  42111. renderContext.depth = this.depth;
  42112. renderContext.stencil = this.stencil;
  42113. }
  42114. renderContext.width >>= activeMipmapLevel;
  42115. renderContext.height >>= activeMipmapLevel;
  42116. renderContext.activeCubeFace = activeCubeFace;
  42117. renderContext.activeMipmapLevel = activeMipmapLevel;
  42118. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  42119. //
  42120. renderContext.scissorValue.max( _vector4.set( 0, 0, 0, 0 ) );
  42121. if ( renderContext.scissorValue.x + renderContext.scissorValue.width > renderContext.width ) {
  42122. renderContext.scissorValue.width = Math.max( renderContext.width - renderContext.scissorValue.x, 0 );
  42123. }
  42124. if ( renderContext.scissorValue.y + renderContext.scissorValue.height > renderContext.height ) {
  42125. renderContext.scissorValue.height = Math.max( renderContext.height - renderContext.scissorValue.y, 0 );
  42126. }
  42127. //
  42128. this._background.update( sceneRef, renderList, renderContext );
  42129. //
  42130. renderContext.camera = camera;
  42131. this.backend.beginRender( renderContext );
  42132. // process render lists
  42133. const {
  42134. bundles,
  42135. lightsNode,
  42136. transparentDoublePass: transparentDoublePassObjects,
  42137. transparent: transparentObjects,
  42138. opaque: opaqueObjects
  42139. } = renderList;
  42140. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  42141. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  42142. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  42143. // finish render pass
  42144. this.backend.finishRender( renderContext );
  42145. // restore render tree
  42146. nodeFrame.renderId = previousRenderId;
  42147. this._currentRenderContext = previousRenderContext;
  42148. this._currentRenderObjectFunction = previousRenderObjectFunction;
  42149. //
  42150. if ( frameBufferTarget !== null ) {
  42151. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  42152. this._renderOutput( renderTarget );
  42153. }
  42154. //
  42155. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  42156. //
  42157. this.inspector.finishRender( this.backend.getTimestampUID( renderContext ) );
  42158. //
  42159. return renderContext;
  42160. }
  42161. _setXRLayerSize( width, height ) {
  42162. // TODO: Find a better solution to resize the canvas when in XR.
  42163. this._canvasTarget._width = width;
  42164. this._canvasTarget._height = height;
  42165. this.setViewport( 0, 0, width, height );
  42166. }
  42167. /**
  42168. * The output pass performs tone mapping and color space conversion.
  42169. *
  42170. * @private
  42171. * @param {RenderTarget} renderTarget - The current render target.
  42172. */
  42173. _renderOutput( renderTarget ) {
  42174. const quad = this._quad;
  42175. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  42176. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  42177. quad.material.needsUpdate = true;
  42178. }
  42179. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  42180. const currentAutoClear = this.autoClear;
  42181. const currentXR = this.xr.enabled;
  42182. this.autoClear = false;
  42183. this.xr.enabled = false;
  42184. this._renderScene( quad, quad.camera, false );
  42185. this.autoClear = currentAutoClear;
  42186. this.xr.enabled = currentXR;
  42187. }
  42188. /**
  42189. * Returns the maximum available anisotropy for texture filtering.
  42190. *
  42191. * @return {number} The maximum available anisotropy.
  42192. */
  42193. getMaxAnisotropy() {
  42194. return this.backend.getMaxAnisotropy();
  42195. }
  42196. /**
  42197. * Returns the active cube face.
  42198. *
  42199. * @return {number} The active cube face.
  42200. */
  42201. getActiveCubeFace() {
  42202. return this._activeCubeFace;
  42203. }
  42204. /**
  42205. * Returns the active mipmap level.
  42206. *
  42207. * @return {number} The active mipmap level.
  42208. */
  42209. getActiveMipmapLevel() {
  42210. return this._activeMipmapLevel;
  42211. }
  42212. /**
  42213. * Applications are advised to always define the animation loop
  42214. * with this method and not manually with `requestAnimationFrame()`
  42215. * for best compatibility.
  42216. *
  42217. * @async
  42218. * @param {?onAnimationCallback} callback - The application's animation loop.
  42219. * @return {Promise} A Promise that resolves when the set has been executed.
  42220. */
  42221. async setAnimationLoop( callback ) {
  42222. if ( this._initialized === false ) await this.init();
  42223. this._animation.setAnimationLoop( callback );
  42224. }
  42225. /**
  42226. * Returns the current animation loop callback.
  42227. *
  42228. * @return {?Function} The current animation loop callback.
  42229. */
  42230. getAnimationLoop() {
  42231. return this._animation.getAnimationLoop();
  42232. }
  42233. /**
  42234. * Can be used to transfer buffer data from a storage buffer attribute
  42235. * from the GPU to the CPU in context of compute shaders.
  42236. *
  42237. * @async
  42238. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  42239. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  42240. */
  42241. async getArrayBufferAsync( attribute ) {
  42242. return await this.backend.getArrayBufferAsync( attribute );
  42243. }
  42244. /**
  42245. * Returns the rendering context.
  42246. *
  42247. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  42248. */
  42249. getContext() {
  42250. return this.backend.getContext();
  42251. }
  42252. /**
  42253. * Returns the pixel ratio.
  42254. *
  42255. * @return {number} The pixel ratio.
  42256. */
  42257. getPixelRatio() {
  42258. return this._canvasTarget.getPixelRatio();
  42259. }
  42260. /**
  42261. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  42262. *
  42263. * @param {Vector2} target - The method writes the result in this target object.
  42264. * @return {Vector2} The drawing buffer size.
  42265. */
  42266. getDrawingBufferSize( target ) {
  42267. return this._canvasTarget.getDrawingBufferSize( target );
  42268. }
  42269. /**
  42270. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  42271. *
  42272. * @param {Vector2} target - The method writes the result in this target object.
  42273. * @return {Vector2} The renderer's size in logical pixels.
  42274. */
  42275. getSize( target ) {
  42276. return this._canvasTarget.getSize( target );
  42277. }
  42278. /**
  42279. * Sets the given pixel ratio and resizes the canvas if necessary.
  42280. *
  42281. * @param {number} [value=1] - The pixel ratio.
  42282. */
  42283. setPixelRatio( value = 1 ) {
  42284. this._canvasTarget.setPixelRatio( value );
  42285. }
  42286. /**
  42287. * This method allows to define the drawing buffer size by specifying
  42288. * width, height and pixel ratio all at once. The size of the drawing
  42289. * buffer is computed with this formula:
  42290. * ```js
  42291. * size.x = width * pixelRatio;
  42292. * size.y = height * pixelRatio;
  42293. * ```
  42294. *
  42295. * @param {number} width - The width in logical pixels.
  42296. * @param {number} height - The height in logical pixels.
  42297. * @param {number} pixelRatio - The pixel ratio.
  42298. */
  42299. setDrawingBufferSize( width, height, pixelRatio ) {
  42300. // Renderer can't be resized while presenting in XR.
  42301. if ( this.xr && this.xr.isPresenting ) return;
  42302. this._canvasTarget.setDrawingBufferSize( width, height, pixelRatio );
  42303. }
  42304. /**
  42305. * Sets the size of the renderer.
  42306. *
  42307. * @param {number} width - The width in logical pixels.
  42308. * @param {number} height - The height in logical pixels.
  42309. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  42310. */
  42311. setSize( width, height, updateStyle = true ) {
  42312. // Renderer can't be resized while presenting in XR.
  42313. if ( this.xr && this.xr.isPresenting ) return;
  42314. this._canvasTarget.setSize( width, height, updateStyle );
  42315. }
  42316. /**
  42317. * Defines a manual sort function for the opaque render list.
  42318. * Pass `null` to use the default sort.
  42319. *
  42320. * @param {Function} method - The sort function.
  42321. */
  42322. setOpaqueSort( method ) {
  42323. this._opaqueSort = method;
  42324. }
  42325. /**
  42326. * Defines a manual sort function for the transparent render list.
  42327. * Pass `null` to use the default sort.
  42328. *
  42329. * @param {Function} method - The sort function.
  42330. */
  42331. setTransparentSort( method ) {
  42332. this._transparentSort = method;
  42333. }
  42334. /**
  42335. * Returns the scissor rectangle.
  42336. *
  42337. * @param {Vector4} target - The method writes the result in this target object.
  42338. * @return {Vector4} The scissor rectangle.
  42339. */
  42340. getScissor( target ) {
  42341. return this._canvasTarget.getScissor( target );
  42342. }
  42343. /**
  42344. * Defines the scissor rectangle.
  42345. *
  42346. * @param {number | Vector4} x - The horizontal coordinate for the upper left corner of the box in logical pixel unit.
  42347. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  42348. * @param {number} y - The vertical coordinate for the upper left corner of the box in logical pixel unit.
  42349. * @param {number} width - The width of the scissor box in logical pixel unit.
  42350. * @param {number} height - The height of the scissor box in logical pixel unit.
  42351. */
  42352. setScissor( x, y, width, height ) {
  42353. this._canvasTarget.setScissor( x, y, width, height );
  42354. }
  42355. /**
  42356. * Returns the scissor test value.
  42357. *
  42358. * @return {boolean} Whether the scissor test should be enabled or not.
  42359. */
  42360. getScissorTest() {
  42361. return this._canvasTarget.getScissorTest();
  42362. }
  42363. /**
  42364. * Defines the scissor test.
  42365. *
  42366. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  42367. */
  42368. setScissorTest( boolean ) {
  42369. this._canvasTarget.setScissorTest( boolean );
  42370. // TODO: Move it to CanvasTarget event listener.
  42371. this.backend.setScissorTest( boolean );
  42372. }
  42373. /**
  42374. * Returns the viewport definition.
  42375. *
  42376. * @param {Vector4} target - The method writes the result in this target object.
  42377. * @return {Vector4} The viewport definition.
  42378. */
  42379. getViewport( target ) {
  42380. return this._canvasTarget.getViewport( target );
  42381. }
  42382. /**
  42383. * Defines the viewport.
  42384. *
  42385. * @param {number | Vector4} x - The horizontal coordinate for the upper left corner of the viewport origin in logical pixel unit.
  42386. * @param {number} y - The vertical coordinate for the upper left corner of the viewport origin in logical pixel unit.
  42387. * @param {number} width - The width of the viewport in logical pixel unit.
  42388. * @param {number} height - The height of the viewport in logical pixel unit.
  42389. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  42390. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  42391. */
  42392. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  42393. this._canvasTarget.setViewport( x, y, width, height, minDepth, maxDepth );
  42394. }
  42395. /**
  42396. * Returns the clear color.
  42397. *
  42398. * @param {Color} target - The method writes the result in this target object.
  42399. * @return {Color} The clear color.
  42400. */
  42401. getClearColor( target ) {
  42402. return target.copy( this._clearColor );
  42403. }
  42404. /**
  42405. * Defines the clear color and optionally the clear alpha.
  42406. *
  42407. * @param {Color} color - The clear color.
  42408. * @param {number} [alpha=1] - The clear alpha.
  42409. */
  42410. setClearColor( color, alpha = 1 ) {
  42411. this._clearColor.set( color );
  42412. this._clearColor.a = alpha;
  42413. }
  42414. /**
  42415. * Returns the clear alpha.
  42416. *
  42417. * @return {number} The clear alpha.
  42418. */
  42419. getClearAlpha() {
  42420. return this._clearColor.a;
  42421. }
  42422. /**
  42423. * Defines the clear alpha.
  42424. *
  42425. * @param {number} alpha - The clear alpha.
  42426. */
  42427. setClearAlpha( alpha ) {
  42428. this._clearColor.a = alpha;
  42429. }
  42430. /**
  42431. * Returns the clear depth.
  42432. *
  42433. * @return {number} The clear depth.
  42434. */
  42435. getClearDepth() {
  42436. return this._clearDepth;
  42437. }
  42438. /**
  42439. * Defines the clear depth.
  42440. *
  42441. * @param {number} depth - The clear depth.
  42442. */
  42443. setClearDepth( depth ) {
  42444. this._clearDepth = depth;
  42445. }
  42446. /**
  42447. * Returns the clear stencil.
  42448. *
  42449. * @return {number} The clear stencil.
  42450. */
  42451. getClearStencil() {
  42452. return this._clearStencil;
  42453. }
  42454. /**
  42455. * Defines the clear stencil.
  42456. *
  42457. * @param {number} stencil - The clear stencil.
  42458. */
  42459. setClearStencil( stencil ) {
  42460. this._clearStencil = stencil;
  42461. }
  42462. /**
  42463. * This method performs an occlusion query for the given 3D object.
  42464. * It returns `true` if the given 3D object is fully occluded by other
  42465. * 3D objects in the scene.
  42466. *
  42467. * @param {Object3D} object - The 3D object to test.
  42468. * @return {boolean} Whether the 3D object is fully occluded or not.
  42469. */
  42470. isOccluded( object ) {
  42471. const renderContext = this._currentRenderContext;
  42472. return renderContext && this.backend.isOccluded( renderContext, object );
  42473. }
  42474. /**
  42475. * Performs a manual clear operation. This method ignores `autoClear` properties.
  42476. *
  42477. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  42478. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  42479. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  42480. */
  42481. clear( color = true, depth = true, stencil = true ) {
  42482. if ( this._initialized === false ) {
  42483. throw new Error( 'Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  42484. }
  42485. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  42486. let renderContext = null;
  42487. if ( renderTarget !== null ) {
  42488. this._textures.updateRenderTarget( renderTarget );
  42489. const renderTargetData = this._textures.get( renderTarget );
  42490. renderContext = this._renderContexts.getForClear( renderTarget );
  42491. renderContext.textures = renderTargetData.textures;
  42492. renderContext.depthTexture = renderTargetData.depthTexture;
  42493. renderContext.width = renderTargetData.width;
  42494. renderContext.height = renderTargetData.height;
  42495. renderContext.renderTarget = renderTarget;
  42496. renderContext.depth = renderTarget.depthBuffer;
  42497. renderContext.stencil = renderTarget.stencilBuffer;
  42498. // #30329
  42499. renderContext.clearColorValue = this.backend.getClearColor();
  42500. renderContext.activeCubeFace = this.getActiveCubeFace();
  42501. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  42502. }
  42503. this.backend.clear( color, depth, stencil, renderContext );
  42504. if ( renderTarget !== null && this._renderTarget === null ) {
  42505. this._renderOutput( renderTarget );
  42506. }
  42507. }
  42508. /**
  42509. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  42510. */
  42511. clearColor() {
  42512. this.clear( true, false, false );
  42513. }
  42514. /**
  42515. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  42516. */
  42517. clearDepth() {
  42518. this.clear( false, true, false );
  42519. }
  42520. /**
  42521. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  42522. */
  42523. clearStencil() {
  42524. this.clear( false, false, true );
  42525. }
  42526. /**
  42527. * Async version of {@link Renderer#clear}.
  42528. *
  42529. * @async
  42530. * @deprecated
  42531. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  42532. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  42533. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  42534. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42535. */
  42536. async clearAsync( color = true, depth = true, stencil = true ) {
  42537. warnOnce( 'Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42538. await this.init();
  42539. this.clear( color, depth, stencil );
  42540. }
  42541. /**
  42542. * Async version of {@link Renderer#clearColor}.
  42543. *
  42544. * @async
  42545. * @deprecated
  42546. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42547. */
  42548. async clearColorAsync() {
  42549. warnOnce( 'Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42550. this.clear( true, false, false );
  42551. }
  42552. /**
  42553. * Async version of {@link Renderer#clearDepth}.
  42554. *
  42555. * @async
  42556. * @deprecated
  42557. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42558. */
  42559. async clearDepthAsync() {
  42560. warnOnce( 'Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42561. this.clear( false, true, false );
  42562. }
  42563. /**
  42564. * Async version of {@link Renderer#clearStencil}.
  42565. *
  42566. * @async
  42567. * @deprecated
  42568. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42569. */
  42570. async clearStencilAsync() {
  42571. warnOnce( 'Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42572. this.clear( false, false, true );
  42573. }
  42574. /**
  42575. * Returns `true` if a framebuffer target is needed to perform tone mapping or color space conversion.
  42576. * If this is the case, the renderer allocates an internal render target for that purpose.
  42577. *
  42578. */
  42579. get needsFrameBufferTarget() {
  42580. const useToneMapping = this.currentToneMapping !== NoToneMapping;
  42581. const useColorSpace = this.currentColorSpace !== ColorManagement.workingColorSpace;
  42582. return useToneMapping || useColorSpace;
  42583. }
  42584. /**
  42585. * The number of samples used for multi-sample anti-aliasing (MSAA).
  42586. *
  42587. * @type {number}
  42588. * @default 0
  42589. */
  42590. get samples() {
  42591. return this._samples;
  42592. }
  42593. /**
  42594. * The current number of samples used for multi-sample anti-aliasing (MSAA).
  42595. *
  42596. * When rendering to a custom render target, the number of samples of that render target is used.
  42597. * If the renderer needs an internal framebuffer target for tone mapping or color space conversion,
  42598. * the number of samples is set to 0.
  42599. *
  42600. * @type {number}
  42601. */
  42602. get currentSamples() {
  42603. let samples = this._samples;
  42604. if ( this._renderTarget !== null ) {
  42605. samples = this._renderTarget.samples;
  42606. } else if ( this.needsFrameBufferTarget ) {
  42607. samples = 0;
  42608. }
  42609. return samples;
  42610. }
  42611. /**
  42612. * The current tone mapping of the renderer. When not producing screen output,
  42613. * the tone mapping is always `NoToneMapping`.
  42614. *
  42615. * @type {number}
  42616. */
  42617. get currentToneMapping() {
  42618. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  42619. }
  42620. /**
  42621. * The current color space of the renderer. When not producing screen output,
  42622. * the color space is always the working color space.
  42623. *
  42624. * @type {string}
  42625. */
  42626. get currentColorSpace() {
  42627. return this.isOutputTarget ? this.outputColorSpace : ColorManagement.workingColorSpace;
  42628. }
  42629. /**
  42630. * Returns `true` if the rendering settings are set to screen output.
  42631. *
  42632. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  42633. */
  42634. get isOutputTarget() {
  42635. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  42636. }
  42637. /**
  42638. * Frees all internal resources of the renderer. Call this method if the renderer
  42639. * is no longer in use by your app.
  42640. */
  42641. dispose() {
  42642. if ( this._initialized === true ) {
  42643. this.info.dispose();
  42644. this.backend.dispose();
  42645. this._animation.dispose();
  42646. this._objects.dispose();
  42647. this._geometries.dispose();
  42648. this._pipelines.dispose();
  42649. this._nodes.dispose();
  42650. this._bindings.dispose();
  42651. this._renderLists.dispose();
  42652. this._renderContexts.dispose();
  42653. this._textures.dispose();
  42654. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  42655. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  42656. if ( queryPool !== null ) queryPool.dispose();
  42657. } );
  42658. }
  42659. this.setRenderTarget( null );
  42660. this.setAnimationLoop( null );
  42661. }
  42662. /**
  42663. * Sets the given render target. Calling this method means the renderer does not
  42664. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  42665. * Use `null` as the first argument to reset the state.
  42666. *
  42667. * @param {?RenderTarget} renderTarget - The render target to set.
  42668. * @param {number} [activeCubeFace=0] - The active cube face.
  42669. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  42670. */
  42671. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  42672. this._renderTarget = renderTarget;
  42673. this._activeCubeFace = activeCubeFace;
  42674. this._activeMipmapLevel = activeMipmapLevel;
  42675. }
  42676. /**
  42677. * Returns the current render target.
  42678. *
  42679. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  42680. */
  42681. getRenderTarget() {
  42682. return this._renderTarget;
  42683. }
  42684. /**
  42685. * Sets the output render target for the renderer.
  42686. *
  42687. * @param {Object} renderTarget - The render target to set as the output target.
  42688. */
  42689. setOutputRenderTarget( renderTarget ) {
  42690. this._outputRenderTarget = renderTarget;
  42691. }
  42692. /**
  42693. * Returns the current output target.
  42694. *
  42695. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  42696. */
  42697. getOutputRenderTarget() {
  42698. return this._outputRenderTarget;
  42699. }
  42700. /**
  42701. * Sets the canvas target. The canvas target manages the HTML canvas
  42702. * or the offscreen canvas the renderer draws into.
  42703. *
  42704. * @param {CanvasTarget} canvasTarget - The canvas target.
  42705. */
  42706. setCanvasTarget( canvasTarget ) {
  42707. this._canvasTarget.removeEventListener( 'resize', this._onCanvasTargetResize );
  42708. this._canvasTarget = canvasTarget;
  42709. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  42710. }
  42711. /**
  42712. * Returns the current canvas target.
  42713. *
  42714. * @return {CanvasTarget} The current canvas target.
  42715. */
  42716. getCanvasTarget() {
  42717. return this._canvasTarget;
  42718. }
  42719. /**
  42720. * Resets the renderer to the initial state before WebXR started.
  42721. *
  42722. * @private
  42723. */
  42724. _resetXRState() {
  42725. this.backend.setXRTarget( null );
  42726. this.setOutputRenderTarget( null );
  42727. this.setRenderTarget( null );
  42728. this._frameBufferTarget.dispose();
  42729. this._frameBufferTarget = null;
  42730. }
  42731. /**
  42732. * Callback for {@link Renderer#setRenderObjectFunction}.
  42733. *
  42734. * @callback renderObjectFunction
  42735. * @param {Object3D} object - The 3D object.
  42736. * @param {Scene} scene - The scene the 3D object belongs to.
  42737. * @param {Camera} camera - The camera the object should be rendered with.
  42738. * @param {BufferGeometry} geometry - The object's geometry.
  42739. * @param {Material} material - The object's material.
  42740. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  42741. * @param {LightsNode} lightsNode - The current lights node.
  42742. * @param {ClippingContext} clippingContext - The clipping context.
  42743. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  42744. */
  42745. /**
  42746. * Sets the given render object function. Calling this method overwrites the default implementation
  42747. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  42748. * if you want to modify the way objects are rendered. For example you can define things like "every
  42749. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  42750. * The custom function must always call `renderObject()` in its implementation.
  42751. *
  42752. * Use `null` as the first argument to reset the state.
  42753. *
  42754. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  42755. */
  42756. setRenderObjectFunction( renderObjectFunction ) {
  42757. this._renderObjectFunction = renderObjectFunction;
  42758. }
  42759. /**
  42760. * Returns the current render object function.
  42761. *
  42762. * @return {?Function} The current render object function. Returns `null` if no function is set.
  42763. */
  42764. getRenderObjectFunction() {
  42765. return this._renderObjectFunction;
  42766. }
  42767. /**
  42768. * Execute a single or an array of compute nodes. This method can only be called
  42769. * if the renderer has been initialized.
  42770. *
  42771. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  42772. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  42773. * - A single number representing count, or
  42774. * - An array [x, y, z] representing dispatch size, or
  42775. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  42776. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  42777. */
  42778. compute( computeNodes, dispatchSize = null ) {
  42779. if ( this._isDeviceLost === true ) return;
  42780. if ( this._initialized === false ) {
  42781. warn( 'Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  42782. return this.computeAsync( computeNodes, dispatchSize );
  42783. }
  42784. //
  42785. const nodeFrame = this._nodes.nodeFrame;
  42786. const previousRenderId = nodeFrame.renderId;
  42787. //
  42788. this.info.calls ++;
  42789. this.info.compute.calls ++;
  42790. this.info.compute.frameCalls ++;
  42791. nodeFrame.renderId = this.info.calls;
  42792. //
  42793. this.backend.updateTimeStampUID( computeNodes );
  42794. this.inspector.beginCompute( this.backend.getTimestampUID( computeNodes ), computeNodes );
  42795. //
  42796. const backend = this.backend;
  42797. const pipelines = this._pipelines;
  42798. const bindings = this._bindings;
  42799. const nodes = this._nodes;
  42800. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  42801. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  42802. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  42803. }
  42804. backend.beginCompute( computeNodes );
  42805. for ( const computeNode of computeList ) {
  42806. // onInit
  42807. if ( pipelines.has( computeNode ) === false ) {
  42808. const dispose = () => {
  42809. computeNode.removeEventListener( 'dispose', dispose );
  42810. pipelines.delete( computeNode );
  42811. bindings.deleteForCompute( computeNode );
  42812. nodes.delete( computeNode );
  42813. };
  42814. computeNode.addEventListener( 'dispose', dispose );
  42815. //
  42816. const onInitFn = computeNode.onInitFunction;
  42817. if ( onInitFn !== null ) {
  42818. onInitFn.call( computeNode, { renderer: this } );
  42819. }
  42820. }
  42821. nodes.updateForCompute( computeNode );
  42822. bindings.updateForCompute( computeNode );
  42823. const computeBindings = bindings.getForCompute( computeNode );
  42824. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  42825. backend.compute( computeNodes, computeNode, computeBindings, computePipeline, dispatchSize );
  42826. }
  42827. backend.finishCompute( computeNodes );
  42828. //
  42829. nodeFrame.renderId = previousRenderId;
  42830. //
  42831. this.inspector.finishCompute( this.backend.getTimestampUID( computeNodes ) );
  42832. }
  42833. /**
  42834. * Execute a single or an array of compute nodes.
  42835. *
  42836. * @async
  42837. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  42838. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  42839. * - A single number representing count, or
  42840. * - An array [x, y, z] representing dispatch size, or
  42841. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  42842. * @return {Promise} A Promise that resolve when the compute has finished.
  42843. */
  42844. async computeAsync( computeNodes, dispatchSize = null ) {
  42845. if ( this._initialized === false ) await this.init();
  42846. this.compute( computeNodes, dispatchSize );
  42847. }
  42848. /**
  42849. * Checks if the given feature is supported by the selected backend.
  42850. *
  42851. * @async
  42852. * @deprecated
  42853. * @param {string} name - The feature's name.
  42854. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  42855. */
  42856. async hasFeatureAsync( name ) {
  42857. warnOnce( 'Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42858. await this.init();
  42859. return this.hasFeature( name );
  42860. }
  42861. async resolveTimestampsAsync( type = 'render' ) {
  42862. if ( this._initialized === false ) await this.init();
  42863. return this.backend.resolveTimestampsAsync( type );
  42864. }
  42865. /**
  42866. * Checks if the given feature is supported by the selected backend. If the
  42867. * renderer has not been initialized, this method always returns `false`.
  42868. *
  42869. * @param {string} name - The feature's name.
  42870. * @return {boolean} Whether the feature is supported or not.
  42871. */
  42872. hasFeature( name ) {
  42873. if ( this._initialized === false ) {
  42874. throw new Error( 'Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  42875. }
  42876. return this.backend.hasFeature( name );
  42877. }
  42878. /**
  42879. * Returns `true` when the renderer has been initialized.
  42880. *
  42881. * @return {boolean} Whether the renderer has been initialized or not.
  42882. */
  42883. hasInitialized() {
  42884. return this._initialized;
  42885. }
  42886. /**
  42887. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  42888. * (which can cause noticeable lags due to decode and GPU upload overhead).
  42889. *
  42890. * @async
  42891. * @deprecated
  42892. * @param {Texture} texture - The texture.
  42893. * @return {Promise} A Promise that resolves when the texture has been initialized.
  42894. */
  42895. async initTextureAsync( texture ) {
  42896. warnOnce( 'Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42897. await this.init();
  42898. this.initTexture( texture );
  42899. }
  42900. /**
  42901. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  42902. * (which can cause noticeable lags due to decode and GPU upload overhead).
  42903. *
  42904. * This method can only be used if the renderer has been initialized.
  42905. *
  42906. * @param {Texture} texture - The texture.
  42907. */
  42908. initTexture( texture ) {
  42909. if ( this._initialized === false ) {
  42910. throw new Error( 'Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  42911. }
  42912. this._textures.updateTexture( texture );
  42913. }
  42914. /**
  42915. * Copies the current bound framebuffer into the given texture.
  42916. *
  42917. * @param {FramebufferTexture} framebufferTexture - The texture.
  42918. * @param {?(Vector2|Vector4)} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  42919. */
  42920. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  42921. if ( rectangle !== null ) {
  42922. if ( rectangle.isVector2 ) {
  42923. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  42924. } else if ( rectangle.isVector4 ) {
  42925. rectangle = _vector4.copy( rectangle ).floor();
  42926. } else {
  42927. error( 'Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  42928. return;
  42929. }
  42930. } else {
  42931. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  42932. }
  42933. //
  42934. let renderContext = this._currentRenderContext;
  42935. let renderTarget;
  42936. if ( renderContext !== null ) {
  42937. renderTarget = renderContext.renderTarget;
  42938. } else {
  42939. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  42940. if ( renderTarget !== null ) {
  42941. this._textures.updateRenderTarget( renderTarget );
  42942. renderContext = this._textures.get( renderTarget );
  42943. }
  42944. }
  42945. //
  42946. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  42947. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  42948. this._inspector.copyFramebufferToTexture( framebufferTexture );
  42949. }
  42950. /**
  42951. * Copies data of the given source texture into a destination texture.
  42952. *
  42953. * @param {Texture} srcTexture - The source texture.
  42954. * @param {Texture} dstTexture - The destination texture.
  42955. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  42956. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  42957. * @param {number} [srcLevel=0] - The source mip level to copy from.
  42958. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  42959. */
  42960. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  42961. this._textures.updateTexture( srcTexture );
  42962. this._textures.updateTexture( dstTexture );
  42963. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  42964. this._inspector.copyTextureToTexture( srcTexture, dstTexture );
  42965. }
  42966. /**
  42967. * Reads pixel data from the given render target.
  42968. *
  42969. * @async
  42970. * @param {RenderTarget} renderTarget - The render target to read from.
  42971. * @param {number} x - The `x` coordinate of the copy region's origin.
  42972. * @param {number} y - The `y` coordinate of the copy region's origin.
  42973. * @param {number} width - The width of the copy region.
  42974. * @param {number} height - The height of the copy region.
  42975. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  42976. * @param {number} [faceIndex=0] - The active cube face index.
  42977. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  42978. */
  42979. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  42980. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  42981. }
  42982. /**
  42983. * Analyzes the given 3D object's hierarchy and builds render lists from the
  42984. * processed hierarchy.
  42985. *
  42986. * @private
  42987. * @param {Object3D} object - The 3D object to process (usually a scene).
  42988. * @param {Camera} camera - The camera the object is rendered with.
  42989. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  42990. * @param {RenderList} renderList - The current render list.
  42991. * @param {ClippingContext} clippingContext - The current clipping context.
  42992. */
  42993. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  42994. if ( object.visible === false ) return;
  42995. const visible = object.layers.test( camera.layers );
  42996. if ( visible ) {
  42997. if ( object.isGroup ) {
  42998. groupOrder = object.renderOrder;
  42999. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  43000. } else if ( object.isLOD ) {
  43001. if ( object.autoUpdate === true ) object.update( camera );
  43002. } else if ( object.isLight ) {
  43003. renderList.pushLight( object );
  43004. } else if ( object.isSprite ) {
  43005. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  43006. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  43007. if ( this.sortObjects === true ) {
  43008. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  43009. }
  43010. const { geometry, material } = object;
  43011. if ( material.visible ) {
  43012. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  43013. }
  43014. }
  43015. } else if ( object.isLineLoop ) {
  43016. error( 'Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  43017. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  43018. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  43019. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  43020. const { geometry, material } = object;
  43021. if ( this.sortObjects === true ) {
  43022. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  43023. _vector4
  43024. .copy( geometry.boundingSphere.center )
  43025. .applyMatrix4( object.matrixWorld )
  43026. .applyMatrix4( _projScreenMatrix );
  43027. }
  43028. if ( Array.isArray( material ) ) {
  43029. const groups = geometry.groups;
  43030. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  43031. const group = groups[ i ];
  43032. const groupMaterial = material[ group.materialIndex ];
  43033. if ( groupMaterial && groupMaterial.visible ) {
  43034. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  43035. }
  43036. }
  43037. } else if ( material.visible ) {
  43038. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  43039. }
  43040. }
  43041. }
  43042. }
  43043. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  43044. const baseRenderList = renderList;
  43045. // replace render list
  43046. renderList = this._renderLists.get( object, camera );
  43047. renderList.begin();
  43048. baseRenderList.pushBundle( {
  43049. bundleGroup: object,
  43050. camera,
  43051. renderList,
  43052. } );
  43053. renderList.finish();
  43054. }
  43055. const children = object.children;
  43056. for ( let i = 0, l = children.length; i < l; i ++ ) {
  43057. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  43058. }
  43059. }
  43060. /**
  43061. * Renders the given render bundles.
  43062. *
  43063. * @private
  43064. * @param {Array<Object>} bundles - Array with render bundle data.
  43065. * @param {Scene} sceneRef - The scene the render bundles belong to.
  43066. * @param {LightsNode} lightsNode - The current lights node.
  43067. */
  43068. _renderBundles( bundles, sceneRef, lightsNode ) {
  43069. for ( const bundle of bundles ) {
  43070. this._renderBundle( bundle, sceneRef, lightsNode );
  43071. }
  43072. }
  43073. /**
  43074. * Renders the transparent objects from the given render lists.
  43075. *
  43076. * @private
  43077. * @param {Array<Object>} renderList - The transparent render list.
  43078. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  43079. * @param {Camera} camera - The camera the render list should be rendered with.
  43080. * @param {Scene} scene - The scene the render list belongs to.
  43081. * @param {LightsNode} lightsNode - The current lights node.
  43082. */
  43083. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  43084. if ( doublePassList.length > 0 ) {
  43085. // render back side
  43086. for ( const { material } of doublePassList ) {
  43087. material.side = BackSide;
  43088. }
  43089. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  43090. // render front side
  43091. for ( const { material } of doublePassList ) {
  43092. material.side = FrontSide;
  43093. }
  43094. this._renderObjects( renderList, camera, scene, lightsNode );
  43095. // restore
  43096. for ( const { material } of doublePassList ) {
  43097. material.side = DoubleSide;
  43098. }
  43099. } else {
  43100. this._renderObjects( renderList, camera, scene, lightsNode );
  43101. }
  43102. }
  43103. /**
  43104. * Renders the objects from the given render list.
  43105. *
  43106. * @private
  43107. * @param {Array<Object>} renderList - The render list.
  43108. * @param {Camera} camera - The camera the render list should be rendered with.
  43109. * @param {Scene} scene - The scene the render list belongs to.
  43110. * @param {LightsNode} lightsNode - The current lights node.
  43111. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  43112. */
  43113. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  43114. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  43115. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  43116. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  43117. }
  43118. }
  43119. /**
  43120. * Retrieves shadow nodes for the given material. This is used to setup shadow passes.
  43121. * The result is cached per material and updated when the material's version changes.
  43122. *
  43123. * @private
  43124. * @param {Material} material
  43125. * @returns {Object} - The shadow nodes for the material.
  43126. */
  43127. _getShadowNodes( material ) {
  43128. const version = material.version;
  43129. let cache = this._cacheShadowNodes.get( material );
  43130. if ( cache === undefined || cache.version !== version ) {
  43131. const hasMap = material.map !== null;
  43132. const hasColorNode = material.colorNode && material.colorNode.isNode;
  43133. const hasCastShadowNode = material.castShadowNode && material.castShadowNode.isNode;
  43134. let positionNode = null;
  43135. let colorNode = null;
  43136. let depthNode = null;
  43137. if ( hasMap || hasColorNode || hasCastShadowNode ) {
  43138. let shadowRGB;
  43139. let shadowAlpha;
  43140. if ( hasCastShadowNode ) {
  43141. shadowRGB = material.castShadowNode.rgb;
  43142. shadowAlpha = material.castShadowNode.a;
  43143. } else {
  43144. shadowRGB = vec3( 0 );
  43145. shadowAlpha = float( 1 );
  43146. }
  43147. if ( hasMap ) {
  43148. shadowAlpha = shadowAlpha.mul( reference( 'map', 'texture', material ).a );
  43149. }
  43150. if ( hasColorNode ) {
  43151. shadowAlpha = shadowAlpha.mul( material.colorNode.a );
  43152. }
  43153. colorNode = vec4( shadowRGB, shadowAlpha );
  43154. }
  43155. if ( material.depthNode && material.depthNode.isNode ) {
  43156. depthNode = material.depthNode;
  43157. }
  43158. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  43159. positionNode = material.castShadowPositionNode;
  43160. } else if ( material.positionNode && material.positionNode.isNode ) {
  43161. positionNode = material.positionNode;
  43162. }
  43163. cache = {
  43164. version,
  43165. colorNode,
  43166. depthNode,
  43167. positionNode
  43168. };
  43169. this._cacheShadowNodes.set( material, cache );
  43170. }
  43171. return cache;
  43172. }
  43173. /**
  43174. * This method represents the default render object function that manages the render lifecycle
  43175. * of the object.
  43176. *
  43177. * @param {Object3D} object - The 3D object.
  43178. * @param {Scene} scene - The scene the 3D object belongs to.
  43179. * @param {Camera} camera - The camera the object should be rendered with.
  43180. * @param {BufferGeometry} geometry - The object's geometry.
  43181. * @param {Material} material - The object's material.
  43182. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  43183. * @param {LightsNode} lightsNode - The current lights node.
  43184. * @param {?ClippingContext} clippingContext - The clipping context.
  43185. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  43186. */
  43187. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  43188. let materialOverride = false;
  43189. let materialColorNode;
  43190. let materialDepthNode;
  43191. let materialPositionNode;
  43192. let materialSide;
  43193. //
  43194. object.onBeforeRender( this, scene, camera, geometry, material, group );
  43195. //
  43196. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  43197. const overrideMaterial = scene.overrideMaterial;
  43198. materialOverride = true;
  43199. // store original nodes
  43200. materialColorNode = scene.overrideMaterial.colorNode;
  43201. materialDepthNode = scene.overrideMaterial.depthNode;
  43202. materialPositionNode = scene.overrideMaterial.positionNode;
  43203. materialSide = scene.overrideMaterial.side;
  43204. if ( material.positionNode && material.positionNode.isNode ) {
  43205. overrideMaterial.positionNode = material.positionNode;
  43206. }
  43207. overrideMaterial.alphaTest = material.alphaTest;
  43208. overrideMaterial.alphaMap = material.alphaMap;
  43209. overrideMaterial.transparent = material.transparent || material.transmission > 0 ||
  43210. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  43211. ( material.backdropNode && material.backdropNode.isNode );
  43212. if ( overrideMaterial.isShadowPassMaterial ) {
  43213. const { colorNode, depthNode, positionNode } = this._getShadowNodes( material );
  43214. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  43215. if ( colorNode !== null ) overrideMaterial.colorNode = colorNode;
  43216. if ( depthNode !== null ) overrideMaterial.depthNode = depthNode;
  43217. if ( positionNode !== null ) overrideMaterial.positionNode = positionNode;
  43218. }
  43219. material = overrideMaterial;
  43220. }
  43221. //
  43222. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  43223. material.side = BackSide;
  43224. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  43225. material.side = FrontSide;
  43226. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  43227. material.side = DoubleSide;
  43228. } else {
  43229. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  43230. }
  43231. //
  43232. if ( materialOverride ) {
  43233. scene.overrideMaterial.colorNode = materialColorNode;
  43234. scene.overrideMaterial.depthNode = materialDepthNode;
  43235. scene.overrideMaterial.positionNode = materialPositionNode;
  43236. scene.overrideMaterial.side = materialSide;
  43237. }
  43238. //
  43239. object.onAfterRender( this, scene, camera, geometry, material, group );
  43240. }
  43241. /**
  43242. * This method represents the default `_handleObjectFunction` implementation which creates
  43243. * a render object from the given data and performs the draw command with the selected backend.
  43244. *
  43245. * @private
  43246. * @param {Object3D} object - The 3D object.
  43247. * @param {Material} material - The object's material.
  43248. * @param {Scene} scene - The scene the 3D object belongs to.
  43249. * @param {Camera} camera - The camera the object should be rendered with.
  43250. * @param {LightsNode} lightsNode - The current lights node.
  43251. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  43252. * @param {ClippingContext} clippingContext - The clipping context.
  43253. * @param {string} [passId] - An optional ID for identifying the pass.
  43254. */
  43255. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  43256. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  43257. renderObject.drawRange = object.geometry.drawRange;
  43258. renderObject.group = group;
  43259. //
  43260. const needsRefresh = this._nodes.needsRefresh( renderObject );
  43261. if ( needsRefresh ) {
  43262. this._nodes.updateBefore( renderObject );
  43263. this._geometries.updateForRender( renderObject );
  43264. this._nodes.updateForRender( renderObject );
  43265. this._bindings.updateForRender( renderObject );
  43266. }
  43267. this._pipelines.updateForRender( renderObject );
  43268. //
  43269. if ( this._currentRenderBundle !== null ) {
  43270. const renderBundleData = this.backend.get( this._currentRenderBundle );
  43271. renderBundleData.renderObjects.push( renderObject );
  43272. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  43273. }
  43274. this.backend.draw( renderObject, this.info );
  43275. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  43276. }
  43277. /**
  43278. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  43279. * Used in `compileAsync()`.
  43280. *
  43281. * @private
  43282. * @param {Object3D} object - The 3D object.
  43283. * @param {Material} material - The object's material.
  43284. * @param {Scene} scene - The scene the 3D object belongs to.
  43285. * @param {Camera} camera - The camera the object should be rendered with.
  43286. * @param {LightsNode} lightsNode - The current lights node.
  43287. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  43288. * @param {ClippingContext} clippingContext - The clipping context.
  43289. * @param {string} [passId] - An optional ID for identifying the pass.
  43290. */
  43291. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  43292. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  43293. renderObject.drawRange = object.geometry.drawRange;
  43294. renderObject.group = group;
  43295. //
  43296. this._nodes.updateBefore( renderObject );
  43297. this._geometries.updateForRender( renderObject );
  43298. this._nodes.updateForRender( renderObject );
  43299. this._bindings.updateForRender( renderObject );
  43300. this._pipelines.getForRender( renderObject, this._compilationPromises );
  43301. this._nodes.updateAfter( renderObject );
  43302. }
  43303. /**
  43304. * Callback when the canvas has been resized.
  43305. *
  43306. * @private
  43307. */
  43308. _onCanvasTargetResize() {
  43309. if ( this._initialized ) this.backend.updateSize();
  43310. }
  43311. /**
  43312. * Alias for `compileAsync()`.
  43313. *
  43314. * @method
  43315. * @param {Object3D} scene - The scene or 3D object to precompile.
  43316. * @param {Camera} camera - The camera that is used to render the scene.
  43317. * @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.
  43318. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  43319. */
  43320. get compile() {
  43321. return this.compileAsync;
  43322. }
  43323. }
  43324. /**
  43325. * A binding represents the connection between a resource (like a texture, sampler
  43326. * or uniform buffer) and the resource definition in a shader stage.
  43327. *
  43328. * This module is an abstract base class for all concrete bindings types.
  43329. *
  43330. * @abstract
  43331. * @private
  43332. */
  43333. class Binding {
  43334. /**
  43335. * Constructs a new binding.
  43336. *
  43337. * @param {string} [name=''] - The binding's name.
  43338. */
  43339. constructor( name = '' ) {
  43340. /**
  43341. * The binding's name.
  43342. *
  43343. * @type {string}
  43344. */
  43345. this.name = name;
  43346. /**
  43347. * A bitmask that defines in what shader stages the
  43348. * binding's resource is accessible.
  43349. *
  43350. * @type {number}
  43351. */
  43352. this.visibility = 0;
  43353. }
  43354. /**
  43355. * Makes sure binding's resource is visible for the given shader stage.
  43356. *
  43357. * @param {number} visibility - The shader stage.
  43358. */
  43359. setVisibility( visibility ) {
  43360. this.visibility |= visibility;
  43361. }
  43362. /**
  43363. * The shader stages in which the binding's resource is visible.
  43364. *
  43365. * @return {number} The visibility bitmask.
  43366. */
  43367. getVisibility() {
  43368. return this.visibility;
  43369. }
  43370. /**
  43371. * Clones the binding.
  43372. *
  43373. * @return {Binding} The cloned binding.
  43374. */
  43375. clone() {
  43376. return Object.assign( new this.constructor(), this );
  43377. }
  43378. }
  43379. /**
  43380. * This function is usually called with the length in bytes of an array buffer.
  43381. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  43382. *
  43383. * @function
  43384. * @param {number} floatLength - The buffer length.
  43385. * @return {number} The padded length.
  43386. */
  43387. function getFloatLength( floatLength ) {
  43388. // ensure chunk size alignment (STD140 layout)
  43389. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  43390. }
  43391. /**
  43392. * Represents a buffer binding type.
  43393. *
  43394. * @private
  43395. * @abstract
  43396. * @augments Binding
  43397. */
  43398. class Buffer extends Binding {
  43399. /**
  43400. * Constructs a new buffer.
  43401. *
  43402. * @param {string} name - The buffer's name.
  43403. * @param {TypedArray} [buffer=null] - The buffer.
  43404. */
  43405. constructor( name, buffer = null ) {
  43406. super( name );
  43407. /**
  43408. * This flag can be used for type testing.
  43409. *
  43410. * @type {boolean}
  43411. * @readonly
  43412. * @default true
  43413. */
  43414. this.isBuffer = true;
  43415. /**
  43416. * The bytes per element.
  43417. *
  43418. * @type {number}
  43419. */
  43420. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  43421. /**
  43422. * A reference to the internal buffer.
  43423. *
  43424. * @private
  43425. * @type {TypedArray}
  43426. */
  43427. this._buffer = buffer;
  43428. /**
  43429. * An array of update ranges.
  43430. *
  43431. * @private
  43432. * @type {Array<{start: number, count: number}>}
  43433. */
  43434. this._updateRanges = [];
  43435. }
  43436. /**
  43437. * The array of update ranges.
  43438. *
  43439. * @type {Array<{start: number, count: number}>}
  43440. */
  43441. get updateRanges() {
  43442. return this._updateRanges;
  43443. }
  43444. /**
  43445. * Adds an update range.
  43446. *
  43447. * @param {number} start - The start index.
  43448. * @param {number} count - The number of elements.
  43449. */
  43450. addUpdateRange( start, count ) {
  43451. this.updateRanges.push( { start, count } );
  43452. }
  43453. /**
  43454. * Clears all update ranges.
  43455. */
  43456. clearUpdateRanges() {
  43457. this.updateRanges.length = 0;
  43458. }
  43459. /**
  43460. * The buffer's byte length.
  43461. *
  43462. * @type {number}
  43463. * @readonly
  43464. */
  43465. get byteLength() {
  43466. return getFloatLength( this._buffer.byteLength );
  43467. }
  43468. /**
  43469. * A reference to the internal buffer.
  43470. *
  43471. * @type {Float32Array}
  43472. * @readonly
  43473. */
  43474. get buffer() {
  43475. return this._buffer;
  43476. }
  43477. /**
  43478. * Updates the binding.
  43479. *
  43480. * @return {boolean} Whether the buffer has been updated and must be
  43481. * uploaded to the GPU.
  43482. */
  43483. update() {
  43484. return true;
  43485. }
  43486. }
  43487. /**
  43488. * Represents a uniform buffer binding type.
  43489. *
  43490. * @private
  43491. * @augments Buffer
  43492. */
  43493. class UniformBuffer extends Buffer {
  43494. /**
  43495. * Constructs a new uniform buffer.
  43496. *
  43497. * @param {string} name - The buffer's name.
  43498. * @param {TypedArray} [buffer=null] - The buffer.
  43499. */
  43500. constructor( name, buffer = null ) {
  43501. super( name, buffer );
  43502. /**
  43503. * This flag can be used for type testing.
  43504. *
  43505. * @type {boolean}
  43506. * @readonly
  43507. * @default true
  43508. */
  43509. this.isUniformBuffer = true;
  43510. }
  43511. }
  43512. let _id$4 = 0;
  43513. /**
  43514. * A special form of uniform buffer binding type.
  43515. * It's buffer value is managed by a node object.
  43516. *
  43517. * @private
  43518. * @augments UniformBuffer
  43519. */
  43520. class NodeUniformBuffer extends UniformBuffer {
  43521. /**
  43522. * Constructs a new node-based uniform buffer.
  43523. *
  43524. * @param {BufferNode} nodeUniform - The uniform buffer node.
  43525. * @param {UniformGroupNode} groupNode - The uniform group node.
  43526. */
  43527. constructor( nodeUniform, groupNode ) {
  43528. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  43529. /**
  43530. * The uniform buffer node.
  43531. *
  43532. * @type {BufferNode}
  43533. */
  43534. this.nodeUniform = nodeUniform;
  43535. /**
  43536. * The uniform group node.
  43537. *
  43538. * @type {UniformGroupNode}
  43539. */
  43540. this.groupNode = groupNode;
  43541. /**
  43542. * This flag can be used for type testing.
  43543. *
  43544. * @type {boolean}
  43545. * @readonly
  43546. * @default true
  43547. */
  43548. this.isNodeUniformBuffer = true;
  43549. }
  43550. /**
  43551. * The array of update ranges.
  43552. *
  43553. * @param {Array<{start: number, count: number}>} value - The update ranges.
  43554. */
  43555. set updateRanges( value ) {
  43556. this.nodeUniform.updateRanges = value;
  43557. }
  43558. /**
  43559. * The array of update ranges.
  43560. *
  43561. * @type {Array<{start: number, count: number}>}
  43562. */
  43563. get updateRanges() {
  43564. return this.nodeUniform.updateRanges;
  43565. }
  43566. /**
  43567. * Adds a range of data in the data array to be updated on the GPU.
  43568. *
  43569. * @param {number} start - Position at which to start update.
  43570. * @param {number} count - The number of components to update.
  43571. */
  43572. addUpdateRange( start, count ) {
  43573. this.nodeUniform.addUpdateRange( start, count );
  43574. }
  43575. /**
  43576. * Clears all update ranges.
  43577. */
  43578. clearUpdateRanges() {
  43579. this.nodeUniform.clearUpdateRanges();
  43580. }
  43581. /**
  43582. * The uniform buffer.
  43583. *
  43584. * @type {Float32Array}
  43585. */
  43586. get buffer() {
  43587. return this.nodeUniform.value;
  43588. }
  43589. }
  43590. /**
  43591. * This class represents a uniform buffer binding but with
  43592. * an API that allows to maintain individual uniform objects.
  43593. *
  43594. * @private
  43595. * @augments UniformBuffer
  43596. */
  43597. class UniformsGroup extends UniformBuffer {
  43598. /**
  43599. * Constructs a new uniforms group.
  43600. *
  43601. * @param {string} name - The group's name.
  43602. */
  43603. constructor( name ) {
  43604. super( name );
  43605. /**
  43606. * This flag can be used for type testing.
  43607. *
  43608. * @type {boolean}
  43609. * @readonly
  43610. * @default true
  43611. */
  43612. this.isUniformsGroup = true;
  43613. /**
  43614. * An array with the raw uniform values.
  43615. *
  43616. * @private
  43617. * @type {?Array<number>}
  43618. * @default null
  43619. */
  43620. this._values = null;
  43621. /**
  43622. * An array of uniform objects.
  43623. *
  43624. * The order of uniforms in this array must match the order of uniforms in the shader.
  43625. *
  43626. * @type {Array<Uniform>}
  43627. */
  43628. this.uniforms = [];
  43629. }
  43630. /**
  43631. * Adds a uniform to this group.
  43632. *
  43633. * @param {Uniform} uniform - The uniform to add.
  43634. * @return {UniformsGroup} A reference to this group.
  43635. */
  43636. addUniform( uniform ) {
  43637. this.uniforms.push( uniform );
  43638. return this;
  43639. }
  43640. /**
  43641. * Removes a uniform from this group.
  43642. *
  43643. * @param {Uniform} uniform - The uniform to remove.
  43644. * @return {UniformsGroup} A reference to this group.
  43645. */
  43646. removeUniform( uniform ) {
  43647. const index = this.uniforms.indexOf( uniform );
  43648. if ( index !== -1 ) {
  43649. this.uniforms.splice( index, 1 );
  43650. }
  43651. return this;
  43652. }
  43653. /**
  43654. * An array with the raw uniform values.
  43655. *
  43656. * @type {Array<number>}
  43657. */
  43658. get values() {
  43659. if ( this._values === null ) {
  43660. this._values = Array.from( this.buffer );
  43661. }
  43662. return this._values;
  43663. }
  43664. /**
  43665. * A Float32 array buffer with the uniform values.
  43666. *
  43667. * @type {Float32Array}
  43668. */
  43669. get buffer() {
  43670. let buffer = this._buffer;
  43671. if ( buffer === null ) {
  43672. const byteLength = this.byteLength;
  43673. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  43674. this._buffer = buffer;
  43675. }
  43676. return buffer;
  43677. }
  43678. /**
  43679. * The byte length of the buffer with correct buffer alignment.
  43680. *
  43681. * @type {number}
  43682. */
  43683. get byteLength() {
  43684. const bytesPerElement = this.bytesPerElement;
  43685. let offset = 0; // global buffer offset in bytes
  43686. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  43687. const uniform = this.uniforms[ i ];
  43688. const boundary = uniform.boundary;
  43689. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  43690. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  43691. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  43692. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  43693. offset += chunkPadding;
  43694. // Check for chunk overflow
  43695. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  43696. // Add padding to the end of the chunk
  43697. offset += ( GPU_CHUNK_BYTES - chunkStart );
  43698. }
  43699. uniform.offset = offset / bytesPerElement;
  43700. offset += itemSize;
  43701. }
  43702. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  43703. }
  43704. /**
  43705. * Updates this group by updating each uniform object of
  43706. * the internal uniform list. The uniform objects check if their
  43707. * values has actually changed so this method only returns
  43708. * `true` if there is a real value change.
  43709. *
  43710. * @return {boolean} Whether the uniforms have been updated and
  43711. * must be uploaded to the GPU.
  43712. */
  43713. update() {
  43714. let updated = false;
  43715. for ( const uniform of this.uniforms ) {
  43716. if ( this.updateByType( uniform ) === true ) {
  43717. updated = true;
  43718. }
  43719. }
  43720. return updated;
  43721. }
  43722. /**
  43723. * Updates a given uniform by calling an update method matching
  43724. * the uniforms type.
  43725. *
  43726. * @param {Uniform} uniform - The uniform to update.
  43727. * @return {boolean} Whether the uniform has been updated or not.
  43728. */
  43729. updateByType( uniform ) {
  43730. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  43731. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  43732. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  43733. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  43734. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  43735. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  43736. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  43737. error( 'WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  43738. }
  43739. /**
  43740. * Updates a given Number uniform.
  43741. *
  43742. * @param {NumberUniform} uniform - The Number uniform.
  43743. * @return {boolean} Whether the uniform has been updated or not.
  43744. */
  43745. updateNumber( uniform ) {
  43746. let updated = false;
  43747. const a = this.values;
  43748. const v = uniform.getValue();
  43749. const offset = uniform.offset;
  43750. const type = uniform.getType();
  43751. if ( a[ offset ] !== v ) {
  43752. const b = this._getBufferForType( type );
  43753. b[ offset ] = a[ offset ] = v;
  43754. updated = true;
  43755. }
  43756. return updated;
  43757. }
  43758. /**
  43759. * Updates a given Vector2 uniform.
  43760. *
  43761. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  43762. * @return {boolean} Whether the uniform has been updated or not.
  43763. */
  43764. updateVector2( uniform ) {
  43765. let updated = false;
  43766. const a = this.values;
  43767. const v = uniform.getValue();
  43768. const offset = uniform.offset;
  43769. const type = uniform.getType();
  43770. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  43771. const b = this._getBufferForType( type );
  43772. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  43773. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  43774. updated = true;
  43775. }
  43776. return updated;
  43777. }
  43778. /**
  43779. * Updates a given Vector3 uniform.
  43780. *
  43781. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  43782. * @return {boolean} Whether the uniform has been updated or not.
  43783. */
  43784. updateVector3( uniform ) {
  43785. let updated = false;
  43786. const a = this.values;
  43787. const v = uniform.getValue();
  43788. const offset = uniform.offset;
  43789. const type = uniform.getType();
  43790. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  43791. const b = this._getBufferForType( type );
  43792. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  43793. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  43794. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  43795. updated = true;
  43796. }
  43797. return updated;
  43798. }
  43799. /**
  43800. * Updates a given Vector4 uniform.
  43801. *
  43802. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  43803. * @return {boolean} Whether the uniform has been updated or not.
  43804. */
  43805. updateVector4( uniform ) {
  43806. let updated = false;
  43807. const a = this.values;
  43808. const v = uniform.getValue();
  43809. const offset = uniform.offset;
  43810. const type = uniform.getType();
  43811. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  43812. const b = this._getBufferForType( type );
  43813. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  43814. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  43815. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  43816. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  43817. updated = true;
  43818. }
  43819. return updated;
  43820. }
  43821. /**
  43822. * Updates a given Color uniform.
  43823. *
  43824. * @param {ColorUniform} uniform - The Color uniform.
  43825. * @return {boolean} Whether the uniform has been updated or not.
  43826. */
  43827. updateColor( uniform ) {
  43828. let updated = false;
  43829. const a = this.values;
  43830. const c = uniform.getValue();
  43831. const offset = uniform.offset;
  43832. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  43833. const b = this.buffer;
  43834. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  43835. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  43836. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  43837. updated = true;
  43838. }
  43839. return updated;
  43840. }
  43841. /**
  43842. * Updates a given Matrix3 uniform.
  43843. *
  43844. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  43845. * @return {boolean} Whether the uniform has been updated or not.
  43846. */
  43847. updateMatrix3( uniform ) {
  43848. let updated = false;
  43849. const a = this.values;
  43850. const e = uniform.getValue().elements;
  43851. const offset = uniform.offset;
  43852. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  43853. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  43854. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  43855. const b = this.buffer;
  43856. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  43857. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  43858. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  43859. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  43860. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  43861. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  43862. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  43863. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  43864. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  43865. updated = true;
  43866. }
  43867. return updated;
  43868. }
  43869. /**
  43870. * Updates a given Matrix4 uniform.
  43871. *
  43872. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  43873. * @return {boolean} Whether the uniform has been updated or not.
  43874. */
  43875. updateMatrix4( uniform ) {
  43876. let updated = false;
  43877. const a = this.values;
  43878. const e = uniform.getValue().elements;
  43879. const offset = uniform.offset;
  43880. if ( arraysEqual( a, e, offset ) === false ) {
  43881. const b = this.buffer;
  43882. b.set( e, offset );
  43883. setArray( a, e, offset );
  43884. updated = true;
  43885. }
  43886. return updated;
  43887. }
  43888. /**
  43889. * Returns a typed array that matches the given data type.
  43890. *
  43891. * @private
  43892. * @param {string} type - The data type.
  43893. * @return {TypedArray} The typed array.
  43894. */
  43895. _getBufferForType( type ) {
  43896. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  43897. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  43898. return this.buffer;
  43899. }
  43900. }
  43901. /**
  43902. * Sets the values of the second array to the first array.
  43903. *
  43904. * @private
  43905. * @param {TypedArray} a - The first array.
  43906. * @param {TypedArray} b - The second array.
  43907. * @param {number} offset - An index offset for the first array.
  43908. */
  43909. function setArray( a, b, offset ) {
  43910. for ( let i = 0, l = b.length; i < l; i ++ ) {
  43911. a[ offset + i ] = b[ i ];
  43912. }
  43913. }
  43914. /**
  43915. * Returns `true` if the given arrays are equal.
  43916. *
  43917. * @private
  43918. * @param {TypedArray} a - The first array.
  43919. * @param {TypedArray} b - The second array.
  43920. * @param {number} offset - An index offset for the first array.
  43921. * @return {boolean} Whether the given arrays are equal or not.
  43922. */
  43923. function arraysEqual( a, b, offset ) {
  43924. for ( let i = 0, l = b.length; i < l; i ++ ) {
  43925. if ( a[ offset + i ] !== b[ i ] ) return false;
  43926. }
  43927. return true;
  43928. }
  43929. let _id$3 = 0;
  43930. /**
  43931. * A special form of uniforms group that represents
  43932. * the individual uniforms as node-based uniforms.
  43933. *
  43934. * @private
  43935. * @augments UniformsGroup
  43936. */
  43937. class NodeUniformsGroup extends UniformsGroup {
  43938. /**
  43939. * Constructs a new node-based uniforms group.
  43940. *
  43941. * @param {string} name - The group's name.
  43942. * @param {UniformGroupNode} groupNode - The uniform group node.
  43943. */
  43944. constructor( name, groupNode ) {
  43945. super( name );
  43946. /**
  43947. * The group's ID.
  43948. *
  43949. * @type {number}
  43950. */
  43951. this.id = _id$3 ++;
  43952. /**
  43953. * The uniform group node.
  43954. *
  43955. * @type {UniformGroupNode}
  43956. */
  43957. this.groupNode = groupNode;
  43958. /**
  43959. * This flag can be used for type testing.
  43960. *
  43961. * @type {boolean}
  43962. * @readonly
  43963. * @default true
  43964. */
  43965. this.isNodeUniformsGroup = true;
  43966. }
  43967. }
  43968. /**
  43969. * Represents a sampler binding type.
  43970. *
  43971. * @private
  43972. * @augments Binding
  43973. */
  43974. class Sampler extends Binding {
  43975. /**
  43976. * Constructs a new sampler.
  43977. *
  43978. * @param {string} name - The samplers's name.
  43979. * @param {?Texture} texture - The texture this binding is referring to.
  43980. */
  43981. constructor( name, texture ) {
  43982. super( name );
  43983. /**
  43984. * The texture the sampler is referring to.
  43985. *
  43986. * @private
  43987. * @type {?Texture}
  43988. */
  43989. this._texture = null;
  43990. /**
  43991. * An event listener which is added to {@link texture}'s dispose event.
  43992. *
  43993. * @private
  43994. * @type {Function}
  43995. */
  43996. this._onTextureDispose = () => {
  43997. this.generation = null;
  43998. this.version = 0;
  43999. };
  44000. // Assignment to the texture via a setter must occur after "_onTextureDispose" is initialized.
  44001. this.texture = texture;
  44002. /**
  44003. * The binding's version.
  44004. *
  44005. * @type {number}
  44006. */
  44007. this.version = texture ? texture.version : 0;
  44008. /**
  44009. * The binding's generation which is an additional version
  44010. * qualifier.
  44011. *
  44012. * @type {?number}
  44013. * @default null
  44014. */
  44015. this.generation = null;
  44016. /**
  44017. * The binding's sampler key.
  44018. *
  44019. * @type {string}
  44020. * @default ''
  44021. */
  44022. this.samplerKey = '';
  44023. /**
  44024. * This flag can be used for type testing.
  44025. *
  44026. * @type {boolean}
  44027. * @readonly
  44028. * @default true
  44029. */
  44030. this.isSampler = true;
  44031. }
  44032. /**
  44033. * Sets the texture of this sampler.
  44034. *
  44035. * @param {Texture} value - The texture to set.
  44036. */
  44037. set texture( value ) {
  44038. if ( this._texture === value ) return;
  44039. if ( this._texture ) {
  44040. this._texture.removeEventListener( 'dispose', this._onTextureDispose );
  44041. }
  44042. this._texture = value;
  44043. this.generation = null;
  44044. this.version = 0;
  44045. if ( this._texture ) {
  44046. this._texture.addEventListener( 'dispose', this._onTextureDispose );
  44047. }
  44048. }
  44049. /**
  44050. * Gets the texture of this sampler.
  44051. * @return {?Texture} The texture.
  44052. */
  44053. get texture() {
  44054. return this._texture;
  44055. }
  44056. /**
  44057. * Updates the binding.
  44058. *
  44059. * @return {boolean} Whether the texture has been updated and must be
  44060. * uploaded to the GPU.
  44061. */
  44062. update() {
  44063. const { texture, version } = this;
  44064. if ( version !== texture.version ) {
  44065. this.version = texture.version;
  44066. return true;
  44067. }
  44068. return false;
  44069. }
  44070. clone() {
  44071. const clonedSampler = super.clone();
  44072. // fix dispose handler for cloned instances
  44073. // TODO: Find better solution, see #31747
  44074. clonedSampler._texture = null;
  44075. clonedSampler._onTextureDispose = () => {
  44076. clonedSampler.generation = null;
  44077. clonedSampler.version = 0;
  44078. };
  44079. clonedSampler.texture = this.texture;
  44080. return clonedSampler;
  44081. }
  44082. }
  44083. let _id$2 = 0;
  44084. /**
  44085. * Represents a sampled texture binding type.
  44086. *
  44087. * @private
  44088. * @augments Sampler
  44089. */
  44090. class SampledTexture extends Sampler {
  44091. /**
  44092. * Constructs a new sampled texture.
  44093. *
  44094. * @param {string} name - The sampled texture's name.
  44095. * @param {?Texture} texture - The texture this binding is referring to.
  44096. */
  44097. constructor( name, texture ) {
  44098. super( name, texture );
  44099. /**
  44100. * This identifier.
  44101. *
  44102. * @type {number}
  44103. */
  44104. this.id = _id$2 ++;
  44105. /**
  44106. * Whether the texture is a storage texture or not.
  44107. *
  44108. * @type {boolean}
  44109. * @default false
  44110. */
  44111. this.store = false;
  44112. /**
  44113. * The mip level to bind for storage textures.
  44114. *
  44115. * @type {number}
  44116. * @default 0
  44117. */
  44118. this.mipLevel = 0;
  44119. /**
  44120. * This flag can be used for type testing.
  44121. *
  44122. * @type {boolean}
  44123. * @readonly
  44124. * @default true
  44125. */
  44126. this.isSampledTexture = true;
  44127. }
  44128. }
  44129. /**
  44130. * A special form of sampled texture binding type.
  44131. * It's texture value is managed by a node object.
  44132. *
  44133. * @private
  44134. * @augments SampledTexture
  44135. */
  44136. class NodeSampledTexture extends SampledTexture {
  44137. /**
  44138. * Constructs a new node-based sampled texture.
  44139. *
  44140. * @param {string} name - The textures's name.
  44141. * @param {TextureNode} textureNode - The texture node.
  44142. * @param {UniformGroupNode} groupNode - The uniform group node.
  44143. * @param {?string} [access=null] - The access type.
  44144. */
  44145. constructor( name, textureNode, groupNode, access = null ) {
  44146. super( name, textureNode ? textureNode.value : null );
  44147. /**
  44148. * The texture node.
  44149. *
  44150. * @type {TextureNode}
  44151. */
  44152. this.textureNode = textureNode;
  44153. /**
  44154. * The uniform group node.
  44155. *
  44156. * @type {UniformGroupNode}
  44157. */
  44158. this.groupNode = groupNode;
  44159. /**
  44160. * The access type.
  44161. *
  44162. * @type {?string}
  44163. * @default null
  44164. */
  44165. this.access = access;
  44166. }
  44167. /**
  44168. * Updates the binding.
  44169. *
  44170. * @return {boolean} Whether the texture has been updated and must be
  44171. * uploaded to the GPU.
  44172. */
  44173. update() {
  44174. const { textureNode } = this;
  44175. if ( this.texture !== textureNode.value ) {
  44176. this.texture = textureNode.value;
  44177. return true;
  44178. }
  44179. return super.update();
  44180. }
  44181. }
  44182. /**
  44183. * A special form of sampled cube texture binding type.
  44184. * It's texture value is managed by a node object.
  44185. *
  44186. * @private
  44187. * @augments NodeSampledTexture
  44188. */
  44189. class NodeSampledCubeTexture extends NodeSampledTexture {
  44190. /**
  44191. * Constructs a new node-based sampled cube texture.
  44192. *
  44193. * @param {string} name - The textures's name.
  44194. * @param {TextureNode} textureNode - The texture node.
  44195. * @param {UniformGroupNode} groupNode - The uniform group node.
  44196. * @param {?string} [access=null] - The access type.
  44197. */
  44198. constructor( name, textureNode, groupNode, access = null ) {
  44199. super( name, textureNode, groupNode, access );
  44200. /**
  44201. * This flag can be used for type testing.
  44202. *
  44203. * @type {boolean}
  44204. * @readonly
  44205. * @default true
  44206. */
  44207. this.isSampledCubeTexture = true;
  44208. }
  44209. }
  44210. /**
  44211. * A special form of sampled 3D texture binding type.
  44212. * It's texture value is managed by a node object.
  44213. *
  44214. * @private
  44215. * @augments NodeSampledTexture
  44216. */
  44217. class NodeSampledTexture3D extends NodeSampledTexture {
  44218. /**
  44219. * Constructs a new node-based sampled 3D texture.
  44220. *
  44221. * @param {string} name - The textures's name.
  44222. * @param {TextureNode} textureNode - The texture node.
  44223. * @param {UniformGroupNode} groupNode - The uniform group node.
  44224. * @param {?string} [access=null] - The access type.
  44225. */
  44226. constructor( name, textureNode, groupNode, access = null ) {
  44227. super( name, textureNode, groupNode, access );
  44228. /**
  44229. * This flag can be used for type testing.
  44230. *
  44231. * @type {boolean}
  44232. * @readonly
  44233. * @default true
  44234. */
  44235. this.isSampledTexture3D = true;
  44236. }
  44237. }
  44238. const glslPolyfills = {
  44239. bitcast_int_uint: new CodeNode( /* glsl */'uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }' ),
  44240. bitcast_uint_int: new CodeNode( /* glsl */'uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }' )
  44241. };
  44242. const glslMethods = {
  44243. textureDimensions: 'textureSize',
  44244. equals: 'equal',
  44245. bitcast_float_int: 'floatBitsToInt',
  44246. bitcast_int_float: 'intBitsToFloat',
  44247. bitcast_uint_float: 'uintBitsToFloat',
  44248. bitcast_float_uint: 'floatBitsToUint',
  44249. bitcast_uint_int: 'tsl_bitcast_uint_to_int',
  44250. bitcast_int_uint: 'tsl_bitcast_int_to_uint',
  44251. floatpack_snorm_2x16: 'packSnorm2x16',
  44252. floatpack_unorm_2x16: 'packUnorm2x16',
  44253. floatpack_float16_2x16: 'packHalf2x16',
  44254. floatunpack_snorm_2x16: 'unpackSnorm2x16',
  44255. floatunpack_unorm_2x16: 'unpackUnorm2x16',
  44256. floatunpack_float16_2x16: 'unpackHalf2x16'
  44257. };
  44258. const precisionLib = {
  44259. low: 'lowp',
  44260. medium: 'mediump',
  44261. high: 'highp'
  44262. };
  44263. const supports$1 = {
  44264. swizzleAssign: true,
  44265. storageBuffer: false
  44266. };
  44267. const interpolationTypeMap = {
  44268. perspective: 'smooth',
  44269. linear: 'noperspective'
  44270. };
  44271. const interpolationModeMap = {
  44272. 'centroid': 'centroid'
  44273. };
  44274. const defaultPrecisions = `
  44275. precision highp float;
  44276. precision highp int;
  44277. precision highp sampler2D;
  44278. precision highp sampler3D;
  44279. precision highp samplerCube;
  44280. precision highp sampler2DArray;
  44281. precision highp usampler2D;
  44282. precision highp usampler3D;
  44283. precision highp usamplerCube;
  44284. precision highp usampler2DArray;
  44285. precision highp isampler2D;
  44286. precision highp isampler3D;
  44287. precision highp isamplerCube;
  44288. precision highp isampler2DArray;
  44289. precision lowp sampler2DShadow;
  44290. precision lowp sampler2DArrayShadow;
  44291. precision lowp samplerCubeShadow;
  44292. `;
  44293. /**
  44294. * A node builder targeting GLSL.
  44295. *
  44296. * This module generates GLSL shader code from node materials and also
  44297. * generates the respective bindings and vertex buffer definitions. These
  44298. * data are later used by the renderer to create render and compute pipelines
  44299. * for render objects.
  44300. *
  44301. * @augments NodeBuilder
  44302. */
  44303. class GLSLNodeBuilder extends NodeBuilder {
  44304. /**
  44305. * Constructs a new GLSL node builder renderer.
  44306. *
  44307. * @param {Object3D} object - The 3D object.
  44308. * @param {Renderer} renderer - The renderer.
  44309. */
  44310. constructor( object, renderer ) {
  44311. super( object, renderer, new GLSLNodeParser() );
  44312. /**
  44313. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  44314. * another dictionary which manages UBOs per group ('render','frame','object').
  44315. *
  44316. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  44317. */
  44318. this.uniformGroups = {};
  44319. /**
  44320. * An array that holds objects defining the varying and attribute data in
  44321. * context of Transform Feedback.
  44322. *
  44323. * @type {Array<Object<string,AttributeNode|string>>}
  44324. */
  44325. this.transforms = [];
  44326. /**
  44327. * A dictionary that holds for each shader stage a Map of used extensions.
  44328. *
  44329. * @type {Object<string,Map<string,Object>>}
  44330. */
  44331. this.extensions = {};
  44332. /**
  44333. * A dictionary that holds for each shader stage an Array of used builtins.
  44334. *
  44335. * @type {Object<string,Array<string>>}
  44336. */
  44337. this.builtins = { vertex: [], fragment: [], compute: [] };
  44338. }
  44339. /**
  44340. * Checks if the given texture requires a manual conversion to the working color space.
  44341. *
  44342. * @param {Texture} texture - The texture to check.
  44343. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  44344. */
  44345. needsToWorkingColorSpace( texture ) {
  44346. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  44347. }
  44348. /**
  44349. * Includes the given method name into the current
  44350. * function node.
  44351. *
  44352. * @private
  44353. * @param {string} name - The method name to include.
  44354. * @return {CodeNode} The respective code node.
  44355. */
  44356. _include( name ) {
  44357. const codeNode = glslPolyfills[ name ];
  44358. codeNode.build( this );
  44359. this.addInclude( codeNode );
  44360. return codeNode;
  44361. }
  44362. /**
  44363. * Returns the native shader method name for a given generic name.
  44364. *
  44365. * @param {string} method - The method name to resolve.
  44366. * @return {string} The resolved GLSL method name.
  44367. */
  44368. getMethod( method ) {
  44369. if ( glslPolyfills[ method ] !== undefined ) {
  44370. this._include( method );
  44371. }
  44372. return glslMethods[ method ] || method;
  44373. }
  44374. /**
  44375. * Returns the bitcast method name for a given input and outputType.
  44376. *
  44377. * @param {string} type - The output type to bitcast to.
  44378. * @param {string} inputType - The input type of the.
  44379. * @return {string} The resolved WGSL bitcast invocation.
  44380. */
  44381. getBitcastMethod( type, inputType ) {
  44382. return this.getMethod( `bitcast_${ inputType }_${ type }` );
  44383. }
  44384. /**
  44385. * Returns the float packing method name for a given numeric encoding.
  44386. *
  44387. * @param {string} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  44388. * @returns {string} The resolved GLSL float packing method name.
  44389. */
  44390. getFloatPackingMethod( encoding ) {
  44391. return this.getMethod( `floatpack_${ encoding }_2x16` );
  44392. }
  44393. /**
  44394. * Returns the float unpacking method name for a given numeric encoding.
  44395. *
  44396. * @param {string} encoding - The numeric encoding that describes how the integer values are mapped to the float range.
  44397. * @returns {string} The resolved GLSL float unpacking method name.
  44398. */
  44399. getFloatUnpackingMethod( encoding ) {
  44400. return this.getMethod( `floatunpack_${ encoding }_2x16` );
  44401. }
  44402. /**
  44403. * Returns the native snippet for a ternary operation.
  44404. *
  44405. * @param {string} condSnippet - The condition determining which expression gets resolved.
  44406. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  44407. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  44408. * @return {string} The resolved method name.
  44409. */
  44410. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  44411. return `${condSnippet} ? ${ifSnippet} : ${elseSnippet}`;
  44412. }
  44413. /**
  44414. * Returns the output struct name. Not relevant for GLSL.
  44415. *
  44416. * @return {string}
  44417. */
  44418. getOutputStructName() {
  44419. return '';
  44420. }
  44421. /**
  44422. * Builds the given shader node.
  44423. *
  44424. * @param {ShaderNodeInternal} shaderNode - The shader node.
  44425. * @return {string} The GLSL function code.
  44426. */
  44427. buildFunctionCode( shaderNode ) {
  44428. const layout = shaderNode.layout;
  44429. const flowData = this.flowShaderNode( shaderNode );
  44430. const parameters = [];
  44431. for ( const input of layout.inputs ) {
  44432. parameters.push( this.getType( input.type ) + ' ' + input.name );
  44433. }
  44434. //
  44435. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  44436. ${ flowData.vars }
  44437. ${ flowData.code }
  44438. return ${ flowData.result };
  44439. }`;
  44440. //
  44441. return code;
  44442. }
  44443. /**
  44444. * Setups the Pixel Buffer Object (PBO) for the given storage
  44445. * buffer node.
  44446. *
  44447. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  44448. */
  44449. setupPBO( storageBufferNode ) {
  44450. const attribute = storageBufferNode.value;
  44451. if ( attribute.pbo === undefined ) {
  44452. const originalArray = attribute.array;
  44453. const numElements = attribute.count * attribute.itemSize;
  44454. const { itemSize } = attribute;
  44455. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  44456. let format = isInteger ? RedIntegerFormat : RedFormat;
  44457. if ( itemSize === 2 ) {
  44458. format = isInteger ? RGIntegerFormat : RGFormat;
  44459. } else if ( itemSize === 3 ) {
  44460. format = isInteger ? RGBIntegerFormat : RGBFormat;
  44461. } else if ( itemSize === 4 ) {
  44462. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  44463. }
  44464. const typeMap = {
  44465. Float32Array: FloatType,
  44466. Uint8Array: UnsignedByteType,
  44467. Uint16Array: UnsignedShortType,
  44468. Uint32Array: UnsignedIntType,
  44469. Int8Array: ByteType,
  44470. Int16Array: ShortType,
  44471. Int32Array: IntType,
  44472. Uint8ClampedArray: UnsignedByteType,
  44473. };
  44474. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  44475. let height = Math.ceil( ( numElements / itemSize ) / width );
  44476. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  44477. const newSize = width * height * itemSize;
  44478. const newArray = new originalArray.constructor( newSize );
  44479. newArray.set( originalArray, 0 );
  44480. attribute.array = newArray;
  44481. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  44482. pboTexture.needsUpdate = true;
  44483. pboTexture.isPBOTexture = true;
  44484. const pbo = new TextureNode( pboTexture, null, null );
  44485. pbo.setPrecision( 'high' );
  44486. attribute.pboNode = pbo;
  44487. attribute.pbo = pbo.value;
  44488. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  44489. }
  44490. }
  44491. /**
  44492. * Returns a GLSL snippet that represents the property name of the given node.
  44493. *
  44494. * @param {Node} node - The node.
  44495. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44496. * @return {string} The property name.
  44497. */
  44498. getPropertyName( node, shaderStage = this.shaderStage ) {
  44499. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  44500. return shaderStage.charAt( 0 ) + '_' + node.name;
  44501. }
  44502. return super.getPropertyName( node, shaderStage );
  44503. }
  44504. /**
  44505. * Setups the Pixel Buffer Object (PBO) for the given storage
  44506. * buffer node.
  44507. *
  44508. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  44509. * @return {string} The property name.
  44510. */
  44511. generatePBO( storageArrayElementNode ) {
  44512. const { node, indexNode } = storageArrayElementNode;
  44513. const attribute = node.value;
  44514. if ( this.renderer.backend.has( attribute ) ) {
  44515. const attributeData = this.renderer.backend.get( attribute );
  44516. attributeData.pbo = attribute.pbo;
  44517. }
  44518. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  44519. const textureName = this.getPropertyName( nodeUniform );
  44520. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  44521. const indexSnippet = indexNode.build( this, 'uint' );
  44522. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  44523. let propertyName = elementNodeData.propertyName;
  44524. if ( propertyName === undefined ) {
  44525. // property element
  44526. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  44527. propertyName = this.getPropertyName( nodeVar );
  44528. // property size
  44529. const bufferNodeData = this.getDataFromNode( node );
  44530. let propertySizeName = bufferNodeData.propertySizeName;
  44531. if ( propertySizeName === undefined ) {
  44532. propertySizeName = propertyName + 'Size';
  44533. this.getVarFromNode( node, propertySizeName, 'uint' );
  44534. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  44535. bufferNodeData.propertySizeName = propertySizeName;
  44536. }
  44537. //
  44538. const { itemSize } = attribute;
  44539. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  44540. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  44541. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, '0', null, null );
  44542. //
  44543. let prefix = 'vec4';
  44544. if ( attribute.pbo.type === UnsignedIntType ) {
  44545. prefix = 'uvec4';
  44546. } else if ( attribute.pbo.type === IntType ) {
  44547. prefix = 'ivec4';
  44548. }
  44549. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  44550. elementNodeData.propertyName = propertyName;
  44551. }
  44552. return propertyName;
  44553. }
  44554. /**
  44555. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  44556. *
  44557. * @param {?Texture} texture - The texture.
  44558. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44559. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44560. * @param {?string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44561. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  44562. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44563. * @return {string} The GLSL snippet.
  44564. */
  44565. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  44566. if ( levelSnippet === null ) levelSnippet = '0';
  44567. let snippet;
  44568. if ( depthSnippet ) {
  44569. if ( offsetSnippet ) {
  44570. snippet = `texelFetchOffset( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet }, ${ offsetSnippet } )`;
  44571. } else {
  44572. snippet = `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  44573. }
  44574. } else {
  44575. if ( offsetSnippet ) {
  44576. snippet = `texelFetchOffset( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  44577. } else {
  44578. snippet = `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  44579. }
  44580. }
  44581. if ( texture !== null && texture.isDepthTexture ) {
  44582. snippet += '.x';
  44583. }
  44584. return snippet;
  44585. }
  44586. /**
  44587. * Generates the GLSL snippet for sampling/loading the given texture.
  44588. *
  44589. * @param {Texture} texture - The texture.
  44590. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44591. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44592. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  44593. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44594. * @return {string} The GLSL snippet.
  44595. */
  44596. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet ) {
  44597. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  44598. if ( texture.isDepthTexture ) {
  44599. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } ).x`;
  44600. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  44601. }
  44602. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } )`;
  44603. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  44604. }
  44605. /**
  44606. * Generates the GLSL snippet when sampling textures with explicit mip level.
  44607. *
  44608. * @param {Texture} texture - The texture.
  44609. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44610. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44611. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44612. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44613. * @return {string} The GLSL snippet.
  44614. */
  44615. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, offsetSnippet ) {
  44616. if ( offsetSnippet ) {
  44617. return `textureLodOffset( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  44618. }
  44619. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  44620. }
  44621. /**
  44622. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  44623. *
  44624. * @param {Texture} texture - The texture.
  44625. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44626. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44627. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  44628. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44629. * @return {string} The GLSL snippet.
  44630. */
  44631. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, offsetSnippet ) {
  44632. if ( offsetSnippet ) {
  44633. return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ biasSnippet } )`;
  44634. }
  44635. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  44636. }
  44637. /**
  44638. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  44639. *
  44640. * @param {Texture} texture - The texture.
  44641. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44642. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44643. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  44644. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44645. * @return {string} The GLSL snippet.
  44646. */
  44647. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, offsetSnippet ) {
  44648. if ( offsetSnippet ) {
  44649. return `textureGradOffset( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  44650. }
  44651. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  44652. }
  44653. /**
  44654. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  44655. * against a reference value.
  44656. *
  44657. * @param {Texture} texture - The texture.
  44658. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44659. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44660. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  44661. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  44662. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44663. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44664. * @return {string} The GLSL snippet.
  44665. */
  44666. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  44667. if ( shaderStage === 'fragment' ) {
  44668. // Cube shadow maps use vec4(direction, compareValue)
  44669. if ( texture.isCubeTexture ) {
  44670. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ compareSnippet } ) )`;
  44671. }
  44672. if ( depthSnippet ) {
  44673. if ( offsetSnippet ) {
  44674. return `textureOffset( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  44675. }
  44676. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  44677. }
  44678. if ( offsetSnippet ) {
  44679. return `textureOffset( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  44680. }
  44681. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  44682. } else {
  44683. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  44684. }
  44685. }
  44686. /**
  44687. * Returns the variables of the given shader stage as a GLSL string.
  44688. *
  44689. * @param {string} shaderStage - The shader stage.
  44690. * @return {string} The GLSL snippet that defines the variables.
  44691. */
  44692. getVars( shaderStage ) {
  44693. const snippets = [];
  44694. const vars = this.vars[ shaderStage ];
  44695. if ( vars !== undefined ) {
  44696. for ( const variable of vars ) {
  44697. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  44698. }
  44699. }
  44700. return snippets.join( '\n\t' );
  44701. }
  44702. /**
  44703. * Returns the uniforms of the given shader stage as a GLSL string.
  44704. *
  44705. * @param {string} shaderStage - The shader stage.
  44706. * @return {string} The GLSL snippet that defines the uniforms.
  44707. */
  44708. getUniforms( shaderStage ) {
  44709. const uniforms = this.uniforms[ shaderStage ];
  44710. const bindingSnippets = [];
  44711. const uniformGroups = {};
  44712. for ( const uniform of uniforms ) {
  44713. let snippet = null;
  44714. let group = false;
  44715. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  44716. const texture = uniform.node.value;
  44717. let typePrefix = '';
  44718. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  44719. if ( texture.type === UnsignedIntType ) {
  44720. typePrefix = 'u';
  44721. } else if ( texture.type === IntType ) {
  44722. typePrefix = 'i';
  44723. }
  44724. }
  44725. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  44726. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  44727. } else if ( texture.compareFunction ) {
  44728. if ( texture.isArrayTexture === true ) {
  44729. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  44730. } else {
  44731. snippet = `sampler2DShadow ${ uniform.name };`;
  44732. }
  44733. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  44734. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  44735. } else {
  44736. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  44737. }
  44738. } else if ( uniform.type === 'cubeTexture' ) {
  44739. snippet = `samplerCube ${ uniform.name };`;
  44740. } else if ( uniform.type === 'cubeDepthTexture' ) {
  44741. snippet = `samplerCubeShadow ${ uniform.name };`;
  44742. } else if ( uniform.type === 'buffer' ) {
  44743. const bufferNode = uniform.node;
  44744. const bufferType = this.getType( bufferNode.bufferType );
  44745. const bufferCount = bufferNode.bufferCount;
  44746. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  44747. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  44748. } else {
  44749. const vectorType = this.getVectorType( uniform.type );
  44750. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  44751. group = true;
  44752. }
  44753. const precision = uniform.node.precision;
  44754. if ( precision !== null ) {
  44755. snippet = precisionLib[ precision ] + ' ' + snippet;
  44756. }
  44757. if ( group ) {
  44758. snippet = '\t' + snippet;
  44759. const groupName = uniform.groupNode.name;
  44760. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  44761. groupSnippets.push( snippet );
  44762. } else {
  44763. snippet = 'uniform ' + snippet;
  44764. bindingSnippets.push( snippet );
  44765. }
  44766. }
  44767. let output = '';
  44768. for ( const name in uniformGroups ) {
  44769. const groupSnippets = uniformGroups[ name ];
  44770. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  44771. }
  44772. output += bindingSnippets.join( '\n' );
  44773. return output;
  44774. }
  44775. /**
  44776. * Returns the type for a given buffer attribute.
  44777. *
  44778. * @param {BufferAttribute} attribute - The buffer attribute.
  44779. * @return {string} The type.
  44780. */
  44781. getTypeFromAttribute( attribute ) {
  44782. let nodeType = super.getTypeFromAttribute( attribute );
  44783. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  44784. let dataAttribute = attribute;
  44785. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  44786. const array = dataAttribute.array;
  44787. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  44788. nodeType = nodeType.slice( 1 );
  44789. }
  44790. }
  44791. return nodeType;
  44792. }
  44793. /**
  44794. * Returns the shader attributes of the given shader stage as a GLSL string.
  44795. *
  44796. * @param {string} shaderStage - The shader stage.
  44797. * @return {string} The GLSL snippet that defines the shader attributes.
  44798. */
  44799. getAttributes( shaderStage ) {
  44800. let snippet = '';
  44801. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  44802. const attributes = this.getAttributesArray();
  44803. let location = 0;
  44804. for ( const attribute of attributes ) {
  44805. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  44806. }
  44807. }
  44808. return snippet;
  44809. }
  44810. /**
  44811. * Returns the members of the given struct type node as a GLSL string.
  44812. *
  44813. * @param {StructTypeNode} struct - The struct type node.
  44814. * @return {string} The GLSL snippet that defines the struct members.
  44815. */
  44816. getStructMembers( struct ) {
  44817. const snippets = [];
  44818. for ( const member of struct.members ) {
  44819. snippets.push( `\t${ member.type } ${ member.name };` );
  44820. }
  44821. return snippets.join( '\n' );
  44822. }
  44823. /**
  44824. * Returns the structs of the given shader stage as a GLSL string.
  44825. *
  44826. * @param {string} shaderStage - The shader stage.
  44827. * @return {string} The GLSL snippet that defines the structs.
  44828. */
  44829. getStructs( shaderStage ) {
  44830. const snippets = [];
  44831. const structs = this.structs[ shaderStage ];
  44832. const outputSnippet = [];
  44833. for ( const struct of structs ) {
  44834. if ( struct.output ) {
  44835. for ( const member of struct.members ) {
  44836. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  44837. }
  44838. } else {
  44839. let snippet = 'struct ' + struct.name + ' {\n';
  44840. snippet += this.getStructMembers( struct );
  44841. snippet += '\n};\n';
  44842. snippets.push( snippet );
  44843. }
  44844. }
  44845. if ( outputSnippet.length === 0 ) {
  44846. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  44847. }
  44848. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  44849. }
  44850. /**
  44851. * Returns the varyings of the given shader stage as a GLSL string.
  44852. *
  44853. * @param {string} shaderStage - The shader stage.
  44854. * @return {string} The GLSL snippet that defines the varyings.
  44855. */
  44856. getVaryings( shaderStage ) {
  44857. let snippet = '';
  44858. const varyings = this.varyings;
  44859. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  44860. for ( const varying of varyings ) {
  44861. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  44862. const type = this.getType( varying.type );
  44863. if ( varying.needsInterpolation ) {
  44864. if ( varying.interpolationType ) {
  44865. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  44866. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  44867. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  44868. } else {
  44869. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  44870. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  44871. }
  44872. } else {
  44873. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  44874. }
  44875. }
  44876. } else if ( shaderStage === 'fragment' ) {
  44877. for ( const varying of varyings ) {
  44878. if ( varying.needsInterpolation ) {
  44879. const type = this.getType( varying.type );
  44880. if ( varying.interpolationType ) {
  44881. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  44882. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  44883. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  44884. } else {
  44885. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  44886. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  44887. }
  44888. }
  44889. }
  44890. }
  44891. for ( const builtin of this.builtins[ shaderStage ] ) {
  44892. snippet += `${builtin};\n`;
  44893. }
  44894. return snippet;
  44895. }
  44896. /**
  44897. * Returns the vertex index builtin.
  44898. *
  44899. * @return {string} The vertex index.
  44900. */
  44901. getVertexIndex() {
  44902. return 'uint( gl_VertexID )';
  44903. }
  44904. /**
  44905. * Contextually returns either the vertex stage instance index builtin
  44906. * or the linearized index of an compute invocation within a grid of workgroups.
  44907. *
  44908. * @return {string} The instance index.
  44909. */
  44910. getInstanceIndex() {
  44911. return 'uint( gl_InstanceID )';
  44912. }
  44913. /**
  44914. * Returns a builtin representing the index of an invocation within its workgroup.
  44915. *
  44916. * @return {string} The invocation local index.
  44917. */
  44918. getInvocationLocalIndex() {
  44919. const workgroupSize = this.object.workgroupSize;
  44920. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  44921. return `uint( gl_InstanceID ) % ${size}u`;
  44922. }
  44923. /**
  44924. * Returns a builtin representing the size of a subgroup within the current shader.
  44925. */
  44926. getSubgroupSize() {
  44927. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node' );
  44928. }
  44929. /**
  44930. * Returns a builtin representing the index of an invocation within its subgroup.
  44931. */
  44932. getInvocationSubgroupIndex() {
  44933. error( 'GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node' );
  44934. }
  44935. /**
  44936. * Returns a builtin representing the index of the current invocation's subgroup within its workgroup.
  44937. */
  44938. getSubgroupIndex() {
  44939. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node' );
  44940. }
  44941. /**
  44942. * Returns the draw index builtin.
  44943. *
  44944. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  44945. */
  44946. getDrawIndex() {
  44947. const extensions = this.renderer.backend.extensions;
  44948. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  44949. return 'uint( gl_DrawID )';
  44950. }
  44951. return null;
  44952. }
  44953. /**
  44954. * Returns the front facing builtin.
  44955. *
  44956. * @return {string} The front facing builtin.
  44957. */
  44958. getFrontFacing() {
  44959. return 'gl_FrontFacing';
  44960. }
  44961. /**
  44962. * Returns the frag coord builtin.
  44963. *
  44964. * @return {string} The frag coord builtin.
  44965. */
  44966. getFragCoord() {
  44967. return 'gl_FragCoord.xy';
  44968. }
  44969. /**
  44970. * Returns the frag depth builtin.
  44971. *
  44972. * @return {string} The frag depth builtin.
  44973. */
  44974. getFragDepth() {
  44975. return 'gl_FragDepth';
  44976. }
  44977. /**
  44978. * Enables the given extension.
  44979. *
  44980. * @param {string} name - The extension name.
  44981. * @param {string} behavior - The extension behavior.
  44982. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  44983. */
  44984. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  44985. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  44986. if ( map.has( name ) === false ) {
  44987. map.set( name, {
  44988. name,
  44989. behavior
  44990. } );
  44991. }
  44992. }
  44993. /**
  44994. * Returns the enabled extensions of the given shader stage as a GLSL string.
  44995. *
  44996. * @param {string} shaderStage - The shader stage.
  44997. * @return {string} The GLSL snippet that defines the enabled extensions.
  44998. */
  44999. getExtensions( shaderStage ) {
  45000. const snippets = [];
  45001. if ( shaderStage === 'vertex' ) {
  45002. const ext = this.renderer.backend.extensions;
  45003. const isBatchedMesh = this.object.isBatchedMesh;
  45004. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  45005. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  45006. }
  45007. }
  45008. const extensions = this.extensions[ shaderStage ];
  45009. if ( extensions !== undefined ) {
  45010. for ( const { name, behavior } of extensions.values() ) {
  45011. snippets.push( `#extension ${name} : ${behavior}` );
  45012. }
  45013. }
  45014. return snippets.join( '\n' );
  45015. }
  45016. /**
  45017. * Returns the clip distances builtin.
  45018. *
  45019. * @return {string} The clip distances builtin.
  45020. */
  45021. getClipDistance() {
  45022. return 'gl_ClipDistance';
  45023. }
  45024. /**
  45025. * Whether the requested feature is available or not.
  45026. *
  45027. * @param {string} name - The requested feature.
  45028. * @return {boolean} Whether the requested feature is supported or not.
  45029. */
  45030. isAvailable( name ) {
  45031. let result = supports$1[ name ];
  45032. if ( result === undefined ) {
  45033. let extensionName;
  45034. result = false;
  45035. switch ( name ) {
  45036. case 'float32Filterable':
  45037. extensionName = 'OES_texture_float_linear';
  45038. break;
  45039. case 'clipDistance':
  45040. extensionName = 'WEBGL_clip_cull_distance';
  45041. break;
  45042. }
  45043. if ( extensionName !== undefined ) {
  45044. const extensions = this.renderer.backend.extensions;
  45045. if ( extensions.has( extensionName ) ) {
  45046. extensions.get( extensionName );
  45047. result = true;
  45048. }
  45049. }
  45050. supports$1[ name ] = result;
  45051. }
  45052. return result;
  45053. }
  45054. /**
  45055. * Whether to flip texture data along its vertical axis or not.
  45056. *
  45057. * @return {boolean} Returns always `true` in context of GLSL.
  45058. */
  45059. isFlipY() {
  45060. return true;
  45061. }
  45062. /**
  45063. * Enables hardware clipping.
  45064. *
  45065. * @param {string} planeCount - The clipping plane count.
  45066. */
  45067. enableHardwareClipping( planeCount ) {
  45068. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  45069. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  45070. }
  45071. /**
  45072. * Enables multiview.
  45073. */
  45074. enableMultiview() {
  45075. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  45076. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  45077. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  45078. }
  45079. /**
  45080. * Registers a transform in context of Transform Feedback.
  45081. *
  45082. * @param {string} varyingName - The varying name.
  45083. * @param {AttributeNode} attributeNode - The attribute node.
  45084. */
  45085. registerTransform( varyingName, attributeNode ) {
  45086. this.transforms.push( { varyingName, attributeNode } );
  45087. }
  45088. /**
  45089. * Returns the transforms of the given shader stage as a GLSL string.
  45090. *
  45091. * @param {string} shaderStage - The shader stage.
  45092. * @return {string} The GLSL snippet that defines the transforms.
  45093. */
  45094. getTransforms( /* shaderStage */ ) {
  45095. const transforms = this.transforms;
  45096. let snippet = '';
  45097. for ( let i = 0; i < transforms.length; i ++ ) {
  45098. const transform = transforms[ i ];
  45099. const attributeName = this.getPropertyName( transform.attributeNode );
  45100. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  45101. }
  45102. return snippet;
  45103. }
  45104. /**
  45105. * Returns a GLSL struct based on the given name and variables.
  45106. *
  45107. * @private
  45108. * @param {string} name - The struct name.
  45109. * @param {string} vars - The struct variables.
  45110. * @return {string} The GLSL snippet representing a struct.
  45111. */
  45112. _getGLSLUniformStruct( name, vars ) {
  45113. return `
  45114. layout( std140 ) uniform ${name} {
  45115. ${vars}
  45116. };`;
  45117. }
  45118. /**
  45119. * Returns a GLSL vertex shader based on the given shader data.
  45120. *
  45121. * @private
  45122. * @param {Object} shaderData - The shader data.
  45123. * @return {string} The vertex shader.
  45124. */
  45125. _getGLSLVertexCode( shaderData ) {
  45126. return `#version 300 es
  45127. ${ this.getSignature() }
  45128. // extensions
  45129. ${shaderData.extensions}
  45130. // precision
  45131. ${ defaultPrecisions }
  45132. // uniforms
  45133. ${shaderData.uniforms}
  45134. // varyings
  45135. ${shaderData.varyings}
  45136. // attributes
  45137. ${shaderData.attributes}
  45138. // codes
  45139. ${shaderData.codes}
  45140. void main() {
  45141. // vars
  45142. ${shaderData.vars}
  45143. // transforms
  45144. ${shaderData.transforms}
  45145. // flow
  45146. ${shaderData.flow}
  45147. gl_PointSize = 1.0;
  45148. }
  45149. `;
  45150. }
  45151. /**
  45152. * Returns a GLSL fragment shader based on the given shader data.
  45153. *
  45154. * @private
  45155. * @param {Object} shaderData - The shader data.
  45156. * @return {string} The vertex shader.
  45157. */
  45158. _getGLSLFragmentCode( shaderData ) {
  45159. return `#version 300 es
  45160. ${ this.getSignature() }
  45161. // extensions
  45162. ${shaderData.extensions}
  45163. // precision
  45164. ${ defaultPrecisions }
  45165. // structs
  45166. ${shaderData.structs}
  45167. // uniforms
  45168. ${shaderData.uniforms}
  45169. // varyings
  45170. ${shaderData.varyings}
  45171. // codes
  45172. ${shaderData.codes}
  45173. void main() {
  45174. // vars
  45175. ${shaderData.vars}
  45176. // flow
  45177. ${shaderData.flow}
  45178. }
  45179. `;
  45180. }
  45181. /**
  45182. * Controls the code build of the shader stages.
  45183. */
  45184. buildCode() {
  45185. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  45186. this.sortBindingGroups();
  45187. for ( const shaderStage in shadersData ) {
  45188. let flow = '// code\n\n';
  45189. flow += this.flowCode[ shaderStage ];
  45190. const flowNodes = this.flowNodes[ shaderStage ];
  45191. const mainNode = flowNodes[ flowNodes.length - 1 ];
  45192. for ( const node of flowNodes ) {
  45193. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  45194. const slotName = node.name;
  45195. if ( slotName ) {
  45196. if ( flow.length > 0 ) flow += '\n';
  45197. flow += `\t// flow -> ${ slotName }\n\t`;
  45198. }
  45199. flow += `${ flowSlotData.code }\n\t`;
  45200. if ( node === mainNode && shaderStage !== 'compute' ) {
  45201. flow += '// result\n\t';
  45202. if ( shaderStage === 'vertex' ) {
  45203. flow += 'gl_Position = ';
  45204. flow += `${ flowSlotData.result };`;
  45205. } else if ( shaderStage === 'fragment' ) {
  45206. if ( ! node.outputNode.isOutputStructNode ) {
  45207. flow += 'fragColor = ';
  45208. flow += `${ flowSlotData.result };`;
  45209. }
  45210. }
  45211. }
  45212. }
  45213. const stageData = shadersData[ shaderStage ];
  45214. stageData.extensions = this.getExtensions( shaderStage );
  45215. stageData.uniforms = this.getUniforms( shaderStage );
  45216. stageData.attributes = this.getAttributes( shaderStage );
  45217. stageData.varyings = this.getVaryings( shaderStage );
  45218. stageData.vars = this.getVars( shaderStage );
  45219. stageData.structs = this.getStructs( shaderStage );
  45220. stageData.codes = this.getCodes( shaderStage );
  45221. stageData.transforms = this.getTransforms( shaderStage );
  45222. stageData.flow = flow;
  45223. }
  45224. if ( this.material !== null ) {
  45225. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  45226. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  45227. } else {
  45228. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  45229. }
  45230. }
  45231. /**
  45232. * This method is one of the more important ones since it's responsible
  45233. * for generating a matching binding instance for the given uniform node.
  45234. *
  45235. * These bindings are later used in the renderer to create bind groups
  45236. * and layouts.
  45237. *
  45238. * @param {UniformNode} node - The uniform node.
  45239. * @param {string} type - The node data type.
  45240. * @param {string} shaderStage - The shader stage.
  45241. * @param {?string} [name=null] - An optional uniform name.
  45242. * @return {NodeUniform} The node uniform object.
  45243. */
  45244. getUniformFromNode( node, type, shaderStage, name = null ) {
  45245. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  45246. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  45247. let uniformGPU = nodeData.uniformGPU;
  45248. if ( uniformGPU === undefined ) {
  45249. const group = node.groupNode;
  45250. const groupName = group.name;
  45251. const bindings = this.getBindGroupArray( groupName, shaderStage );
  45252. if ( type === 'texture' ) {
  45253. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  45254. bindings.push( uniformGPU );
  45255. } else if ( type === 'cubeTexture' || type === 'cubeDepthTexture' ) {
  45256. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  45257. bindings.push( uniformGPU );
  45258. } else if ( type === 'texture3D' ) {
  45259. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  45260. bindings.push( uniformGPU );
  45261. } else if ( type === 'buffer' ) {
  45262. uniformNode.name = `buffer${ node.id }`;
  45263. const sharedData = this.getSharedDataFromNode( node );
  45264. let buffer = sharedData.buffer;
  45265. if ( buffer === undefined ) {
  45266. node.name = `NodeBuffer_${ node.id }`;
  45267. buffer = new NodeUniformBuffer( node, group );
  45268. buffer.name = node.name;
  45269. sharedData.buffer = buffer;
  45270. }
  45271. bindings.push( buffer );
  45272. uniformGPU = buffer;
  45273. } else {
  45274. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  45275. let uniformsGroup = uniformsStage[ groupName ];
  45276. if ( uniformsGroup === undefined ) {
  45277. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  45278. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  45279. uniformsStage[ groupName ] = uniformsGroup;
  45280. bindings.push( uniformsGroup );
  45281. }
  45282. uniformGPU = this.getNodeUniform( uniformNode, type );
  45283. uniformsGroup.addUniform( uniformGPU );
  45284. }
  45285. nodeData.uniformGPU = uniformGPU;
  45286. }
  45287. return uniformNode;
  45288. }
  45289. }
  45290. let _vector2 = null;
  45291. let _color4 = null;
  45292. /**
  45293. * Most of the rendering related logic is implemented in the
  45294. * {@link Renderer} module and related management components.
  45295. * Sometimes it is required though to execute commands which are
  45296. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  45297. * This abstract base class defines an interface that encapsulates
  45298. * all backend-related logic. Derived classes for each backend must
  45299. * implement the interface.
  45300. *
  45301. * @abstract
  45302. * @private
  45303. */
  45304. class Backend {
  45305. /**
  45306. * Constructs a new backend.
  45307. *
  45308. * @param {Object} parameters - An object holding parameters for the backend.
  45309. */
  45310. constructor( parameters = {} ) {
  45311. /**
  45312. * The parameters of the backend.
  45313. *
  45314. * @type {Object}
  45315. */
  45316. this.parameters = Object.assign( {}, parameters );
  45317. /**
  45318. * This weak map holds backend-specific data of objects
  45319. * like textures, attributes or render targets.
  45320. *
  45321. * @type {WeakMap<Object, Object>}
  45322. */
  45323. this.data = new WeakMap();
  45324. /**
  45325. * A reference to the renderer.
  45326. *
  45327. * @type {?Renderer}
  45328. * @default null
  45329. */
  45330. this.renderer = null;
  45331. /**
  45332. * A reference to the canvas element the renderer is drawing to.
  45333. *
  45334. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  45335. * @default null
  45336. */
  45337. this.domElement = null;
  45338. /**
  45339. * A reference to the timestamp query pool.
  45340. *
  45341. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  45342. */
  45343. this.timestampQueryPool = {
  45344. [ TimestampQuery.RENDER ]: null,
  45345. [ TimestampQuery.COMPUTE ]: null
  45346. };
  45347. /**
  45348. * Whether to track timestamps with a Timestamp Query API or not.
  45349. *
  45350. * @type {boolean}
  45351. * @default false
  45352. */
  45353. this.trackTimestamp = ( parameters.trackTimestamp === true );
  45354. }
  45355. /**
  45356. * Initializes the backend so it is ready for usage. Concrete backends
  45357. * are supposed to implement their rendering context creation and related
  45358. * operations in this method.
  45359. *
  45360. * @async
  45361. * @param {Renderer} renderer - The renderer.
  45362. * @return {Promise} A Promise that resolves when the backend has been initialized.
  45363. */
  45364. async init( renderer ) {
  45365. this.renderer = renderer;
  45366. }
  45367. /**
  45368. * The coordinate system of the backend.
  45369. *
  45370. * @abstract
  45371. * @type {number}
  45372. * @readonly
  45373. */
  45374. get coordinateSystem() {}
  45375. // render context
  45376. /**
  45377. * This method is executed at the beginning of a render call and
  45378. * can be used by the backend to prepare the state for upcoming
  45379. * draw calls.
  45380. *
  45381. * @abstract
  45382. * @param {RenderContext} renderContext - The render context.
  45383. */
  45384. beginRender( /*renderContext*/ ) {}
  45385. /**
  45386. * This method is executed at the end of a render call and
  45387. * can be used by the backend to finalize work after draw
  45388. * calls.
  45389. *
  45390. * @abstract
  45391. * @param {RenderContext} renderContext - The render context.
  45392. */
  45393. finishRender( /*renderContext*/ ) {}
  45394. /**
  45395. * This method is executed at the beginning of a compute call and
  45396. * can be used by the backend to prepare the state for upcoming
  45397. * compute tasks.
  45398. *
  45399. * @abstract
  45400. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  45401. */
  45402. beginCompute( /*computeGroup*/ ) {}
  45403. /**
  45404. * This method is executed at the end of a compute call and
  45405. * can be used by the backend to finalize work after compute
  45406. * tasks.
  45407. *
  45408. * @abstract
  45409. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  45410. */
  45411. finishCompute( /*computeGroup*/ ) {}
  45412. // render object
  45413. /**
  45414. * Executes a draw command for the given render object.
  45415. *
  45416. * @abstract
  45417. * @param {RenderObject} renderObject - The render object to draw.
  45418. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  45419. */
  45420. draw( /*renderObject, info*/ ) { }
  45421. // compute node
  45422. /**
  45423. * Executes a compute command for the given compute node.
  45424. *
  45425. * @abstract
  45426. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  45427. * @param {Node} computeNode - The compute node.
  45428. * @param {Array<BindGroup>} bindings - The bindings.
  45429. * @param {ComputePipeline} computePipeline - The compute pipeline.
  45430. */
  45431. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  45432. // program
  45433. /**
  45434. * Creates a shader program from the given programmable stage.
  45435. *
  45436. * @abstract
  45437. * @param {ProgrammableStage} program - The programmable stage.
  45438. */
  45439. createProgram( /*program*/ ) { }
  45440. /**
  45441. * Destroys the shader program of the given programmable stage.
  45442. *
  45443. * @abstract
  45444. * @param {ProgrammableStage} program - The programmable stage.
  45445. */
  45446. destroyProgram( /*program*/ ) { }
  45447. // bindings
  45448. /**
  45449. * Creates bindings from the given bind group definition.
  45450. *
  45451. * @abstract
  45452. * @param {BindGroup} bindGroup - The bind group.
  45453. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45454. * @param {number} cacheIndex - The cache index.
  45455. * @param {number} version - The version.
  45456. */
  45457. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  45458. /**
  45459. * Updates the given bind group definition.
  45460. *
  45461. * @abstract
  45462. * @param {BindGroup} bindGroup - The bind group.
  45463. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45464. * @param {number} cacheIndex - The cache index.
  45465. * @param {number} version - The version.
  45466. */
  45467. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  45468. /**
  45469. * Updates a buffer binding.
  45470. *
  45471. * @abstract
  45472. * @param {Buffer} binding - The buffer binding to update.
  45473. */
  45474. updateBinding( /*binding*/ ) { }
  45475. // pipeline
  45476. /**
  45477. * Creates a render pipeline for the given render object.
  45478. *
  45479. * @abstract
  45480. * @param {RenderObject} renderObject - The render object.
  45481. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  45482. */
  45483. createRenderPipeline( /*renderObject, promises*/ ) { }
  45484. /**
  45485. * Creates a compute pipeline for the given compute node.
  45486. *
  45487. * @abstract
  45488. * @param {ComputePipeline} computePipeline - The compute pipeline.
  45489. * @param {Array<BindGroup>} bindings - The bindings.
  45490. */
  45491. createComputePipeline( /*computePipeline, bindings*/ ) { }
  45492. // cache key
  45493. /**
  45494. * Returns `true` if the render pipeline requires an update.
  45495. *
  45496. * @abstract
  45497. * @param {RenderObject} renderObject - The render object.
  45498. * @return {boolean} Whether the render pipeline requires an update or not.
  45499. */
  45500. needsRenderUpdate( /*renderObject*/ ) { }
  45501. /**
  45502. * Returns a cache key that is used to identify render pipelines.
  45503. *
  45504. * @abstract
  45505. * @param {RenderObject} renderObject - The render object.
  45506. * @return {string} The cache key.
  45507. */
  45508. getRenderCacheKey( /*renderObject*/ ) { }
  45509. // node builder
  45510. /**
  45511. * Returns a node builder for the given render object.
  45512. *
  45513. * @abstract
  45514. * @param {RenderObject} renderObject - The render object.
  45515. * @param {Renderer} renderer - The renderer.
  45516. * @return {NodeBuilder} The node builder.
  45517. */
  45518. createNodeBuilder( /*renderObject, renderer*/ ) { }
  45519. // textures
  45520. /**
  45521. * Updates a GPU sampler for the given texture.
  45522. *
  45523. * @abstract
  45524. * @param {Texture} texture - The texture to update the sampler for.
  45525. * @return {string} The current sampler key.
  45526. */
  45527. updateSampler( /*texture*/ ) { }
  45528. /**
  45529. * Creates a default texture for the given texture that can be used
  45530. * as a placeholder until the actual texture is ready for usage.
  45531. *
  45532. * @abstract
  45533. * @param {Texture} texture - The texture to create a default texture for.
  45534. */
  45535. createDefaultTexture( /*texture*/ ) { }
  45536. /**
  45537. * Defines a texture on the GPU for the given texture object.
  45538. *
  45539. * @abstract
  45540. * @param {Texture} texture - The texture.
  45541. * @param {Object} [options={}] - Optional configuration parameter.
  45542. */
  45543. createTexture( /*texture, options={}*/ ) { }
  45544. /**
  45545. * Uploads the updated texture data to the GPU.
  45546. *
  45547. * @abstract
  45548. * @param {Texture} texture - The texture.
  45549. * @param {Object} [options={}] - Optional configuration parameter.
  45550. */
  45551. updateTexture( /*texture, options = {}*/ ) { }
  45552. /**
  45553. * Generates mipmaps for the given texture.
  45554. *
  45555. * @abstract
  45556. * @param {Texture} texture - The texture.
  45557. */
  45558. generateMipmaps( /*texture*/ ) { }
  45559. /**
  45560. * Destroys the GPU data for the given texture object.
  45561. *
  45562. * @abstract
  45563. * @param {Texture} texture - The texture.
  45564. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  45565. */
  45566. destroyTexture( /*texture, isDefaultTexture*/ ) { }
  45567. /**
  45568. * Returns texture data as a typed array.
  45569. *
  45570. * @abstract
  45571. * @async
  45572. * @param {Texture} texture - The texture to copy.
  45573. * @param {number} x - The x coordinate of the copy origin.
  45574. * @param {number} y - The y coordinate of the copy origin.
  45575. * @param {number} width - The width of the copy.
  45576. * @param {number} height - The height of the copy.
  45577. * @param {number} faceIndex - The face index.
  45578. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  45579. */
  45580. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  45581. /**
  45582. * Copies data of the given source texture to the given destination texture.
  45583. *
  45584. * @abstract
  45585. * @param {Texture} srcTexture - The source texture.
  45586. * @param {Texture} dstTexture - The destination texture.
  45587. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  45588. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  45589. * @param {number} [srcLevel=0] - The source mip level to copy from.
  45590. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  45591. */
  45592. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  45593. /**
  45594. * Copies the current bound framebuffer to the given texture.
  45595. *
  45596. * @abstract
  45597. * @param {Texture} texture - The destination texture.
  45598. * @param {RenderContext} renderContext - The render context.
  45599. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  45600. */
  45601. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  45602. // attributes
  45603. /**
  45604. * Creates the GPU buffer of a shader attribute.
  45605. *
  45606. * @abstract
  45607. * @param {BufferAttribute} attribute - The buffer attribute.
  45608. */
  45609. createAttribute( /*attribute*/ ) { }
  45610. /**
  45611. * Creates the GPU buffer of an indexed shader attribute.
  45612. *
  45613. * @abstract
  45614. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  45615. */
  45616. createIndexAttribute( /*attribute*/ ) { }
  45617. /**
  45618. * Creates the GPU buffer of a storage attribute.
  45619. *
  45620. * @abstract
  45621. * @param {BufferAttribute} attribute - The buffer attribute.
  45622. */
  45623. createStorageAttribute( /*attribute*/ ) { }
  45624. /**
  45625. * Updates the GPU buffer of a shader attribute.
  45626. *
  45627. * @abstract
  45628. * @param {BufferAttribute} attribute - The buffer attribute to update.
  45629. */
  45630. updateAttribute( /*attribute*/ ) { }
  45631. /**
  45632. * Destroys the GPU buffer of a shader attribute.
  45633. *
  45634. * @abstract
  45635. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  45636. */
  45637. destroyAttribute( /*attribute*/ ) { }
  45638. // canvas
  45639. /**
  45640. * Returns the backend's rendering context.
  45641. *
  45642. * @abstract
  45643. * @return {Object} The rendering context.
  45644. */
  45645. getContext() { }
  45646. /**
  45647. * Backends can use this method if they have to run
  45648. * logic when the renderer gets resized.
  45649. *
  45650. * @abstract
  45651. */
  45652. updateSize() { }
  45653. /**
  45654. * Updates the viewport with the values from the given render context.
  45655. *
  45656. * @abstract
  45657. * @param {RenderContext} renderContext - The render context.
  45658. */
  45659. updateViewport( /*renderContext*/ ) {}
  45660. // utils
  45661. /**
  45662. * Updates a unique identifier for the given render context that can be used
  45663. * to allocate resources like occlusion queries or timestamp queries.
  45664. *
  45665. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  45666. */
  45667. updateTimeStampUID( abstractRenderContext ) {
  45668. const contextData = this.get( abstractRenderContext );
  45669. const frame = this.renderer.info.frame;
  45670. let prefix;
  45671. if ( abstractRenderContext.isComputeNode === true ) {
  45672. prefix = 'c:' + this.renderer.info.compute.frameCalls;
  45673. } else {
  45674. prefix = 'r:' + this.renderer.info.render.frameCalls;
  45675. }
  45676. contextData.timestampUID = prefix + ':' + abstractRenderContext.id + ':f' + frame;
  45677. }
  45678. /**
  45679. * Returns a unique identifier for the given render context that can be used
  45680. * to allocate resources like occlusion queries or timestamp queries.
  45681. *
  45682. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  45683. * @return {string} The unique identifier.
  45684. */
  45685. getTimestampUID( abstractRenderContext ) {
  45686. return this.get( abstractRenderContext ).timestampUID;
  45687. }
  45688. /**
  45689. * Returns all timestamp frames for the given type.
  45690. *
  45691. * @param {string} type - The type of the time stamp.
  45692. * @return {Array<number>} The timestamp frames.
  45693. */
  45694. getTimestampFrames( type ) {
  45695. const queryPool = this.timestampQueryPool[ type ];
  45696. return queryPool ? queryPool.getTimestampFrames() : [];
  45697. }
  45698. /**
  45699. * Returns the query pool for the given uid.
  45700. *
  45701. * @param {string} uid - The unique identifier.
  45702. * @return {TimestampQueryPool} The query pool.
  45703. */
  45704. _getQueryPool( uid ) {
  45705. const type = uid.startsWith( 'c:' ) ? TimestampQuery.COMPUTE : TimestampQuery.RENDER;
  45706. const queryPool = this.timestampQueryPool[ type ];
  45707. return queryPool;
  45708. }
  45709. /**
  45710. * Returns the timestamp for the given uid.
  45711. *
  45712. * @param {string} uid - The unique identifier.
  45713. * @return {number} The timestamp.
  45714. */
  45715. getTimestamp( uid ) {
  45716. const queryPool = this._getQueryPool( uid );
  45717. return queryPool.getTimestamp( uid );
  45718. }
  45719. /**
  45720. * Returns `true` if a timestamp for the given uid is available.
  45721. *
  45722. * @param {string} uid - The unique identifier.
  45723. * @return {boolean} Whether the timestamp is available or not.
  45724. */
  45725. hasTimestamp( uid ) {
  45726. const queryPool = this._getQueryPool( uid );
  45727. return queryPool.hasTimestamp( uid );
  45728. }
  45729. /**
  45730. * Returns `true` if the given 3D object is fully occluded by other
  45731. * 3D objects in the scene. Backends must implement this method by using
  45732. * a Occlusion Query API.
  45733. *
  45734. * @abstract
  45735. * @param {RenderContext} renderContext - The render context.
  45736. * @param {Object3D} object - The 3D object to test.
  45737. * @return {boolean} Whether the 3D object is fully occluded or not.
  45738. */
  45739. isOccluded( /*renderContext, object*/ ) {}
  45740. /**
  45741. * Resolves the time stamp for the given render context and type.
  45742. *
  45743. * @async
  45744. * @abstract
  45745. * @param {string} [type='render'] - The type of the time stamp.
  45746. * @return {Promise<number>} A Promise that resolves with the time stamp.
  45747. */
  45748. async resolveTimestampsAsync( type = 'render' ) {
  45749. if ( ! this.trackTimestamp ) {
  45750. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  45751. return;
  45752. }
  45753. const queryPool = this.timestampQueryPool[ type ];
  45754. if ( ! queryPool ) {
  45755. return;
  45756. }
  45757. const duration = await queryPool.resolveQueriesAsync();
  45758. this.renderer.info[ type ].timestamp = duration;
  45759. return duration;
  45760. }
  45761. /**
  45762. * This method performs a readback operation by moving buffer data from
  45763. * a storage buffer attribute from the GPU to the CPU.
  45764. *
  45765. * @async
  45766. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  45767. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  45768. */
  45769. async getArrayBufferAsync( /* attribute */ ) {}
  45770. /**
  45771. * Checks if the given feature is supported by the backend.
  45772. *
  45773. * @async
  45774. * @abstract
  45775. * @param {string} name - The feature's name.
  45776. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  45777. */
  45778. async hasFeatureAsync( /*name*/ ) { }
  45779. /**
  45780. * Checks if the given feature is supported by the backend.
  45781. *
  45782. * @abstract
  45783. * @param {string} name - The feature's name.
  45784. * @return {boolean} Whether the feature is supported or not.
  45785. */
  45786. hasFeature( /*name*/ ) {}
  45787. /**
  45788. * Returns the maximum anisotropy texture filtering value.
  45789. *
  45790. * @abstract
  45791. * @return {number} The maximum anisotropy texture filtering value.
  45792. */
  45793. getMaxAnisotropy() {}
  45794. /**
  45795. * Returns the drawing buffer size.
  45796. *
  45797. * @return {Vector2} The drawing buffer size.
  45798. */
  45799. getDrawingBufferSize() {
  45800. _vector2 = _vector2 || new Vector2();
  45801. return this.renderer.getDrawingBufferSize( _vector2 );
  45802. }
  45803. /**
  45804. * Defines the scissor test.
  45805. *
  45806. * @abstract
  45807. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  45808. */
  45809. setScissorTest( /*boolean*/ ) { }
  45810. /**
  45811. * Returns the clear color and alpha into a single
  45812. * color object.
  45813. *
  45814. * @return {Color4} The clear color.
  45815. */
  45816. getClearColor() {
  45817. const renderer = this.renderer;
  45818. _color4 = _color4 || new Color4();
  45819. renderer.getClearColor( _color4 );
  45820. _color4.getRGB( _color4 );
  45821. return _color4;
  45822. }
  45823. /**
  45824. * Returns the DOM element. If no DOM element exists, the backend
  45825. * creates a new one.
  45826. *
  45827. * @return {HTMLCanvasElement} The DOM element.
  45828. */
  45829. getDomElement() {
  45830. let domElement = this.domElement;
  45831. if ( domElement === null ) {
  45832. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  45833. // OffscreenCanvas does not have setAttribute, see #22811
  45834. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  45835. this.domElement = domElement;
  45836. }
  45837. return domElement;
  45838. }
  45839. /**
  45840. * Sets a dictionary for the given object into the
  45841. * internal data structure.
  45842. *
  45843. * @param {Object} object - The object.
  45844. * @param {Object} value - The dictionary to set.
  45845. */
  45846. set( object, value ) {
  45847. this.data.set( object, value );
  45848. }
  45849. /**
  45850. * Returns the dictionary for the given object.
  45851. *
  45852. * @param {Object} object - The object.
  45853. * @return {Object} The object's dictionary.
  45854. */
  45855. get( object ) {
  45856. let map = this.data.get( object );
  45857. if ( map === undefined ) {
  45858. map = {};
  45859. this.data.set( object, map );
  45860. }
  45861. return map;
  45862. }
  45863. /**
  45864. * Checks if the given object has a dictionary
  45865. * with data defined.
  45866. *
  45867. * @param {Object} object - The object.
  45868. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  45869. */
  45870. has( object ) {
  45871. return this.data.has( object );
  45872. }
  45873. /**
  45874. * Deletes an object from the internal data structure.
  45875. *
  45876. * @param {Object} object - The object to delete.
  45877. */
  45878. delete( object ) {
  45879. this.data.delete( object );
  45880. }
  45881. /**
  45882. * Delete GPU data associated with a bind group.
  45883. *
  45884. * @abstract
  45885. * @param {BindGroup} bindGroup - The bind group.
  45886. */
  45887. deleteBindGroupData( /*bindGroup*/ ) { }
  45888. /**
  45889. * Frees internal resources.
  45890. *
  45891. * @abstract
  45892. */
  45893. dispose() { }
  45894. }
  45895. let _id$1 = 0;
  45896. /**
  45897. * This module is internally used in context of compute shaders.
  45898. * This type of shader is not natively supported in WebGL 2 and
  45899. * thus implemented via Transform Feedback. `DualAttributeData`
  45900. * manages the related data.
  45901. *
  45902. * @private
  45903. */
  45904. class DualAttributeData {
  45905. constructor( attributeData, dualBuffer ) {
  45906. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  45907. this.type = attributeData.type;
  45908. this.bufferType = attributeData.bufferType;
  45909. this.pbo = attributeData.pbo;
  45910. this.byteLength = attributeData.byteLength;
  45911. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  45912. this.version = attributeData.version;
  45913. this.isInteger = attributeData.isInteger;
  45914. this.activeBufferIndex = 0;
  45915. this.baseId = attributeData.id;
  45916. }
  45917. get id() {
  45918. return `${ this.baseId }|${ this.activeBufferIndex }`;
  45919. }
  45920. get bufferGPU() {
  45921. return this.buffers[ this.activeBufferIndex ];
  45922. }
  45923. get transformBuffer() {
  45924. return this.buffers[ this.activeBufferIndex ^ 1 ];
  45925. }
  45926. switchBuffers() {
  45927. this.activeBufferIndex ^= 1;
  45928. }
  45929. }
  45930. /**
  45931. * A WebGL 2 backend utility module for managing shader attributes.
  45932. *
  45933. * @private
  45934. */
  45935. class WebGLAttributeUtils {
  45936. /**
  45937. * Constructs a new utility object.
  45938. *
  45939. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45940. */
  45941. constructor( backend ) {
  45942. /**
  45943. * A reference to the WebGL 2 backend.
  45944. *
  45945. * @type {WebGLBackend}
  45946. */
  45947. this.backend = backend;
  45948. }
  45949. /**
  45950. * Creates the GPU buffer for the given buffer attribute.
  45951. *
  45952. * @param {BufferAttribute} attribute - The buffer attribute.
  45953. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  45954. */
  45955. createAttribute( attribute, bufferType ) {
  45956. const backend = this.backend;
  45957. const { gl } = backend;
  45958. const array = attribute.array;
  45959. const usage = attribute.usage || gl.STATIC_DRAW;
  45960. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  45961. const bufferData = backend.get( bufferAttribute );
  45962. let bufferGPU = bufferData.bufferGPU;
  45963. if ( bufferGPU === undefined ) {
  45964. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  45965. bufferData.bufferGPU = bufferGPU;
  45966. bufferData.bufferType = bufferType;
  45967. bufferData.version = bufferAttribute.version;
  45968. }
  45969. //attribute.onUploadCallback();
  45970. let type;
  45971. if ( array instanceof Float32Array ) {
  45972. type = gl.FLOAT;
  45973. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  45974. type = gl.HALF_FLOAT;
  45975. } else if ( array instanceof Uint16Array ) {
  45976. if ( attribute.isFloat16BufferAttribute ) {
  45977. type = gl.HALF_FLOAT;
  45978. } else {
  45979. type = gl.UNSIGNED_SHORT;
  45980. }
  45981. } else if ( array instanceof Int16Array ) {
  45982. type = gl.SHORT;
  45983. } else if ( array instanceof Uint32Array ) {
  45984. type = gl.UNSIGNED_INT;
  45985. } else if ( array instanceof Int32Array ) {
  45986. type = gl.INT;
  45987. } else if ( array instanceof Int8Array ) {
  45988. type = gl.BYTE;
  45989. } else if ( array instanceof Uint8Array ) {
  45990. type = gl.UNSIGNED_BYTE;
  45991. } else if ( array instanceof Uint8ClampedArray ) {
  45992. type = gl.UNSIGNED_BYTE;
  45993. } else {
  45994. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  45995. }
  45996. let attributeData = {
  45997. bufferGPU,
  45998. bufferType,
  45999. type,
  46000. byteLength: array.byteLength,
  46001. bytesPerElement: array.BYTES_PER_ELEMENT,
  46002. version: attribute.version,
  46003. pbo: attribute.pbo,
  46004. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  46005. id: _id$1 ++
  46006. };
  46007. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  46008. // create buffer for transform feedback use
  46009. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  46010. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  46011. }
  46012. backend.set( attribute, attributeData );
  46013. }
  46014. /**
  46015. * Updates the GPU buffer of the given buffer attribute.
  46016. *
  46017. * @param {BufferAttribute} attribute - The buffer attribute.
  46018. */
  46019. updateAttribute( attribute ) {
  46020. const backend = this.backend;
  46021. const { gl } = backend;
  46022. const array = attribute.array;
  46023. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  46024. const bufferData = backend.get( bufferAttribute );
  46025. const bufferType = bufferData.bufferType;
  46026. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  46027. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  46028. if ( updateRanges.length === 0 ) {
  46029. // Not using update ranges
  46030. gl.bufferSubData( bufferType, 0, array );
  46031. } else {
  46032. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  46033. const range = updateRanges[ i ];
  46034. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  46035. array, range.start, range.count );
  46036. }
  46037. bufferAttribute.clearUpdateRanges();
  46038. }
  46039. gl.bindBuffer( bufferType, null );
  46040. bufferData.version = bufferAttribute.version;
  46041. }
  46042. /**
  46043. * Destroys the GPU buffer of the given buffer attribute.
  46044. *
  46045. * @param {BufferAttribute} attribute - The buffer attribute.
  46046. */
  46047. destroyAttribute( attribute ) {
  46048. const backend = this.backend;
  46049. const { gl } = backend;
  46050. if ( attribute.isInterleavedBufferAttribute ) {
  46051. backend.delete( attribute.data );
  46052. }
  46053. const attributeData = backend.get( attribute );
  46054. gl.deleteBuffer( attributeData.bufferGPU );
  46055. backend.delete( attribute );
  46056. }
  46057. /**
  46058. * This method performs a readback operation by moving buffer data from
  46059. * a storage buffer attribute from the GPU to the CPU.
  46060. *
  46061. * @async
  46062. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  46063. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  46064. */
  46065. async getArrayBufferAsync( attribute ) {
  46066. const backend = this.backend;
  46067. const { gl } = backend;
  46068. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  46069. const { bufferGPU } = backend.get( bufferAttribute );
  46070. const array = attribute.array;
  46071. const byteLength = array.byteLength;
  46072. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  46073. const writeBuffer = gl.createBuffer();
  46074. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  46075. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  46076. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  46077. await backend.utils._clientWaitAsync();
  46078. const dstBuffer = new attribute.array.constructor( array.length );
  46079. // Ensure the buffer is bound before reading
  46080. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  46081. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  46082. gl.deleteBuffer( writeBuffer );
  46083. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  46084. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  46085. return dstBuffer.buffer;
  46086. }
  46087. /**
  46088. * Creates a WebGL buffer with the given data.
  46089. *
  46090. * @private
  46091. * @param {WebGL2RenderingContext} gl - The rendering context.
  46092. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  46093. * @param {TypedArray} array - The array of the buffer attribute.
  46094. * @param {GLenum} usage - The usage.
  46095. * @return {WebGLBuffer} The WebGL buffer.
  46096. */
  46097. _createBuffer( gl, bufferType, array, usage ) {
  46098. const bufferGPU = gl.createBuffer();
  46099. gl.bindBuffer( bufferType, bufferGPU );
  46100. gl.bufferData( bufferType, array, usage );
  46101. gl.bindBuffer( bufferType, null );
  46102. return bufferGPU;
  46103. }
  46104. }
  46105. let equationToGL, factorToGL;
  46106. /**
  46107. * A WebGL 2 backend utility module for managing the WebGL state.
  46108. *
  46109. * The major goal of this module is to reduce the number of state changes
  46110. * by caching the WEbGL state with a series of variables. In this way, the
  46111. * renderer only executes state change commands when necessary which
  46112. * improves the overall performance.
  46113. *
  46114. * @private
  46115. */
  46116. class WebGLState {
  46117. /**
  46118. * Constructs a new utility object.
  46119. *
  46120. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46121. */
  46122. constructor( backend ) {
  46123. /**
  46124. * A reference to the WebGL 2 backend.
  46125. *
  46126. * @type {WebGLBackend}
  46127. */
  46128. this.backend = backend;
  46129. /**
  46130. * A reference to the rendering context.
  46131. *
  46132. * @type {WebGL2RenderingContext}
  46133. */
  46134. this.gl = this.backend.gl;
  46135. // Below properties are intended to cache
  46136. // the WebGL state and are not explicitly
  46137. // documented for convenience reasons.
  46138. this.enabled = {};
  46139. this.currentFlipSided = null;
  46140. this.currentCullFace = null;
  46141. this.currentProgram = null;
  46142. this.currentBlendingEnabled = false;
  46143. this.currentBlending = null;
  46144. this.currentBlendSrc = null;
  46145. this.currentBlendDst = null;
  46146. this.currentBlendSrcAlpha = null;
  46147. this.currentBlendDstAlpha = null;
  46148. this.currentPremultipledAlpha = null;
  46149. this.currentPolygonOffsetFactor = null;
  46150. this.currentPolygonOffsetUnits = null;
  46151. this.currentColorMask = null;
  46152. this.currentDepthFunc = null;
  46153. this.currentDepthMask = null;
  46154. this.currentStencilFunc = null;
  46155. this.currentStencilRef = null;
  46156. this.currentStencilFuncMask = null;
  46157. this.currentStencilFail = null;
  46158. this.currentStencilZFail = null;
  46159. this.currentStencilZPass = null;
  46160. this.currentStencilMask = null;
  46161. this.currentLineWidth = null;
  46162. this.currentClippingPlanes = 0;
  46163. this.currentVAO = null;
  46164. this.currentIndex = null;
  46165. this.currentBoundFramebuffers = {};
  46166. this.currentDrawbuffers = new WeakMap();
  46167. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  46168. this.currentTextureSlot = null;
  46169. this.currentBoundTextures = {};
  46170. this.currentBoundBufferBases = {};
  46171. this._init();
  46172. }
  46173. /**
  46174. * Inits the state of the utility.
  46175. *
  46176. * @private
  46177. */
  46178. _init() {
  46179. const gl = this.gl;
  46180. // Store only WebGL constants here.
  46181. equationToGL = {
  46182. [ AddEquation ]: gl.FUNC_ADD,
  46183. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  46184. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  46185. };
  46186. factorToGL = {
  46187. [ ZeroFactor ]: gl.ZERO,
  46188. [ OneFactor ]: gl.ONE,
  46189. [ SrcColorFactor ]: gl.SRC_COLOR,
  46190. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  46191. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  46192. [ DstColorFactor ]: gl.DST_COLOR,
  46193. [ DstAlphaFactor ]: gl.DST_ALPHA,
  46194. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  46195. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  46196. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  46197. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  46198. };
  46199. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  46200. const viewportParam = gl.getParameter( gl.VIEWPORT );
  46201. this.currentScissor = new Vector4().fromArray( scissorParam );
  46202. this.currentViewport = new Vector4().fromArray( viewportParam );
  46203. this._tempVec4 = new Vector4();
  46204. }
  46205. /**
  46206. * Enables the given WebGL capability.
  46207. *
  46208. * This method caches the capability state so
  46209. * `gl.enable()` is only called when necessary.
  46210. *
  46211. * @param {GLenum} id - The capability to enable.
  46212. */
  46213. enable( id ) {
  46214. const { enabled } = this;
  46215. if ( enabled[ id ] !== true ) {
  46216. this.gl.enable( id );
  46217. enabled[ id ] = true;
  46218. }
  46219. }
  46220. /**
  46221. * Disables the given WebGL capability.
  46222. *
  46223. * This method caches the capability state so
  46224. * `gl.disable()` is only called when necessary.
  46225. *
  46226. * @param {GLenum} id - The capability to enable.
  46227. */
  46228. disable( id ) {
  46229. const { enabled } = this;
  46230. if ( enabled[ id ] !== false ) {
  46231. this.gl.disable( id );
  46232. enabled[ id ] = false;
  46233. }
  46234. }
  46235. /**
  46236. * Specifies whether polygons are front- or back-facing
  46237. * by setting the winding orientation.
  46238. *
  46239. * This method caches the state so `gl.frontFace()` is only
  46240. * called when necessary.
  46241. *
  46242. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  46243. */
  46244. setFlipSided( flipSided ) {
  46245. if ( this.currentFlipSided !== flipSided ) {
  46246. const { gl } = this;
  46247. if ( flipSided ) {
  46248. gl.frontFace( gl.CW );
  46249. } else {
  46250. gl.frontFace( gl.CCW );
  46251. }
  46252. this.currentFlipSided = flipSided;
  46253. }
  46254. }
  46255. /**
  46256. * Specifies whether or not front- and/or back-facing
  46257. * polygons can be culled.
  46258. *
  46259. * This method caches the state so `gl.cullFace()` is only
  46260. * called when necessary.
  46261. *
  46262. * @param {number} cullFace - Defines which polygons are candidates for culling.
  46263. */
  46264. setCullFace( cullFace ) {
  46265. const { gl } = this;
  46266. if ( cullFace !== CullFaceNone ) {
  46267. this.enable( gl.CULL_FACE );
  46268. if ( cullFace !== this.currentCullFace ) {
  46269. if ( cullFace === CullFaceBack ) {
  46270. gl.cullFace( gl.BACK );
  46271. } else if ( cullFace === CullFaceFront ) {
  46272. gl.cullFace( gl.FRONT );
  46273. } else {
  46274. gl.cullFace( gl.FRONT_AND_BACK );
  46275. }
  46276. }
  46277. } else {
  46278. this.disable( gl.CULL_FACE );
  46279. }
  46280. this.currentCullFace = cullFace;
  46281. }
  46282. /**
  46283. * Specifies the width of line primitives.
  46284. *
  46285. * This method caches the state so `gl.lineWidth()` is only
  46286. * called when necessary.
  46287. *
  46288. * @param {number} width - The line width.
  46289. */
  46290. setLineWidth( width ) {
  46291. const { currentLineWidth, gl } = this;
  46292. if ( width !== currentLineWidth ) {
  46293. gl.lineWidth( width );
  46294. this.currentLineWidth = width;
  46295. }
  46296. }
  46297. setMRTBlending( textures ) {
  46298. const gl = this.gl;
  46299. const drawBuffersIndexedExt = this.backend.drawBuffersIndexedExt;
  46300. if ( ! drawBuffersIndexedExt ) return;
  46301. for ( let i = 1; i < textures.length; i ++ ) {
  46302. // use opaque blending for additional render targets
  46303. drawBuffersIndexedExt.blendFuncSeparateiOES( i, gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  46304. }
  46305. }
  46306. /**
  46307. * Defines the blending.
  46308. *
  46309. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  46310. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  46311. *
  46312. * @param {number} blending - The blending type.
  46313. * @param {number} blendEquation - The blending equation.
  46314. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  46315. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  46316. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  46317. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  46318. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  46319. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  46320. */
  46321. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  46322. const { gl } = this;
  46323. if ( blending === NoBlending ) {
  46324. if ( this.currentBlendingEnabled === true ) {
  46325. this.disable( gl.BLEND );
  46326. this.currentBlendingEnabled = false;
  46327. }
  46328. return;
  46329. }
  46330. if ( this.currentBlendingEnabled === false ) {
  46331. this.enable( gl.BLEND );
  46332. this.currentBlendingEnabled = true;
  46333. }
  46334. if ( blending !== CustomBlending ) {
  46335. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  46336. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  46337. gl.blendEquation( gl.FUNC_ADD );
  46338. this.currentBlendEquation = AddEquation;
  46339. this.currentBlendEquationAlpha = AddEquation;
  46340. }
  46341. if ( premultipliedAlpha ) {
  46342. switch ( blending ) {
  46343. case NormalBlending:
  46344. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  46345. break;
  46346. case AdditiveBlending:
  46347. gl.blendFunc( gl.ONE, gl.ONE );
  46348. break;
  46349. case SubtractiveBlending:
  46350. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  46351. break;
  46352. case MultiplyBlending:
  46353. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  46354. break;
  46355. default:
  46356. error( 'WebGLState: Invalid blending: ', blending );
  46357. break;
  46358. }
  46359. } else {
  46360. switch ( blending ) {
  46361. case NormalBlending:
  46362. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  46363. break;
  46364. case AdditiveBlending:
  46365. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  46366. break;
  46367. case SubtractiveBlending:
  46368. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  46369. break;
  46370. case MultiplyBlending:
  46371. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  46372. break;
  46373. default:
  46374. error( 'WebGLState: Invalid blending: ', blending );
  46375. break;
  46376. }
  46377. }
  46378. this.currentBlendSrc = null;
  46379. this.currentBlendDst = null;
  46380. this.currentBlendSrcAlpha = null;
  46381. this.currentBlendDstAlpha = null;
  46382. this.currentBlending = blending;
  46383. this.currentPremultipledAlpha = premultipliedAlpha;
  46384. }
  46385. return;
  46386. }
  46387. // custom blending
  46388. blendEquationAlpha = blendEquationAlpha || blendEquation;
  46389. blendSrcAlpha = blendSrcAlpha || blendSrc;
  46390. blendDstAlpha = blendDstAlpha || blendDst;
  46391. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  46392. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  46393. this.currentBlendEquation = blendEquation;
  46394. this.currentBlendEquationAlpha = blendEquationAlpha;
  46395. }
  46396. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  46397. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  46398. this.currentBlendSrc = blendSrc;
  46399. this.currentBlendDst = blendDst;
  46400. this.currentBlendSrcAlpha = blendSrcAlpha;
  46401. this.currentBlendDstAlpha = blendDstAlpha;
  46402. }
  46403. this.currentBlending = blending;
  46404. this.currentPremultipledAlpha = false;
  46405. }
  46406. /**
  46407. * Specifies whether colors can be written when rendering
  46408. * into a framebuffer or not.
  46409. *
  46410. * This method caches the state so `gl.colorMask()` is only
  46411. * called when necessary.
  46412. *
  46413. * @param {boolean} colorMask - The color mask.
  46414. */
  46415. setColorMask( colorMask ) {
  46416. if ( this.currentColorMask !== colorMask ) {
  46417. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  46418. this.currentColorMask = colorMask;
  46419. }
  46420. }
  46421. /**
  46422. * Specifies whether the depth test is enabled or not.
  46423. *
  46424. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  46425. */
  46426. setDepthTest( depthTest ) {
  46427. const { gl } = this;
  46428. if ( depthTest ) {
  46429. this.enable( gl.DEPTH_TEST );
  46430. } else {
  46431. this.disable( gl.DEPTH_TEST );
  46432. }
  46433. }
  46434. /**
  46435. * Specifies whether depth values can be written when rendering
  46436. * into a framebuffer or not.
  46437. *
  46438. * This method caches the state so `gl.depthMask()` is only
  46439. * called when necessary.
  46440. *
  46441. * @param {boolean} depthMask - The depth mask.
  46442. */
  46443. setDepthMask( depthMask ) {
  46444. if ( this.currentDepthMask !== depthMask ) {
  46445. this.gl.depthMask( depthMask );
  46446. this.currentDepthMask = depthMask;
  46447. }
  46448. }
  46449. /**
  46450. * Specifies the depth compare function.
  46451. *
  46452. * This method caches the state so `gl.depthFunc()` is only
  46453. * called when necessary.
  46454. *
  46455. * @param {number} depthFunc - The depth compare function.
  46456. */
  46457. setDepthFunc( depthFunc ) {
  46458. if ( this.currentDepthFunc !== depthFunc ) {
  46459. const { gl } = this;
  46460. switch ( depthFunc ) {
  46461. case NeverDepth:
  46462. gl.depthFunc( gl.NEVER );
  46463. break;
  46464. case AlwaysDepth:
  46465. gl.depthFunc( gl.ALWAYS );
  46466. break;
  46467. case LessDepth:
  46468. gl.depthFunc( gl.LESS );
  46469. break;
  46470. case LessEqualDepth:
  46471. gl.depthFunc( gl.LEQUAL );
  46472. break;
  46473. case EqualDepth:
  46474. gl.depthFunc( gl.EQUAL );
  46475. break;
  46476. case GreaterEqualDepth:
  46477. gl.depthFunc( gl.GEQUAL );
  46478. break;
  46479. case GreaterDepth:
  46480. gl.depthFunc( gl.GREATER );
  46481. break;
  46482. case NotEqualDepth:
  46483. gl.depthFunc( gl.NOTEQUAL );
  46484. break;
  46485. default:
  46486. gl.depthFunc( gl.LEQUAL );
  46487. }
  46488. this.currentDepthFunc = depthFunc;
  46489. }
  46490. }
  46491. /**
  46492. * Specifies the scissor box.
  46493. *
  46494. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  46495. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  46496. * @param {number} width - The width of the viewport.
  46497. * @param {number} height - The height of the viewport.
  46498. *
  46499. */
  46500. scissor( x, y, width, height ) {
  46501. const scissor = this._tempVec4.set( x, y, width, height );
  46502. if ( this.currentScissor.equals( scissor ) === false ) {
  46503. const { gl } = this;
  46504. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  46505. this.currentScissor.copy( scissor );
  46506. }
  46507. }
  46508. /**
  46509. * Specifies the viewport.
  46510. *
  46511. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  46512. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  46513. * @param {number} width - The width of the viewport.
  46514. * @param {number} height - The height of the viewport.
  46515. *
  46516. */
  46517. viewport( x, y, width, height ) {
  46518. const viewport = this._tempVec4.set( x, y, width, height );
  46519. if ( this.currentViewport.equals( viewport ) === false ) {
  46520. const { gl } = this;
  46521. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  46522. this.currentViewport.copy( viewport );
  46523. }
  46524. }
  46525. /**
  46526. * Defines the scissor test.
  46527. *
  46528. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  46529. */
  46530. setScissorTest( boolean ) {
  46531. const gl = this.gl;
  46532. if ( boolean ) {
  46533. this.enable( gl.SCISSOR_TEST );
  46534. } else {
  46535. this.disable( gl.SCISSOR_TEST );
  46536. }
  46537. }
  46538. /**
  46539. * Specifies whether the stencil test is enabled or not.
  46540. *
  46541. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  46542. */
  46543. setStencilTest( stencilTest ) {
  46544. const { gl } = this;
  46545. if ( stencilTest ) {
  46546. this.enable( gl.STENCIL_TEST );
  46547. } else {
  46548. this.disable( gl.STENCIL_TEST );
  46549. }
  46550. }
  46551. /**
  46552. * Specifies whether stencil values can be written when rendering
  46553. * into a framebuffer or not.
  46554. *
  46555. * This method caches the state so `gl.stencilMask()` is only
  46556. * called when necessary.
  46557. *
  46558. * @param {boolean} stencilMask - The stencil mask.
  46559. */
  46560. setStencilMask( stencilMask ) {
  46561. if ( this.currentStencilMask !== stencilMask ) {
  46562. this.gl.stencilMask( stencilMask );
  46563. this.currentStencilMask = stencilMask;
  46564. }
  46565. }
  46566. /**
  46567. * Specifies whether the stencil test functions.
  46568. *
  46569. * This method caches the state so `gl.stencilFunc()` is only
  46570. * called when necessary.
  46571. *
  46572. * @param {number} stencilFunc - The stencil compare function.
  46573. * @param {number} stencilRef - The reference value for the stencil test.
  46574. * @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.
  46575. */
  46576. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  46577. if ( this.currentStencilFunc !== stencilFunc ||
  46578. this.currentStencilRef !== stencilRef ||
  46579. this.currentStencilFuncMask !== stencilMask ) {
  46580. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  46581. this.currentStencilFunc = stencilFunc;
  46582. this.currentStencilRef = stencilRef;
  46583. this.currentStencilFuncMask = stencilMask;
  46584. }
  46585. }
  46586. /**
  46587. * Specifies whether the stencil test operation.
  46588. *
  46589. * This method caches the state so `gl.stencilOp()` is only
  46590. * called when necessary.
  46591. *
  46592. * @param {number} stencilFail - The function to use when the stencil test fails.
  46593. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  46594. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  46595. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  46596. */
  46597. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  46598. if ( this.currentStencilFail !== stencilFail ||
  46599. this.currentStencilZFail !== stencilZFail ||
  46600. this.currentStencilZPass !== stencilZPass ) {
  46601. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  46602. this.currentStencilFail = stencilFail;
  46603. this.currentStencilZFail = stencilZFail;
  46604. this.currentStencilZPass = stencilZPass;
  46605. }
  46606. }
  46607. /**
  46608. * Configures the WebGL state for the given material.
  46609. *
  46610. * @param {Material} material - The material to configure the state for.
  46611. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  46612. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  46613. */
  46614. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  46615. const { gl } = this;
  46616. material.side === DoubleSide
  46617. ? this.disable( gl.CULL_FACE )
  46618. : this.enable( gl.CULL_FACE );
  46619. let flipSided = ( material.side === BackSide );
  46620. if ( frontFaceCW ) flipSided = ! flipSided;
  46621. this.setFlipSided( flipSided );
  46622. ( material.blending === NormalBlending && material.transparent === false )
  46623. ? this.setBlending( NoBlending )
  46624. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  46625. this.setDepthFunc( material.depthFunc );
  46626. this.setDepthTest( material.depthTest );
  46627. this.setDepthMask( material.depthWrite );
  46628. this.setColorMask( material.colorWrite );
  46629. const stencilWrite = material.stencilWrite;
  46630. this.setStencilTest( stencilWrite );
  46631. if ( stencilWrite ) {
  46632. this.setStencilMask( material.stencilWriteMask );
  46633. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  46634. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  46635. }
  46636. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  46637. material.alphaToCoverage === true && this.backend.renderer.currentSamples > 0
  46638. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  46639. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  46640. if ( hardwareClippingPlanes > 0 ) {
  46641. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  46642. const CLIP_DISTANCE0_WEBGL = 0x3000;
  46643. for ( let i = 0; i < 8; i ++ ) {
  46644. if ( i < hardwareClippingPlanes ) {
  46645. this.enable( CLIP_DISTANCE0_WEBGL + i );
  46646. } else {
  46647. this.disable( CLIP_DISTANCE0_WEBGL + i );
  46648. }
  46649. }
  46650. }
  46651. }
  46652. }
  46653. /**
  46654. * Specifies the polygon offset.
  46655. *
  46656. * This method caches the state so `gl.polygonOffset()` is only
  46657. * called when necessary.
  46658. *
  46659. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  46660. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  46661. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  46662. */
  46663. setPolygonOffset( polygonOffset, factor, units ) {
  46664. const { gl } = this;
  46665. if ( polygonOffset ) {
  46666. this.enable( gl.POLYGON_OFFSET_FILL );
  46667. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  46668. gl.polygonOffset( factor, units );
  46669. this.currentPolygonOffsetFactor = factor;
  46670. this.currentPolygonOffsetUnits = units;
  46671. }
  46672. } else {
  46673. this.disable( gl.POLYGON_OFFSET_FILL );
  46674. }
  46675. }
  46676. /**
  46677. * Defines the usage of the given WebGL program.
  46678. *
  46679. * This method caches the state so `gl.useProgram()` is only
  46680. * called when necessary.
  46681. *
  46682. * @param {WebGLProgram} program - The WebGL program to use.
  46683. * @return {boolean} Whether a program change has been executed or not.
  46684. */
  46685. useProgram( program ) {
  46686. if ( this.currentProgram !== program ) {
  46687. this.gl.useProgram( program );
  46688. this.currentProgram = program;
  46689. return true;
  46690. }
  46691. return false;
  46692. }
  46693. /**
  46694. * Sets the vertex state by binding the given VAO and element buffer.
  46695. *
  46696. * @param {WebGLVertexArrayObject} vao - The VAO.
  46697. * @param {?WebGLBuffer} indexBuffer - The index buffer.
  46698. * @return {boolean} Whether a vertex state has been changed or not.
  46699. */
  46700. setVertexState( vao, indexBuffer = null ) {
  46701. const gl = this.gl;
  46702. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  46703. gl.bindVertexArray( vao );
  46704. if ( indexBuffer !== null ) {
  46705. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  46706. }
  46707. this.currentVAO = vao;
  46708. this.currentIndex = indexBuffer;
  46709. return true;
  46710. }
  46711. return false;
  46712. }
  46713. /**
  46714. * Resets the vertex array state by resetting the VAO and element buffer.
  46715. */
  46716. resetVertexState() {
  46717. const gl = this.gl;
  46718. gl.bindVertexArray( null );
  46719. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  46720. this.currentVAO = null;
  46721. this.currentIndex = null;
  46722. }
  46723. // framebuffer
  46724. /**
  46725. * Binds the given framebuffer.
  46726. *
  46727. * This method caches the state so `gl.bindFramebuffer()` is only
  46728. * called when necessary.
  46729. *
  46730. * @param {number} target - The binding point (target).
  46731. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  46732. * @return {boolean} Whether a bind has been executed or not.
  46733. */
  46734. bindFramebuffer( target, framebuffer ) {
  46735. const { gl, currentBoundFramebuffers } = this;
  46736. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  46737. gl.bindFramebuffer( target, framebuffer );
  46738. currentBoundFramebuffers[ target ] = framebuffer;
  46739. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  46740. if ( target === gl.DRAW_FRAMEBUFFER ) {
  46741. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  46742. }
  46743. if ( target === gl.FRAMEBUFFER ) {
  46744. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  46745. }
  46746. return true;
  46747. }
  46748. return false;
  46749. }
  46750. /**
  46751. * Defines draw buffers to which fragment colors are written into.
  46752. * Configures the MRT setup of custom framebuffers.
  46753. *
  46754. * This method caches the state so `gl.drawBuffers()` is only
  46755. * called when necessary.
  46756. *
  46757. * @param {RenderContext} renderContext - The render context.
  46758. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  46759. */
  46760. drawBuffers( renderContext, framebuffer ) {
  46761. const { gl } = this;
  46762. let drawBuffers = [];
  46763. let needsUpdate = false;
  46764. if ( renderContext.textures !== null ) {
  46765. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  46766. if ( drawBuffers === undefined ) {
  46767. drawBuffers = [];
  46768. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  46769. }
  46770. const textures = renderContext.textures;
  46771. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  46772. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  46773. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  46774. }
  46775. drawBuffers.length = textures.length;
  46776. needsUpdate = true;
  46777. }
  46778. } else {
  46779. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  46780. drawBuffers[ 0 ] = gl.BACK;
  46781. needsUpdate = true;
  46782. }
  46783. }
  46784. if ( needsUpdate ) {
  46785. gl.drawBuffers( drawBuffers );
  46786. }
  46787. }
  46788. // texture
  46789. /**
  46790. * Makes the given texture unit active.
  46791. *
  46792. * This method caches the state so `gl.activeTexture()` is only
  46793. * called when necessary.
  46794. *
  46795. * @param {number} webglSlot - The texture unit to make active.
  46796. */
  46797. activeTexture( webglSlot ) {
  46798. const { gl, currentTextureSlot, maxTextures } = this;
  46799. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  46800. if ( currentTextureSlot !== webglSlot ) {
  46801. gl.activeTexture( webglSlot );
  46802. this.currentTextureSlot = webglSlot;
  46803. }
  46804. }
  46805. /**
  46806. * Binds the given WebGL texture to a target.
  46807. *
  46808. * This method caches the state so `gl.bindTexture()` is only
  46809. * called when necessary.
  46810. *
  46811. * @param {number} webglType - The binding point (target).
  46812. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  46813. * @param {number} webglSlot - The texture.
  46814. */
  46815. bindTexture( webglType, webglTexture, webglSlot ) {
  46816. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  46817. if ( webglSlot === undefined ) {
  46818. if ( currentTextureSlot === null ) {
  46819. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  46820. } else {
  46821. webglSlot = currentTextureSlot;
  46822. }
  46823. }
  46824. let boundTexture = currentBoundTextures[ webglSlot ];
  46825. if ( boundTexture === undefined ) {
  46826. boundTexture = { type: undefined, texture: undefined };
  46827. currentBoundTextures[ webglSlot ] = boundTexture;
  46828. }
  46829. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  46830. if ( currentTextureSlot !== webglSlot ) {
  46831. gl.activeTexture( webglSlot );
  46832. this.currentTextureSlot = webglSlot;
  46833. }
  46834. gl.bindTexture( webglType, webglTexture );
  46835. boundTexture.type = webglType;
  46836. boundTexture.texture = webglTexture;
  46837. }
  46838. }
  46839. /**
  46840. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  46841. *
  46842. * This method caches the state so `gl.bindBufferBase()` is only
  46843. * called when necessary.
  46844. *
  46845. * @param {number} target - The target for the bind operation.
  46846. * @param {number} index - The index of the target.
  46847. * @param {WebGLBuffer} buffer - The WebGL buffer.
  46848. * @return {boolean} Whether a bind has been executed or not.
  46849. */
  46850. bindBufferBase( target, index, buffer ) {
  46851. const { gl } = this;
  46852. const key = `${target}-${index}`;
  46853. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  46854. gl.bindBufferBase( target, index, buffer );
  46855. this.currentBoundBufferBases[ key ] = buffer;
  46856. return true;
  46857. }
  46858. return false;
  46859. }
  46860. /**
  46861. * Unbinds the current bound texture.
  46862. *
  46863. * This method caches the state so `gl.bindTexture()` is only
  46864. * called when necessary.
  46865. */
  46866. unbindTexture() {
  46867. const { gl, currentTextureSlot, currentBoundTextures } = this;
  46868. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  46869. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  46870. gl.bindTexture( boundTexture.type, null );
  46871. boundTexture.type = undefined;
  46872. boundTexture.texture = undefined;
  46873. }
  46874. }
  46875. }
  46876. /**
  46877. * A WebGL 2 backend utility module with common helpers.
  46878. *
  46879. * @private
  46880. */
  46881. class WebGLUtils {
  46882. /**
  46883. * Constructs a new utility object.
  46884. *
  46885. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46886. */
  46887. constructor( backend ) {
  46888. /**
  46889. * A reference to the WebGL 2 backend.
  46890. *
  46891. * @type {WebGLBackend}
  46892. */
  46893. this.backend = backend;
  46894. /**
  46895. * A reference to the rendering context.
  46896. *
  46897. * @type {WebGL2RenderingContext}
  46898. */
  46899. this.gl = this.backend.gl;
  46900. /**
  46901. * A reference to a backend module holding extension-related
  46902. * utility functions.
  46903. *
  46904. * @type {WebGLExtensions}
  46905. */
  46906. this.extensions = backend.extensions;
  46907. }
  46908. /**
  46909. * Converts the given three.js constant into a WebGL constant.
  46910. * The method currently supports the conversion of texture formats
  46911. * and types.
  46912. *
  46913. * @param {number} p - The three.js constant.
  46914. * @param {string} [colorSpace=NoColorSpace] - The color space.
  46915. * @return {?number} The corresponding WebGL constant.
  46916. */
  46917. convert( p, colorSpace = NoColorSpace ) {
  46918. const { gl, extensions } = this;
  46919. let extension;
  46920. const transfer = ColorManagement.getTransfer( colorSpace );
  46921. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  46922. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  46923. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  46924. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  46925. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  46926. if ( p === ByteType ) return gl.BYTE;
  46927. if ( p === ShortType ) return gl.SHORT;
  46928. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  46929. if ( p === IntType ) return gl.INT;
  46930. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  46931. if ( p === FloatType ) return gl.FLOAT;
  46932. if ( p === HalfFloatType ) {
  46933. return gl.HALF_FLOAT;
  46934. }
  46935. if ( p === AlphaFormat ) return gl.ALPHA;
  46936. if ( p === RGBFormat ) return gl.RGB;
  46937. if ( p === RGBAFormat ) return gl.RGBA;
  46938. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  46939. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  46940. // WebGL2 formats.
  46941. if ( p === RedFormat ) return gl.RED;
  46942. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  46943. if ( p === RGFormat ) return gl.RG;
  46944. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  46945. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  46946. // S3TC
  46947. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  46948. if ( transfer === SRGBTransfer ) {
  46949. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  46950. if ( extension !== null ) {
  46951. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  46952. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  46953. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  46954. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  46955. } else {
  46956. return null;
  46957. }
  46958. } else {
  46959. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  46960. if ( extension !== null ) {
  46961. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  46962. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  46963. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  46964. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  46965. } else {
  46966. return null;
  46967. }
  46968. }
  46969. }
  46970. // PVRTC
  46971. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  46972. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  46973. if ( extension !== null ) {
  46974. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  46975. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  46976. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  46977. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  46978. } else {
  46979. return null;
  46980. }
  46981. }
  46982. // ETC
  46983. 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 ) {
  46984. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  46985. if ( extension !== null ) {
  46986. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  46987. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  46988. if ( p === R11_EAC_Format ) return extension.COMPRESSED_R11_EAC;
  46989. if ( p === SIGNED_R11_EAC_Format ) return extension.COMPRESSED_SIGNED_R11_EAC;
  46990. if ( p === RG11_EAC_Format ) return extension.COMPRESSED_RG11_EAC;
  46991. if ( p === SIGNED_RG11_EAC_Format ) return extension.COMPRESSED_SIGNED_RG11_EAC;
  46992. } else {
  46993. return null;
  46994. }
  46995. }
  46996. // ASTC
  46997. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  46998. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  46999. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  47000. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  47001. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  47002. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  47003. if ( extension !== null ) {
  47004. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  47005. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  47006. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  47007. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  47008. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  47009. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  47010. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  47011. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  47012. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  47013. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  47014. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  47015. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  47016. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  47017. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  47018. } else {
  47019. return null;
  47020. }
  47021. }
  47022. // BPTC
  47023. if ( p === RGBA_BPTC_Format ) {
  47024. extension = extensions.get( 'EXT_texture_compression_bptc' );
  47025. if ( extension !== null ) {
  47026. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  47027. } else {
  47028. return null;
  47029. }
  47030. }
  47031. // RGTC
  47032. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  47033. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  47034. if ( extension !== null ) {
  47035. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  47036. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  47037. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  47038. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  47039. } else {
  47040. return null;
  47041. }
  47042. }
  47043. //
  47044. if ( p === UnsignedInt248Type ) {
  47045. return gl.UNSIGNED_INT_24_8;
  47046. }
  47047. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  47048. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  47049. }
  47050. /**
  47051. * This method can be used to synchronize the CPU with the GPU by waiting until
  47052. * ongoing GPU commands have been completed.
  47053. *
  47054. * @private
  47055. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  47056. */
  47057. _clientWaitAsync() {
  47058. const { gl } = this;
  47059. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  47060. gl.flush();
  47061. return new Promise( ( resolve, reject ) => {
  47062. function test() {
  47063. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  47064. if ( res === gl.WAIT_FAILED ) {
  47065. gl.deleteSync( sync );
  47066. reject();
  47067. return;
  47068. }
  47069. if ( res === gl.TIMEOUT_EXPIRED ) {
  47070. requestAnimationFrame( test );
  47071. return;
  47072. }
  47073. gl.deleteSync( sync );
  47074. resolve();
  47075. }
  47076. test();
  47077. } );
  47078. }
  47079. }
  47080. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  47081. /**
  47082. * A WebGL 2 backend utility module for managing textures.
  47083. *
  47084. * @private
  47085. */
  47086. class WebGLTextureUtils {
  47087. /**
  47088. * Constructs a new utility object.
  47089. *
  47090. * @param {WebGLBackend} backend - The WebGL 2 backend.
  47091. */
  47092. constructor( backend ) {
  47093. /**
  47094. * A reference to the WebGL 2 backend.
  47095. *
  47096. * @type {WebGLBackend}
  47097. */
  47098. this.backend = backend;
  47099. /**
  47100. * A reference to the rendering context.
  47101. *
  47102. * @type {WebGL2RenderingContext}
  47103. */
  47104. this.gl = backend.gl;
  47105. /**
  47106. * A reference to a backend module holding extension-related
  47107. * utility functions.
  47108. *
  47109. * @type {WebGLExtensions}
  47110. */
  47111. this.extensions = backend.extensions;
  47112. /**
  47113. * A dictionary for managing default textures. The key
  47114. * is the binding point (target), the value the WEbGL texture object.
  47115. *
  47116. * @type {Object<GLenum,WebGLTexture>}
  47117. */
  47118. this.defaultTextures = {};
  47119. /**
  47120. * A scratch framebuffer used for attaching the source texture in
  47121. * {@link copyTextureToTexture}.
  47122. *
  47123. * @private
  47124. * @type {?WebGLFramebuffer}
  47125. */
  47126. this._srcFramebuffer = null;
  47127. /**
  47128. * A scratch framebuffer used for attaching the destination texture in
  47129. * {@link copyTextureToTexture}.
  47130. *
  47131. * @private
  47132. * @type {?WebGLFramebuffer}
  47133. */
  47134. this._dstFramebuffer = null;
  47135. if ( initialized === false ) {
  47136. this._init();
  47137. initialized = true;
  47138. }
  47139. }
  47140. /**
  47141. * Inits the state of the utility.
  47142. *
  47143. * @private
  47144. */
  47145. _init() {
  47146. const gl = this.gl;
  47147. // Store only WebGL constants here.
  47148. wrappingToGL = {
  47149. [ RepeatWrapping ]: gl.REPEAT,
  47150. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  47151. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  47152. };
  47153. filterToGL = {
  47154. [ NearestFilter ]: gl.NEAREST,
  47155. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  47156. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  47157. [ LinearFilter ]: gl.LINEAR,
  47158. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  47159. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  47160. };
  47161. compareToGL = {
  47162. [ NeverCompare ]: gl.NEVER,
  47163. [ AlwaysCompare ]: gl.ALWAYS,
  47164. [ LessCompare ]: gl.LESS,
  47165. [ LessEqualCompare ]: gl.LEQUAL,
  47166. [ EqualCompare ]: gl.EQUAL,
  47167. [ GreaterEqualCompare ]: gl.GEQUAL,
  47168. [ GreaterCompare ]: gl.GREATER,
  47169. [ NotEqualCompare ]: gl.NOTEQUAL
  47170. };
  47171. }
  47172. /**
  47173. * Returns the native texture type for the given texture.
  47174. *
  47175. * @param {Texture} texture - The texture.
  47176. * @return {GLenum} The native texture type.
  47177. */
  47178. getGLTextureType( texture ) {
  47179. const { gl } = this;
  47180. let glTextureType;
  47181. if ( texture.isCubeTexture === true ) {
  47182. glTextureType = gl.TEXTURE_CUBE_MAP;
  47183. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  47184. glTextureType = gl.TEXTURE_2D_ARRAY;
  47185. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  47186. glTextureType = gl.TEXTURE_3D;
  47187. } else {
  47188. glTextureType = gl.TEXTURE_2D;
  47189. }
  47190. return glTextureType;
  47191. }
  47192. /**
  47193. * Returns the native texture type for the given texture.
  47194. *
  47195. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  47196. * @param {GLenum} glFormat - The WebGL format.
  47197. * @param {GLenum} glType - The WebGL type.
  47198. * @param {string} colorSpace - The texture's color space.
  47199. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  47200. * @return {GLenum} The internal format.
  47201. */
  47202. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  47203. const { gl, extensions } = this;
  47204. if ( internalFormatName !== null ) {
  47205. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  47206. warn( 'WebGLBackend: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  47207. }
  47208. let internalFormat = glFormat;
  47209. if ( glFormat === gl.RED ) {
  47210. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  47211. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  47212. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  47213. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  47214. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  47215. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  47216. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  47217. if ( glType === gl.INT ) internalFormat = gl.R32I;
  47218. }
  47219. if ( glFormat === gl.RED_INTEGER ) {
  47220. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  47221. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  47222. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  47223. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  47224. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  47225. if ( glType === gl.INT ) internalFormat = gl.R32I;
  47226. }
  47227. if ( glFormat === gl.RG ) {
  47228. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  47229. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  47230. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  47231. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  47232. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  47233. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  47234. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  47235. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  47236. }
  47237. if ( glFormat === gl.RG_INTEGER ) {
  47238. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  47239. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  47240. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  47241. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  47242. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  47243. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  47244. }
  47245. if ( glFormat === gl.RGB ) {
  47246. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  47247. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  47248. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  47249. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  47250. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  47251. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  47252. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  47253. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  47254. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  47255. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  47256. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  47257. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  47258. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  47259. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  47260. if ( glType === gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = gl.R11F_G11F_B10F;
  47261. }
  47262. if ( glFormat === gl.RGB_INTEGER ) {
  47263. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  47264. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  47265. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  47266. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  47267. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  47268. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  47269. }
  47270. if ( glFormat === gl.RGBA ) {
  47271. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  47272. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  47273. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  47274. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  47275. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  47276. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  47277. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  47278. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  47279. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  47280. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  47281. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  47282. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  47283. }
  47284. if ( glFormat === gl.RGBA_INTEGER ) {
  47285. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  47286. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  47287. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  47288. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  47289. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  47290. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  47291. }
  47292. if ( glFormat === gl.DEPTH_COMPONENT ) {
  47293. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  47294. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  47295. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  47296. }
  47297. if ( glFormat === gl.DEPTH_STENCIL ) {
  47298. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  47299. }
  47300. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  47301. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  47302. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  47303. extensions.get( 'EXT_color_buffer_float' );
  47304. }
  47305. return internalFormat;
  47306. }
  47307. /**
  47308. * Sets the texture parameters for the given texture.
  47309. *
  47310. * @param {GLenum} textureType - The texture type.
  47311. * @param {Texture} texture - The texture.
  47312. */
  47313. setTextureParameters( textureType, texture ) {
  47314. const { gl, extensions, backend } = this;
  47315. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  47316. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  47317. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  47318. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  47319. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  47320. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  47321. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  47322. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  47323. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  47324. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  47325. // WebGL 2 does not support wrapping for depth 2D array textures
  47326. if ( ! texture.isArrayTexture ) {
  47327. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  47328. }
  47329. }
  47330. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  47331. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  47332. // follow WebGPU backend mapping for texture filtering
  47333. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  47334. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  47335. if ( texture.compareFunction ) {
  47336. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  47337. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  47338. }
  47339. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  47340. if ( texture.magFilter === NearestFilter ) return;
  47341. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  47342. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  47343. if ( texture.anisotropy > 1 ) {
  47344. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  47345. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  47346. }
  47347. }
  47348. }
  47349. /**
  47350. * Creates a default texture for the given texture that can be used
  47351. * as a placeholder until the actual texture is ready for usage.
  47352. *
  47353. * @param {Texture} texture - The texture to create a default texture for.
  47354. */
  47355. createDefaultTexture( texture ) {
  47356. const { gl, backend, defaultTextures } = this;
  47357. const glTextureType = this.getGLTextureType( texture );
  47358. let textureGPU = defaultTextures[ glTextureType ];
  47359. if ( textureGPU === undefined ) {
  47360. textureGPU = gl.createTexture();
  47361. backend.state.bindTexture( glTextureType, textureGPU );
  47362. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  47363. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  47364. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  47365. defaultTextures[ glTextureType ] = textureGPU;
  47366. }
  47367. backend.set( texture, {
  47368. textureGPU,
  47369. glTextureType
  47370. } );
  47371. }
  47372. /**
  47373. * Defines a texture on the GPU for the given texture object.
  47374. *
  47375. * @param {Texture} texture - The texture.
  47376. * @param {Object} [options={}] - Optional configuration parameter.
  47377. * @return {undefined}
  47378. */
  47379. createTexture( texture, options ) {
  47380. const { gl, backend } = this;
  47381. const { levels, width, height, depth } = options;
  47382. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  47383. const glType = backend.utils.convert( texture.type );
  47384. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  47385. const textureGPU = gl.createTexture();
  47386. const glTextureType = this.getGLTextureType( texture );
  47387. backend.state.bindTexture( glTextureType, textureGPU );
  47388. this.setTextureParameters( glTextureType, texture );
  47389. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  47390. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  47391. } else if ( texture.isData3DTexture ) {
  47392. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  47393. } else if ( ! texture.isVideoTexture ) {
  47394. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  47395. }
  47396. backend.set( texture, {
  47397. textureGPU,
  47398. glTextureType,
  47399. glFormat,
  47400. glType,
  47401. glInternalFormat
  47402. } );
  47403. }
  47404. /**
  47405. * Uploads texture buffer data to the GPU memory.
  47406. *
  47407. * @param {WebGLBuffer} buffer - The buffer data.
  47408. * @param {Texture} texture - The texture,
  47409. */
  47410. copyBufferToTexture( buffer, texture ) {
  47411. const { gl, backend } = this;
  47412. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  47413. const { width, height } = texture.source.data;
  47414. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  47415. backend.state.bindTexture( glTextureType, textureGPU );
  47416. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  47417. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  47418. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  47419. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  47420. backend.state.unbindTexture();
  47421. // debug
  47422. // const framebuffer = gl.createFramebuffer();
  47423. // backend.state.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  47424. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  47425. // const readout = new Float32Array( width * height * 4 );
  47426. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  47427. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  47428. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  47429. // backend.state.bindFramebuffer( gl.FRAMEBUFFER, null );
  47430. // log( readout );
  47431. }
  47432. /**
  47433. * Uploads the updated texture data to the GPU.
  47434. *
  47435. * @param {Texture} texture - The texture.
  47436. * @param {Object} [options={}] - Optional configuration parameter.
  47437. */
  47438. updateTexture( texture, options ) {
  47439. const { gl } = this;
  47440. const { width, height } = options;
  47441. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  47442. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  47443. return;
  47444. this.backend.state.bindTexture( glTextureType, textureGPU );
  47445. this.setTextureParameters( glTextureType, texture );
  47446. if ( texture.isCompressedTexture ) {
  47447. const mipmaps = texture.mipmaps;
  47448. const image = options.image;
  47449. for ( let i = 0; i < mipmaps.length; i ++ ) {
  47450. const mipmap = mipmaps[ i ];
  47451. if ( texture.isCompressedArrayTexture ) {
  47452. if ( texture.format !== gl.RGBA ) {
  47453. if ( glFormat !== null ) {
  47454. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  47455. } else {
  47456. warn( 'WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  47457. }
  47458. } else {
  47459. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  47460. }
  47461. } else {
  47462. if ( glFormat !== null ) {
  47463. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  47464. } else {
  47465. warn( 'WebGLBackend: Unsupported compressed texture format' );
  47466. }
  47467. }
  47468. }
  47469. } else if ( texture.isCubeTexture ) {
  47470. const images = options.images;
  47471. const mipmaps = texture.mipmaps;
  47472. for ( let i = 0; i < 6; i ++ ) {
  47473. const image = getImage( images[ i ] );
  47474. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  47475. for ( let j = 0; j < mipmaps.length; j ++ ) {
  47476. const mipmap = mipmaps[ j ];
  47477. const image = getImage( mipmap.images[ i ] );
  47478. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, image.width, image.height, glFormat, glType, image );
  47479. }
  47480. }
  47481. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  47482. const image = options.image;
  47483. if ( texture.layerUpdates.size > 0 ) {
  47484. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  47485. for ( const layerIndex of texture.layerUpdates ) {
  47486. const layerData = image.data.subarray(
  47487. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  47488. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  47489. );
  47490. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  47491. }
  47492. texture.clearLayerUpdates();
  47493. } else {
  47494. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  47495. }
  47496. } else if ( texture.isData3DTexture ) {
  47497. const image = options.image;
  47498. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  47499. } else if ( texture.isVideoTexture ) {
  47500. texture.update();
  47501. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  47502. } else {
  47503. const mipmaps = texture.mipmaps;
  47504. if ( mipmaps.length > 0 ) {
  47505. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  47506. const mipmap = mipmaps[ i ];
  47507. const image = getImage( mipmap );
  47508. gl.texSubImage2D( glTextureType, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, image );
  47509. }
  47510. } else {
  47511. const image = getImage( options.image );
  47512. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  47513. }
  47514. }
  47515. }
  47516. /**
  47517. * Generates mipmaps for the given texture.
  47518. *
  47519. * @param {Texture} texture - The texture.
  47520. */
  47521. generateMipmaps( texture ) {
  47522. const { gl, backend } = this;
  47523. const { textureGPU, glTextureType } = backend.get( texture );
  47524. backend.state.bindTexture( glTextureType, textureGPU );
  47525. gl.generateMipmap( glTextureType );
  47526. }
  47527. /**
  47528. * Deallocates the render buffers of the given render target.
  47529. *
  47530. * @param {RenderTarget} renderTarget - The render target.
  47531. */
  47532. deallocateRenderBuffers( renderTarget ) {
  47533. const { gl, backend } = this;
  47534. // remove framebuffer reference
  47535. if ( renderTarget ) {
  47536. const renderContextData = backend.get( renderTarget );
  47537. renderContextData.renderBufferStorageSetup = undefined;
  47538. if ( renderContextData.framebuffers ) {
  47539. for ( const cacheKey in renderContextData.framebuffers ) {
  47540. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  47541. }
  47542. delete renderContextData.framebuffers;
  47543. }
  47544. if ( renderContextData.depthRenderbuffer ) {
  47545. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  47546. delete renderContextData.depthRenderbuffer;
  47547. }
  47548. if ( renderContextData.stencilRenderbuffer ) {
  47549. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  47550. delete renderContextData.stencilRenderbuffer;
  47551. }
  47552. if ( renderContextData.msaaFrameBuffer ) {
  47553. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  47554. delete renderContextData.msaaFrameBuffer;
  47555. }
  47556. if ( renderContextData.msaaRenderbuffers ) {
  47557. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  47558. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  47559. }
  47560. delete renderContextData.msaaRenderbuffers;
  47561. }
  47562. }
  47563. }
  47564. /**
  47565. * Destroys the GPU data for the given texture object.
  47566. *
  47567. * @param {Texture} texture - The texture.
  47568. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  47569. */
  47570. destroyTexture( texture, isDefaultTexture = false ) {
  47571. const { gl, backend } = this;
  47572. const { textureGPU, renderTarget } = backend.get( texture );
  47573. this.deallocateRenderBuffers( renderTarget );
  47574. if ( isDefaultTexture === false ) {
  47575. gl.deleteTexture( textureGPU );
  47576. }
  47577. backend.delete( texture );
  47578. }
  47579. /**
  47580. * Copies data of the given source texture to the given destination texture.
  47581. *
  47582. * @param {Texture} srcTexture - The source texture.
  47583. * @param {Texture} dstTexture - The destination texture.
  47584. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  47585. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  47586. * @param {number} [srcLevel=0] - The source mip level to copy from.
  47587. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  47588. */
  47589. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  47590. const { gl, backend } = this;
  47591. const { state } = this.backend;
  47592. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  47593. state.bindTexture( glTextureType, dstTextureGPU );
  47594. // gather the necessary dimensions to copy
  47595. let width, height, depth, minX, minY, minZ;
  47596. let dstX, dstY, dstZ;
  47597. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  47598. if ( srcRegion !== null ) {
  47599. width = srcRegion.max.x - srcRegion.min.x;
  47600. height = srcRegion.max.y - srcRegion.min.y;
  47601. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  47602. minX = srcRegion.min.x;
  47603. minY = srcRegion.min.y;
  47604. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  47605. } else {
  47606. const levelScale = Math.pow( 2, - srcLevel );
  47607. width = Math.floor( image.width * levelScale );
  47608. height = Math.floor( image.height * levelScale );
  47609. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  47610. depth = image.depth;
  47611. } else if ( srcTexture.isData3DTexture ) {
  47612. depth = Math.floor( image.depth * levelScale );
  47613. } else {
  47614. depth = 1;
  47615. }
  47616. minX = 0;
  47617. minY = 0;
  47618. minZ = 0;
  47619. }
  47620. if ( dstPosition !== null ) {
  47621. dstX = dstPosition.x;
  47622. dstY = dstPosition.y;
  47623. dstZ = dstPosition.z;
  47624. } else {
  47625. dstX = 0;
  47626. dstY = 0;
  47627. dstZ = 0;
  47628. }
  47629. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  47630. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  47631. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  47632. // used for copying data from cpu
  47633. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  47634. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  47635. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  47636. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  47637. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  47638. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  47639. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  47640. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  47641. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  47642. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  47643. // set up the src texture
  47644. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture || dstTexture.isArrayTexture;
  47645. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  47646. if ( srcTexture.isDepthTexture ) {
  47647. const srcTextureData = backend.get( srcTexture );
  47648. const dstTextureData = backend.get( dstTexture );
  47649. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  47650. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  47651. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  47652. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  47653. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  47654. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  47655. for ( let i = 0; i < depth; i ++ ) {
  47656. // if the source or destination are a 3d target then a layer needs to be bound
  47657. if ( isSrc3D ) {
  47658. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  47659. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  47660. }
  47661. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.DEPTH_BUFFER_BIT, gl.NEAREST );
  47662. }
  47663. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  47664. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  47665. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || backend.has( srcTexture ) ) {
  47666. // get the appropriate frame buffers
  47667. const srcTextureData = backend.get( srcTexture );
  47668. if ( this._srcFramebuffer === null ) this._srcFramebuffer = gl.createFramebuffer();
  47669. if ( this._dstFramebuffer === null ) this._dstFramebuffer = gl.createFramebuffer();
  47670. // bind the frame buffer targets
  47671. state.bindFramebuffer( gl.READ_FRAMEBUFFER, this._srcFramebuffer );
  47672. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, this._dstFramebuffer );
  47673. for ( let i = 0; i < depth; i ++ ) {
  47674. // assign the correct layers and mip maps to the frame buffers
  47675. if ( isSrc3D ) {
  47676. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  47677. } else {
  47678. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, srcTextureData.textureGPU, srcLevel );
  47679. }
  47680. if ( isDst3D ) {
  47681. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  47682. } else {
  47683. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dstTextureGPU, dstLevel );
  47684. }
  47685. // copy the data using the fastest function that can achieve the copy
  47686. if ( srcLevel !== 0 ) {
  47687. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST );
  47688. } else if ( isDst3D ) {
  47689. gl.copyTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  47690. } else {
  47691. gl.copyTexSubImage2D( glTextureType, dstLevel, dstX, dstY, minX, minY, width, height );
  47692. }
  47693. }
  47694. // unbind read, draw buffers
  47695. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  47696. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  47697. } else {
  47698. if ( isDst3D ) {
  47699. // copy data into the 3d texture
  47700. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  47701. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  47702. } else if ( dstTexture.isCompressedArrayTexture ) {
  47703. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  47704. } else {
  47705. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  47706. }
  47707. } else {
  47708. // copy data into the 2d texture
  47709. if ( srcTexture.isDataTexture ) {
  47710. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  47711. } else if ( srcTexture.isCompressedTexture ) {
  47712. gl.compressedTexSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  47713. } else {
  47714. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  47715. }
  47716. }
  47717. }
  47718. // reset values
  47719. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  47720. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  47721. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  47722. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  47723. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  47724. // Generate mipmaps only when copying level 0
  47725. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  47726. gl.generateMipmap( glTextureType );
  47727. }
  47728. state.unbindTexture();
  47729. }
  47730. /**
  47731. * Copies the current bound framebuffer to the given texture.
  47732. *
  47733. * @param {Texture} texture - The destination texture.
  47734. * @param {RenderContext} renderContext - The render context.
  47735. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  47736. */
  47737. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  47738. const { gl } = this;
  47739. const { state } = this.backend;
  47740. const { textureGPU } = this.backend.get( texture );
  47741. const { x, y, z: width, w: height } = rectangle;
  47742. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  47743. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  47744. if ( requireDrawFrameBuffer ) {
  47745. const partial = ( x !== 0 || y !== 0 );
  47746. let mask;
  47747. let attachment;
  47748. if ( texture.isDepthTexture === true ) {
  47749. mask = gl.DEPTH_BUFFER_BIT;
  47750. attachment = gl.DEPTH_ATTACHMENT;
  47751. if ( renderContext.stencil ) {
  47752. mask |= gl.STENCIL_BUFFER_BIT;
  47753. }
  47754. } else {
  47755. mask = gl.COLOR_BUFFER_BIT;
  47756. attachment = gl.COLOR_ATTACHMENT0;
  47757. }
  47758. if ( partial ) {
  47759. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  47760. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  47761. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  47762. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  47763. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  47764. const flippedY = srcHeight - y - height;
  47765. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  47766. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  47767. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  47768. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  47769. state.unbindTexture();
  47770. } else {
  47771. const fb = gl.createFramebuffer();
  47772. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  47773. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  47774. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  47775. gl.deleteFramebuffer( fb );
  47776. }
  47777. } else {
  47778. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  47779. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  47780. state.unbindTexture();
  47781. }
  47782. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  47783. this.backend._setFramebuffer( renderContext );
  47784. }
  47785. /**
  47786. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  47787. *
  47788. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  47789. * @param {RenderContext} renderContext - The render context.
  47790. * @param {number} samples - The MSAA sample count.
  47791. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  47792. */
  47793. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  47794. const { gl } = this;
  47795. const renderTarget = renderContext.renderTarget;
  47796. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  47797. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  47798. if ( depthBuffer && ! stencilBuffer ) {
  47799. let glInternalFormat = gl.DEPTH_COMPONENT24;
  47800. if ( useMultisampledRTT === true ) {
  47801. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  47802. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  47803. } else if ( samples > 0 ) {
  47804. if ( depthTexture && depthTexture.isDepthTexture ) {
  47805. if ( depthTexture.type === gl.FLOAT ) {
  47806. glInternalFormat = gl.DEPTH_COMPONENT32F;
  47807. }
  47808. }
  47809. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  47810. } else {
  47811. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  47812. }
  47813. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  47814. } else if ( depthBuffer && stencilBuffer ) {
  47815. if ( samples > 0 ) {
  47816. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  47817. } else {
  47818. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  47819. }
  47820. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  47821. }
  47822. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  47823. }
  47824. /**
  47825. * Returns texture data as a typed array.
  47826. *
  47827. * @async
  47828. * @param {Texture} texture - The texture to copy.
  47829. * @param {number} x - The x coordinate of the copy origin.
  47830. * @param {number} y - The y coordinate of the copy origin.
  47831. * @param {number} width - The width of the copy.
  47832. * @param {number} height - The height of the copy.
  47833. * @param {number} faceIndex - The face index.
  47834. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  47835. */
  47836. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  47837. const { backend, gl } = this;
  47838. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  47839. const fb = gl.createFramebuffer();
  47840. backend.state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  47841. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  47842. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  47843. const typedArrayType = this._getTypedArrayType( glType );
  47844. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  47845. const elementCount = width * height;
  47846. const byteLength = elementCount * bytesPerTexel;
  47847. const buffer = gl.createBuffer();
  47848. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  47849. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  47850. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  47851. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  47852. await backend.utils._clientWaitAsync();
  47853. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  47854. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  47855. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  47856. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  47857. backend.state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  47858. gl.deleteFramebuffer( fb );
  47859. return dstBuffer;
  47860. }
  47861. /**
  47862. * Returns the corresponding typed array type for the given WebGL data type.
  47863. *
  47864. * @private
  47865. * @param {GLenum} glType - The WebGL data type.
  47866. * @return {TypedArray.constructor} The typed array type.
  47867. */
  47868. _getTypedArrayType( glType ) {
  47869. const { gl } = this;
  47870. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  47871. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  47872. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  47873. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  47874. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  47875. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  47876. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  47877. if ( glType === gl.FLOAT ) return Float32Array;
  47878. throw new Error( `Unsupported WebGL type: ${glType}` );
  47879. }
  47880. /**
  47881. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  47882. *
  47883. * @private
  47884. * @param {GLenum} glType - The WebGL data type.
  47885. * @param {GLenum} glFormat - The WebGL texture format.
  47886. * @return {number} The bytes-per-texel.
  47887. */
  47888. _getBytesPerTexel( glType, glFormat ) {
  47889. const { gl } = this;
  47890. let bytesPerComponent = 0;
  47891. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  47892. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  47893. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  47894. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  47895. glType === gl.UNSIGNED_SHORT ||
  47896. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  47897. if ( glType === gl.UNSIGNED_INT ||
  47898. glType === gl.FLOAT ) bytesPerComponent = 4;
  47899. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  47900. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  47901. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  47902. }
  47903. /**
  47904. * Frees the internal resources.
  47905. */
  47906. dispose() {
  47907. const { gl } = this;
  47908. if ( this._srcFramebuffer !== null ) gl.deleteFramebuffer( this._srcFramebuffer );
  47909. if ( this._dstFramebuffer !== null ) gl.deleteFramebuffer( this._dstFramebuffer );
  47910. }
  47911. }
  47912. function getImage( source ) {
  47913. if ( source.isDataTexture ) {
  47914. return source.image.data;
  47915. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  47916. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  47917. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  47918. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  47919. return source;
  47920. }
  47921. return source.data;
  47922. }
  47923. /**
  47924. * A WebGL 2 backend utility module for managing extensions.
  47925. *
  47926. * @private
  47927. */
  47928. class WebGLExtensions {
  47929. /**
  47930. * Constructs a new utility object.
  47931. *
  47932. * @param {WebGLBackend} backend - The WebGL 2 backend.
  47933. */
  47934. constructor( backend ) {
  47935. /**
  47936. * A reference to the WebGL 2 backend.
  47937. *
  47938. * @type {WebGLBackend}
  47939. */
  47940. this.backend = backend;
  47941. /**
  47942. * A reference to the rendering context.
  47943. *
  47944. * @type {WebGL2RenderingContext}
  47945. */
  47946. this.gl = this.backend.gl;
  47947. /**
  47948. * A list with all the supported WebGL extensions.
  47949. *
  47950. * @type {Array<string>}
  47951. */
  47952. this.availableExtensions = this.gl.getSupportedExtensions();
  47953. /**
  47954. * A dictionary with requested WebGL extensions.
  47955. * The key is the name of the extension, the value
  47956. * the requested extension object.
  47957. *
  47958. * @type {Object<string,Object>}
  47959. */
  47960. this.extensions = {};
  47961. }
  47962. /**
  47963. * Returns the extension object for the given extension name.
  47964. *
  47965. * @param {string} name - The extension name.
  47966. * @return {Object} The extension object.
  47967. */
  47968. get( name ) {
  47969. let extension = this.extensions[ name ];
  47970. if ( extension === undefined ) {
  47971. extension = this.gl.getExtension( name );
  47972. this.extensions[ name ] = extension;
  47973. }
  47974. return extension;
  47975. }
  47976. /**
  47977. * Returns `true` if the requested extension is available.
  47978. *
  47979. * @param {string} name - The extension name.
  47980. * @return {boolean} Whether the given extension is available or not.
  47981. */
  47982. has( name ) {
  47983. return this.availableExtensions.includes( name );
  47984. }
  47985. }
  47986. /**
  47987. * A WebGL 2 backend utility module for managing the device's capabilities.
  47988. *
  47989. * @private
  47990. */
  47991. class WebGLCapabilities {
  47992. /**
  47993. * Constructs a new utility object.
  47994. *
  47995. * @param {WebGLBackend} backend - The WebGL 2 backend.
  47996. */
  47997. constructor( backend ) {
  47998. /**
  47999. * A reference to the WebGL 2 backend.
  48000. *
  48001. * @type {WebGLBackend}
  48002. */
  48003. this.backend = backend;
  48004. /**
  48005. * This value holds the cached max anisotropy value.
  48006. *
  48007. * @type {?number}
  48008. * @default null
  48009. */
  48010. this.maxAnisotropy = null;
  48011. }
  48012. /**
  48013. * Returns the maximum anisotropy texture filtering value. This value
  48014. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  48015. * WebGL extension.
  48016. *
  48017. * @return {number} The maximum anisotropy texture filtering value.
  48018. */
  48019. getMaxAnisotropy() {
  48020. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  48021. const gl = this.backend.gl;
  48022. const extensions = this.backend.extensions;
  48023. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  48024. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  48025. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  48026. } else {
  48027. this.maxAnisotropy = 0;
  48028. }
  48029. return this.maxAnisotropy;
  48030. }
  48031. }
  48032. const GLFeatureName = {
  48033. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  48034. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  48035. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  48036. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  48037. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  48038. 'WEBGL_compressed_texture_s3tc': 'texture-compression-s3tc',
  48039. 'EXT_texture_compression_bptc': 'texture-compression-bc',
  48040. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  48041. 'OVR_multiview2': 'OVR_multiview2'
  48042. };
  48043. class WebGLBufferRenderer {
  48044. constructor( backend ) {
  48045. this.gl = backend.gl;
  48046. this.extensions = backend.extensions;
  48047. this.info = backend.renderer.info;
  48048. this.mode = null;
  48049. this.index = 0;
  48050. this.type = null;
  48051. this.object = null;
  48052. }
  48053. render( start, count ) {
  48054. const { gl, mode, object, type, info, index } = this;
  48055. if ( index !== 0 ) {
  48056. gl.drawElements( mode, count, type, start );
  48057. } else {
  48058. gl.drawArrays( mode, start, count );
  48059. }
  48060. info.update( object, count, 1 );
  48061. }
  48062. renderInstances( start, count, primcount ) {
  48063. const { gl, mode, type, index, object, info } = this;
  48064. if ( primcount === 0 ) return;
  48065. if ( index !== 0 ) {
  48066. gl.drawElementsInstanced( mode, count, type, start, primcount );
  48067. } else {
  48068. gl.drawArraysInstanced( mode, start, count, primcount );
  48069. }
  48070. info.update( object, count, primcount );
  48071. }
  48072. renderMultiDraw( starts, counts, drawCount ) {
  48073. const { extensions, mode, object, info } = this;
  48074. if ( drawCount === 0 ) return;
  48075. const extension = extensions.get( 'WEBGL_multi_draw' );
  48076. if ( extension === null ) {
  48077. for ( let i = 0; i < drawCount; i ++ ) {
  48078. this.render( starts[ i ], counts[ i ] );
  48079. }
  48080. } else {
  48081. if ( this.index !== 0 ) {
  48082. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  48083. } else {
  48084. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  48085. }
  48086. let elementCount = 0;
  48087. for ( let i = 0; i < drawCount; i ++ ) {
  48088. elementCount += counts[ i ];
  48089. }
  48090. info.update( object, elementCount, 1 );
  48091. }
  48092. }
  48093. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  48094. const { extensions, mode, object, info } = this;
  48095. if ( drawCount === 0 ) return;
  48096. const extension = extensions.get( 'WEBGL_multi_draw' );
  48097. if ( extension === null ) {
  48098. for ( let i = 0; i < drawCount; i ++ ) {
  48099. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  48100. }
  48101. } else {
  48102. if ( this.index !== 0 ) {
  48103. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  48104. } else {
  48105. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  48106. }
  48107. let elementCount = 0;
  48108. for ( let i = 0; i < drawCount; i ++ ) {
  48109. elementCount += counts[ i ] * primcount[ i ];
  48110. }
  48111. info.update( object, elementCount, 1 );
  48112. }
  48113. }
  48114. //
  48115. }
  48116. /**
  48117. * Abstract base class of a timestamp query pool.
  48118. *
  48119. * @abstract
  48120. */
  48121. class TimestampQueryPool {
  48122. /**
  48123. * Creates a new timestamp query pool.
  48124. *
  48125. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  48126. */
  48127. constructor( maxQueries = 256 ) {
  48128. /**
  48129. * Whether to track timestamps or not.
  48130. *
  48131. * @type {boolean}
  48132. * @default true
  48133. */
  48134. this.trackTimestamp = true;
  48135. /**
  48136. * Maximum number of queries this pool can hold.
  48137. *
  48138. * @type {number}
  48139. * @default 256
  48140. */
  48141. this.maxQueries = maxQueries;
  48142. /**
  48143. * How many queries allocated so far.
  48144. *
  48145. * @type {number}
  48146. * @default 0
  48147. */
  48148. this.currentQueryIndex = 0;
  48149. /**
  48150. * Tracks offsets for different contexts.
  48151. *
  48152. * @type {Map<string, number>}
  48153. */
  48154. this.queryOffsets = new Map();
  48155. /**
  48156. * Whether the pool has been disposed or not.
  48157. *
  48158. * @type {boolean}
  48159. * @default false
  48160. */
  48161. this.isDisposed = false;
  48162. /**
  48163. * TODO
  48164. *
  48165. * @type {number}
  48166. * @default 0
  48167. */
  48168. this.lastValue = 0;
  48169. /**
  48170. * Stores all timestamp frames.
  48171. *
  48172. * @type {Array<number>}
  48173. */
  48174. this.frames = [];
  48175. /**
  48176. * TODO
  48177. *
  48178. * @type {boolean}
  48179. * @default false
  48180. */
  48181. this.pendingResolve = false;
  48182. /**
  48183. * Stores the latest timestamp for each render context.
  48184. *
  48185. * @type {Map<string, number>}
  48186. */
  48187. this.timestamps = new Map();
  48188. }
  48189. /**
  48190. * Returns all timestamp frames.
  48191. *
  48192. * @return {Array<number>} The timestamp frames.
  48193. */
  48194. getTimestampFrames() {
  48195. return this.frames;
  48196. }
  48197. /**
  48198. * Returns the timestamp for a given render context.
  48199. *
  48200. * @param {string} uid - A unique identifier for the render context.
  48201. * @return {?number} The timestamp, or undefined if not available.
  48202. */
  48203. getTimestamp( uid ) {
  48204. let timestamp = this.timestamps.get( uid );
  48205. if ( timestamp === undefined ) {
  48206. warn( `TimestampQueryPool: No timestamp available for uid ${ uid }.` );
  48207. timestamp = 0;
  48208. }
  48209. return timestamp;
  48210. }
  48211. /**
  48212. * Returns whether a timestamp is available for a given render context.
  48213. *
  48214. * @param {string} uid - A unique identifier for the render context.
  48215. * @return {boolean} True if a timestamp is available, false otherwise.
  48216. */
  48217. hasTimestamp( uid ) {
  48218. return this.timestamps.has( uid );
  48219. }
  48220. /**
  48221. * Allocate queries for a specific uid.
  48222. *
  48223. * @abstract
  48224. * @param {string} uid - A unique identifier for the render context.
  48225. * @param {number} frameId - The current frame identifier.
  48226. * @returns {?number}
  48227. */
  48228. allocateQueriesForContext( /* uid, frameId */ ) {}
  48229. /**
  48230. * Resolve all timestamps and return data (or process them).
  48231. *
  48232. * @abstract
  48233. * @async
  48234. * @returns {Promise<number>|number} The resolved timestamp value.
  48235. */
  48236. async resolveQueriesAsync() {}
  48237. /**
  48238. * Dispose of the query pool.
  48239. *
  48240. * @abstract
  48241. */
  48242. dispose() {}
  48243. }
  48244. /**
  48245. * Manages a pool of WebGL timestamp queries for performance measurement.
  48246. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  48247. *
  48248. * @augments TimestampQueryPool
  48249. */
  48250. class WebGLTimestampQueryPool extends TimestampQueryPool {
  48251. /**
  48252. * Creates a new WebGL timestamp query pool.
  48253. *
  48254. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  48255. * @param {string} type - The type identifier for this query pool.
  48256. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  48257. */
  48258. constructor( gl, type, maxQueries = 2048 ) {
  48259. super( maxQueries );
  48260. this.gl = gl;
  48261. this.type = type;
  48262. // Check for timer query extensions
  48263. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  48264. gl.getExtension( 'EXT_disjoint_timer_query' );
  48265. if ( ! this.ext ) {
  48266. warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  48267. this.trackTimestamp = false;
  48268. return;
  48269. }
  48270. // Create query objects
  48271. this.queries = [];
  48272. for ( let i = 0; i < this.maxQueries; i ++ ) {
  48273. this.queries.push( gl.createQuery() );
  48274. }
  48275. this.activeQuery = null;
  48276. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  48277. }
  48278. /**
  48279. * Allocates a pair of queries for a given render context.
  48280. *
  48281. * @param {string} uid - A unique identifier for the render context.
  48282. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  48283. */
  48284. allocateQueriesForContext( uid ) {
  48285. if ( ! this.trackTimestamp ) return null;
  48286. // Check if we have enough space for a new query pair
  48287. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  48288. 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() } ).` );
  48289. return null;
  48290. }
  48291. const baseOffset = this.currentQueryIndex;
  48292. this.currentQueryIndex += 2;
  48293. // Initialize query states
  48294. this.queryStates.set( baseOffset, 'inactive' );
  48295. this.queryOffsets.set( uid, baseOffset );
  48296. return baseOffset;
  48297. }
  48298. /**
  48299. * Begins a timestamp query for the specified render context.
  48300. *
  48301. * @param {string} uid - A unique identifier for the render context.
  48302. */
  48303. beginQuery( uid ) {
  48304. if ( ! this.trackTimestamp || this.isDisposed ) {
  48305. return;
  48306. }
  48307. const baseOffset = this.queryOffsets.get( uid );
  48308. if ( baseOffset == null ) {
  48309. return;
  48310. }
  48311. // Don't start a new query if there's an active one
  48312. if ( this.activeQuery !== null ) {
  48313. return;
  48314. }
  48315. const query = this.queries[ baseOffset ];
  48316. if ( ! query ) {
  48317. return;
  48318. }
  48319. try {
  48320. // Only begin if query is inactive
  48321. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  48322. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  48323. this.activeQuery = baseOffset;
  48324. this.queryStates.set( baseOffset, 'started' );
  48325. }
  48326. } catch ( e ) {
  48327. error( 'Error in beginQuery:', e );
  48328. this.activeQuery = null;
  48329. this.queryStates.set( baseOffset, 'inactive' );
  48330. }
  48331. }
  48332. /**
  48333. * Ends the active timestamp query for the specified render context.
  48334. *
  48335. * @param {string} uid - A unique identifier for the render context.
  48336. */
  48337. endQuery( uid ) {
  48338. if ( ! this.trackTimestamp || this.isDisposed ) {
  48339. return;
  48340. }
  48341. const baseOffset = this.queryOffsets.get( uid );
  48342. if ( baseOffset == null ) {
  48343. return;
  48344. }
  48345. // Only end if this is the active query
  48346. if ( this.activeQuery !== baseOffset ) {
  48347. return;
  48348. }
  48349. try {
  48350. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  48351. this.queryStates.set( baseOffset, 'ended' );
  48352. this.activeQuery = null;
  48353. } catch ( e ) {
  48354. error( 'Error in endQuery:', e );
  48355. // Reset state on error
  48356. this.queryStates.set( baseOffset, 'inactive' );
  48357. this.activeQuery = null;
  48358. }
  48359. }
  48360. /**
  48361. * Asynchronously resolves all completed queries and returns the total duration.
  48362. *
  48363. * @async
  48364. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  48365. */
  48366. async resolveQueriesAsync() {
  48367. if ( ! this.trackTimestamp || this.pendingResolve ) {
  48368. return this.lastValue;
  48369. }
  48370. this.pendingResolve = true;
  48371. try {
  48372. // Wait for all ended queries to complete
  48373. const resolvePromises = new Map();
  48374. for ( const [ uid, baseOffset ] of this.queryOffsets ) {
  48375. const state = this.queryStates.get( baseOffset );
  48376. if ( state === 'ended' ) {
  48377. const query = this.queries[ baseOffset ];
  48378. resolvePromises.set( uid, this.resolveQuery( query ) );
  48379. }
  48380. }
  48381. if ( resolvePromises.size === 0 ) {
  48382. return this.lastValue;
  48383. }
  48384. //
  48385. const framesDuration = {};
  48386. const frames = [];
  48387. for ( const [ uid, promise ] of resolvePromises ) {
  48388. const match = uid.match( /^(.*):f(\d+)$/ );
  48389. const frame = parseInt( match[ 2 ] );
  48390. if ( frames.includes( frame ) === false ) {
  48391. frames.push( frame );
  48392. }
  48393. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  48394. const duration = await promise;
  48395. this.timestamps.set( uid, duration );
  48396. framesDuration[ frame ] += duration;
  48397. }
  48398. // Return the total duration of the last frame
  48399. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  48400. // Store the last valid result
  48401. this.lastValue = totalDuration;
  48402. this.frames = frames;
  48403. // Reset states
  48404. this.currentQueryIndex = 0;
  48405. this.queryOffsets.clear();
  48406. this.queryStates.clear();
  48407. this.activeQuery = null;
  48408. return totalDuration;
  48409. } catch ( e ) {
  48410. error( 'Error resolving queries:', e );
  48411. return this.lastValue;
  48412. } finally {
  48413. this.pendingResolve = false;
  48414. }
  48415. }
  48416. /**
  48417. * Resolves a single query, checking for completion and disjoint operation.
  48418. *
  48419. * @async
  48420. * @param {WebGLQuery} query - The query object to resolve.
  48421. * @returns {Promise<number>} The elapsed time in milliseconds.
  48422. */
  48423. async resolveQuery( query ) {
  48424. return new Promise( ( resolve ) => {
  48425. if ( this.isDisposed ) {
  48426. resolve( this.lastValue );
  48427. return;
  48428. }
  48429. let timeoutId;
  48430. let isResolved = false;
  48431. const cleanup = () => {
  48432. if ( timeoutId ) {
  48433. clearTimeout( timeoutId );
  48434. timeoutId = null;
  48435. }
  48436. };
  48437. const finalizeResolution = ( value ) => {
  48438. if ( ! isResolved ) {
  48439. isResolved = true;
  48440. cleanup();
  48441. resolve( value );
  48442. }
  48443. };
  48444. const checkQuery = () => {
  48445. if ( this.isDisposed ) {
  48446. finalizeResolution( this.lastValue );
  48447. return;
  48448. }
  48449. try {
  48450. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  48451. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  48452. if ( disjoint ) {
  48453. finalizeResolution( this.lastValue );
  48454. return;
  48455. }
  48456. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  48457. if ( ! available ) {
  48458. timeoutId = setTimeout( checkQuery, 1 );
  48459. return;
  48460. }
  48461. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  48462. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  48463. } catch ( e ) {
  48464. error( 'Error checking query:', e );
  48465. resolve( this.lastValue );
  48466. }
  48467. };
  48468. checkQuery();
  48469. } );
  48470. }
  48471. /**
  48472. * Releases all resources held by this query pool.
  48473. * This includes deleting all query objects and clearing internal state.
  48474. */
  48475. dispose() {
  48476. if ( this.isDisposed ) {
  48477. return;
  48478. }
  48479. this.isDisposed = true;
  48480. if ( ! this.trackTimestamp ) return;
  48481. for ( const query of this.queries ) {
  48482. this.gl.deleteQuery( query );
  48483. }
  48484. this.queries = [];
  48485. this.queryStates.clear();
  48486. this.queryOffsets.clear();
  48487. this.lastValue = 0;
  48488. this.activeQuery = null;
  48489. }
  48490. }
  48491. /**
  48492. * A backend implementation targeting WebGL 2.
  48493. *
  48494. * @private
  48495. * @augments Backend
  48496. */
  48497. class WebGLBackend extends Backend {
  48498. /**
  48499. * WebGLBackend options.
  48500. *
  48501. * @typedef {Object} WebGLBackend~Options
  48502. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  48503. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  48504. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  48505. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  48506. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  48507. * @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.
  48508. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  48509. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  48510. */
  48511. /**
  48512. * Constructs a new WebGPU backend.
  48513. *
  48514. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  48515. */
  48516. constructor( parameters = {} ) {
  48517. super( parameters );
  48518. /**
  48519. * This flag can be used for type testing.
  48520. *
  48521. * @type {boolean}
  48522. * @readonly
  48523. * @default true
  48524. */
  48525. this.isWebGLBackend = true;
  48526. /**
  48527. * A reference to a backend module holding shader attribute-related
  48528. * utility functions.
  48529. *
  48530. * @type {?WebGLAttributeUtils}
  48531. * @default null
  48532. */
  48533. this.attributeUtils = null;
  48534. /**
  48535. * A reference to a backend module holding extension-related
  48536. * utility functions.
  48537. *
  48538. * @type {?WebGLExtensions}
  48539. * @default null
  48540. */
  48541. this.extensions = null;
  48542. /**
  48543. * A reference to a backend module holding capability-related
  48544. * utility functions.
  48545. *
  48546. * @type {?WebGLCapabilities}
  48547. * @default null
  48548. */
  48549. this.capabilities = null;
  48550. /**
  48551. * A reference to a backend module holding texture-related
  48552. * utility functions.
  48553. *
  48554. * @type {?WebGLTextureUtils}
  48555. * @default null
  48556. */
  48557. this.textureUtils = null;
  48558. /**
  48559. * A reference to a backend module holding renderer-related
  48560. * utility functions.
  48561. *
  48562. * @type {?WebGLBufferRenderer}
  48563. * @default null
  48564. */
  48565. this.bufferRenderer = null;
  48566. /**
  48567. * A reference to the rendering context.
  48568. *
  48569. * @type {?WebGL2RenderingContext}
  48570. * @default null
  48571. */
  48572. this.gl = null;
  48573. /**
  48574. * A reference to a backend module holding state-related
  48575. * utility functions.
  48576. *
  48577. * @type {?WebGLState}
  48578. * @default null
  48579. */
  48580. this.state = null;
  48581. /**
  48582. * A reference to a backend module holding common
  48583. * utility functions.
  48584. *
  48585. * @type {?WebGLUtils}
  48586. * @default null
  48587. */
  48588. this.utils = null;
  48589. /**
  48590. * Dictionary for caching VAOs.
  48591. *
  48592. * @type {Object<string,WebGLVertexArrayObject>}
  48593. */
  48594. this.vaoCache = {};
  48595. /**
  48596. * Dictionary for caching transform feedback objects.
  48597. *
  48598. * @type {Object<string,WebGLTransformFeedback>}
  48599. */
  48600. this.transformFeedbackCache = {};
  48601. /**
  48602. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  48603. * Only relevant when using compute shaders.
  48604. *
  48605. * @type {boolean}
  48606. * @default false
  48607. */
  48608. this.discard = false;
  48609. /**
  48610. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  48611. * device does not support the extension.
  48612. *
  48613. * @type {?EXTDisjointTimerQueryWebGL2}
  48614. * @default null
  48615. */
  48616. this.disjoint = null;
  48617. /**
  48618. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  48619. * device does not support the extension.
  48620. *
  48621. * @type {?KHRParallelShaderCompile}
  48622. * @default null
  48623. */
  48624. this.parallel = null;
  48625. /**
  48626. * A reference to the current render context.
  48627. *
  48628. * @private
  48629. * @type {RenderContext}
  48630. * @default null
  48631. */
  48632. this._currentContext = null;
  48633. /**
  48634. * A unique collection of bindings.
  48635. *
  48636. * @private
  48637. * @type {WeakSet<Array<BindGroup>>}
  48638. */
  48639. this._knownBindings = new WeakSet();
  48640. /**
  48641. * Whether the device supports framebuffers invalidation or not.
  48642. *
  48643. * @private
  48644. * @type {boolean}
  48645. */
  48646. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  48647. /**
  48648. * The target framebuffer when rendering with
  48649. * the WebXR device API.
  48650. *
  48651. * @private
  48652. * @type {?WebGLFramebuffer}
  48653. * @default null
  48654. */
  48655. this._xrFramebuffer = null;
  48656. }
  48657. /**
  48658. * Initializes the backend so it is ready for usage.
  48659. *
  48660. * @param {Renderer} renderer - The renderer.
  48661. */
  48662. init( renderer ) {
  48663. super.init( renderer );
  48664. //
  48665. const parameters = this.parameters;
  48666. const contextAttributes = {
  48667. antialias: renderer.currentSamples > 0,
  48668. alpha: true, // always true for performance reasons
  48669. depth: renderer.depth,
  48670. stencil: renderer.stencil
  48671. };
  48672. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  48673. function onContextLost( event ) {
  48674. event.preventDefault();
  48675. const contextLossInfo = {
  48676. api: 'WebGL',
  48677. message: event.statusMessage || 'Unknown reason',
  48678. reason: null,
  48679. originalEvent: event
  48680. };
  48681. renderer.onDeviceLost( contextLossInfo );
  48682. }
  48683. this._onContextLost = onContextLost;
  48684. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  48685. this.gl = glContext;
  48686. this.extensions = new WebGLExtensions( this );
  48687. this.capabilities = new WebGLCapabilities( this );
  48688. this.attributeUtils = new WebGLAttributeUtils( this );
  48689. this.textureUtils = new WebGLTextureUtils( this );
  48690. this.bufferRenderer = new WebGLBufferRenderer( this );
  48691. this.state = new WebGLState( this );
  48692. this.utils = new WebGLUtils( this );
  48693. this.extensions.get( 'EXT_color_buffer_float' );
  48694. this.extensions.get( 'WEBGL_clip_cull_distance' );
  48695. this.extensions.get( 'OES_texture_float_linear' );
  48696. this.extensions.get( 'EXT_color_buffer_half_float' );
  48697. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  48698. this.extensions.get( 'WEBGL_render_shared_exponent' );
  48699. this.extensions.get( 'WEBGL_multi_draw' );
  48700. this.extensions.get( 'OVR_multiview2' );
  48701. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  48702. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  48703. this.drawBuffersIndexedExt = this.extensions.get( 'OES_draw_buffers_indexed' );
  48704. }
  48705. /**
  48706. * The coordinate system of the backend.
  48707. *
  48708. * @type {number}
  48709. * @readonly
  48710. */
  48711. get coordinateSystem() {
  48712. return WebGLCoordinateSystem;
  48713. }
  48714. /**
  48715. * This method performs a readback operation by moving buffer data from
  48716. * a storage buffer attribute from the GPU to the CPU.
  48717. *
  48718. * @async
  48719. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  48720. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  48721. */
  48722. async getArrayBufferAsync( attribute ) {
  48723. return await this.attributeUtils.getArrayBufferAsync( attribute );
  48724. }
  48725. /**
  48726. * Ensures the backend is XR compatible.
  48727. *
  48728. * @async
  48729. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  48730. */
  48731. async makeXRCompatible() {
  48732. const attributes = this.gl.getContextAttributes();
  48733. if ( attributes.xrCompatible !== true ) {
  48734. await this.gl.makeXRCompatible();
  48735. }
  48736. }
  48737. /**
  48738. * Sets the XR rendering destination.
  48739. *
  48740. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  48741. */
  48742. setXRTarget( xrFramebuffer ) {
  48743. this._xrFramebuffer = xrFramebuffer;
  48744. }
  48745. /**
  48746. * Configures the given XR render target with external textures.
  48747. *
  48748. * This method is only relevant when using the WebXR Layers API.
  48749. *
  48750. * @param {XRRenderTarget} renderTarget - The XR render target.
  48751. * @param {WebGLTexture} colorTexture - A native color texture.
  48752. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  48753. */
  48754. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  48755. const gl = this.gl;
  48756. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  48757. if ( depthTexture !== null ) {
  48758. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  48759. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  48760. // The multisample_render_to_texture extension doesn't work properly if there
  48761. // are midframe flushes and an external depth texture.
  48762. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  48763. warn( 'WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  48764. }
  48765. renderTarget._autoAllocateDepthBuffer = false;
  48766. }
  48767. }
  48768. /**
  48769. * Inits a time stamp query for the given render context.
  48770. *
  48771. * @param {string} type - The type of the timestamp query.
  48772. * @param {string} uid - A unique identifier for the timestamp query.
  48773. */
  48774. initTimestampQuery( type, uid ) {
  48775. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  48776. if ( ! this.timestampQueryPool[ type ] ) {
  48777. // TODO: Variable maxQueries?
  48778. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  48779. }
  48780. const timestampQueryPool = this.timestampQueryPool[ type ];
  48781. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  48782. if ( baseOffset !== null ) {
  48783. timestampQueryPool.beginQuery( uid );
  48784. }
  48785. }
  48786. // timestamp utils
  48787. /**
  48788. * Prepares the timestamp buffer.
  48789. *
  48790. * @param {string} type - The type of the timestamp query.
  48791. * @param {string} uid - A unique identifier for the timestamp query.
  48792. */
  48793. prepareTimestampBuffer( type, uid ) {
  48794. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  48795. const timestampQueryPool = this.timestampQueryPool[ type ];
  48796. timestampQueryPool.endQuery( uid );
  48797. }
  48798. /**
  48799. * Returns the backend's rendering context.
  48800. *
  48801. * @return {WebGL2RenderingContext} The rendering context.
  48802. */
  48803. getContext() {
  48804. return this.gl;
  48805. }
  48806. /**
  48807. * This method is executed at the beginning of a render call and prepares
  48808. * the WebGL state for upcoming render calls
  48809. *
  48810. * @param {RenderContext} renderContext - The render context.
  48811. */
  48812. beginRender( renderContext ) {
  48813. const { state } = this;
  48814. const renderContextData = this.get( renderContext );
  48815. //
  48816. if ( renderContext.viewport ) {
  48817. this.updateViewport( renderContext );
  48818. } else {
  48819. const { width, height } = this.getDrawingBufferSize();
  48820. state.viewport( 0, 0, width, height );
  48821. }
  48822. if ( renderContext.scissor ) {
  48823. const { x, y, width, height } = renderContext.scissorValue;
  48824. state.scissor( x, renderContext.height - height - y, width, height );
  48825. }
  48826. //
  48827. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  48828. renderContextData.previousContext = this._currentContext;
  48829. this._currentContext = renderContext;
  48830. this._setFramebuffer( renderContext );
  48831. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  48832. const occlusionQueryCount = renderContext.occlusionQueryCount;
  48833. if ( occlusionQueryCount > 0 ) {
  48834. // Get a reference to the array of objects with queries. The renderContextData property
  48835. // can be changed by another render pass before the async reading of all previous queries complete
  48836. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  48837. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  48838. renderContextData.lastOcclusionObject = null;
  48839. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  48840. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  48841. renderContextData.occlusionQueryIndex = 0;
  48842. }
  48843. }
  48844. /**
  48845. * This method is executed at the end of a render call and finalizes work
  48846. * after draw calls.
  48847. *
  48848. * @param {RenderContext} renderContext - The render context.
  48849. */
  48850. finishRender( renderContext ) {
  48851. const { gl, state } = this;
  48852. const renderContextData = this.get( renderContext );
  48853. const previousContext = renderContextData.previousContext;
  48854. state.resetVertexState();
  48855. const occlusionQueryCount = renderContext.occlusionQueryCount;
  48856. if ( occlusionQueryCount > 0 ) {
  48857. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  48858. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  48859. }
  48860. this.resolveOccludedAsync( renderContext );
  48861. }
  48862. const textures = renderContext.textures;
  48863. if ( textures !== null ) {
  48864. for ( let i = 0; i < textures.length; i ++ ) {
  48865. const texture = textures[ i ];
  48866. if ( texture.generateMipmaps ) {
  48867. this.generateMipmaps( texture );
  48868. }
  48869. }
  48870. }
  48871. this._currentContext = previousContext;
  48872. this._resolveRenderTarget( renderContext );
  48873. if ( previousContext !== null ) {
  48874. this._setFramebuffer( previousContext );
  48875. if ( previousContext.viewport ) {
  48876. this.updateViewport( previousContext );
  48877. } else {
  48878. const { width, height } = this.getDrawingBufferSize();
  48879. state.viewport( 0, 0, width, height );
  48880. }
  48881. }
  48882. this.prepareTimestampBuffer( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  48883. }
  48884. /**
  48885. * This method processes the result of occlusion queries and writes it
  48886. * into render context data.
  48887. *
  48888. * @async
  48889. * @param {RenderContext} renderContext - The render context.
  48890. */
  48891. resolveOccludedAsync( renderContext ) {
  48892. const renderContextData = this.get( renderContext );
  48893. // handle occlusion query results
  48894. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  48895. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  48896. const occluded = new WeakSet();
  48897. const { gl } = this;
  48898. renderContextData.currentOcclusionQueryObjects = null;
  48899. renderContextData.currentOcclusionQueries = null;
  48900. const check = () => {
  48901. let completed = 0;
  48902. // check all queries and requeue as appropriate
  48903. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  48904. const query = currentOcclusionQueries[ i ];
  48905. if ( query === null ) continue;
  48906. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  48907. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  48908. currentOcclusionQueries[ i ] = null;
  48909. gl.deleteQuery( query );
  48910. completed ++;
  48911. }
  48912. }
  48913. if ( completed < currentOcclusionQueries.length ) {
  48914. requestAnimationFrame( check );
  48915. } else {
  48916. renderContextData.occluded = occluded;
  48917. }
  48918. };
  48919. check();
  48920. }
  48921. }
  48922. /**
  48923. * Returns `true` if the given 3D object is fully occluded by other
  48924. * 3D objects in the scene.
  48925. *
  48926. * @param {RenderContext} renderContext - The render context.
  48927. * @param {Object3D} object - The 3D object to test.
  48928. * @return {boolean} Whether the 3D object is fully occluded or not.
  48929. */
  48930. isOccluded( renderContext, object ) {
  48931. const renderContextData = this.get( renderContext );
  48932. return renderContextData.occluded && renderContextData.occluded.has( object );
  48933. }
  48934. /**
  48935. * Updates the viewport with the values from the given render context.
  48936. *
  48937. * @param {RenderContext} renderContext - The render context.
  48938. */
  48939. updateViewport( renderContext ) {
  48940. const { state } = this;
  48941. const { x, y, width, height } = renderContext.viewportValue;
  48942. state.viewport( x, renderContext.height - height - y, width, height );
  48943. }
  48944. /**
  48945. * Defines the scissor test.
  48946. *
  48947. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  48948. */
  48949. setScissorTest( boolean ) {
  48950. const state = this.state;
  48951. state.setScissorTest( boolean );
  48952. }
  48953. /**
  48954. * Returns the clear color and alpha into a single
  48955. * color object.
  48956. *
  48957. * @return {Color4} The clear color.
  48958. */
  48959. getClearColor() {
  48960. const clearColor = super.getClearColor();
  48961. // Since the canvas is always created with alpha: true,
  48962. // WebGL must always premultiply the clear color.
  48963. clearColor.r *= clearColor.a;
  48964. clearColor.g *= clearColor.a;
  48965. clearColor.b *= clearColor.a;
  48966. return clearColor;
  48967. }
  48968. /**
  48969. * Performs a clear operation.
  48970. *
  48971. * @param {boolean} color - Whether the color buffer should be cleared or not.
  48972. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  48973. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  48974. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  48975. * @param {boolean} [setFrameBuffer=true] - Controls whether the intermediate framebuffer should be set or not.
  48976. * @param {boolean} [resolveRenderTarget=true] - Controls whether an active render target should be resolved
  48977. * or not. Only relevant for explicit clears.
  48978. */
  48979. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true, resolveRenderTarget = true ) {
  48980. const { gl, renderer } = this;
  48981. if ( descriptor === null ) {
  48982. const clearColor = this.getClearColor();
  48983. descriptor = {
  48984. textures: null,
  48985. clearColorValue: clearColor
  48986. };
  48987. }
  48988. //
  48989. let clear = 0;
  48990. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  48991. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  48992. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  48993. if ( clear !== 0 ) {
  48994. let clearColor;
  48995. if ( descriptor.clearColorValue ) {
  48996. clearColor = descriptor.clearColorValue;
  48997. } else {
  48998. clearColor = this.getClearColor();
  48999. }
  49000. const clearDepth = renderer.getClearDepth();
  49001. const clearStencil = renderer.getClearStencil();
  49002. if ( depth ) this.state.setDepthMask( true );
  49003. if ( descriptor.textures === null ) {
  49004. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  49005. gl.clear( clear );
  49006. } else {
  49007. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  49008. if ( color ) {
  49009. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  49010. if ( i === 0 ) {
  49011. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  49012. } else {
  49013. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  49014. }
  49015. }
  49016. }
  49017. if ( depth && stencil ) {
  49018. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  49019. } else if ( depth ) {
  49020. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  49021. } else if ( stencil ) {
  49022. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  49023. }
  49024. if ( setFrameBuffer && resolveRenderTarget ) this._resolveRenderTarget( descriptor );
  49025. }
  49026. }
  49027. }
  49028. /**
  49029. * This method is executed at the beginning of a compute call and
  49030. * prepares the state for upcoming compute tasks.
  49031. *
  49032. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  49033. */
  49034. beginCompute( computeGroup ) {
  49035. const { state, gl } = this;
  49036. //
  49037. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  49038. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  49039. }
  49040. /**
  49041. * Executes a compute command for the given compute node.
  49042. *
  49043. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  49044. * @param {Node} computeNode - The compute node.
  49045. * @param {Array<BindGroup>} bindings - The bindings.
  49046. * @param {ComputePipeline} pipeline - The compute pipeline.
  49047. * @param {?number} [count=null] - The count of compute invocations. If `null`, the count is determined by the compute node.
  49048. */
  49049. compute( computeGroup, computeNode, bindings, pipeline, count = null ) {
  49050. const { state, gl } = this;
  49051. if ( this.discard === false ) {
  49052. // required here to handle async behaviour of render.compute()
  49053. state.enable( gl.RASTERIZER_DISCARD );
  49054. this.discard = true;
  49055. }
  49056. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  49057. const vaoKey = this._getVaoKey( attributes );
  49058. const vaoGPU = this.vaoCache[ vaoKey ];
  49059. if ( vaoGPU === undefined ) {
  49060. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  49061. } else {
  49062. state.setVertexState( vaoGPU );
  49063. }
  49064. state.useProgram( programGPU );
  49065. this._bindUniforms( bindings );
  49066. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  49067. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  49068. gl.beginTransformFeedback( gl.POINTS );
  49069. count = ( count !== null ) ? count : computeNode.count;
  49070. if ( Array.isArray( count ) ) {
  49071. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not an array.' );
  49072. count = count[ 0 ];
  49073. } else if ( count && typeof count === 'object' && count.isIndirectStorageBufferAttribute ) {
  49074. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute' );
  49075. count = computeNode.count;
  49076. }
  49077. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  49078. gl.drawArraysInstanced( gl.POINTS, 0, 1, count );
  49079. } else {
  49080. gl.drawArrays( gl.POINTS, 0, count );
  49081. }
  49082. gl.endTransformFeedback();
  49083. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  49084. // switch active buffers
  49085. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  49086. const dualAttributeData = transformBuffers[ i ];
  49087. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  49088. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  49089. }
  49090. dualAttributeData.switchBuffers();
  49091. }
  49092. }
  49093. /**
  49094. * This method is executed at the end of a compute call and
  49095. * finalizes work after compute tasks.
  49096. *
  49097. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  49098. */
  49099. finishCompute( computeGroup ) {
  49100. const { state, gl } = this;
  49101. this.discard = false;
  49102. state.disable( gl.RASTERIZER_DISCARD );
  49103. this.prepareTimestampBuffer( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  49104. if ( this._currentContext ) {
  49105. this._setFramebuffer( this._currentContext );
  49106. }
  49107. }
  49108. /**
  49109. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  49110. *
  49111. * @param {RenderContext} renderContext - The render context.
  49112. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  49113. *
  49114. * @private
  49115. */
  49116. _isRenderCameraDepthArray( renderContext ) {
  49117. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  49118. }
  49119. /**
  49120. * Executes a draw command for the given render object.
  49121. *
  49122. * @param {RenderObject} renderObject - The render object to draw.
  49123. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  49124. */
  49125. draw( renderObject/*, info*/ ) {
  49126. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  49127. const { programGPU } = this.get( pipeline );
  49128. const { gl, state } = this;
  49129. const contextData = this.get( context );
  49130. const drawParams = renderObject.getDrawParameters();
  49131. if ( drawParams === null ) return;
  49132. //
  49133. this._bindUniforms( renderObject.getBindings() );
  49134. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  49135. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  49136. if ( context.textures !== null && context.textures.length > 1 ) {
  49137. state.setMRTBlending( context.textures );
  49138. }
  49139. state.useProgram( programGPU );
  49140. // vertex state
  49141. const attributes = renderObject.getAttributes();
  49142. const attributesData = this.get( attributes );
  49143. let vaoGPU = attributesData.vaoGPU;
  49144. if ( vaoGPU === undefined ) {
  49145. const vaoKey = this._getVaoKey( attributes );
  49146. vaoGPU = this.vaoCache[ vaoKey ];
  49147. if ( vaoGPU === undefined ) {
  49148. vaoGPU = this._createVao( attributes );
  49149. this.vaoCache[ vaoKey ] = vaoGPU;
  49150. attributesData.vaoGPU = vaoGPU;
  49151. }
  49152. }
  49153. const index = renderObject.getIndex();
  49154. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  49155. state.setVertexState( vaoGPU, indexGPU );
  49156. //
  49157. const lastObject = contextData.lastOcclusionObject;
  49158. if ( lastObject !== object && lastObject !== undefined ) {
  49159. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  49160. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  49161. contextData.occlusionQueryIndex ++;
  49162. }
  49163. if ( object.occlusionTest === true ) {
  49164. const query = gl.createQuery();
  49165. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  49166. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  49167. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  49168. }
  49169. contextData.lastOcclusionObject = object;
  49170. }
  49171. //
  49172. const renderer = this.bufferRenderer;
  49173. if ( object.isPoints ) renderer.mode = gl.POINTS;
  49174. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  49175. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  49176. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  49177. else {
  49178. if ( material.wireframe === true ) {
  49179. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  49180. renderer.mode = gl.LINES;
  49181. } else {
  49182. renderer.mode = gl.TRIANGLES;
  49183. }
  49184. }
  49185. //
  49186. const { vertexCount, instanceCount } = drawParams;
  49187. let { firstVertex } = drawParams;
  49188. renderer.object = object;
  49189. if ( index !== null ) {
  49190. firstVertex *= index.array.BYTES_PER_ELEMENT;
  49191. const indexData = this.get( index );
  49192. renderer.index = index.count;
  49193. renderer.type = indexData.type;
  49194. } else {
  49195. renderer.index = 0;
  49196. }
  49197. const draw = () => {
  49198. if ( object.isBatchedMesh ) {
  49199. if ( object._multiDrawInstances !== null ) {
  49200. // @deprecated, r174
  49201. warnOnce( 'WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  49202. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  49203. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  49204. warnOnce( 'WebGLBackend: WEBGL_multi_draw not supported.' );
  49205. } else {
  49206. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  49207. }
  49208. } else if ( instanceCount > 1 ) {
  49209. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  49210. } else {
  49211. renderer.render( firstVertex, vertexCount );
  49212. }
  49213. };
  49214. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  49215. const cameraData = this.get( renderObject.camera );
  49216. const cameras = renderObject.camera.cameras;
  49217. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  49218. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  49219. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  49220. const indexesGPU = [];
  49221. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  49222. const bufferGPU = gl.createBuffer();
  49223. data[ 0 ] = i;
  49224. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49225. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  49226. indexesGPU.push( bufferGPU );
  49227. }
  49228. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  49229. }
  49230. const cameraIndexData = this.get( cameraIndex );
  49231. const pixelRatio = this.renderer.getPixelRatio();
  49232. const renderTarget = this._currentContext.renderTarget;
  49233. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  49234. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  49235. if ( isRenderCameraDepthArray ) {
  49236. // Clear the depth texture
  49237. const textureData = this.get( renderTarget.depthTexture );
  49238. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  49239. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  49240. const { stencilBuffer } = renderTarget;
  49241. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  49242. this.renderer._activeCubeFace = i;
  49243. this._currentContext.activeCubeFace = i;
  49244. this._setFramebuffer( this._currentContext );
  49245. this.clear( false, true, stencilBuffer, this._currentContext, false, false );
  49246. }
  49247. this.renderer._activeCubeFace = prevActiveCubeFace;
  49248. this._currentContext.activeCubeFace = prevActiveCubeFace;
  49249. }
  49250. }
  49251. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  49252. const subCamera = cameras[ i ];
  49253. if ( object.layers.test( subCamera.layers ) ) {
  49254. if ( isRenderCameraDepthArray ) {
  49255. // Update the active layer
  49256. this.renderer._activeCubeFace = i;
  49257. this._currentContext.activeCubeFace = i;
  49258. this._setFramebuffer( this._currentContext );
  49259. }
  49260. const vp = subCamera.viewport;
  49261. if ( vp !== undefined ) {
  49262. const x = vp.x * pixelRatio;
  49263. const y = vp.y * pixelRatio;
  49264. const width = vp.width * pixelRatio;
  49265. const height = vp.height * pixelRatio;
  49266. state.viewport(
  49267. Math.floor( x ),
  49268. Math.floor( renderObject.context.height - height - y ),
  49269. Math.floor( width ),
  49270. Math.floor( height )
  49271. );
  49272. }
  49273. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  49274. draw();
  49275. }
  49276. this._currentContext.activeCubeFace = prevActiveCubeFace;
  49277. this.renderer._activeCubeFace = prevActiveCubeFace;
  49278. }
  49279. } else {
  49280. draw();
  49281. }
  49282. }
  49283. /**
  49284. * Explain why always null is returned.
  49285. *
  49286. * @param {RenderObject} renderObject - The render object.
  49287. * @return {boolean} Whether the render pipeline requires an update or not.
  49288. */
  49289. needsRenderUpdate( /*renderObject*/ ) {
  49290. return false;
  49291. }
  49292. /**
  49293. * Explain why no cache key is computed.
  49294. *
  49295. * @param {RenderObject} renderObject - The render object.
  49296. * @return {string} The cache key.
  49297. */
  49298. getRenderCacheKey( /*renderObject*/ ) {
  49299. return '';
  49300. }
  49301. // textures
  49302. /**
  49303. * Creates a default texture for the given texture that can be used
  49304. * as a placeholder until the actual texture is ready for usage.
  49305. *
  49306. * @param {Texture} texture - The texture to create a default texture for.
  49307. */
  49308. createDefaultTexture( texture ) {
  49309. this.textureUtils.createDefaultTexture( texture );
  49310. }
  49311. /**
  49312. * Defines a texture on the GPU for the given texture object.
  49313. *
  49314. * @param {Texture} texture - The texture.
  49315. * @param {Object} [options={}] - Optional configuration parameter.
  49316. */
  49317. createTexture( texture, options ) {
  49318. this.textureUtils.createTexture( texture, options );
  49319. }
  49320. /**
  49321. * Uploads the updated texture data to the GPU.
  49322. *
  49323. * @param {Texture} texture - The texture.
  49324. * @param {Object} [options={}] - Optional configuration parameter.
  49325. */
  49326. updateTexture( texture, options ) {
  49327. this.textureUtils.updateTexture( texture, options );
  49328. }
  49329. /**
  49330. * Generates mipmaps for the given texture.
  49331. *
  49332. * @param {Texture} texture - The texture.
  49333. */
  49334. generateMipmaps( texture ) {
  49335. this.textureUtils.generateMipmaps( texture );
  49336. }
  49337. /**
  49338. * Destroys the GPU data for the given texture object.
  49339. *
  49340. * @param {Texture} texture - The texture.
  49341. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  49342. */
  49343. destroyTexture( texture, isDefaultTexture = false ) {
  49344. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  49345. }
  49346. /**
  49347. * Returns texture data as a typed array.
  49348. *
  49349. * @async
  49350. * @param {Texture} texture - The texture to copy.
  49351. * @param {number} x - The x coordinate of the copy origin.
  49352. * @param {number} y - The y coordinate of the copy origin.
  49353. * @param {number} width - The width of the copy.
  49354. * @param {number} height - The height of the copy.
  49355. * @param {number} faceIndex - The face index.
  49356. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  49357. */
  49358. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  49359. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  49360. }
  49361. /**
  49362. * This method does nothing since WebGL 2 has no concept of samplers.
  49363. *
  49364. * @param {Texture} texture - The texture to update the sampler for.
  49365. * @return {string} The current sampler key.
  49366. */
  49367. updateSampler( /*texture*/ ) {
  49368. return '';
  49369. }
  49370. // node builder
  49371. /**
  49372. * Returns a node builder for the given render object.
  49373. *
  49374. * @param {RenderObject} object - The render object.
  49375. * @param {Renderer} renderer - The renderer.
  49376. * @return {GLSLNodeBuilder} The node builder.
  49377. */
  49378. createNodeBuilder( object, renderer ) {
  49379. return new GLSLNodeBuilder( object, renderer );
  49380. }
  49381. // program
  49382. /**
  49383. * Creates a shader program from the given programmable stage.
  49384. *
  49385. * @param {ProgrammableStage} program - The programmable stage.
  49386. */
  49387. createProgram( program ) {
  49388. const gl = this.gl;
  49389. const { stage, code } = program;
  49390. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  49391. gl.shaderSource( shader, code );
  49392. gl.compileShader( shader );
  49393. this.set( program, {
  49394. shaderGPU: shader
  49395. } );
  49396. }
  49397. /**
  49398. * Destroys the shader program of the given programmable stage.
  49399. *
  49400. * @param {ProgrammableStage} program - The programmable stage.
  49401. */
  49402. destroyProgram( program ) {
  49403. this.delete( program );
  49404. }
  49405. /**
  49406. * Creates a render pipeline for the given render object.
  49407. *
  49408. * @param {RenderObject} renderObject - The render object.
  49409. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  49410. */
  49411. createRenderPipeline( renderObject, promises ) {
  49412. const gl = this.gl;
  49413. const pipeline = renderObject.pipeline;
  49414. // Program
  49415. const { fragmentProgram, vertexProgram } = pipeline;
  49416. const programGPU = gl.createProgram();
  49417. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  49418. const vertexShader = this.get( vertexProgram ).shaderGPU;
  49419. gl.attachShader( programGPU, fragmentShader );
  49420. gl.attachShader( programGPU, vertexShader );
  49421. gl.linkProgram( programGPU );
  49422. this.set( pipeline, {
  49423. programGPU,
  49424. fragmentShader,
  49425. vertexShader
  49426. } );
  49427. if ( promises !== null && this.parallel ) {
  49428. const p = new Promise( ( resolve /*, reject*/ ) => {
  49429. const parallel = this.parallel;
  49430. const checkStatus = () => {
  49431. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  49432. this._completeCompile( renderObject, pipeline );
  49433. resolve();
  49434. } else {
  49435. requestAnimationFrame( checkStatus );
  49436. }
  49437. };
  49438. checkStatus();
  49439. } );
  49440. promises.push( p );
  49441. return;
  49442. }
  49443. this._completeCompile( renderObject, pipeline );
  49444. }
  49445. /**
  49446. * Formats the source code of error messages.
  49447. *
  49448. * @private
  49449. * @param {string} string - The code.
  49450. * @param {number} errorLine - The error line.
  49451. * @return {string} The formatted code.
  49452. */
  49453. _handleSource( string, errorLine ) {
  49454. const lines = string.split( '\n' );
  49455. const lines2 = [];
  49456. const from = Math.max( errorLine - 6, 0 );
  49457. const to = Math.min( errorLine + 6, lines.length );
  49458. for ( let i = from; i < to; i ++ ) {
  49459. const line = i + 1;
  49460. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  49461. }
  49462. return lines2.join( '\n' );
  49463. }
  49464. /**
  49465. * Gets the shader compilation errors from the info log.
  49466. *
  49467. * @private
  49468. * @param {WebGL2RenderingContext} gl - The rendering context.
  49469. * @param {WebGLShader} shader - The WebGL shader object.
  49470. * @param {string} type - The shader type.
  49471. * @return {string} The shader errors.
  49472. */
  49473. _getShaderErrors( gl, shader, type ) {
  49474. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  49475. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  49476. const errors = shaderInfoLog.trim();
  49477. if ( status && errors === '' ) return '';
  49478. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  49479. if ( errorMatches ) {
  49480. const errorLine = parseInt( errorMatches[ 1 ] );
  49481. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  49482. } else {
  49483. return errors;
  49484. }
  49485. }
  49486. /**
  49487. * Logs shader compilation errors.
  49488. *
  49489. * @private
  49490. * @param {WebGLProgram} programGPU - The WebGL program.
  49491. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  49492. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  49493. */
  49494. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  49495. if ( this.renderer.debug.checkShaderErrors ) {
  49496. const gl = this.gl;
  49497. const programInfoLog = gl.getProgramInfoLog( programGPU ) || '';
  49498. const programLog = programInfoLog.trim();
  49499. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  49500. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  49501. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  49502. } else {
  49503. // default error reporting
  49504. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  49505. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  49506. error(
  49507. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  49508. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  49509. 'Program Info Log: ' + programLog + '\n' +
  49510. vertexErrors + '\n' +
  49511. fragmentErrors
  49512. );
  49513. }
  49514. } else if ( programLog !== '' ) {
  49515. warn( 'WebGLProgram: Program Info Log:', programLog );
  49516. }
  49517. }
  49518. }
  49519. /**
  49520. * Completes the shader program setup for the given render object.
  49521. *
  49522. * @private
  49523. * @param {RenderObject} renderObject - The render object.
  49524. * @param {RenderPipeline} pipeline - The render pipeline.
  49525. */
  49526. _completeCompile( renderObject, pipeline ) {
  49527. const { state, gl } = this;
  49528. const pipelineData = this.get( pipeline );
  49529. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  49530. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  49531. this._logProgramError( programGPU, fragmentShader, vertexShader );
  49532. }
  49533. state.useProgram( programGPU );
  49534. // Bindings
  49535. const bindings = renderObject.getBindings();
  49536. this._setupBindings( bindings, programGPU );
  49537. //
  49538. this.set( pipeline, {
  49539. programGPU
  49540. } );
  49541. }
  49542. /**
  49543. * Creates a compute pipeline for the given compute node.
  49544. *
  49545. * @param {ComputePipeline} computePipeline - The compute pipeline.
  49546. * @param {Array<BindGroup>} bindings - The bindings.
  49547. */
  49548. createComputePipeline( computePipeline, bindings ) {
  49549. const { state, gl } = this;
  49550. // Program
  49551. const fragmentProgram = {
  49552. stage: 'fragment',
  49553. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  49554. };
  49555. this.createProgram( fragmentProgram );
  49556. const { computeProgram } = computePipeline;
  49557. const programGPU = gl.createProgram();
  49558. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  49559. const vertexShader = this.get( computeProgram ).shaderGPU;
  49560. const transforms = computeProgram.transforms;
  49561. const transformVaryingNames = [];
  49562. const transformAttributeNodes = [];
  49563. for ( let i = 0; i < transforms.length; i ++ ) {
  49564. const transform = transforms[ i ];
  49565. transformVaryingNames.push( transform.varyingName );
  49566. transformAttributeNodes.push( transform.attributeNode );
  49567. }
  49568. gl.attachShader( programGPU, fragmentShader );
  49569. gl.attachShader( programGPU, vertexShader );
  49570. gl.transformFeedbackVaryings(
  49571. programGPU,
  49572. transformVaryingNames,
  49573. gl.SEPARATE_ATTRIBS
  49574. );
  49575. gl.linkProgram( programGPU );
  49576. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  49577. this._logProgramError( programGPU, fragmentShader, vertexShader );
  49578. }
  49579. state.useProgram( programGPU );
  49580. // Bindings
  49581. this._setupBindings( bindings, programGPU );
  49582. const attributeNodes = computeProgram.attributes;
  49583. const attributes = [];
  49584. const transformBuffers = [];
  49585. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  49586. const attribute = attributeNodes[ i ].node.attribute;
  49587. attributes.push( attribute );
  49588. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49589. }
  49590. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  49591. const attribute = transformAttributeNodes[ i ].attribute;
  49592. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49593. const attributeData = this.get( attribute );
  49594. transformBuffers.push( attributeData );
  49595. }
  49596. //
  49597. this.set( computePipeline, {
  49598. programGPU,
  49599. transformBuffers,
  49600. attributes
  49601. } );
  49602. }
  49603. /**
  49604. * Creates bindings from the given bind group definition.
  49605. *
  49606. * @param {BindGroup} bindGroup - The bind group.
  49607. * @param {Array<BindGroup>} bindings - Array of bind groups.
  49608. * @param {number} cacheIndex - The cache index.
  49609. * @param {number} version - The version.
  49610. */
  49611. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  49612. if ( this._knownBindings.has( bindings ) === false ) {
  49613. this._knownBindings.add( bindings );
  49614. let uniformBuffers = 0;
  49615. let textures = 0;
  49616. for ( const bindGroup of bindings ) {
  49617. this.set( bindGroup, {
  49618. textures: textures,
  49619. uniformBuffers: uniformBuffers
  49620. } );
  49621. for ( const binding of bindGroup.bindings ) {
  49622. if ( binding.isUniformBuffer ) uniformBuffers ++;
  49623. if ( binding.isSampledTexture ) textures ++;
  49624. }
  49625. }
  49626. }
  49627. this.updateBindings( bindGroup, bindings );
  49628. }
  49629. /**
  49630. * Updates the given bind group definition.
  49631. *
  49632. * @param {BindGroup} bindGroup - The bind group.
  49633. * @param {Array<BindGroup>} bindings - Array of bind groups.
  49634. * @param {number} cacheIndex - The cache index.
  49635. * @param {number} version - The version.
  49636. */
  49637. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  49638. const { gl } = this;
  49639. const bindGroupData = this.get( bindGroup );
  49640. let i = bindGroupData.uniformBuffers;
  49641. let t = bindGroupData.textures;
  49642. for ( const binding of bindGroup.bindings ) {
  49643. const map = this.get( binding );
  49644. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  49645. const array = binding.buffer;
  49646. let { bufferGPU } = this.get( array );
  49647. if ( bufferGPU === undefined ) {
  49648. // create
  49649. bufferGPU = gl.createBuffer();
  49650. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49651. gl.bufferData( gl.UNIFORM_BUFFER, array.byteLength, gl.DYNAMIC_DRAW );
  49652. this.set( array, { bufferGPU } );
  49653. } else {
  49654. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49655. }
  49656. // update
  49657. const updateRanges = binding.updateRanges;
  49658. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49659. if ( updateRanges.length === 0 ) {
  49660. gl.bufferData( gl.UNIFORM_BUFFER, array, gl.DYNAMIC_DRAW );
  49661. } else {
  49662. const isTyped = isTypedArray( array );
  49663. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  49664. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  49665. const range = updateRanges[ i ];
  49666. const dataOffset = range.start * byteOffsetFactor;
  49667. const size = range.count * byteOffsetFactor;
  49668. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  49669. gl.bufferSubData( gl.UNIFORM_BUFFER, bufferOffset, array, dataOffset, size );
  49670. }
  49671. }
  49672. map.index = i ++;
  49673. map.bufferGPU = bufferGPU;
  49674. this.set( binding, map );
  49675. } else if ( binding.isSampledTexture ) {
  49676. const { textureGPU, glTextureType } = this.get( binding.texture );
  49677. map.index = t ++;
  49678. map.textureGPU = textureGPU;
  49679. map.glTextureType = glTextureType;
  49680. this.set( binding, map );
  49681. }
  49682. }
  49683. }
  49684. /**
  49685. * Updates a buffer binding.
  49686. *
  49687. * @param {Buffer} binding - The buffer binding to update.
  49688. */
  49689. updateBinding( binding ) {
  49690. const gl = this.gl;
  49691. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  49692. const bindingData = this.get( binding );
  49693. const bufferGPU = bindingData.bufferGPU;
  49694. const array = binding.buffer;
  49695. const updateRanges = binding.updateRanges;
  49696. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49697. if ( updateRanges.length === 0 ) {
  49698. gl.bufferData( gl.UNIFORM_BUFFER, array, gl.DYNAMIC_DRAW );
  49699. } else {
  49700. const isTyped = isTypedArray( array );
  49701. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  49702. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  49703. const range = updateRanges[ i ];
  49704. const dataOffset = range.start * byteOffsetFactor;
  49705. const size = range.count * byteOffsetFactor;
  49706. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  49707. gl.bufferSubData( gl.UNIFORM_BUFFER, bufferOffset, array, dataOffset, size );
  49708. }
  49709. }
  49710. }
  49711. }
  49712. // attributes
  49713. /**
  49714. * Creates the GPU buffer of an indexed shader attribute.
  49715. *
  49716. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  49717. */
  49718. createIndexAttribute( attribute ) {
  49719. const gl = this.gl;
  49720. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  49721. }
  49722. /**
  49723. * Creates the GPU buffer of a shader attribute.
  49724. *
  49725. * @param {BufferAttribute} attribute - The buffer attribute.
  49726. */
  49727. createAttribute( attribute ) {
  49728. if ( this.has( attribute ) ) return;
  49729. const gl = this.gl;
  49730. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49731. }
  49732. /**
  49733. * Creates the GPU buffer of a storage attribute.
  49734. *
  49735. * @param {BufferAttribute} attribute - The buffer attribute.
  49736. */
  49737. createStorageAttribute( attribute ) {
  49738. if ( this.has( attribute ) ) return;
  49739. const gl = this.gl;
  49740. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49741. }
  49742. /**
  49743. * Updates the GPU buffer of a shader attribute.
  49744. *
  49745. * @param {BufferAttribute} attribute - The buffer attribute to update.
  49746. */
  49747. updateAttribute( attribute ) {
  49748. this.attributeUtils.updateAttribute( attribute );
  49749. }
  49750. /**
  49751. * Destroys the GPU buffer of a shader attribute.
  49752. *
  49753. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  49754. */
  49755. destroyAttribute( attribute ) {
  49756. this.attributeUtils.destroyAttribute( attribute );
  49757. }
  49758. /**
  49759. * Checks if the given feature is supported by the backend.
  49760. *
  49761. * @param {string} name - The feature's name.
  49762. * @return {boolean} Whether the feature is supported or not.
  49763. */
  49764. hasFeature( name ) {
  49765. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  49766. const extensions = this.extensions;
  49767. for ( let i = 0; i < keysMatching.length; i ++ ) {
  49768. if ( extensions.has( keysMatching[ i ] ) ) return true;
  49769. }
  49770. return false;
  49771. }
  49772. /**
  49773. * Returns the maximum anisotropy texture filtering value.
  49774. *
  49775. * @return {number} The maximum anisotropy texture filtering value.
  49776. */
  49777. getMaxAnisotropy() {
  49778. return this.capabilities.getMaxAnisotropy();
  49779. }
  49780. /**
  49781. * Copies data of the given source texture to the given destination texture.
  49782. *
  49783. * @param {Texture} srcTexture - The source texture.
  49784. * @param {Texture} dstTexture - The destination texture.
  49785. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  49786. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  49787. * @param {number} [srcLevel=0] - The source mip level to copy from.
  49788. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  49789. */
  49790. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  49791. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  49792. }
  49793. /**
  49794. * Copies the current bound framebuffer to the given texture.
  49795. *
  49796. * @param {Texture} texture - The destination texture.
  49797. * @param {RenderContext} renderContext - The render context.
  49798. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  49799. */
  49800. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  49801. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  49802. }
  49803. /**
  49804. * Configures the active framebuffer from the given render context.
  49805. *
  49806. * @private
  49807. * @param {RenderContext} descriptor - The render context.
  49808. */
  49809. _setFramebuffer( descriptor ) {
  49810. const { gl, state } = this;
  49811. let currentFrameBuffer = null;
  49812. if ( descriptor.textures !== null ) {
  49813. const renderTarget = descriptor.renderTarget;
  49814. const renderTargetContextData = this.get( renderTarget );
  49815. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  49816. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  49817. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  49818. const isRenderTargetArray = renderTarget.depth > 1;
  49819. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  49820. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  49821. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  49822. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  49823. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  49824. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  49825. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  49826. const cacheKey = getCacheKey( descriptor );
  49827. let fb;
  49828. if ( isCube ) {
  49829. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  49830. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  49831. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  49832. fb = this._xrFramebuffer;
  49833. } else {
  49834. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  49835. fb = renderTargetContextData.framebuffers[ cacheKey ];
  49836. }
  49837. if ( fb === undefined ) {
  49838. fb = gl.createFramebuffer();
  49839. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  49840. const textures = descriptor.textures;
  49841. const depthInvalidationArray = [];
  49842. if ( isCube ) {
  49843. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  49844. const { textureGPU } = this.get( textures[ 0 ] );
  49845. const cubeFace = this.renderer._activeCubeFace;
  49846. const mipLevel = this.renderer._activeMipmapLevel;
  49847. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, mipLevel );
  49848. } else {
  49849. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  49850. for ( let i = 0; i < textures.length; i ++ ) {
  49851. const texture = textures[ i ];
  49852. const textureData = this.get( texture );
  49853. textureData.renderTarget = descriptor.renderTarget;
  49854. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  49855. const attachment = gl.COLOR_ATTACHMENT0 + i;
  49856. if ( renderTarget.multiview ) {
  49857. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  49858. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  49859. const layer = this.renderer._activeCubeFace;
  49860. const mipLevel = this.renderer._activeMipmapLevel;
  49861. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, mipLevel, layer );
  49862. } else {
  49863. if ( useMultisampledRTT ) {
  49864. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  49865. } else {
  49866. const mipLevel = this.renderer._activeMipmapLevel;
  49867. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, mipLevel );
  49868. }
  49869. }
  49870. }
  49871. }
  49872. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  49873. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  49874. const renderbuffer = gl.createRenderbuffer();
  49875. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  49876. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  49877. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  49878. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  49879. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  49880. } else {
  49881. if ( descriptor.depthTexture !== null ) {
  49882. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  49883. const textureData = this.get( descriptor.depthTexture );
  49884. textureData.renderTarget = descriptor.renderTarget;
  49885. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  49886. if ( renderTarget.multiview ) {
  49887. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  49888. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  49889. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  49890. } else {
  49891. if ( descriptor.depthTexture.isArrayTexture ) {
  49892. const layer = this.renderer._activeCubeFace;
  49893. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  49894. } else if ( descriptor.depthTexture.isCubeTexture ) {
  49895. const cubeFace = this.renderer._activeCubeFace;
  49896. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureData.textureGPU, 0 );
  49897. } else {
  49898. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  49899. }
  49900. }
  49901. }
  49902. }
  49903. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  49904. } else {
  49905. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  49906. if ( isRenderCameraDepthArray ) {
  49907. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  49908. const layer = this.renderer._activeCubeFace;
  49909. const depthData = this.get( descriptor.depthTexture );
  49910. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  49911. gl.framebufferTextureLayer(
  49912. gl.FRAMEBUFFER,
  49913. depthStyle,
  49914. depthData.textureGPU,
  49915. 0,
  49916. layer
  49917. );
  49918. }
  49919. // rebind external XR textures
  49920. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  49921. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  49922. // rebind color
  49923. const textureData = this.get( descriptor.textures[ 0 ] );
  49924. if ( renderTarget.multiview ) {
  49925. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  49926. } else if ( useMultisampledRTT ) {
  49927. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  49928. } else {
  49929. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  49930. }
  49931. // rebind depth
  49932. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  49933. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  49934. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  49935. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  49936. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  49937. } else {
  49938. const textureData = this.get( descriptor.depthTexture );
  49939. if ( renderTarget.multiview ) {
  49940. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  49941. } else if ( useMultisampledRTT ) {
  49942. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  49943. } else {
  49944. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  49945. }
  49946. }
  49947. }
  49948. }
  49949. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  49950. if ( msaaFb === undefined ) {
  49951. const invalidationArray = [];
  49952. msaaFb = gl.createFramebuffer();
  49953. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  49954. const msaaRenderbuffers = [];
  49955. const textures = descriptor.textures;
  49956. for ( let i = 0; i < textures.length; i ++ ) {
  49957. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  49958. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  49959. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  49960. const texture = descriptor.textures[ i ];
  49961. const textureData = this.get( texture );
  49962. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  49963. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  49964. }
  49965. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  49966. renderTargetContextData.msaaFrameBuffer = msaaFb;
  49967. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  49968. if ( depthBuffer && depthRenderbuffer === undefined ) {
  49969. depthRenderbuffer = gl.createRenderbuffer();
  49970. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  49971. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  49972. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  49973. invalidationArray.push( depthStyle );
  49974. }
  49975. renderTargetContextData.invalidationArray = invalidationArray;
  49976. }
  49977. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  49978. } else {
  49979. currentFrameBuffer = fb;
  49980. }
  49981. state.drawBuffers( descriptor, fb );
  49982. }
  49983. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  49984. }
  49985. /**
  49986. * Computes the VAO key for the given index and attributes.
  49987. *
  49988. * @private
  49989. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  49990. * @return {string} The VAO key.
  49991. */
  49992. _getVaoKey( attributes ) {
  49993. let key = '';
  49994. for ( let i = 0; i < attributes.length; i ++ ) {
  49995. const attributeData = this.get( attributes[ i ] );
  49996. key += ':' + attributeData.id;
  49997. }
  49998. return key;
  49999. }
  50000. /**
  50001. * Creates a VAO from the index and attributes.
  50002. *
  50003. * @private
  50004. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  50005. * @return {Object} The VAO data.
  50006. */
  50007. _createVao( attributes ) {
  50008. const { gl } = this;
  50009. const vaoGPU = gl.createVertexArray();
  50010. gl.bindVertexArray( vaoGPU );
  50011. for ( let i = 0; i < attributes.length; i ++ ) {
  50012. const attribute = attributes[ i ];
  50013. const attributeData = this.get( attribute );
  50014. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  50015. gl.enableVertexAttribArray( i );
  50016. let stride, offset;
  50017. if ( attribute.isInterleavedBufferAttribute === true ) {
  50018. stride = attribute.data.stride * attributeData.bytesPerElement;
  50019. offset = attribute.offset * attributeData.bytesPerElement;
  50020. } else {
  50021. stride = 0;
  50022. offset = 0;
  50023. }
  50024. if ( attributeData.isInteger ) {
  50025. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  50026. } else {
  50027. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  50028. }
  50029. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  50030. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  50031. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  50032. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  50033. }
  50034. }
  50035. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  50036. return vaoGPU;
  50037. }
  50038. /**
  50039. * Creates a transform feedback from the given transform buffers.
  50040. *
  50041. * @private
  50042. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  50043. * @return {WebGLTransformFeedback} The transform feedback.
  50044. */
  50045. _getTransformFeedback( transformBuffers ) {
  50046. let key = '';
  50047. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  50048. key += ':' + transformBuffers[ i ].id;
  50049. }
  50050. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  50051. if ( transformFeedbackGPU !== undefined ) {
  50052. return transformFeedbackGPU;
  50053. }
  50054. const { gl } = this;
  50055. transformFeedbackGPU = gl.createTransformFeedback();
  50056. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  50057. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  50058. const attributeData = transformBuffers[ i ];
  50059. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  50060. }
  50061. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  50062. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  50063. return transformFeedbackGPU;
  50064. }
  50065. /**
  50066. * Setups the given bindings.
  50067. *
  50068. * @private
  50069. * @param {Array<BindGroup>} bindings - The bindings.
  50070. * @param {WebGLProgram} programGPU - The WebGL program.
  50071. */
  50072. _setupBindings( bindings, programGPU ) {
  50073. const gl = this.gl;
  50074. for ( const bindGroup of bindings ) {
  50075. for ( const binding of bindGroup.bindings ) {
  50076. const bindingData = this.get( binding );
  50077. const index = bindingData.index;
  50078. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  50079. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  50080. gl.uniformBlockBinding( programGPU, location, index );
  50081. } else if ( binding.isSampledTexture ) {
  50082. const location = gl.getUniformLocation( programGPU, binding.name );
  50083. gl.uniform1i( location, index );
  50084. }
  50085. }
  50086. }
  50087. }
  50088. /**
  50089. * Binds the given uniforms.
  50090. *
  50091. * @private
  50092. * @param {Array<BindGroup>} bindings - The bindings.
  50093. */
  50094. _bindUniforms( bindings ) {
  50095. const { gl, state } = this;
  50096. for ( const bindGroup of bindings ) {
  50097. for ( const binding of bindGroup.bindings ) {
  50098. const bindingData = this.get( binding );
  50099. const index = bindingData.index;
  50100. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  50101. // TODO USE bindBufferRange to group multiple uniform buffers
  50102. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  50103. } else if ( binding.isSampledTexture ) {
  50104. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  50105. }
  50106. }
  50107. }
  50108. }
  50109. /**
  50110. * The method ensures multisampled render targets are resolved.
  50111. *
  50112. * @private
  50113. * @param {RenderContext} renderContext - The render context.
  50114. */
  50115. _resolveRenderTarget( renderContext ) {
  50116. const { gl, state } = this;
  50117. const renderTarget = renderContext.renderTarget;
  50118. if ( renderContext.textures !== null && renderTarget ) {
  50119. const renderTargetContextData = this.get( renderTarget );
  50120. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  50121. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  50122. let mask = gl.COLOR_BUFFER_BIT;
  50123. if ( renderTarget.resolveDepthBuffer ) {
  50124. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  50125. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  50126. }
  50127. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  50128. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  50129. const textures = renderContext.textures;
  50130. const isMRT = textures.length > 1;
  50131. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  50132. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  50133. if ( isMRT ) {
  50134. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  50135. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  50136. for ( let i = 0; i < textures.length; i ++ ) {
  50137. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  50138. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  50139. }
  50140. }
  50141. for ( let i = 0; i < textures.length; i ++ ) {
  50142. if ( isMRT ) {
  50143. // configure attachment for resolve
  50144. const { textureGPU } = this.get( textures[ i ] );
  50145. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  50146. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  50147. }
  50148. if ( renderContext.scissor ) {
  50149. const { x, y, width, height } = renderContext.scissorValue;
  50150. const viewY = renderContext.height - height - y;
  50151. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  50152. } else {
  50153. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  50154. }
  50155. }
  50156. if ( isMRT ) {
  50157. // restore attachments
  50158. for ( let i = 0; i < textures.length; i ++ ) {
  50159. const { textureGPU } = this.get( textures[ i ] );
  50160. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  50161. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  50162. }
  50163. }
  50164. if ( this._supportsInvalidateFramebuffer === true ) {
  50165. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  50166. }
  50167. } else if ( renderTarget.resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  50168. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  50169. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  50170. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  50171. }
  50172. }
  50173. }
  50174. /**
  50175. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  50176. * should be used when MSAA is enabled.
  50177. *
  50178. * @private
  50179. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  50180. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  50181. */
  50182. _useMultisampledExtension( renderTarget ) {
  50183. if ( renderTarget.multiview === true ) {
  50184. return true;
  50185. }
  50186. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  50187. }
  50188. /**
  50189. * Frees internal resources.
  50190. */
  50191. dispose() {
  50192. if ( this.textureUtils !== null ) this.textureUtils.dispose();
  50193. const extension = this.extensions.get( 'WEBGL_lose_context' );
  50194. if ( extension ) extension.loseContext();
  50195. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  50196. }
  50197. }
  50198. const GPUPrimitiveTopology = {
  50199. PointList: 'point-list',
  50200. LineList: 'line-list',
  50201. LineStrip: 'line-strip',
  50202. TriangleList: 'triangle-list',
  50203. TriangleStrip: 'triangle-strip',
  50204. };
  50205. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  50206. const GPUCompareFunction = {
  50207. Never: 'never',
  50208. Less: 'less',
  50209. Equal: 'equal',
  50210. LessEqual: 'less-equal',
  50211. Greater: 'greater',
  50212. NotEqual: 'not-equal',
  50213. GreaterEqual: 'greater-equal',
  50214. Always: 'always'
  50215. };
  50216. const GPUStoreOp = {
  50217. Store: 'store'};
  50218. const GPULoadOp = {
  50219. Load: 'load',
  50220. Clear: 'clear'
  50221. };
  50222. const GPUFrontFace = {
  50223. CCW: 'ccw',
  50224. CW: 'cw'
  50225. };
  50226. const GPUCullMode = {
  50227. None: 'none',
  50228. Back: 'back'
  50229. };
  50230. const GPUIndexFormat = {
  50231. Uint16: 'uint16',
  50232. Uint32: 'uint32'
  50233. };
  50234. const GPUTextureFormat = {
  50235. // 8-bit formats
  50236. R8Unorm: 'r8unorm',
  50237. R8Snorm: 'r8snorm',
  50238. R8Uint: 'r8uint',
  50239. R8Sint: 'r8sint',
  50240. // 16-bit formats
  50241. R16Uint: 'r16uint',
  50242. R16Sint: 'r16sint',
  50243. R16Float: 'r16float',
  50244. RG8Unorm: 'rg8unorm',
  50245. RG8Snorm: 'rg8snorm',
  50246. RG8Uint: 'rg8uint',
  50247. RG8Sint: 'rg8sint',
  50248. // 32-bit formats
  50249. R32Uint: 'r32uint',
  50250. R32Sint: 'r32sint',
  50251. R32Float: 'r32float',
  50252. RG16Uint: 'rg16uint',
  50253. RG16Sint: 'rg16sint',
  50254. RG16Float: 'rg16float',
  50255. RGBA8Unorm: 'rgba8unorm',
  50256. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  50257. RGBA8Snorm: 'rgba8snorm',
  50258. RGBA8Uint: 'rgba8uint',
  50259. RGBA8Sint: 'rgba8sint',
  50260. BGRA8Unorm: 'bgra8unorm',
  50261. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  50262. // Packed 32-bit formats
  50263. RGB9E5UFloat: 'rgb9e5ufloat',
  50264. RGB10A2Unorm: 'rgb10a2unorm',
  50265. RG11B10UFloat: 'rg11b10ufloat',
  50266. // 64-bit formats
  50267. RG32Uint: 'rg32uint',
  50268. RG32Sint: 'rg32sint',
  50269. RG32Float: 'rg32float',
  50270. RGBA16Uint: 'rgba16uint',
  50271. RGBA16Sint: 'rgba16sint',
  50272. RGBA16Float: 'rgba16float',
  50273. // 128-bit formats
  50274. RGBA32Uint: 'rgba32uint',
  50275. RGBA32Sint: 'rgba32sint',
  50276. RGBA32Float: 'rgba32float',
  50277. Depth16Unorm: 'depth16unorm',
  50278. Depth24Plus: 'depth24plus',
  50279. Depth24PlusStencil8: 'depth24plus-stencil8',
  50280. Depth32Float: 'depth32float',
  50281. // 'depth32float-stencil8' extension
  50282. Depth32FloatStencil8: 'depth32float-stencil8',
  50283. // BC compressed formats usable if 'texture-compression-bc' is both
  50284. // supported by the device/user agent and enabled in requestDevice.
  50285. BC1RGBAUnorm: 'bc1-rgba-unorm',
  50286. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  50287. BC2RGBAUnorm: 'bc2-rgba-unorm',
  50288. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  50289. BC3RGBAUnorm: 'bc3-rgba-unorm',
  50290. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  50291. BC4RUnorm: 'bc4-r-unorm',
  50292. BC4RSnorm: 'bc4-r-snorm',
  50293. BC5RGUnorm: 'bc5-rg-unorm',
  50294. BC5RGSnorm: 'bc5-rg-snorm',
  50295. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  50296. BC6HRGBFloat: 'bc6h-rgb-float',
  50297. BC7RGBAUnorm: 'bc7-rgba-unorm',
  50298. BC7RGBAUnormSRGB: 'bc7-rgba-unorm-srgb',
  50299. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  50300. // supported by the device/user agent and enabled in requestDevice.
  50301. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  50302. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  50303. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  50304. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  50305. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  50306. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  50307. EACR11Unorm: 'eac-r11unorm',
  50308. EACR11Snorm: 'eac-r11snorm',
  50309. EACRG11Unorm: 'eac-rg11unorm',
  50310. EACRG11Snorm: 'eac-rg11snorm',
  50311. // ASTC compressed formats usable if 'texture-compression-astc' is both
  50312. // supported by the device/user agent and enabled in requestDevice.
  50313. ASTC4x4Unorm: 'astc-4x4-unorm',
  50314. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  50315. ASTC5x4Unorm: 'astc-5x4-unorm',
  50316. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  50317. ASTC5x5Unorm: 'astc-5x5-unorm',
  50318. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  50319. ASTC6x5Unorm: 'astc-6x5-unorm',
  50320. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  50321. ASTC6x6Unorm: 'astc-6x6-unorm',
  50322. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  50323. ASTC8x5Unorm: 'astc-8x5-unorm',
  50324. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  50325. ASTC8x6Unorm: 'astc-8x6-unorm',
  50326. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  50327. ASTC8x8Unorm: 'astc-8x8-unorm',
  50328. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  50329. ASTC10x5Unorm: 'astc-10x5-unorm',
  50330. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  50331. ASTC10x6Unorm: 'astc-10x6-unorm',
  50332. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  50333. ASTC10x8Unorm: 'astc-10x8-unorm',
  50334. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  50335. ASTC10x10Unorm: 'astc-10x10-unorm',
  50336. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  50337. ASTC12x10Unorm: 'astc-12x10-unorm',
  50338. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  50339. ASTC12x12Unorm: 'astc-12x12-unorm',
  50340. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  50341. };
  50342. const GPUAddressMode = {
  50343. ClampToEdge: 'clamp-to-edge',
  50344. Repeat: 'repeat',
  50345. MirrorRepeat: 'mirror-repeat'
  50346. };
  50347. const GPUFilterMode = {
  50348. Linear: 'linear',
  50349. Nearest: 'nearest'
  50350. };
  50351. const GPUBlendFactor = {
  50352. Zero: 'zero',
  50353. One: 'one',
  50354. Src: 'src',
  50355. OneMinusSrc: 'one-minus-src',
  50356. SrcAlpha: 'src-alpha',
  50357. OneMinusSrcAlpha: 'one-minus-src-alpha',
  50358. Dst: 'dst',
  50359. OneMinusDst: 'one-minus-dst',
  50360. DstAlpha: 'dst-alpha',
  50361. OneMinusDstAlpha: 'one-minus-dst-alpha',
  50362. SrcAlphaSaturated: 'src-alpha-saturated',
  50363. Constant: 'constant',
  50364. OneMinusConstant: 'one-minus-constant'
  50365. };
  50366. const GPUBlendOperation = {
  50367. Add: 'add',
  50368. Subtract: 'subtract',
  50369. ReverseSubtract: 'reverse-subtract',
  50370. Min: 'min',
  50371. Max: 'max'
  50372. };
  50373. const GPUColorWriteFlags = {
  50374. None: 0,
  50375. All: 0xF
  50376. };
  50377. const GPUStencilOperation = {
  50378. Keep: 'keep',
  50379. Zero: 'zero',
  50380. Replace: 'replace',
  50381. Invert: 'invert',
  50382. IncrementClamp: 'increment-clamp',
  50383. DecrementClamp: 'decrement-clamp',
  50384. IncrementWrap: 'increment-wrap',
  50385. DecrementWrap: 'decrement-wrap'
  50386. };
  50387. const GPUBufferBindingType = {
  50388. Storage: 'storage',
  50389. ReadOnlyStorage: 'read-only-storage'
  50390. };
  50391. const GPUStorageTextureAccess = {
  50392. WriteOnly: 'write-only',
  50393. ReadOnly: 'read-only',
  50394. ReadWrite: 'read-write',
  50395. };
  50396. const GPUSamplerBindingType = {
  50397. NonFiltering: 'non-filtering',
  50398. Comparison: 'comparison'
  50399. };
  50400. const GPUTextureSampleType = {
  50401. Float: 'float',
  50402. UnfilterableFloat: 'unfilterable-float',
  50403. Depth: 'depth',
  50404. SInt: 'sint',
  50405. UInt: 'uint'
  50406. };
  50407. const GPUTextureDimension = {
  50408. TwoD: '2d',
  50409. ThreeD: '3d'
  50410. };
  50411. const GPUTextureViewDimension = {
  50412. TwoD: '2d',
  50413. TwoDArray: '2d-array',
  50414. Cube: 'cube',
  50415. ThreeD: '3d'
  50416. };
  50417. const GPUTextureAspect = {
  50418. All: 'all'};
  50419. const GPUInputStepMode = {
  50420. Vertex: 'vertex',
  50421. Instance: 'instance'
  50422. };
  50423. const GPUFeatureName = {
  50424. CoreFeaturesAndLimits: 'core-features-and-limits',
  50425. DepthClipControl: 'depth-clip-control',
  50426. Depth32FloatStencil8: 'depth32float-stencil8',
  50427. TextureCompressionBC: 'texture-compression-bc',
  50428. TextureCompressionBCSliced3D: 'texture-compression-bc-sliced-3d',
  50429. TextureCompressionETC2: 'texture-compression-etc2',
  50430. TextureCompressionASTC: 'texture-compression-astc',
  50431. TextureCompressionASTCSliced3D: 'texture-compression-astc-sliced-3d',
  50432. TimestampQuery: 'timestamp-query',
  50433. IndirectFirstInstance: 'indirect-first-instance',
  50434. ShaderF16: 'shader-f16',
  50435. RG11B10UFloat: 'rg11b10ufloat-renderable',
  50436. BGRA8UNormStorage: 'bgra8unorm-storage',
  50437. Float32Filterable: 'float32-filterable',
  50438. Float32Blendable: 'float32-blendable',
  50439. ClipDistances: 'clip-distances',
  50440. DualSourceBlending: 'dual-source-blending',
  50441. Subgroups: 'subgroups',
  50442. TextureFormatsTier1: 'texture-formats-tier1',
  50443. TextureFormatsTier2: 'texture-formats-tier2'
  50444. };
  50445. const GPUFeatureMap = {
  50446. 'texture-compression-s3tc': 'texture-compression-bc',
  50447. 'texture-compression-etc1': 'texture-compression-etc2'
  50448. };
  50449. /**
  50450. * A special form of sampler binding type.
  50451. * It's texture value is managed by a node object.
  50452. *
  50453. * @private
  50454. * @augments Sampler
  50455. */
  50456. class NodeSampler extends Sampler {
  50457. /**
  50458. * Constructs a new node-based sampler.
  50459. *
  50460. * @param {string} name - The samplers's name.
  50461. * @param {TextureNode} textureNode - The texture node.
  50462. * @param {UniformGroupNode} groupNode - The uniform group node.
  50463. */
  50464. constructor( name, textureNode, groupNode ) {
  50465. super( name, textureNode ? textureNode.value : null );
  50466. /**
  50467. * The texture node.
  50468. *
  50469. * @type {TextureNode}
  50470. */
  50471. this.textureNode = textureNode;
  50472. /**
  50473. * The uniform group node.
  50474. *
  50475. * @type {UniformGroupNode}
  50476. */
  50477. this.groupNode = groupNode;
  50478. }
  50479. /**
  50480. * Updates the texture value of this sampler.
  50481. *
  50482. * @return {boolean} Whether the sampler needs an update or not.
  50483. */
  50484. update() {
  50485. const { textureNode } = this;
  50486. if ( this.texture !== textureNode.value ) {
  50487. this.texture = textureNode.value;
  50488. return true;
  50489. }
  50490. return super.update();
  50491. }
  50492. }
  50493. /**
  50494. * Represents a storage buffer binding type.
  50495. *
  50496. * @private
  50497. * @augments Buffer
  50498. */
  50499. class StorageBuffer extends Buffer {
  50500. /**
  50501. * Constructs a new uniform buffer.
  50502. *
  50503. * @param {string} name - The buffer's name.
  50504. * @param {BufferAttribute} attribute - The buffer attribute.
  50505. */
  50506. constructor( name, attribute ) {
  50507. super( name, attribute ? attribute.array : null );
  50508. /**
  50509. * This flag can be used for type testing.
  50510. *
  50511. * @type {BufferAttribute}
  50512. */
  50513. this.attribute = attribute;
  50514. /**
  50515. * This flag can be used for type testing.
  50516. *
  50517. * @type {boolean}
  50518. * @readonly
  50519. * @default true
  50520. */
  50521. this.isStorageBuffer = true;
  50522. }
  50523. }
  50524. let _id = 0;
  50525. /**
  50526. * A special form of storage buffer binding type.
  50527. * It's buffer value is managed by a node object.
  50528. *
  50529. * @private
  50530. * @augments StorageBuffer
  50531. */
  50532. class NodeStorageBuffer extends StorageBuffer {
  50533. /**
  50534. * Constructs a new node-based storage buffer.
  50535. *
  50536. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  50537. * @param {UniformGroupNode} groupNode - The uniform group node.
  50538. */
  50539. constructor( nodeUniform, groupNode ) {
  50540. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  50541. /**
  50542. * The node uniform.
  50543. *
  50544. * @type {StorageBufferNode}
  50545. */
  50546. this.nodeUniform = nodeUniform;
  50547. /**
  50548. * The access type.
  50549. *
  50550. * @type {string}
  50551. */
  50552. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  50553. /**
  50554. * The uniform group node.
  50555. *
  50556. * @type {UniformGroupNode}
  50557. */
  50558. this.groupNode = groupNode;
  50559. }
  50560. /**
  50561. * The storage buffer.
  50562. *
  50563. * @type {BufferAttribute}
  50564. */
  50565. get buffer() {
  50566. return this.nodeUniform.value;
  50567. }
  50568. }
  50569. /**
  50570. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  50571. *
  50572. * @private
  50573. */
  50574. class WebGPUTexturePassUtils extends DataMap {
  50575. /**
  50576. * Constructs a new utility object.
  50577. *
  50578. * @param {GPUDevice} device - The WebGPU device.
  50579. */
  50580. constructor( device ) {
  50581. super();
  50582. /**
  50583. * The WebGPU device.
  50584. *
  50585. * @type {GPUDevice}
  50586. */
  50587. this.device = device;
  50588. const mipmapVertexSource = `
  50589. struct VarysStruct {
  50590. @builtin( position ) Position: vec4<f32>,
  50591. @location( 0 ) vTex : vec2<f32>
  50592. };
  50593. @vertex
  50594. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  50595. var Varys : VarysStruct;
  50596. var pos = array< vec2<f32>, 4 >(
  50597. vec2<f32>( -1.0, 1.0 ),
  50598. vec2<f32>( 1.0, 1.0 ),
  50599. vec2<f32>( -1.0, -1.0 ),
  50600. vec2<f32>( 1.0, -1.0 )
  50601. );
  50602. var tex = array< vec2<f32>, 4 >(
  50603. vec2<f32>( 0.0, 0.0 ),
  50604. vec2<f32>( 1.0, 0.0 ),
  50605. vec2<f32>( 0.0, 1.0 ),
  50606. vec2<f32>( 1.0, 1.0 )
  50607. );
  50608. Varys.vTex = tex[ vertexIndex ];
  50609. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  50610. return Varys;
  50611. }
  50612. `;
  50613. const mipmapFragmentSource = `
  50614. @group( 0 ) @binding( 0 )
  50615. var imgSampler : sampler;
  50616. @group( 0 ) @binding( 1 )
  50617. var img : texture_2d<f32>;
  50618. @fragment
  50619. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  50620. return textureSample( img, imgSampler, vTex );
  50621. }
  50622. `;
  50623. const flipYFragmentSource = `
  50624. @group( 0 ) @binding( 0 )
  50625. var imgSampler : sampler;
  50626. @group( 0 ) @binding( 1 )
  50627. var img : texture_2d<f32>;
  50628. @fragment
  50629. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  50630. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  50631. }
  50632. `;
  50633. /**
  50634. * The mipmap GPU sampler.
  50635. *
  50636. * @type {GPUSampler}
  50637. */
  50638. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  50639. /**
  50640. * The flipY GPU sampler.
  50641. *
  50642. * @type {GPUSampler}
  50643. */
  50644. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  50645. /**
  50646. * A cache for GPU render pipelines used for copy/transfer passes.
  50647. * Every texture format requires a unique pipeline.
  50648. *
  50649. * @type {Object<string,GPURenderPipeline>}
  50650. */
  50651. this.transferPipelines = {};
  50652. /**
  50653. * A cache for GPU render pipelines used for flipY passes.
  50654. * Every texture format requires a unique pipeline.
  50655. *
  50656. * @type {Object<string,GPURenderPipeline>}
  50657. */
  50658. this.flipYPipelines = {};
  50659. /**
  50660. * The mipmap vertex shader module.
  50661. *
  50662. * @type {GPUShaderModule}
  50663. */
  50664. this.mipmapVertexShaderModule = device.createShaderModule( {
  50665. label: 'mipmapVertex',
  50666. code: mipmapVertexSource
  50667. } );
  50668. /**
  50669. * The mipmap fragment shader module.
  50670. *
  50671. * @type {GPUShaderModule}
  50672. */
  50673. this.mipmapFragmentShaderModule = device.createShaderModule( {
  50674. label: 'mipmapFragment',
  50675. code: mipmapFragmentSource
  50676. } );
  50677. /**
  50678. * The flipY fragment shader module.
  50679. *
  50680. * @type {GPUShaderModule}
  50681. */
  50682. this.flipYFragmentShaderModule = device.createShaderModule( {
  50683. label: 'flipYFragment',
  50684. code: flipYFragmentSource
  50685. } );
  50686. }
  50687. /**
  50688. * Returns a render pipeline for the internal copy render pass. The pass
  50689. * requires a unique render pipeline for each texture format.
  50690. *
  50691. * @param {string} format - The GPU texture format
  50692. * @return {GPURenderPipeline} The GPU render pipeline.
  50693. */
  50694. getTransferPipeline( format ) {
  50695. let pipeline = this.transferPipelines[ format ];
  50696. if ( pipeline === undefined ) {
  50697. pipeline = this.device.createRenderPipeline( {
  50698. label: `mipmap-${ format }`,
  50699. vertex: {
  50700. module: this.mipmapVertexShaderModule,
  50701. entryPoint: 'main'
  50702. },
  50703. fragment: {
  50704. module: this.mipmapFragmentShaderModule,
  50705. entryPoint: 'main',
  50706. targets: [ { format } ]
  50707. },
  50708. primitive: {
  50709. topology: GPUPrimitiveTopology.TriangleStrip,
  50710. stripIndexFormat: GPUIndexFormat.Uint32
  50711. },
  50712. layout: 'auto'
  50713. } );
  50714. this.transferPipelines[ format ] = pipeline;
  50715. }
  50716. return pipeline;
  50717. }
  50718. /**
  50719. * Returns a render pipeline for the flipY render pass. The pass
  50720. * requires a unique render pipeline for each texture format.
  50721. *
  50722. * @param {string} format - The GPU texture format
  50723. * @return {GPURenderPipeline} The GPU render pipeline.
  50724. */
  50725. getFlipYPipeline( format ) {
  50726. let pipeline = this.flipYPipelines[ format ];
  50727. if ( pipeline === undefined ) {
  50728. pipeline = this.device.createRenderPipeline( {
  50729. label: `flipY-${ format }`,
  50730. vertex: {
  50731. module: this.mipmapVertexShaderModule,
  50732. entryPoint: 'main'
  50733. },
  50734. fragment: {
  50735. module: this.flipYFragmentShaderModule,
  50736. entryPoint: 'main',
  50737. targets: [ { format } ]
  50738. },
  50739. primitive: {
  50740. topology: GPUPrimitiveTopology.TriangleStrip,
  50741. stripIndexFormat: GPUIndexFormat.Uint32
  50742. },
  50743. layout: 'auto'
  50744. } );
  50745. this.flipYPipelines[ format ] = pipeline;
  50746. }
  50747. return pipeline;
  50748. }
  50749. /**
  50750. * Flip the contents of the given GPU texture along its vertical axis.
  50751. *
  50752. * @param {GPUTexture} textureGPU - The GPU texture object.
  50753. * @param {Object} textureGPUDescriptor - The texture descriptor.
  50754. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  50755. */
  50756. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  50757. const format = textureGPUDescriptor.format;
  50758. const { width, height } = textureGPUDescriptor.size;
  50759. const transferPipeline = this.getTransferPipeline( format );
  50760. const flipYPipeline = this.getFlipYPipeline( format );
  50761. const tempTexture = this.device.createTexture( {
  50762. size: { width, height, depthOrArrayLayers: 1 },
  50763. format,
  50764. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  50765. } );
  50766. const srcView = textureGPU.createView( {
  50767. baseMipLevel: 0,
  50768. mipLevelCount: 1,
  50769. dimension: GPUTextureViewDimension.TwoD,
  50770. baseArrayLayer
  50771. } );
  50772. const dstView = tempTexture.createView( {
  50773. baseMipLevel: 0,
  50774. mipLevelCount: 1,
  50775. dimension: GPUTextureViewDimension.TwoD,
  50776. baseArrayLayer: 0
  50777. } );
  50778. const commandEncoder = this.device.createCommandEncoder( {} );
  50779. const pass = ( pipeline, sourceView, destinationView ) => {
  50780. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  50781. const bindGroup = this.device.createBindGroup( {
  50782. layout: bindGroupLayout,
  50783. entries: [ {
  50784. binding: 0,
  50785. resource: this.flipYSampler
  50786. }, {
  50787. binding: 1,
  50788. resource: sourceView
  50789. } ]
  50790. } );
  50791. const passEncoder = commandEncoder.beginRenderPass( {
  50792. colorAttachments: [ {
  50793. view: destinationView,
  50794. loadOp: GPULoadOp.Clear,
  50795. storeOp: GPUStoreOp.Store,
  50796. clearValue: [ 0, 0, 0, 0 ]
  50797. } ]
  50798. } );
  50799. passEncoder.setPipeline( pipeline );
  50800. passEncoder.setBindGroup( 0, bindGroup );
  50801. passEncoder.draw( 4, 1, 0, 0 );
  50802. passEncoder.end();
  50803. };
  50804. pass( transferPipeline, srcView, dstView );
  50805. pass( flipYPipeline, dstView, srcView );
  50806. this.device.queue.submit( [ commandEncoder.finish() ] );
  50807. tempTexture.destroy();
  50808. }
  50809. /**
  50810. * Generates mipmaps for the given GPU texture.
  50811. *
  50812. * @param {GPUTexture} textureGPU - The GPU texture object.
  50813. * @param {Object} textureGPUDescriptor - The texture descriptor.
  50814. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  50815. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  50816. */
  50817. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0, encoder = null ) {
  50818. const textureData = this.get( textureGPU );
  50819. if ( textureData.layers === undefined ) {
  50820. textureData.layers = [];
  50821. }
  50822. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  50823. const commandEncoder = encoder || this.device.createCommandEncoder( { label: 'mipmapEncoder' } );
  50824. this._mipmapRunBundles( commandEncoder, passes );
  50825. if ( encoder === null ) this.device.queue.submit( [ commandEncoder.finish() ] );
  50826. textureData.layers[ baseArrayLayer ] = passes;
  50827. }
  50828. /**
  50829. * Since multiple copy render passes are required to generate mipmaps, the passes
  50830. * are managed as render bundles to improve performance.
  50831. *
  50832. * @param {GPUTexture} textureGPU - The GPU texture object.
  50833. * @param {Object} textureGPUDescriptor - The texture descriptor.
  50834. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  50835. * @return {Array<Object>} An array of render bundles.
  50836. */
  50837. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  50838. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  50839. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  50840. let srcView = textureGPU.createView( {
  50841. baseMipLevel: 0,
  50842. mipLevelCount: 1,
  50843. dimension: GPUTextureViewDimension.TwoD,
  50844. baseArrayLayer
  50845. } );
  50846. const passes = [];
  50847. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  50848. const bindGroup = this.device.createBindGroup( {
  50849. layout: bindGroupLayout,
  50850. entries: [ {
  50851. binding: 0,
  50852. resource: this.mipmapSampler
  50853. }, {
  50854. binding: 1,
  50855. resource: srcView
  50856. } ]
  50857. } );
  50858. const dstView = textureGPU.createView( {
  50859. baseMipLevel: i,
  50860. mipLevelCount: 1,
  50861. dimension: GPUTextureViewDimension.TwoD,
  50862. baseArrayLayer
  50863. } );
  50864. const passDescriptor = {
  50865. colorAttachments: [ {
  50866. view: dstView,
  50867. loadOp: GPULoadOp.Clear,
  50868. storeOp: GPUStoreOp.Store,
  50869. clearValue: [ 0, 0, 0, 0 ]
  50870. } ]
  50871. };
  50872. const passEncoder = this.device.createRenderBundleEncoder( {
  50873. colorFormats: [ textureGPUDescriptor.format ]
  50874. } );
  50875. passEncoder.setPipeline( pipeline );
  50876. passEncoder.setBindGroup( 0, bindGroup );
  50877. passEncoder.draw( 4, 1, 0, 0 );
  50878. passes.push( {
  50879. renderBundles: [ passEncoder.finish() ],
  50880. passDescriptor
  50881. } );
  50882. srcView = dstView;
  50883. }
  50884. return passes;
  50885. }
  50886. /**
  50887. * Executes the render bundles.
  50888. *
  50889. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  50890. * @param {Array<Object>} passes - An array of render bundles.
  50891. */
  50892. _mipmapRunBundles( commandEncoder, passes ) {
  50893. const levels = passes.length;
  50894. for ( let i = 0; i < levels; i ++ ) {
  50895. const pass = passes[ i ];
  50896. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  50897. passEncoder.executeBundles( pass.renderBundles );
  50898. passEncoder.end();
  50899. }
  50900. }
  50901. }
  50902. const _compareToWebGPU = {
  50903. [ NeverCompare ]: 'never',
  50904. [ LessCompare ]: 'less',
  50905. [ EqualCompare ]: 'equal',
  50906. [ LessEqualCompare ]: 'less-equal',
  50907. [ GreaterCompare ]: 'greater',
  50908. [ GreaterEqualCompare ]: 'greater-equal',
  50909. [ AlwaysCompare ]: 'always',
  50910. [ NotEqualCompare ]: 'not-equal'
  50911. };
  50912. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  50913. /**
  50914. * A WebGPU backend utility module for managing textures.
  50915. *
  50916. * @private
  50917. */
  50918. class WebGPUTextureUtils {
  50919. /**
  50920. * Constructs a new utility object.
  50921. *
  50922. * @param {WebGPUBackend} backend - The WebGPU backend.
  50923. */
  50924. constructor( backend ) {
  50925. /**
  50926. * A reference to the WebGPU backend.
  50927. *
  50928. * @type {WebGPUBackend}
  50929. */
  50930. this.backend = backend;
  50931. /**
  50932. * A reference to the pass utils.
  50933. *
  50934. * @type {?WebGPUTexturePassUtils}
  50935. * @default null
  50936. */
  50937. this._passUtils = null;
  50938. /**
  50939. * A dictionary for managing default textures. The key
  50940. * is the texture format, the value the texture object.
  50941. *
  50942. * @type {Object<string,Texture>}
  50943. */
  50944. this.defaultTexture = {};
  50945. /**
  50946. * A dictionary for managing default cube textures. The key
  50947. * is the texture format, the value the texture object.
  50948. *
  50949. * @type {Object<string,CubeTexture>}
  50950. */
  50951. this.defaultCubeTexture = {};
  50952. /**
  50953. * A default video frame.
  50954. *
  50955. * @type {?VideoFrame}
  50956. * @default null
  50957. */
  50958. this.defaultVideoFrame = null;
  50959. /**
  50960. * A cache of shared texture samplers.
  50961. *
  50962. * @type {Map<string, Object>}
  50963. */
  50964. this._samplerCache = new Map();
  50965. }
  50966. /**
  50967. * Creates a GPU sampler for the given texture.
  50968. *
  50969. * @param {Texture} texture - The texture to create the sampler for.
  50970. * @return {string} The current sampler key.
  50971. */
  50972. updateSampler( texture ) {
  50973. const backend = this.backend;
  50974. const samplerKey = texture.minFilter + '-' + texture.magFilter + '-' +
  50975. texture.wrapS + '-' + texture.wrapT + '-' + ( texture.wrapR || '0' ) + '-' +
  50976. texture.anisotropy + '-' + ( texture.compareFunction || 0 );
  50977. let samplerData = this._samplerCache.get( samplerKey );
  50978. if ( samplerData === undefined ) {
  50979. const samplerDescriptorGPU = {
  50980. addressModeU: this._convertAddressMode( texture.wrapS ),
  50981. addressModeV: this._convertAddressMode( texture.wrapT ),
  50982. addressModeW: this._convertAddressMode( texture.wrapR ),
  50983. magFilter: this._convertFilterMode( texture.magFilter ),
  50984. minFilter: this._convertFilterMode( texture.minFilter ),
  50985. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  50986. maxAnisotropy: 1
  50987. };
  50988. // anisotropy can only be used when all filter modes are set to linear.
  50989. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  50990. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  50991. }
  50992. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  50993. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  50994. }
  50995. const sampler = backend.device.createSampler( samplerDescriptorGPU );
  50996. samplerData = { sampler, usedTimes: 0 };
  50997. this._samplerCache.set( samplerKey, samplerData );
  50998. }
  50999. const textureData = backend.get( texture );
  51000. if ( textureData.sampler !== samplerData.sampler ) {
  51001. // check if previous sampler is unused so it can be deleted
  51002. if ( textureData.sampler !== undefined ) {
  51003. const oldSamplerData = this._samplerCache.get( textureData.samplerKey );
  51004. oldSamplerData.usedTimes --;
  51005. if ( oldSamplerData.usedTimes === 0 ) {
  51006. this._samplerCache.delete( textureData.samplerKey );
  51007. }
  51008. }
  51009. // update to new sampler data
  51010. textureData.samplerKey = samplerKey;
  51011. textureData.sampler = samplerData.sampler;
  51012. samplerData.usedTimes ++;
  51013. }
  51014. return samplerKey;
  51015. }
  51016. /**
  51017. * Creates a default texture for the given texture that can be used
  51018. * as a placeholder until the actual texture is ready for usage.
  51019. *
  51020. * @param {Texture} texture - The texture to create a default texture for.
  51021. */
  51022. createDefaultTexture( texture ) {
  51023. let textureGPU;
  51024. const format = getFormat( texture );
  51025. if ( texture.isCubeTexture ) {
  51026. textureGPU = this._getDefaultCubeTextureGPU( format );
  51027. } else {
  51028. textureGPU = this._getDefaultTextureGPU( format );
  51029. }
  51030. this.backend.get( texture ).texture = textureGPU;
  51031. }
  51032. /**
  51033. * Defines a texture on the GPU for the given texture object.
  51034. *
  51035. * @param {Texture} texture - The texture.
  51036. * @param {Object} [options={}] - Optional configuration parameter.
  51037. */
  51038. createTexture( texture, options = {} ) {
  51039. const backend = this.backend;
  51040. const textureData = backend.get( texture );
  51041. if ( textureData.initialized ) {
  51042. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  51043. }
  51044. if ( texture.isExternalTexture ) {
  51045. textureData.texture = texture.sourceTexture;
  51046. textureData.initialized = true;
  51047. return;
  51048. }
  51049. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  51050. if ( options.levels === undefined ) options.levels = 1;
  51051. if ( options.depth === undefined ) options.depth = 1;
  51052. const { width, height, depth, levels } = options;
  51053. if ( texture.isFramebufferTexture ) {
  51054. if ( options.renderTarget ) {
  51055. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  51056. } else {
  51057. options.format = this.backend.utils.getPreferredCanvasFormat();
  51058. }
  51059. }
  51060. const dimension = this._getDimension( texture );
  51061. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  51062. textureData.format = format;
  51063. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  51064. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  51065. if ( texture.isStorageTexture === true ) {
  51066. usage |= GPUTextureUsage.STORAGE_BINDING;
  51067. }
  51068. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true && format !== GPUTextureFormat.RGB9E5UFloat ) {
  51069. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  51070. }
  51071. const textureDescriptorGPU = {
  51072. label: texture.name,
  51073. size: {
  51074. width: width,
  51075. height: height,
  51076. depthOrArrayLayers: depth,
  51077. },
  51078. mipLevelCount: levels,
  51079. sampleCount: primarySamples,
  51080. dimension: dimension,
  51081. format: format,
  51082. usage: usage
  51083. };
  51084. // texture creation
  51085. if ( format === undefined ) {
  51086. warn( 'WebGPURenderer: Texture format not supported.' );
  51087. this.createDefaultTexture( texture );
  51088. return;
  51089. }
  51090. if ( texture.isCubeTexture ) {
  51091. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  51092. }
  51093. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  51094. if ( isMSAA ) {
  51095. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  51096. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  51097. msaaTextureDescriptorGPU.sampleCount = samples;
  51098. msaaTextureDescriptorGPU.mipLevelCount = 1; // See https://www.w3.org/TR/webgpu/#texture-creation
  51099. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  51100. }
  51101. textureData.initialized = true;
  51102. textureData.textureDescriptorGPU = textureDescriptorGPU;
  51103. }
  51104. /**
  51105. * Destroys the GPU data for the given texture object.
  51106. *
  51107. * @param {Texture} texture - The texture.
  51108. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  51109. */
  51110. destroyTexture( texture, isDefaultTexture = false ) {
  51111. const backend = this.backend;
  51112. const textureData = backend.get( texture );
  51113. if ( textureData.texture !== undefined && isDefaultTexture === false ) textureData.texture.destroy();
  51114. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  51115. backend.delete( texture );
  51116. }
  51117. /**
  51118. * Generates mipmaps for the given texture.
  51119. *
  51120. * @param {Texture} texture - The texture.
  51121. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  51122. */
  51123. generateMipmaps( texture, encoder = null ) {
  51124. const textureData = this.backend.get( texture );
  51125. if ( texture.isCubeTexture ) {
  51126. for ( let i = 0; i < 6; i ++ ) {
  51127. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i, encoder );
  51128. }
  51129. } else {
  51130. const depth = texture.image.depth || 1;
  51131. for ( let i = 0; i < depth; i ++ ) {
  51132. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i, encoder );
  51133. }
  51134. }
  51135. }
  51136. /**
  51137. * Returns the color buffer representing the color
  51138. * attachment of the default framebuffer.
  51139. *
  51140. * @return {GPUTexture} The color buffer.
  51141. */
  51142. getColorBuffer() {
  51143. const backend = this.backend;
  51144. const canvasTarget = backend.renderer.getCanvasTarget();
  51145. const { width, height } = backend.getDrawingBufferSize();
  51146. const samples = backend.renderer.currentSamples;
  51147. const colorTexture = canvasTarget.colorTexture;
  51148. const colorTextureData = backend.get( colorTexture );
  51149. if ( colorTexture.width === width && colorTexture.height === height && colorTexture.samples === samples ) {
  51150. return colorTextureData.texture;
  51151. }
  51152. // recreate
  51153. let colorBuffer = colorTextureData.texture;
  51154. if ( colorBuffer ) colorBuffer.destroy();
  51155. colorBuffer = backend.device.createTexture( {
  51156. label: 'colorBuffer',
  51157. size: {
  51158. width: width,
  51159. height: height,
  51160. depthOrArrayLayers: 1
  51161. },
  51162. sampleCount: backend.utils.getSampleCount( backend.renderer.currentSamples ),
  51163. format: backend.utils.getPreferredCanvasFormat(),
  51164. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  51165. } );
  51166. //
  51167. colorTexture.source.width = width;
  51168. colorTexture.source.height = height;
  51169. colorTexture.samples = samples;
  51170. colorTextureData.texture = colorBuffer;
  51171. return colorBuffer;
  51172. }
  51173. /**
  51174. * Returns the depth buffer representing the depth
  51175. * attachment of the default framebuffer.
  51176. *
  51177. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  51178. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  51179. * @return {GPUTexture} The depth buffer.
  51180. */
  51181. getDepthBuffer( depth = true, stencil = false ) {
  51182. const backend = this.backend;
  51183. const canvasTarget = backend.renderer.getCanvasTarget();
  51184. const { width, height } = backend.getDrawingBufferSize();
  51185. const samples = backend.renderer.currentSamples;
  51186. const depthTexture = canvasTarget.depthTexture;
  51187. if ( depthTexture.width === width &&
  51188. depthTexture.height === height &&
  51189. depthTexture.samples === samples &&
  51190. depthTexture.depth === depth &&
  51191. depthTexture.stencil === stencil ) {
  51192. return backend.get( depthTexture ).texture;
  51193. }
  51194. //
  51195. const depthTextureGPU = backend.get( depthTexture ).texture;
  51196. let format, type;
  51197. if ( stencil ) {
  51198. format = DepthStencilFormat;
  51199. type = UnsignedInt248Type;
  51200. } else if ( depth ) {
  51201. format = DepthFormat;
  51202. type = UnsignedIntType;
  51203. }
  51204. if ( depthTextureGPU !== undefined ) {
  51205. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type && depthTexture.samples === samples ) {
  51206. return depthTextureGPU;
  51207. }
  51208. this.destroyTexture( depthTexture );
  51209. }
  51210. // recreate
  51211. depthTexture.name = 'depthBuffer';
  51212. depthTexture.format = format;
  51213. depthTexture.type = type;
  51214. depthTexture.image.width = width;
  51215. depthTexture.image.height = height;
  51216. depthTexture.samples = samples;
  51217. this.createTexture( depthTexture, { width, height } );
  51218. return backend.get( depthTexture ).texture;
  51219. }
  51220. /**
  51221. * Uploads the updated texture data to the GPU.
  51222. *
  51223. * @param {Texture} texture - The texture.
  51224. * @param {Object} [options={}] - Optional configuration parameter.
  51225. */
  51226. updateTexture( texture, options ) {
  51227. const textureData = this.backend.get( texture );
  51228. const mipmaps = texture.mipmaps;
  51229. const { textureDescriptorGPU } = textureData;
  51230. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  51231. return;
  51232. // transfer texture data
  51233. if ( texture.isDataTexture ) {
  51234. if ( mipmaps.length > 0 ) {
  51235. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  51236. const mipmap = mipmaps[ i ];
  51237. this._copyBufferToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, 0, i );
  51238. }
  51239. } else {
  51240. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  51241. }
  51242. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  51243. for ( let i = 0; i < options.image.depth; i ++ ) {
  51244. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  51245. }
  51246. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  51247. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  51248. } else if ( texture.isCubeTexture ) {
  51249. this._copyCubeMapToTexture( texture, textureData.texture, textureDescriptorGPU );
  51250. } else {
  51251. if ( mipmaps.length > 0 ) {
  51252. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  51253. const mipmap = mipmaps[ i ];
  51254. this._copyImageToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha, i );
  51255. }
  51256. } else {
  51257. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  51258. }
  51259. }
  51260. //
  51261. textureData.version = texture.version;
  51262. }
  51263. /**
  51264. * Returns texture data as a typed array.
  51265. *
  51266. * @async
  51267. * @param {Texture} texture - The texture to copy.
  51268. * @param {number} x - The x coordinate of the copy origin.
  51269. * @param {number} y - The y coordinate of the copy origin.
  51270. * @param {number} width - The width of the copy.
  51271. * @param {number} height - The height of the copy.
  51272. * @param {number} faceIndex - The face index.
  51273. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  51274. */
  51275. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  51276. const device = this.backend.device;
  51277. const textureData = this.backend.get( texture );
  51278. const textureGPU = textureData.texture;
  51279. const format = textureData.textureDescriptorGPU.format;
  51280. const bytesPerTexel = this._getBytesPerTexel( format );
  51281. let bytesPerRow = width * bytesPerTexel;
  51282. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  51283. const readBuffer = device.createBuffer(
  51284. {
  51285. size: ( ( height - 1 ) * bytesPerRow ) + ( width * bytesPerTexel ), // see https://github.com/mrdoob/three.js/issues/31658#issuecomment-3229442010
  51286. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  51287. }
  51288. );
  51289. const encoder = device.createCommandEncoder();
  51290. encoder.copyTextureToBuffer(
  51291. {
  51292. texture: textureGPU,
  51293. origin: { x, y, z: faceIndex },
  51294. },
  51295. {
  51296. buffer: readBuffer,
  51297. bytesPerRow: bytesPerRow
  51298. },
  51299. {
  51300. width: width,
  51301. height: height
  51302. }
  51303. );
  51304. const typedArrayType = this._getTypedArrayType( format );
  51305. device.queue.submit( [ encoder.finish() ] );
  51306. await readBuffer.mapAsync( GPUMapMode.READ );
  51307. const buffer = readBuffer.getMappedRange();
  51308. return new typedArrayType( buffer );
  51309. }
  51310. /**
  51311. * Frees all internal resources.
  51312. */
  51313. dispose() {
  51314. this._samplerCache.clear();
  51315. }
  51316. /**
  51317. * Returns the default GPU texture for the given format.
  51318. *
  51319. * @private
  51320. * @param {string} format - The GPU format.
  51321. * @return {GPUTexture} The GPU texture.
  51322. */
  51323. _getDefaultTextureGPU( format ) {
  51324. let defaultTexture = this.defaultTexture[ format ];
  51325. if ( defaultTexture === undefined ) {
  51326. const texture = new Texture();
  51327. texture.minFilter = NearestFilter;
  51328. texture.magFilter = NearestFilter;
  51329. this.createTexture( texture, { width: 1, height: 1, format } );
  51330. this.defaultTexture[ format ] = defaultTexture = texture;
  51331. }
  51332. return this.backend.get( defaultTexture ).texture;
  51333. }
  51334. /**
  51335. * Returns the default GPU cube texture for the given format.
  51336. *
  51337. * @private
  51338. * @param {string} format - The GPU format.
  51339. * @return {GPUTexture} The GPU texture.
  51340. */
  51341. _getDefaultCubeTextureGPU( format ) {
  51342. let defaultCubeTexture = this.defaultCubeTexture[ format ];
  51343. if ( defaultCubeTexture === undefined ) {
  51344. const texture = new CubeTexture();
  51345. texture.minFilter = NearestFilter;
  51346. texture.magFilter = NearestFilter;
  51347. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  51348. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  51349. }
  51350. return this.backend.get( defaultCubeTexture ).texture;
  51351. }
  51352. /**
  51353. * Uploads cube texture image data to the GPU memory.
  51354. *
  51355. * @private
  51356. * @param {CubeTexture} texture - The cube texture.
  51357. * @param {GPUTexture} textureGPU - The GPU texture.
  51358. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51359. */
  51360. _copyCubeMapToTexture( texture, textureGPU, textureDescriptorGPU ) {
  51361. const images = texture.images;
  51362. const mipmaps = texture.mipmaps;
  51363. for ( let i = 0; i < 6; i ++ ) {
  51364. const image = images[ i ];
  51365. const flipIndex = texture.flipY === true ? _flipMap[ i ] : i;
  51366. if ( image.isDataTexture ) {
  51367. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY );
  51368. } else {
  51369. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha );
  51370. }
  51371. for ( let j = 0; j < mipmaps.length; j ++ ) {
  51372. const mipmap = mipmaps[ j ];
  51373. const image = mipmap.images[ i ];
  51374. if ( image.isDataTexture ) {
  51375. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, 0, j + 1 );
  51376. } else {
  51377. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha, j + 1 );
  51378. }
  51379. }
  51380. }
  51381. }
  51382. /**
  51383. * Uploads texture image data to the GPU memory.
  51384. *
  51385. * @private
  51386. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  51387. * @param {GPUTexture} textureGPU - The GPU texture.
  51388. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51389. * @param {number} originDepth - The origin depth.
  51390. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  51391. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  51392. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  51393. */
  51394. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha, mipLevel = 0 ) {
  51395. const device = this.backend.device;
  51396. const width = ( mipLevel > 0 ) ? image.width : textureDescriptorGPU.size.width;
  51397. const height = ( mipLevel > 0 ) ? image.height : textureDescriptorGPU.size.height;
  51398. try {
  51399. device.queue.copyExternalImageToTexture(
  51400. {
  51401. source: image,
  51402. flipY: flipY
  51403. }, {
  51404. texture: textureGPU,
  51405. mipLevel: mipLevel,
  51406. origin: { x: 0, y: 0, z: originDepth },
  51407. premultipliedAlpha: premultiplyAlpha
  51408. }, {
  51409. width: width,
  51410. height: height,
  51411. depthOrArrayLayers: 1
  51412. }
  51413. );
  51414. // try/catch has been added to fix bad video frame data on certain devices, see #32391
  51415. } catch ( _ ) {}
  51416. }
  51417. /**
  51418. * Returns the pass utils singleton.
  51419. *
  51420. * @private
  51421. * @return {WebGPUTexturePassUtils} The utils instance.
  51422. */
  51423. _getPassUtils() {
  51424. let passUtils = this._passUtils;
  51425. if ( passUtils === null ) {
  51426. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  51427. }
  51428. return passUtils;
  51429. }
  51430. /**
  51431. * Generates mipmaps for the given GPU texture.
  51432. *
  51433. * @private
  51434. * @param {GPUTexture} textureGPU - The GPU texture object.
  51435. * @param {Object} textureDescriptorGPU - The texture descriptor.
  51436. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  51437. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  51438. */
  51439. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0, encoder = null ) {
  51440. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer, encoder );
  51441. }
  51442. /**
  51443. * Flip the contents of the given GPU texture along its vertical axis.
  51444. *
  51445. * @private
  51446. * @param {GPUTexture} textureGPU - The GPU texture object.
  51447. * @param {Object} textureDescriptorGPU - The texture descriptor.
  51448. * @param {number} [originDepth=0] - The origin depth.
  51449. */
  51450. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  51451. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  51452. }
  51453. /**
  51454. * Uploads texture buffer data to the GPU memory.
  51455. *
  51456. * @private
  51457. * @param {Object} image - An object defining the image buffer data.
  51458. * @param {GPUTexture} textureGPU - The GPU texture.
  51459. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51460. * @param {number} originDepth - The origin depth.
  51461. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  51462. * @param {number} [depth=0] - The depth offset when copying array or 3D texture data.
  51463. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  51464. */
  51465. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0, mipLevel = 0 ) {
  51466. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  51467. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  51468. const device = this.backend.device;
  51469. const data = image.data;
  51470. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  51471. const bytesPerRow = image.width * bytesPerTexel;
  51472. device.queue.writeTexture(
  51473. {
  51474. texture: textureGPU,
  51475. mipLevel: mipLevel,
  51476. origin: { x: 0, y: 0, z: originDepth }
  51477. },
  51478. data,
  51479. {
  51480. offset: image.width * image.height * bytesPerTexel * depth,
  51481. bytesPerRow
  51482. },
  51483. {
  51484. width: image.width,
  51485. height: image.height,
  51486. depthOrArrayLayers: 1
  51487. } );
  51488. if ( flipY === true ) {
  51489. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  51490. }
  51491. }
  51492. /**
  51493. * Uploads compressed texture data to the GPU memory.
  51494. *
  51495. * @private
  51496. * @param {Array<Object>} mipmaps - An array with mipmap data.
  51497. * @param {GPUTexture} textureGPU - The GPU texture.
  51498. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51499. */
  51500. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  51501. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  51502. const device = this.backend.device;
  51503. const blockData = this._getBlockData( textureDescriptorGPU.format );
  51504. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  51505. for ( let i = 0; i < mipmaps.length; i ++ ) {
  51506. const mipmap = mipmaps[ i ];
  51507. const width = mipmap.width;
  51508. const height = mipmap.height;
  51509. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  51510. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  51511. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  51512. for ( let j = 0; j < depth; j ++ ) {
  51513. device.queue.writeTexture(
  51514. {
  51515. texture: textureGPU,
  51516. mipLevel: i,
  51517. origin: { x: 0, y: 0, z: j }
  51518. },
  51519. mipmap.data,
  51520. {
  51521. offset: j * bytesPerImage,
  51522. bytesPerRow,
  51523. rowsPerImage: Math.ceil( height / blockData.height )
  51524. },
  51525. {
  51526. width: Math.ceil( width / blockData.width ) * blockData.width,
  51527. height: Math.ceil( height / blockData.height ) * blockData.height,
  51528. depthOrArrayLayers: 1
  51529. }
  51530. );
  51531. }
  51532. }
  51533. }
  51534. /**
  51535. * This method is only relevant for compressed texture formats. It returns a block
  51536. * data descriptor for the given GPU compressed texture format.
  51537. *
  51538. * @private
  51539. * @param {string} format - The GPU compressed texture format.
  51540. * @return {Object} The block data descriptor.
  51541. */
  51542. _getBlockData( format ) {
  51543. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  51544. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  51545. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  51546. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  51547. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  51548. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  51549. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  51550. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  51551. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  51552. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  51553. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  51554. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  51555. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  51556. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  51557. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  51558. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  51559. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  51560. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  51561. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  51562. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  51563. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  51564. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  51565. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  51566. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  51567. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  51568. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  51569. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  51570. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  51571. }
  51572. /**
  51573. * Converts the three.js uv wrapping constants to GPU address mode constants.
  51574. *
  51575. * @private
  51576. * @param {number} value - The three.js constant defining a uv wrapping mode.
  51577. * @return {string} The GPU address mode.
  51578. */
  51579. _convertAddressMode( value ) {
  51580. let addressMode = GPUAddressMode.ClampToEdge;
  51581. if ( value === RepeatWrapping ) {
  51582. addressMode = GPUAddressMode.Repeat;
  51583. } else if ( value === MirroredRepeatWrapping ) {
  51584. addressMode = GPUAddressMode.MirrorRepeat;
  51585. }
  51586. return addressMode;
  51587. }
  51588. /**
  51589. * Converts the three.js filter constants to GPU filter constants.
  51590. *
  51591. * @private
  51592. * @param {number} value - The three.js constant defining a filter mode.
  51593. * @return {string} The GPU filter mode.
  51594. */
  51595. _convertFilterMode( value ) {
  51596. let filterMode = GPUFilterMode.Linear;
  51597. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  51598. filterMode = GPUFilterMode.Nearest;
  51599. }
  51600. return filterMode;
  51601. }
  51602. /**
  51603. * Returns the bytes-per-texel value for the given GPU texture format.
  51604. *
  51605. * @private
  51606. * @param {string} format - The GPU texture format.
  51607. * @return {number} The bytes-per-texel.
  51608. */
  51609. _getBytesPerTexel( format ) {
  51610. // 8-bit formats
  51611. if ( format === GPUTextureFormat.R8Unorm ||
  51612. format === GPUTextureFormat.R8Snorm ||
  51613. format === GPUTextureFormat.R8Uint ||
  51614. format === GPUTextureFormat.R8Sint ) return 1;
  51615. // 16-bit formats
  51616. if ( format === GPUTextureFormat.R16Uint ||
  51617. format === GPUTextureFormat.R16Sint ||
  51618. format === GPUTextureFormat.R16Float ||
  51619. format === GPUTextureFormat.RG8Unorm ||
  51620. format === GPUTextureFormat.RG8Snorm ||
  51621. format === GPUTextureFormat.RG8Uint ||
  51622. format === GPUTextureFormat.RG8Sint ) return 2;
  51623. // 32-bit formats
  51624. if ( format === GPUTextureFormat.R32Uint ||
  51625. format === GPUTextureFormat.R32Sint ||
  51626. format === GPUTextureFormat.R32Float ||
  51627. format === GPUTextureFormat.RG16Uint ||
  51628. format === GPUTextureFormat.RG16Sint ||
  51629. format === GPUTextureFormat.RG16Float ||
  51630. format === GPUTextureFormat.RGBA8Unorm ||
  51631. format === GPUTextureFormat.RGBA8UnormSRGB ||
  51632. format === GPUTextureFormat.RGBA8Snorm ||
  51633. format === GPUTextureFormat.RGBA8Uint ||
  51634. format === GPUTextureFormat.RGBA8Sint ||
  51635. format === GPUTextureFormat.BGRA8Unorm ||
  51636. format === GPUTextureFormat.BGRA8UnormSRGB ||
  51637. // Packed 32-bit formats
  51638. format === GPUTextureFormat.RGB9E5UFloat ||
  51639. format === GPUTextureFormat.RGB10A2Unorm ||
  51640. format === GPUTextureFormat.RG11B10UFloat ||
  51641. format === GPUTextureFormat.Depth32Float ||
  51642. format === GPUTextureFormat.Depth24Plus ||
  51643. format === GPUTextureFormat.Depth24PlusStencil8 ||
  51644. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  51645. // 64-bit formats
  51646. if ( format === GPUTextureFormat.RG32Uint ||
  51647. format === GPUTextureFormat.RG32Sint ||
  51648. format === GPUTextureFormat.RG32Float ||
  51649. format === GPUTextureFormat.RGBA16Uint ||
  51650. format === GPUTextureFormat.RGBA16Sint ||
  51651. format === GPUTextureFormat.RGBA16Float ) return 8;
  51652. // 128-bit formats
  51653. if ( format === GPUTextureFormat.RGBA32Uint ||
  51654. format === GPUTextureFormat.RGBA32Sint ||
  51655. format === GPUTextureFormat.RGBA32Float ) return 16;
  51656. }
  51657. /**
  51658. * Returns the corresponding typed array type for the given GPU texture format.
  51659. *
  51660. * @private
  51661. * @param {string} format - The GPU texture format.
  51662. * @return {TypedArray.constructor} The typed array type.
  51663. */
  51664. _getTypedArrayType( format ) {
  51665. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  51666. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  51667. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  51668. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  51669. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  51670. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  51671. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  51672. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  51673. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  51674. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  51675. if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return Uint8Array;
  51676. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  51677. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  51678. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  51679. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  51680. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  51681. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  51682. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  51683. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  51684. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  51685. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  51686. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  51687. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  51688. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  51689. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  51690. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  51691. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  51692. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  51693. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  51694. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  51695. if ( format === GPUTextureFormat.BGRA8Unorm || format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  51696. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  51697. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  51698. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  51699. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  51700. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  51701. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  51702. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  51703. }
  51704. /**
  51705. * Returns the GPU dimensions for the given texture.
  51706. *
  51707. * @private
  51708. * @param {Texture} texture - The texture.
  51709. * @return {string} The GPU dimension.
  51710. */
  51711. _getDimension( texture ) {
  51712. let dimension;
  51713. if ( texture.is3DTexture || texture.isData3DTexture ) {
  51714. dimension = GPUTextureDimension.ThreeD;
  51715. } else {
  51716. dimension = GPUTextureDimension.TwoD;
  51717. }
  51718. return dimension;
  51719. }
  51720. }
  51721. /**
  51722. * Returns the GPU format for the given texture.
  51723. *
  51724. * @param {Texture} texture - The texture.
  51725. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  51726. * It is not necessary to apply the device for most formats.
  51727. * @return {string} The GPU format.
  51728. */
  51729. function getFormat( texture, device = null ) {
  51730. const format = texture.format;
  51731. const type = texture.type;
  51732. const colorSpace = texture.colorSpace;
  51733. const transfer = ColorManagement.getTransfer( colorSpace );
  51734. let formatGPU;
  51735. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  51736. switch ( format ) {
  51737. case RGB_S3TC_DXT1_Format:
  51738. case RGBA_S3TC_DXT1_Format:
  51739. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  51740. break;
  51741. case RGBA_S3TC_DXT3_Format:
  51742. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  51743. break;
  51744. case RGBA_S3TC_DXT5_Format:
  51745. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  51746. break;
  51747. case RED_RGTC1_Format:
  51748. formatGPU = GPUTextureFormat.BC4RUnorm;
  51749. break;
  51750. case SIGNED_RED_RGTC1_Format:
  51751. formatGPU = GPUTextureFormat.BC4RSnorm;
  51752. break;
  51753. case RED_GREEN_RGTC2_Format:
  51754. formatGPU = GPUTextureFormat.BC5RGUnorm;
  51755. break;
  51756. case SIGNED_RED_GREEN_RGTC2_Format:
  51757. formatGPU = GPUTextureFormat.BC5RGSnorm;
  51758. break;
  51759. case RGBA_BPTC_Format:
  51760. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC7RGBAUnormSRGB : GPUTextureFormat.BC7RGBAUnorm;
  51761. break;
  51762. case RGB_ETC2_Format:
  51763. case RGB_ETC1_Format:
  51764. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  51765. break;
  51766. case RGBA_ETC2_EAC_Format:
  51767. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  51768. break;
  51769. case R11_EAC_Format:
  51770. formatGPU = GPUTextureFormat.EACR11Unorm;
  51771. break;
  51772. case SIGNED_R11_EAC_Format:
  51773. formatGPU = GPUTextureFormat.EACR11Snorm;
  51774. break;
  51775. case RG11_EAC_Format:
  51776. formatGPU = GPUTextureFormat.EACRG11Unorm;
  51777. break;
  51778. case SIGNED_RG11_EAC_Format:
  51779. formatGPU = GPUTextureFormat.EACRG11Snorm;
  51780. break;
  51781. case RGBA_ASTC_4x4_Format:
  51782. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  51783. break;
  51784. case RGBA_ASTC_5x4_Format:
  51785. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  51786. break;
  51787. case RGBA_ASTC_5x5_Format:
  51788. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  51789. break;
  51790. case RGBA_ASTC_6x5_Format:
  51791. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  51792. break;
  51793. case RGBA_ASTC_6x6_Format:
  51794. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  51795. break;
  51796. case RGBA_ASTC_8x5_Format:
  51797. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  51798. break;
  51799. case RGBA_ASTC_8x6_Format:
  51800. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  51801. break;
  51802. case RGBA_ASTC_8x8_Format:
  51803. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  51804. break;
  51805. case RGBA_ASTC_10x5_Format:
  51806. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  51807. break;
  51808. case RGBA_ASTC_10x6_Format:
  51809. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  51810. break;
  51811. case RGBA_ASTC_10x8_Format:
  51812. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  51813. break;
  51814. case RGBA_ASTC_10x10_Format:
  51815. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  51816. break;
  51817. case RGBA_ASTC_12x10_Format:
  51818. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  51819. break;
  51820. case RGBA_ASTC_12x12_Format:
  51821. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  51822. break;
  51823. case RGBAFormat:
  51824. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  51825. break;
  51826. default:
  51827. error( 'WebGPURenderer: Unsupported texture format.', format );
  51828. }
  51829. } else {
  51830. switch ( format ) {
  51831. case RGBAFormat:
  51832. switch ( type ) {
  51833. case ByteType:
  51834. formatGPU = GPUTextureFormat.RGBA8Snorm;
  51835. break;
  51836. case ShortType:
  51837. formatGPU = GPUTextureFormat.RGBA16Sint;
  51838. break;
  51839. case UnsignedShortType:
  51840. formatGPU = GPUTextureFormat.RGBA16Uint;
  51841. break;
  51842. case UnsignedIntType:
  51843. formatGPU = GPUTextureFormat.RGBA32Uint;
  51844. break;
  51845. case IntType:
  51846. formatGPU = GPUTextureFormat.RGBA32Sint;
  51847. break;
  51848. case UnsignedByteType:
  51849. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  51850. break;
  51851. case HalfFloatType:
  51852. formatGPU = GPUTextureFormat.RGBA16Float;
  51853. break;
  51854. case FloatType:
  51855. formatGPU = GPUTextureFormat.RGBA32Float;
  51856. break;
  51857. default:
  51858. error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  51859. }
  51860. break;
  51861. case RGBFormat:
  51862. switch ( type ) {
  51863. case UnsignedInt5999Type:
  51864. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  51865. break;
  51866. case UnsignedInt101111Type:
  51867. formatGPU = GPUTextureFormat.RG11B10UFloat;
  51868. break;
  51869. default:
  51870. error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  51871. }
  51872. break;
  51873. case RedFormat:
  51874. switch ( type ) {
  51875. case ByteType:
  51876. formatGPU = GPUTextureFormat.R8Snorm;
  51877. break;
  51878. case ShortType:
  51879. formatGPU = GPUTextureFormat.R16Sint;
  51880. break;
  51881. case UnsignedShortType:
  51882. formatGPU = GPUTextureFormat.R16Uint;
  51883. break;
  51884. case UnsignedIntType:
  51885. formatGPU = GPUTextureFormat.R32Uint;
  51886. break;
  51887. case IntType:
  51888. formatGPU = GPUTextureFormat.R32Sint;
  51889. break;
  51890. case UnsignedByteType:
  51891. formatGPU = GPUTextureFormat.R8Unorm;
  51892. break;
  51893. case HalfFloatType:
  51894. formatGPU = GPUTextureFormat.R16Float;
  51895. break;
  51896. case FloatType:
  51897. formatGPU = GPUTextureFormat.R32Float;
  51898. break;
  51899. default:
  51900. error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  51901. }
  51902. break;
  51903. case RGFormat:
  51904. switch ( type ) {
  51905. case ByteType:
  51906. formatGPU = GPUTextureFormat.RG8Snorm;
  51907. break;
  51908. case ShortType:
  51909. formatGPU = GPUTextureFormat.RG16Sint;
  51910. break;
  51911. case UnsignedShortType:
  51912. formatGPU = GPUTextureFormat.RG16Uint;
  51913. break;
  51914. case UnsignedIntType:
  51915. formatGPU = GPUTextureFormat.RG32Uint;
  51916. break;
  51917. case IntType:
  51918. formatGPU = GPUTextureFormat.RG32Sint;
  51919. break;
  51920. case UnsignedByteType:
  51921. formatGPU = GPUTextureFormat.RG8Unorm;
  51922. break;
  51923. case HalfFloatType:
  51924. formatGPU = GPUTextureFormat.RG16Float;
  51925. break;
  51926. case FloatType:
  51927. formatGPU = GPUTextureFormat.RG32Float;
  51928. break;
  51929. default:
  51930. error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  51931. }
  51932. break;
  51933. case DepthFormat:
  51934. switch ( type ) {
  51935. case UnsignedShortType:
  51936. formatGPU = GPUTextureFormat.Depth16Unorm;
  51937. break;
  51938. case UnsignedIntType:
  51939. formatGPU = GPUTextureFormat.Depth24Plus;
  51940. break;
  51941. case FloatType:
  51942. formatGPU = GPUTextureFormat.Depth32Float;
  51943. break;
  51944. default:
  51945. error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  51946. }
  51947. break;
  51948. case DepthStencilFormat:
  51949. switch ( type ) {
  51950. case UnsignedInt248Type:
  51951. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  51952. break;
  51953. case FloatType:
  51954. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  51955. error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  51956. }
  51957. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  51958. break;
  51959. default:
  51960. error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  51961. }
  51962. break;
  51963. case RedIntegerFormat:
  51964. switch ( type ) {
  51965. case IntType:
  51966. formatGPU = GPUTextureFormat.R32Sint;
  51967. break;
  51968. case UnsignedIntType:
  51969. formatGPU = GPUTextureFormat.R32Uint;
  51970. break;
  51971. default:
  51972. error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  51973. }
  51974. break;
  51975. case RGIntegerFormat:
  51976. switch ( type ) {
  51977. case IntType:
  51978. formatGPU = GPUTextureFormat.RG32Sint;
  51979. break;
  51980. case UnsignedIntType:
  51981. formatGPU = GPUTextureFormat.RG32Uint;
  51982. break;
  51983. default:
  51984. error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  51985. }
  51986. break;
  51987. case RGBAIntegerFormat:
  51988. switch ( type ) {
  51989. case IntType:
  51990. formatGPU = GPUTextureFormat.RGBA32Sint;
  51991. break;
  51992. case UnsignedIntType:
  51993. formatGPU = GPUTextureFormat.RGBA32Uint;
  51994. break;
  51995. default:
  51996. error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  51997. }
  51998. break;
  51999. default:
  52000. error( 'WebGPURenderer: Unsupported texture format.', format );
  52001. }
  52002. }
  52003. return formatGPU;
  52004. }
  52005. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  52006. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  52007. const wgslTypeLib$1 = {
  52008. 'f32': 'float',
  52009. 'i32': 'int',
  52010. 'u32': 'uint',
  52011. 'bool': 'bool',
  52012. 'vec2<f32>': 'vec2',
  52013. 'vec2<i32>': 'ivec2',
  52014. 'vec2<u32>': 'uvec2',
  52015. 'vec2<bool>': 'bvec2',
  52016. 'vec2f': 'vec2',
  52017. 'vec2i': 'ivec2',
  52018. 'vec2u': 'uvec2',
  52019. 'vec2b': 'bvec2',
  52020. 'vec3<f32>': 'vec3',
  52021. 'vec3<i32>': 'ivec3',
  52022. 'vec3<u32>': 'uvec3',
  52023. 'vec3<bool>': 'bvec3',
  52024. 'vec3f': 'vec3',
  52025. 'vec3i': 'ivec3',
  52026. 'vec3u': 'uvec3',
  52027. 'vec3b': 'bvec3',
  52028. 'vec4<f32>': 'vec4',
  52029. 'vec4<i32>': 'ivec4',
  52030. 'vec4<u32>': 'uvec4',
  52031. 'vec4<bool>': 'bvec4',
  52032. 'vec4f': 'vec4',
  52033. 'vec4i': 'ivec4',
  52034. 'vec4u': 'uvec4',
  52035. 'vec4b': 'bvec4',
  52036. 'mat2x2<f32>': 'mat2',
  52037. 'mat2x2f': 'mat2',
  52038. 'mat3x3<f32>': 'mat3',
  52039. 'mat3x3f': 'mat3',
  52040. 'mat4x4<f32>': 'mat4',
  52041. 'mat4x4f': 'mat4',
  52042. 'sampler': 'sampler',
  52043. 'texture_1d': 'texture',
  52044. 'texture_2d': 'texture',
  52045. 'texture_2d_array': 'texture',
  52046. 'texture_multisampled_2d': 'cubeTexture',
  52047. 'texture_depth_2d': 'depthTexture',
  52048. 'texture_depth_2d_array': 'depthTexture',
  52049. 'texture_depth_multisampled_2d': 'depthTexture',
  52050. 'texture_depth_cube': 'depthTexture',
  52051. 'texture_depth_cube_array': 'depthTexture',
  52052. 'texture_3d': 'texture3D',
  52053. 'texture_cube': 'cubeTexture',
  52054. 'texture_cube_array': 'cubeTexture',
  52055. 'texture_storage_1d': 'storageTexture',
  52056. 'texture_storage_2d': 'storageTexture',
  52057. 'texture_storage_2d_array': 'storageTexture',
  52058. 'texture_storage_3d': 'storageTexture'
  52059. };
  52060. const parse = ( source ) => {
  52061. source = source.trim();
  52062. const declaration = source.match( declarationRegexp );
  52063. if ( declaration !== null && declaration.length === 4 ) {
  52064. const inputsCode = declaration[ 2 ];
  52065. const propsMatches = [];
  52066. let match = null;
  52067. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  52068. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  52069. }
  52070. // Process matches to correctly pair names and types
  52071. const inputs = [];
  52072. for ( let i = 0; i < propsMatches.length; i ++ ) {
  52073. const { name, type } = propsMatches[ i ];
  52074. let resolvedType = type;
  52075. if ( resolvedType.startsWith( 'ptr' ) ) {
  52076. resolvedType = 'pointer';
  52077. } else {
  52078. if ( resolvedType.startsWith( 'texture' ) ) {
  52079. resolvedType = type.split( '<' )[ 0 ];
  52080. }
  52081. resolvedType = wgslTypeLib$1[ resolvedType ];
  52082. }
  52083. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  52084. }
  52085. const blockCode = source.substring( declaration[ 0 ].length );
  52086. const outputType = declaration[ 3 ] || 'void';
  52087. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  52088. const type = wgslTypeLib$1[ outputType ] || outputType;
  52089. return {
  52090. type,
  52091. inputs,
  52092. name,
  52093. inputsCode,
  52094. blockCode,
  52095. outputType
  52096. };
  52097. } else {
  52098. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  52099. }
  52100. };
  52101. /**
  52102. * This class represents a WSL node function.
  52103. *
  52104. * @augments NodeFunction
  52105. */
  52106. class WGSLNodeFunction extends NodeFunction {
  52107. /**
  52108. * Constructs a new WGSL node function.
  52109. *
  52110. * @param {string} source - The WGSL source.
  52111. */
  52112. constructor( source ) {
  52113. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  52114. super( type, inputs, name );
  52115. this.inputsCode = inputsCode;
  52116. this.blockCode = blockCode;
  52117. this.outputType = outputType;
  52118. }
  52119. /**
  52120. * This method returns the WGSL code of the node function.
  52121. *
  52122. * @param {string} [name=this.name] - The function's name.
  52123. * @return {string} The shader code.
  52124. */
  52125. getCode( name = this.name ) {
  52126. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  52127. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  52128. }
  52129. }
  52130. /**
  52131. * A WGSL node parser.
  52132. *
  52133. * @augments NodeParser
  52134. */
  52135. class WGSLNodeParser extends NodeParser {
  52136. /**
  52137. * The method parses the given WGSL code an returns a node function.
  52138. *
  52139. * @param {string} source - The WGSL code.
  52140. * @return {WGSLNodeFunction} A node function.
  52141. */
  52142. parseFunction( source ) {
  52143. return new WGSLNodeFunction( source );
  52144. }
  52145. }
  52146. const accessNames = {
  52147. [ NodeAccess.READ_ONLY ]: 'read',
  52148. [ NodeAccess.WRITE_ONLY ]: 'write',
  52149. [ NodeAccess.READ_WRITE ]: 'read_write'
  52150. };
  52151. const wrapNames = {
  52152. [ RepeatWrapping ]: 'repeat',
  52153. [ ClampToEdgeWrapping ]: 'clamp',
  52154. [ MirroredRepeatWrapping ]: 'mirror'
  52155. };
  52156. const gpuShaderStageLib = {
  52157. 'vertex': GPUShaderStage.VERTEX,
  52158. 'fragment': GPUShaderStage.FRAGMENT,
  52159. 'compute': GPUShaderStage.COMPUTE
  52160. };
  52161. const supports = {
  52162. instance: true,
  52163. swizzleAssign: false,
  52164. storageBuffer: true
  52165. };
  52166. const wgslFnOpLib = {
  52167. '^^': 'tsl_xor'
  52168. };
  52169. const wgslTypeLib = {
  52170. float: 'f32',
  52171. int: 'i32',
  52172. uint: 'u32',
  52173. bool: 'bool',
  52174. color: 'vec3<f32>',
  52175. vec2: 'vec2<f32>',
  52176. ivec2: 'vec2<i32>',
  52177. uvec2: 'vec2<u32>',
  52178. bvec2: 'vec2<bool>',
  52179. vec3: 'vec3<f32>',
  52180. ivec3: 'vec3<i32>',
  52181. uvec3: 'vec3<u32>',
  52182. bvec3: 'vec3<bool>',
  52183. vec4: 'vec4<f32>',
  52184. ivec4: 'vec4<i32>',
  52185. uvec4: 'vec4<u32>',
  52186. bvec4: 'vec4<bool>',
  52187. mat2: 'mat2x2<f32>',
  52188. mat3: 'mat3x3<f32>',
  52189. mat4: 'mat4x4<f32>'
  52190. };
  52191. const wgslCodeCache = {};
  52192. const wgslPolyfill = {
  52193. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  52194. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  52195. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  52196. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  52197. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  52198. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  52199. 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 ); }' ),
  52200. 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 ); }' ),
  52201. 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 ); }' ),
  52202. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  52203. 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 ); }' ),
  52204. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  52205. biquadraticTexture: new CodeNode( /* wgsl */`
  52206. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  52207. let res = vec2f( iRes );
  52208. let uvScaled = coord * res;
  52209. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  52210. // https://www.shadertoy.com/view/WtyXRy
  52211. let uv = uvWrapping - 0.5;
  52212. let iuv = floor( uv );
  52213. let f = fract( uv );
  52214. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  52215. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  52216. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  52217. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  52218. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  52219. }
  52220. ` )
  52221. };
  52222. const wgslMethods = {
  52223. dFdx: 'dpdx',
  52224. dFdy: '- dpdy',
  52225. mod_float: 'tsl_mod_float',
  52226. mod_vec2: 'tsl_mod_vec2',
  52227. mod_vec3: 'tsl_mod_vec3',
  52228. mod_vec4: 'tsl_mod_vec4',
  52229. equals_bool: 'tsl_equals_bool',
  52230. equals_bvec2: 'tsl_equals_bvec2',
  52231. equals_bvec3: 'tsl_equals_bvec3',
  52232. equals_bvec4: 'tsl_equals_bvec4',
  52233. inversesqrt: 'inverseSqrt',
  52234. bitcast: 'bitcast<f32>',
  52235. floatpack_snorm_2x16: 'pack2x16snorm',
  52236. floatpack_unorm_2x16: 'pack2x16unorm',
  52237. floatpack_float16_2x16: 'pack2x16float',
  52238. floatunpack_snorm_2x16: 'unpack2x16snorm',
  52239. floatunpack_unorm_2x16: 'unpack2x16unorm',
  52240. floatunpack_float16_2x16: 'unpack2x16float'
  52241. };
  52242. //
  52243. let diagnostics = '';
  52244. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  52245. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  52246. }
  52247. /**
  52248. * A node builder targeting WGSL.
  52249. *
  52250. * This module generates WGSL shader code from node materials and also
  52251. * generates the respective bindings and vertex buffer definitions. These
  52252. * data are later used by the renderer to create render and compute pipelines
  52253. * for render objects.
  52254. *
  52255. * @augments NodeBuilder
  52256. */
  52257. class WGSLNodeBuilder extends NodeBuilder {
  52258. /**
  52259. * Constructs a new WGSL node builder renderer.
  52260. *
  52261. * @param {Object3D} object - The 3D object.
  52262. * @param {Renderer} renderer - The renderer.
  52263. */
  52264. constructor( object, renderer ) {
  52265. super( object, renderer, new WGSLNodeParser() );
  52266. /**
  52267. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  52268. * another dictionary which manages UBOs per group ('render','frame','object').
  52269. *
  52270. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  52271. */
  52272. this.uniformGroups = {};
  52273. /**
  52274. * A dictionary that holds for each shader stage a Map of builtins.
  52275. *
  52276. * @type {Object<string,Map<string,Object>>}
  52277. */
  52278. this.builtins = {};
  52279. /**
  52280. * A dictionary that holds for each shader stage a Set of directives.
  52281. *
  52282. * @type {Object<string,Set<string>>}
  52283. */
  52284. this.directives = {};
  52285. /**
  52286. * A map for managing scope arrays. Only relevant for when using
  52287. * {@link WorkgroupInfoNode} in context of compute shaders.
  52288. *
  52289. * @type {Map<string,Object>}
  52290. */
  52291. this.scopedArrays = new Map();
  52292. }
  52293. /**
  52294. * Generates the WGSL snippet for sampled textures.
  52295. *
  52296. * @private
  52297. * @param {Texture} texture - The texture.
  52298. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52299. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52300. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52301. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52302. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52303. * @return {string} The WGSL snippet.
  52304. */
  52305. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52306. if ( shaderStage === 'fragment' ) {
  52307. if ( depthSnippet ) {
  52308. if ( offsetSnippet ) {
  52309. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ offsetSnippet } )`;
  52310. }
  52311. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  52312. } else {
  52313. if ( offsetSnippet ) {
  52314. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ offsetSnippet } )`;
  52315. }
  52316. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  52317. }
  52318. } else {
  52319. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  52320. }
  52321. }
  52322. /**
  52323. * Generates the WGSL snippet when sampling textures with explicit mip level.
  52324. *
  52325. * @private
  52326. * @param {Texture} texture - The texture.
  52327. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52328. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52329. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52330. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52331. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52332. * @return {string} The WGSL snippet.
  52333. */
  52334. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  52335. if ( this.isUnfilterable( texture ) === false ) {
  52336. if ( offsetSnippet ) {
  52337. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  52338. }
  52339. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  52340. } else if ( this.isFilteredTexture( texture ) ) {
  52341. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  52342. } else {
  52343. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  52344. }
  52345. }
  52346. /**
  52347. * Generates a wrap function used in context of textures.
  52348. *
  52349. * @param {Texture} texture - The texture to generate the function for.
  52350. * @return {string} The name of the generated function.
  52351. */
  52352. generateWrapFunction( texture ) {
  52353. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.is3DTexture || texture.isData3DTexture ? '3d' : '2d' }T`;
  52354. let nodeCode = wgslCodeCache[ functionName ];
  52355. if ( nodeCode === undefined ) {
  52356. const includes = [];
  52357. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  52358. const coordType = texture.is3DTexture || texture.isData3DTexture ? 'vec3f' : 'vec2f';
  52359. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  52360. const addWrapSnippet = ( wrap, axis ) => {
  52361. if ( wrap === RepeatWrapping ) {
  52362. includes.push( wgslPolyfill.repeatWrapping_float );
  52363. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  52364. } else if ( wrap === ClampToEdgeWrapping ) {
  52365. includes.push( wgslPolyfill.clampWrapping_float );
  52366. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  52367. } else if ( wrap === MirroredRepeatWrapping ) {
  52368. includes.push( wgslPolyfill.mirrorWrapping_float );
  52369. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  52370. } else {
  52371. code += `\t\tcoord.${ axis }`;
  52372. warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  52373. }
  52374. };
  52375. addWrapSnippet( texture.wrapS, 'x' );
  52376. code += ',\n';
  52377. addWrapSnippet( texture.wrapT, 'y' );
  52378. if ( texture.is3DTexture || texture.isData3DTexture ) {
  52379. code += ',\n';
  52380. addWrapSnippet( texture.wrapR, 'z' );
  52381. }
  52382. code += '\n\t);\n\n}\n';
  52383. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  52384. }
  52385. nodeCode.build( this );
  52386. return functionName;
  52387. }
  52388. /**
  52389. * Generates the array declaration string.
  52390. *
  52391. * @param {string} type - The type.
  52392. * @param {?number} [count] - The count.
  52393. * @return {string} The generated value as a shader string.
  52394. */
  52395. generateArrayDeclaration( type, count ) {
  52396. return `array< ${ this.getType( type ) }, ${ count } >`;
  52397. }
  52398. /**
  52399. * Generates a WGSL variable that holds the texture dimension of the given texture.
  52400. * It also returns information about the number of layers (elements) of an arrayed
  52401. * texture as well as the cube face count of cube textures.
  52402. *
  52403. * @param {Texture} texture - The texture to generate the function for.
  52404. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  52405. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52406. * @return {string} The name of the dimension variable.
  52407. */
  52408. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  52409. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  52410. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  52411. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  52412. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  52413. let textureDimensionsParams;
  52414. let dimensionType;
  52415. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  52416. const isMultisampled = primarySamples > 1;
  52417. if ( texture.is3DTexture || texture.isData3DTexture ) {
  52418. dimensionType = 'vec3<u32>';
  52419. } else {
  52420. // Regular 2D textures, depth textures, etc.
  52421. dimensionType = 'vec2<u32>';
  52422. }
  52423. // Build parameters string based on texture type and multisampling
  52424. if ( isMultisampled || texture.isStorageTexture ) {
  52425. textureDimensionsParams = textureProperty;
  52426. } else {
  52427. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  52428. }
  52429. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  52430. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  52431. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.is3DTexture || texture.isData3DTexture ) {
  52432. textureData.arrayLayerCount = new VarNode(
  52433. new ExpressionNode(
  52434. `textureNumLayers(${textureProperty})`,
  52435. 'u32'
  52436. )
  52437. );
  52438. }
  52439. // For cube textures, we know it's always 6 faces
  52440. if ( texture.isTextureCube ) {
  52441. textureData.cubeFaceCount = new VarNode(
  52442. new ExpressionNode( '6u', 'u32' )
  52443. );
  52444. }
  52445. }
  52446. return textureDimensionNode.build( this );
  52447. }
  52448. /**
  52449. * Generates the WGSL snippet for a manual filtered texture.
  52450. *
  52451. * @param {Texture} texture - The texture.
  52452. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52453. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52454. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52455. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52456. * @return {string} The WGSL snippet.
  52457. */
  52458. generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet = '0u' ) {
  52459. this._include( 'biquadraticTexture' );
  52460. const wrapFunction = this.generateWrapFunction( texture );
  52461. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  52462. if ( offsetSnippet ) {
  52463. uvSnippet = `${ uvSnippet } + vec2<f32>(${ offsetSnippet }) / ${ textureDimension }`;
  52464. }
  52465. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  52466. }
  52467. /**
  52468. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  52469. * Since it's a lookup, no sampling or filtering is applied.
  52470. *
  52471. * @param {Texture} texture - The texture.
  52472. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52473. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52474. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52475. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52476. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52477. * @return {string} The WGSL snippet.
  52478. */
  52479. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet = '0u' ) {
  52480. const wrapFunction = this.generateWrapFunction( texture );
  52481. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  52482. const vecType = texture.is3DTexture || texture.isData3DTexture ? 'vec3' : 'vec2';
  52483. if ( offsetSnippet ) {
  52484. uvSnippet = `${ uvSnippet } + ${ vecType }<f32>(${ offsetSnippet }) / ${ vecType }<f32>( ${ textureDimension } )`;
  52485. }
  52486. const coordSnippet = `${ vecType }<u32>( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) )`;
  52487. return this.generateTextureLoad( texture, textureProperty, coordSnippet, levelSnippet, depthSnippet, null );
  52488. }
  52489. /**
  52490. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  52491. *
  52492. * @param {Texture} texture - The texture.
  52493. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52494. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52495. * @param {?string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52496. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52497. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52498. * @return {string} The WGSL snippet.
  52499. */
  52500. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  52501. if ( levelSnippet === null ) levelSnippet = '0u';
  52502. if ( offsetSnippet ) {
  52503. uvIndexSnippet = `${ uvIndexSnippet } + ${ offsetSnippet }`;
  52504. }
  52505. let snippet;
  52506. if ( depthSnippet ) {
  52507. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  52508. } else {
  52509. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  52510. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  52511. snippet += '.x';
  52512. }
  52513. }
  52514. return snippet;
  52515. }
  52516. /**
  52517. * Generates the WGSL snippet that writes a single texel to a texture.
  52518. *
  52519. * @param {Texture} texture - The texture.
  52520. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52521. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52522. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52523. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  52524. * @return {string} The WGSL snippet.
  52525. */
  52526. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  52527. let snippet;
  52528. if ( depthSnippet ) {
  52529. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  52530. } else {
  52531. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  52532. }
  52533. return snippet;
  52534. }
  52535. /**
  52536. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  52537. *
  52538. * @param {Texture} texture - The texture.
  52539. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  52540. */
  52541. isSampleCompare( texture ) {
  52542. return texture.isDepthTexture === true && texture.compareFunction !== null;
  52543. }
  52544. /**
  52545. * Returns `true` if the given texture is unfilterable.
  52546. *
  52547. * @param {Texture} texture - The texture.
  52548. * @return {boolean} Whether the given texture is unfilterable or not.
  52549. */
  52550. isUnfilterable( texture ) {
  52551. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  52552. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  52553. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  52554. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  52555. }
  52556. /**
  52557. * Generates the WGSL snippet for sampling/loading the given texture.
  52558. *
  52559. * @param {Texture} texture - The texture.
  52560. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52561. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52562. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52563. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52564. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52565. * @return {string} The WGSL snippet.
  52566. */
  52567. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52568. let snippet = null;
  52569. if ( this.isUnfilterable( texture ) ) {
  52570. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, '0', shaderStage );
  52571. } else {
  52572. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage );
  52573. }
  52574. return snippet;
  52575. }
  52576. /**
  52577. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  52578. *
  52579. * @param {Texture} texture - The texture.
  52580. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52581. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52582. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  52583. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52584. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52585. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52586. * @return {string} The WGSL snippet.
  52587. */
  52588. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52589. if ( shaderStage === 'fragment' ) {
  52590. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  52591. if ( offsetSnippet ) {
  52592. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  52593. }
  52594. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  52595. } else {
  52596. error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  52597. }
  52598. }
  52599. /**
  52600. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  52601. * against a reference value.
  52602. *
  52603. * @param {Texture} texture - The texture.
  52604. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52605. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52606. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  52607. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52608. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52609. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52610. * @return {string} The WGSL snippet.
  52611. */
  52612. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52613. if ( shaderStage === 'fragment' ) {
  52614. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  52615. if ( offsetSnippet ) {
  52616. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  52617. }
  52618. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  52619. }
  52620. if ( offsetSnippet ) {
  52621. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  52622. }
  52623. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  52624. } else {
  52625. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  52626. }
  52627. }
  52628. /**
  52629. * Generates the WGSL snippet when sampling textures with explicit mip level.
  52630. *
  52631. * @param {Texture} texture - The texture.
  52632. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52633. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52634. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52635. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52636. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52637. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52638. * @return {string} The WGSL snippet.
  52639. */
  52640. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  52641. if ( this.isUnfilterable( texture ) === false ) {
  52642. if ( offsetSnippet ) {
  52643. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  52644. }
  52645. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  52646. } else if ( this.isFilteredTexture( texture ) ) {
  52647. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  52648. } else {
  52649. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  52650. }
  52651. }
  52652. /**
  52653. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  52654. *
  52655. * @param {Texture} texture - The texture.
  52656. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52657. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52658. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  52659. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52660. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52661. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52662. * @return {string} The WGSL snippet.
  52663. */
  52664. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52665. if ( shaderStage === 'fragment' ) {
  52666. if ( offsetSnippet ) {
  52667. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  52668. }
  52669. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  52670. } else {
  52671. error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  52672. }
  52673. }
  52674. /**
  52675. * Returns a WGSL snippet that represents the property name of the given node.
  52676. *
  52677. * @param {Node} node - The node.
  52678. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52679. * @return {string} The property name.
  52680. */
  52681. getPropertyName( node, shaderStage = this.shaderStage ) {
  52682. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  52683. if ( shaderStage === 'vertex' ) {
  52684. return `varyings.${ node.name }`;
  52685. }
  52686. } else if ( node.isNodeUniform === true ) {
  52687. const name = node.name;
  52688. const type = node.type;
  52689. if ( type === 'texture' || type === 'cubeTexture' || type === 'cubeDepthTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  52690. return name;
  52691. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  52692. if ( this.isCustomStruct( node ) ) {
  52693. return name;
  52694. }
  52695. return name + '.value';
  52696. } else {
  52697. return node.groupNode.name + '.' + name;
  52698. }
  52699. }
  52700. return super.getPropertyName( node );
  52701. }
  52702. /**
  52703. * Returns the output struct name.
  52704. *
  52705. * @return {string} The name of the output struct.
  52706. */
  52707. getOutputStructName() {
  52708. return 'output';
  52709. }
  52710. /**
  52711. * Returns the native shader operator name for a given generic name.
  52712. *
  52713. * @param {string} op - The operator name to resolve.
  52714. * @return {?string} The resolved operator name.
  52715. */
  52716. getFunctionOperator( op ) {
  52717. const fnOp = wgslFnOpLib[ op ];
  52718. if ( fnOp !== undefined ) {
  52719. this._include( fnOp );
  52720. return fnOp;
  52721. }
  52722. return null;
  52723. }
  52724. /**
  52725. * Returns the node access for the given node and shader stage.
  52726. *
  52727. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  52728. * @param {string} shaderStage - The shader stage.
  52729. * @return {string} The node access.
  52730. */
  52731. getNodeAccess( node, shaderStage ) {
  52732. if ( shaderStage !== 'compute' ) {
  52733. if ( node.isAtomic === true ) {
  52734. warn( 'WebGPURenderer: Atomic operations are only supported in compute shaders.' );
  52735. return NodeAccess.READ_WRITE;
  52736. }
  52737. return NodeAccess.READ_ONLY;
  52738. }
  52739. return node.access;
  52740. }
  52741. /**
  52742. * Returns A WGSL snippet representing the storage access.
  52743. *
  52744. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  52745. * @param {string} shaderStage - The shader stage.
  52746. * @return {string} The WGSL snippet representing the storage access.
  52747. */
  52748. getStorageAccess( node, shaderStage ) {
  52749. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  52750. }
  52751. /**
  52752. * This method is one of the more important ones since it's responsible
  52753. * for generating a matching binding instance for the given uniform node.
  52754. *
  52755. * These bindings are later used in the renderer to create bind groups
  52756. * and layouts.
  52757. *
  52758. * @param {UniformNode} node - The uniform node.
  52759. * @param {string} type - The node data type.
  52760. * @param {string} shaderStage - The shader stage.
  52761. * @param {?string} [name=null] - An optional uniform name.
  52762. * @return {NodeUniform} The node uniform object.
  52763. */
  52764. getUniformFromNode( node, type, shaderStage, name = null ) {
  52765. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  52766. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  52767. if ( nodeData.uniformGPU === undefined ) {
  52768. let uniformGPU;
  52769. const group = node.groupNode;
  52770. const groupName = group.name;
  52771. const bindings = this.getBindGroupArray( groupName, shaderStage );
  52772. if ( type === 'texture' || type === 'cubeTexture' || type === 'cubeDepthTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  52773. let texture = null;
  52774. const access = this.getNodeAccess( node, shaderStage );
  52775. if ( type === 'texture' || type === 'storageTexture' ) {
  52776. if ( node.value.is3DTexture === true ) {
  52777. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  52778. } else {
  52779. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  52780. }
  52781. } else if ( type === 'cubeTexture' || type === 'cubeDepthTexture' ) {
  52782. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  52783. } else if ( type === 'texture3D' ) {
  52784. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  52785. }
  52786. texture.store = node.isStorageTextureNode === true;
  52787. texture.mipLevel = texture.store ? node.mipLevel : 0;
  52788. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  52789. if ( this.isUnfilterable( node.value ) === false && texture.store === false ) {
  52790. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  52791. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  52792. bindings.push( sampler, texture );
  52793. uniformGPU = [ sampler, texture ];
  52794. } else {
  52795. bindings.push( texture );
  52796. uniformGPU = [ texture ];
  52797. }
  52798. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  52799. const sharedData = this.getSharedDataFromNode( node );
  52800. let buffer = sharedData.buffer;
  52801. if ( buffer === undefined ) {
  52802. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  52803. buffer = new bufferClass( node, group );
  52804. sharedData.buffer = buffer;
  52805. }
  52806. buffer.setVisibility( buffer.getVisibility() | gpuShaderStageLib[ shaderStage ] );
  52807. bindings.push( buffer );
  52808. uniformGPU = buffer;
  52809. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  52810. } else {
  52811. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  52812. let uniformsGroup = uniformsStage[ groupName ];
  52813. if ( uniformsGroup === undefined ) {
  52814. uniformsGroup = new NodeUniformsGroup( groupName, group );
  52815. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  52816. uniformsStage[ groupName ] = uniformsGroup;
  52817. bindings.push( uniformsGroup );
  52818. }
  52819. uniformGPU = this.getNodeUniform( uniformNode, type );
  52820. uniformsGroup.addUniform( uniformGPU );
  52821. }
  52822. nodeData.uniformGPU = uniformGPU;
  52823. }
  52824. return uniformNode;
  52825. }
  52826. /**
  52827. * This method should be used whenever builtins are required in nodes.
  52828. * The internal builtins data structure will make sure builtins are
  52829. * defined in the WGSL source.
  52830. *
  52831. * @param {string} name - The builtin name.
  52832. * @param {string} property - The property name.
  52833. * @param {string} type - The node data type.
  52834. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52835. * @return {string} The property name.
  52836. */
  52837. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  52838. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  52839. if ( map.has( name ) === false ) {
  52840. map.set( name, {
  52841. name,
  52842. property,
  52843. type
  52844. } );
  52845. }
  52846. return property;
  52847. }
  52848. /**
  52849. * Returns `true` if the given builtin is defined in the given shader stage.
  52850. *
  52851. * @param {string} name - The builtin name.
  52852. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52853. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  52854. */
  52855. hasBuiltin( name, shaderStage = this.shaderStage ) {
  52856. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  52857. }
  52858. /**
  52859. * Returns the vertex index builtin.
  52860. *
  52861. * @return {string} The vertex index.
  52862. */
  52863. getVertexIndex() {
  52864. if ( this.shaderStage === 'vertex' ) {
  52865. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  52866. }
  52867. return 'vertexIndex';
  52868. }
  52869. /**
  52870. * Builds the given shader node.
  52871. *
  52872. * @param {ShaderNodeInternal} shaderNode - The shader node.
  52873. * @return {string} The WGSL function code.
  52874. */
  52875. buildFunctionCode( shaderNode ) {
  52876. const layout = shaderNode.layout;
  52877. const flowData = this.flowShaderNode( shaderNode );
  52878. const parameters = [];
  52879. for ( const input of layout.inputs ) {
  52880. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  52881. }
  52882. //
  52883. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  52884. ${ flowData.vars }
  52885. ${ flowData.code }
  52886. `;
  52887. if ( flowData.result ) {
  52888. code += `\treturn ${ flowData.result };\n`;
  52889. }
  52890. code += '\n}\n';
  52891. //
  52892. return code;
  52893. }
  52894. /**
  52895. * Contextually returns either the vertex stage instance index builtin
  52896. * or the linearized index of an compute invocation within a grid of workgroups.
  52897. *
  52898. * @return {string} The instance index.
  52899. */
  52900. getInstanceIndex() {
  52901. if ( this.shaderStage === 'vertex' ) {
  52902. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  52903. }
  52904. return 'instanceIndex';
  52905. }
  52906. /**
  52907. * Returns a builtin representing the index of a compute invocation within the scope of a workgroup load.
  52908. *
  52909. * @return {string} The invocation local index.
  52910. */
  52911. getInvocationLocalIndex() {
  52912. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  52913. }
  52914. /**
  52915. * Returns a builtin representing the size of a subgroup within the current shader.
  52916. *
  52917. * @return {string} The subgroup size.
  52918. */
  52919. getSubgroupSize() {
  52920. this.enableSubGroups();
  52921. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  52922. }
  52923. /**
  52924. * Returns a builtin representing the index of a compute invocation within the scope of a subgroup.
  52925. *
  52926. * @return {string} The invocation subgroup index.
  52927. */
  52928. getInvocationSubgroupIndex() {
  52929. this.enableSubGroups();
  52930. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  52931. }
  52932. /**
  52933. * Returns a builtin representing the index of a compute invocation's subgroup within its workgroup.
  52934. *
  52935. * @return {string} The subgroup index.
  52936. */
  52937. getSubgroupIndex() {
  52938. this.enableSubGroups();
  52939. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  52940. }
  52941. /**
  52942. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  52943. *
  52944. * @return {null} Null.
  52945. */
  52946. getDrawIndex() {
  52947. return null;
  52948. }
  52949. /**
  52950. * Returns the front facing builtin.
  52951. *
  52952. * @return {string} The front facing builtin.
  52953. */
  52954. getFrontFacing() {
  52955. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  52956. }
  52957. /**
  52958. * Returns the frag coord builtin.
  52959. *
  52960. * @return {string} The frag coord builtin.
  52961. */
  52962. getFragCoord() {
  52963. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  52964. }
  52965. /**
  52966. * Returns the frag depth builtin.
  52967. *
  52968. * @return {string} The frag depth builtin.
  52969. */
  52970. getFragDepth() {
  52971. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  52972. }
  52973. /**
  52974. * Returns the clip distances builtin.
  52975. *
  52976. * @return {string} The clip distances builtin.
  52977. */
  52978. getClipDistance() {
  52979. return 'varyings.hw_clip_distances';
  52980. }
  52981. /**
  52982. * Whether to flip texture data along its vertical axis or not.
  52983. *
  52984. * @return {boolean} Returns always `false` in context of WGSL.
  52985. */
  52986. isFlipY() {
  52987. return false;
  52988. }
  52989. /**
  52990. * Enables the given directive for the given shader stage.
  52991. *
  52992. * @param {string} name - The directive name.
  52993. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  52994. */
  52995. enableDirective( name, shaderStage = this.shaderStage ) {
  52996. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  52997. stage.add( name );
  52998. }
  52999. /**
  53000. * Returns the directives of the given shader stage as a WGSL string.
  53001. *
  53002. * @param {string} shaderStage - The shader stage.
  53003. * @return {string} A WGSL snippet that enables the directives of the given stage.
  53004. */
  53005. getDirectives( shaderStage ) {
  53006. const snippets = [];
  53007. const directives = this.directives[ shaderStage ];
  53008. if ( directives !== undefined ) {
  53009. for ( const directive of directives ) {
  53010. snippets.push( `enable ${directive};` );
  53011. }
  53012. }
  53013. return snippets.join( '\n' );
  53014. }
  53015. /**
  53016. * Enables the 'subgroups' directive.
  53017. */
  53018. enableSubGroups() {
  53019. this.enableDirective( 'subgroups' );
  53020. }
  53021. /**
  53022. * Enables the 'subgroups-f16' directive.
  53023. */
  53024. enableSubgroupsF16() {
  53025. this.enableDirective( 'subgroups-f16' );
  53026. }
  53027. /**
  53028. * Enables the 'clip_distances' directive.
  53029. */
  53030. enableClipDistances() {
  53031. this.enableDirective( 'clip_distances' );
  53032. }
  53033. /**
  53034. * Enables the 'f16' directive.
  53035. */
  53036. enableShaderF16() {
  53037. this.enableDirective( 'f16' );
  53038. }
  53039. /**
  53040. * Enables the 'dual_source_blending' directive.
  53041. */
  53042. enableDualSourceBlending() {
  53043. this.enableDirective( 'dual_source_blending' );
  53044. }
  53045. /**
  53046. * Enables hardware clipping.
  53047. *
  53048. * @param {string} planeCount - The clipping plane count.
  53049. */
  53050. enableHardwareClipping( planeCount ) {
  53051. this.enableClipDistances();
  53052. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  53053. }
  53054. /**
  53055. * Returns the builtins of the given shader stage as a WGSL string.
  53056. *
  53057. * @param {string} shaderStage - The shader stage.
  53058. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  53059. */
  53060. getBuiltins( shaderStage ) {
  53061. const snippets = [];
  53062. const builtins = this.builtins[ shaderStage ];
  53063. if ( builtins !== undefined ) {
  53064. for ( const { name, property, type } of builtins.values() ) {
  53065. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  53066. }
  53067. }
  53068. return snippets.join( ',\n\t' );
  53069. }
  53070. /**
  53071. * This method should be used when a new scoped buffer is used in context of
  53072. * compute shaders. It adds the array to the internal data structure which is
  53073. * later used to generate the respective WGSL.
  53074. *
  53075. * @param {string} name - The array name.
  53076. * @param {string} scope - The scope.
  53077. * @param {string} bufferType - The buffer type.
  53078. * @param {string} bufferCount - The buffer count.
  53079. * @return {string} The array name.
  53080. */
  53081. getScopedArray( name, scope, bufferType, bufferCount ) {
  53082. if ( this.scopedArrays.has( name ) === false ) {
  53083. this.scopedArrays.set( name, {
  53084. name,
  53085. scope,
  53086. bufferType,
  53087. bufferCount
  53088. } );
  53089. }
  53090. return name;
  53091. }
  53092. /**
  53093. * Returns the scoped arrays of the given shader stage as a WGSL string.
  53094. *
  53095. * @param {string} shaderStage - The shader stage.
  53096. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  53097. * Returns `undefined` when used in the vertex or fragment stage.
  53098. */
  53099. getScopedArrays( shaderStage ) {
  53100. if ( shaderStage !== 'compute' ) {
  53101. return;
  53102. }
  53103. const snippets = [];
  53104. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  53105. const type = this.getType( bufferType );
  53106. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  53107. }
  53108. return snippets.join( '\n' );
  53109. }
  53110. /**
  53111. * Returns the shader attributes of the given shader stage as a WGSL string.
  53112. *
  53113. * @param {string} shaderStage - The shader stage.
  53114. * @return {string} The WGSL snippet that defines the shader attributes.
  53115. */
  53116. getAttributes( shaderStage ) {
  53117. const snippets = [];
  53118. if ( shaderStage === 'compute' ) {
  53119. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  53120. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  53121. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  53122. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  53123. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  53124. this.enableDirective( 'subgroups', shaderStage );
  53125. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  53126. }
  53127. }
  53128. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  53129. const builtins = this.getBuiltins( 'attribute' );
  53130. if ( builtins ) snippets.push( builtins );
  53131. const attributes = this.getAttributesArray();
  53132. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  53133. const attribute = attributes[ index ];
  53134. const name = attribute.name;
  53135. const type = this.getType( attribute.type );
  53136. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  53137. }
  53138. }
  53139. return snippets.join( ',\n\t' );
  53140. }
  53141. /**
  53142. * Returns the members of the given struct type node as a WGSL string.
  53143. *
  53144. * @param {StructTypeNode} struct - The struct type node.
  53145. * @return {string} The WGSL snippet that defines the struct members.
  53146. */
  53147. getStructMembers( struct ) {
  53148. const snippets = [];
  53149. for ( const member of struct.members ) {
  53150. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  53151. let type = this.getType( member.type );
  53152. if ( member.atomic ) {
  53153. type = 'atomic< ' + type + ' >';
  53154. }
  53155. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  53156. }
  53157. if ( struct.output ) {
  53158. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  53159. }
  53160. return snippets.join( ',\n' );
  53161. }
  53162. /**
  53163. * Returns the structs of the given shader stage as a WGSL string.
  53164. *
  53165. * @param {string} shaderStage - The shader stage.
  53166. * @return {string} The WGSL snippet that defines the structs.
  53167. */
  53168. getStructs( shaderStage ) {
  53169. let result = '';
  53170. const structs = this.structs[ shaderStage ];
  53171. if ( structs.length > 0 ) {
  53172. const snippets = [];
  53173. for ( const struct of structs ) {
  53174. let snippet = `struct ${ struct.name } {\n`;
  53175. snippet += this.getStructMembers( struct );
  53176. snippet += '\n};';
  53177. snippets.push( snippet );
  53178. }
  53179. result = '\n' + snippets.join( '\n\n' ) + '\n';
  53180. }
  53181. return result;
  53182. }
  53183. /**
  53184. * Returns a WGSL string representing a variable.
  53185. *
  53186. * @param {string} type - The variable's type.
  53187. * @param {string} name - The variable's name.
  53188. * @param {?number} [count=null] - The array length.
  53189. * @return {string} The WGSL snippet that defines a variable.
  53190. */
  53191. getVar( type, name, count = null ) {
  53192. let snippet = `var ${ name } : `;
  53193. if ( count !== null ) {
  53194. snippet += this.generateArrayDeclaration( type, count );
  53195. } else {
  53196. snippet += this.getType( type );
  53197. }
  53198. return snippet;
  53199. }
  53200. /**
  53201. * Returns the variables of the given shader stage as a WGSL string.
  53202. *
  53203. * @param {string} shaderStage - The shader stage.
  53204. * @return {string} The WGSL snippet that defines the variables.
  53205. */
  53206. getVars( shaderStage ) {
  53207. const snippets = [];
  53208. const vars = this.vars[ shaderStage ];
  53209. if ( vars !== undefined ) {
  53210. for ( const variable of vars ) {
  53211. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  53212. }
  53213. }
  53214. return `\n${ snippets.join( '\n' ) }\n`;
  53215. }
  53216. /**
  53217. * Returns the varyings of the given shader stage as a WGSL string.
  53218. *
  53219. * @param {string} shaderStage - The shader stage.
  53220. * @return {string} The WGSL snippet that defines the varyings.
  53221. */
  53222. getVaryings( shaderStage ) {
  53223. const snippets = [];
  53224. if ( shaderStage === 'vertex' ) {
  53225. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  53226. }
  53227. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  53228. const varyings = this.varyings;
  53229. const vars = this.vars[ shaderStage ];
  53230. for ( let index = 0; index < varyings.length; index ++ ) {
  53231. const varying = varyings[ index ];
  53232. if ( varying.needsInterpolation ) {
  53233. let attributesSnippet = `@location( ${index} )`;
  53234. if ( varying.interpolationType ) {
  53235. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  53236. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  53237. // Otherwise, optimize interpolation when sensible
  53238. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  53239. attributesSnippet += ` @interpolate( ${ this.renderer.backend.compatibilityMode ? 'flat, either' : 'flat' } )`;
  53240. }
  53241. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  53242. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  53243. vars.push( varying );
  53244. }
  53245. }
  53246. }
  53247. const builtins = this.getBuiltins( shaderStage );
  53248. if ( builtins ) snippets.push( builtins );
  53249. const code = snippets.join( ',\n\t' );
  53250. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  53251. }
  53252. isCustomStruct( nodeUniform ) {
  53253. const attribute = nodeUniform.value;
  53254. const bufferNode = nodeUniform.node;
  53255. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  53256. const isStructArray =
  53257. ( bufferNode.value && bufferNode.value.array ) &&
  53258. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  53259. return isAttributeStructType && ! isStructArray;
  53260. }
  53261. /**
  53262. * Returns the uniforms of the given shader stage as a WGSL string.
  53263. *
  53264. * @param {string} shaderStage - The shader stage.
  53265. * @return {string} The WGSL snippet that defines the uniforms.
  53266. */
  53267. getUniforms( shaderStage ) {
  53268. const uniforms = this.uniforms[ shaderStage ];
  53269. const bindingSnippets = [];
  53270. const bufferSnippets = [];
  53271. const structSnippets = [];
  53272. const uniformGroups = {};
  53273. for ( const uniform of uniforms ) {
  53274. const groupName = uniform.groupNode.name;
  53275. const uniformIndexes = this.bindingsIndexes[ groupName ];
  53276. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'cubeDepthTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  53277. const texture = uniform.node.value;
  53278. if ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  53279. if ( this.isSampleCompare( texture ) ) {
  53280. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  53281. } else {
  53282. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  53283. }
  53284. }
  53285. let textureType;
  53286. let multisampled = '';
  53287. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  53288. if ( primarySamples > 1 ) {
  53289. multisampled = '_multisampled';
  53290. }
  53291. if ( texture.isCubeTexture === true && texture.isDepthTexture === true ) {
  53292. textureType = 'texture_depth_cube';
  53293. } else if ( texture.isCubeTexture === true ) {
  53294. textureType = 'texture_cube<f32>';
  53295. } else if ( texture.isDepthTexture === true ) {
  53296. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  53297. textureType = `texture${ multisampled }_2d<f32>`;
  53298. } else {
  53299. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  53300. }
  53301. } else if ( uniform.node.isStorageTextureNode === true ) {
  53302. const format = getFormat( texture );
  53303. const access = this.getStorageAccess( uniform.node, shaderStage );
  53304. const is3D = uniform.node.value.is3DTexture;
  53305. const isArrayTexture = uniform.node.value.isArrayTexture;
  53306. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  53307. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  53308. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  53309. textureType = 'texture_2d_array<f32>';
  53310. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  53311. textureType = 'texture_3d<f32>';
  53312. } else {
  53313. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  53314. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  53315. }
  53316. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  53317. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  53318. const bufferNode = uniform.node;
  53319. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  53320. const bufferCount = bufferNode.bufferCount;
  53321. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  53322. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  53323. if ( this.isCustomStruct( uniform ) ) {
  53324. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  53325. } else {
  53326. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  53327. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  53328. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  53329. }
  53330. } else {
  53331. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  53332. const groupName = uniform.groupNode.name;
  53333. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  53334. index: uniformIndexes.binding ++,
  53335. id: uniformIndexes.group,
  53336. snippets: []
  53337. } );
  53338. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  53339. }
  53340. }
  53341. for ( const name in uniformGroups ) {
  53342. const group = uniformGroups[ name ];
  53343. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  53344. }
  53345. const code = [ ...bindingSnippets, ...bufferSnippets, ...structSnippets ].join( '\n' );
  53346. return code;
  53347. }
  53348. /**
  53349. * Controls the code build of the shader stages.
  53350. */
  53351. buildCode() {
  53352. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  53353. this.sortBindingGroups();
  53354. for ( const shaderStage in shadersData ) {
  53355. this.shaderStage = shaderStage;
  53356. const stageData = shadersData[ shaderStage ];
  53357. stageData.uniforms = this.getUniforms( shaderStage );
  53358. stageData.attributes = this.getAttributes( shaderStage );
  53359. stageData.varyings = this.getVaryings( shaderStage );
  53360. stageData.structs = this.getStructs( shaderStage );
  53361. stageData.vars = this.getVars( shaderStage );
  53362. stageData.codes = this.getCodes( shaderStage );
  53363. stageData.directives = this.getDirectives( shaderStage );
  53364. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  53365. //
  53366. let flow = '// code\n\n';
  53367. flow += this.flowCode[ shaderStage ];
  53368. const flowNodes = this.flowNodes[ shaderStage ];
  53369. const mainNode = flowNodes[ flowNodes.length - 1 ];
  53370. const outputNode = mainNode.outputNode;
  53371. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  53372. for ( const node of flowNodes ) {
  53373. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  53374. const slotName = node.name;
  53375. if ( slotName ) {
  53376. if ( flow.length > 0 ) flow += '\n';
  53377. flow += `\t// flow -> ${ slotName }\n`;
  53378. }
  53379. flow += `${ flowSlotData.code }\n\t`;
  53380. if ( node === mainNode && shaderStage !== 'compute' ) {
  53381. flow += '// result\n\n\t';
  53382. if ( shaderStage === 'vertex' ) {
  53383. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  53384. } else if ( shaderStage === 'fragment' ) {
  53385. if ( isOutputStruct ) {
  53386. stageData.returnType = outputNode.getNodeType( this );
  53387. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  53388. flow += `return ${ flowSlotData.result };`;
  53389. } else {
  53390. let structSnippet = '\t@location(0) color: vec4<f32>';
  53391. const builtins = this.getBuiltins( 'output' );
  53392. if ( builtins ) structSnippet += ',\n\t' + builtins;
  53393. stageData.returnType = 'OutputStruct';
  53394. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  53395. stageData.structs += '\nvar<private> output : OutputStruct;';
  53396. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  53397. }
  53398. }
  53399. }
  53400. }
  53401. stageData.flow = flow;
  53402. }
  53403. this.shaderStage = null;
  53404. if ( this.material !== null ) {
  53405. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  53406. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  53407. } else {
  53408. // Early strictly validated in computeNode
  53409. const workgroupSize = this.object.workgroupSize;
  53410. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  53411. }
  53412. }
  53413. /**
  53414. * Returns the native shader method name for a given generic name.
  53415. *
  53416. * @param {string} method - The method name to resolve.
  53417. * @param {?string} [output=null] - An optional output.
  53418. * @return {string} The resolved WGSL method name.
  53419. */
  53420. getMethod( method, output = null ) {
  53421. let wgslMethod;
  53422. if ( output !== null ) {
  53423. wgslMethod = this._getWGSLMethod( method + '_' + output );
  53424. }
  53425. if ( wgslMethod === undefined ) {
  53426. wgslMethod = this._getWGSLMethod( method );
  53427. }
  53428. return wgslMethod || method;
  53429. }
  53430. /**
  53431. * Returns the bitcast method name for a given input and outputType.
  53432. *
  53433. * @param {string} type - The output type to bitcast to.
  53434. * @return {string} The resolved WGSL bitcast invocation.
  53435. */
  53436. getBitcastMethod( type ) {
  53437. const dataType = this.getType( type );
  53438. return `bitcast<${ dataType }>`;
  53439. }
  53440. /**
  53441. * Returns the float packing method name for a given numeric encoding.
  53442. *
  53443. * @param {string} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  53444. * @returns {string} The resolve WGSL float packing method name.
  53445. */
  53446. getFloatPackingMethod( encoding ) {
  53447. return this.getMethod( `floatpack_${ encoding }_2x16` );
  53448. }
  53449. /**
  53450. * Returns the float unpacking method name for a given numeric encoding.
  53451. *
  53452. * @param {string} encoding - The numeric encoding that describes how the integer values are mapped to the float range.
  53453. * @returns {string} The resolve WGSL float unpacking method name.
  53454. */
  53455. getFloatUnpackingMethod( encoding ) {
  53456. return this.getMethod( `floatunpack_${ encoding }_2x16` );
  53457. }
  53458. /**
  53459. * Returns the native snippet for a ternary operation.
  53460. *
  53461. * @param {string} condSnippet - The condition determining which expression gets resolved.
  53462. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  53463. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  53464. * @return {string} The resolved method name.
  53465. */
  53466. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  53467. return `select( ${elseSnippet}, ${ifSnippet}, ${condSnippet} )`;
  53468. }
  53469. /**
  53470. * Returns the WGSL type of the given node data type.
  53471. *
  53472. * @param {string} type - The node data type.
  53473. * @return {string} The WGSL type.
  53474. */
  53475. getType( type ) {
  53476. return wgslTypeLib[ type ] || type;
  53477. }
  53478. /**
  53479. * Whether the requested feature is available or not.
  53480. *
  53481. * @param {string} name - The requested feature.
  53482. * @return {boolean} Whether the requested feature is supported or not.
  53483. */
  53484. isAvailable( name ) {
  53485. let result = supports[ name ];
  53486. if ( result === undefined ) {
  53487. if ( name === 'float32Filterable' ) {
  53488. result = this.renderer.hasFeature( 'float32-filterable' );
  53489. } else if ( name === 'clipDistance' ) {
  53490. result = this.renderer.hasFeature( 'clip-distances' );
  53491. }
  53492. supports[ name ] = result;
  53493. }
  53494. return result;
  53495. }
  53496. /**
  53497. * Returns the native shader method name for a given generic name.
  53498. *
  53499. * @private
  53500. * @param {string} method - The method name to resolve.
  53501. * @return {string} The resolved WGSL method name.
  53502. */
  53503. _getWGSLMethod( method ) {
  53504. if ( wgslPolyfill[ method ] !== undefined ) {
  53505. this._include( method );
  53506. }
  53507. return wgslMethods[ method ];
  53508. }
  53509. /**
  53510. * Includes the given method name into the current
  53511. * function node.
  53512. *
  53513. * @private
  53514. * @param {string} name - The method name to include.
  53515. * @return {CodeNode} The respective code node.
  53516. */
  53517. _include( name ) {
  53518. const codeNode = wgslPolyfill[ name ];
  53519. codeNode.build( this );
  53520. this.addInclude( codeNode );
  53521. return codeNode;
  53522. }
  53523. /**
  53524. * Returns a WGSL vertex shader based on the given shader data.
  53525. *
  53526. * @private
  53527. * @param {Object} shaderData - The shader data.
  53528. * @return {string} The vertex shader.
  53529. */
  53530. _getWGSLVertexCode( shaderData ) {
  53531. return `${ this.getSignature() }
  53532. // directives
  53533. ${shaderData.directives}
  53534. // structs
  53535. ${shaderData.structs}
  53536. // uniforms
  53537. ${shaderData.uniforms}
  53538. // varyings
  53539. ${shaderData.varyings}
  53540. var<private> varyings : VaryingsStruct;
  53541. // codes
  53542. ${shaderData.codes}
  53543. @vertex
  53544. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  53545. // vars
  53546. ${shaderData.vars}
  53547. // flow
  53548. ${shaderData.flow}
  53549. return varyings;
  53550. }
  53551. `;
  53552. }
  53553. /**
  53554. * Returns a WGSL fragment shader based on the given shader data.
  53555. *
  53556. * @private
  53557. * @param {Object} shaderData - The shader data.
  53558. * @return {string} The vertex shader.
  53559. */
  53560. _getWGSLFragmentCode( shaderData ) {
  53561. return `${ this.getSignature() }
  53562. // global
  53563. ${ diagnostics }
  53564. // structs
  53565. ${shaderData.structs}
  53566. // uniforms
  53567. ${shaderData.uniforms}
  53568. // codes
  53569. ${shaderData.codes}
  53570. @fragment
  53571. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  53572. // vars
  53573. ${shaderData.vars}
  53574. // flow
  53575. ${shaderData.flow}
  53576. }
  53577. `;
  53578. }
  53579. /**
  53580. * Returns a WGSL compute shader based on the given shader data.
  53581. *
  53582. * @private
  53583. * @param {Object} shaderData - The shader data.
  53584. * @param {string} workgroupSize - The workgroup size.
  53585. * @return {string} The vertex shader.
  53586. */
  53587. _getWGSLComputeCode( shaderData, workgroupSize ) {
  53588. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  53589. return `${ this.getSignature() }
  53590. // directives
  53591. ${ shaderData.directives }
  53592. // system
  53593. var<private> instanceIndex : u32;
  53594. // locals
  53595. ${ shaderData.scopedArrays }
  53596. // structs
  53597. ${ shaderData.structs }
  53598. // uniforms
  53599. ${ shaderData.uniforms }
  53600. // codes
  53601. ${ shaderData.codes }
  53602. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  53603. fn main( ${ shaderData.attributes } ) {
  53604. // system
  53605. instanceIndex = globalId.x
  53606. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  53607. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  53608. // vars
  53609. ${ shaderData.vars }
  53610. // flow
  53611. ${ shaderData.flow }
  53612. }
  53613. `;
  53614. }
  53615. /**
  53616. * Returns a WGSL struct based on the given name and variables.
  53617. *
  53618. * @private
  53619. * @param {string} name - The struct name.
  53620. * @param {string} vars - The struct variables.
  53621. * @return {string} The WGSL snippet representing a struct.
  53622. */
  53623. _getWGSLStruct( name, vars ) {
  53624. return `
  53625. struct ${name} {
  53626. ${vars}
  53627. };`;
  53628. }
  53629. /**
  53630. * Returns a WGSL struct binding.
  53631. *
  53632. * @private
  53633. * @param {string} name - The struct name.
  53634. * @param {string} vars - The struct variables.
  53635. * @param {string} access - The access.
  53636. * @param {number} [binding=0] - The binding index.
  53637. * @param {number} [group=0] - The group index.
  53638. * @return {string} The WGSL snippet representing a struct binding.
  53639. */
  53640. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  53641. const structName = name + 'Struct';
  53642. const structSnippet = this._getWGSLStruct( structName, vars );
  53643. return `${structSnippet}
  53644. @binding( ${ binding } ) @group( ${ group } )
  53645. var<${access}> ${ name } : ${ structName };`;
  53646. }
  53647. }
  53648. /**
  53649. * A WebGPU backend utility module with common helpers.
  53650. *
  53651. * @private
  53652. */
  53653. class WebGPUUtils {
  53654. /**
  53655. * Constructs a new utility object.
  53656. *
  53657. * @param {WebGPUBackend} backend - The WebGPU backend.
  53658. */
  53659. constructor( backend ) {
  53660. /**
  53661. * A reference to the WebGPU backend.
  53662. *
  53663. * @type {WebGPUBackend}
  53664. */
  53665. this.backend = backend;
  53666. }
  53667. /**
  53668. * Returns the depth/stencil GPU format for the given render context.
  53669. *
  53670. * @param {RenderContext} renderContext - The render context.
  53671. * @return {string} The depth/stencil GPU texture format.
  53672. */
  53673. getCurrentDepthStencilFormat( renderContext ) {
  53674. let format;
  53675. if ( renderContext.depthTexture !== null ) {
  53676. format = this.getTextureFormatGPU( renderContext.depthTexture );
  53677. } else if ( renderContext.depth && renderContext.stencil ) {
  53678. format = GPUTextureFormat.Depth24PlusStencil8;
  53679. } else if ( renderContext.depth ) {
  53680. format = GPUTextureFormat.Depth24Plus;
  53681. }
  53682. return format;
  53683. }
  53684. /**
  53685. * Returns the GPU format for the given texture.
  53686. *
  53687. * @param {Texture} texture - The texture.
  53688. * @return {string} The GPU texture format.
  53689. */
  53690. getTextureFormatGPU( texture ) {
  53691. return this.backend.get( texture ).format;
  53692. }
  53693. /**
  53694. * Returns an object that defines the multi-sampling state of the given texture.
  53695. *
  53696. * @param {Texture} texture - The texture.
  53697. * @return {Object} The multi-sampling state.
  53698. */
  53699. getTextureSampleData( texture ) {
  53700. let samples;
  53701. if ( texture.isFramebufferTexture ) {
  53702. samples = 1;
  53703. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  53704. const renderer = this.backend.renderer;
  53705. const renderTarget = renderer.getRenderTarget();
  53706. samples = renderTarget ? renderTarget.samples : renderer.currentSamples;
  53707. } else if ( texture.renderTarget ) {
  53708. samples = texture.renderTarget.samples;
  53709. }
  53710. samples = samples || 1;
  53711. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  53712. const primarySamples = isMSAA ? 1 : samples;
  53713. return { samples, primarySamples, isMSAA };
  53714. }
  53715. /**
  53716. * Returns the default color attachment's GPU format of the current render context.
  53717. *
  53718. * @param {RenderContext} renderContext - The render context.
  53719. * @return {string} The GPU texture format of the default color attachment.
  53720. */
  53721. getCurrentColorFormat( renderContext ) {
  53722. let format;
  53723. if ( renderContext.textures !== null ) {
  53724. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  53725. } else {
  53726. format = this.getPreferredCanvasFormat(); // default context format
  53727. }
  53728. return format;
  53729. }
  53730. /**
  53731. * Returns the GPU formats of all color attachments of the current render context.
  53732. *
  53733. * @param {RenderContext} renderContext - The render context.
  53734. * @return {Array<string>} The GPU texture formats of all color attachments.
  53735. */
  53736. getCurrentColorFormats( renderContext ) {
  53737. if ( renderContext.textures !== null ) {
  53738. return renderContext.textures.map( t => this.getTextureFormatGPU( t ) );
  53739. } else {
  53740. return [ this.getPreferredCanvasFormat() ]; // default context format
  53741. }
  53742. }
  53743. /**
  53744. * Returns the output color space of the current render context.
  53745. *
  53746. * @param {RenderContext} renderContext - The render context.
  53747. * @return {string} The output color space.
  53748. */
  53749. getCurrentColorSpace( renderContext ) {
  53750. if ( renderContext.textures !== null ) {
  53751. return renderContext.textures[ 0 ].colorSpace;
  53752. }
  53753. return this.backend.renderer.outputColorSpace;
  53754. }
  53755. /**
  53756. * Returns GPU primitive topology for the given object and material.
  53757. *
  53758. * @param {Object3D} object - The 3D object.
  53759. * @param {Material} material - The material.
  53760. * @return {string} The GPU primitive topology.
  53761. */
  53762. getPrimitiveTopology( object, material ) {
  53763. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  53764. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  53765. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  53766. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  53767. }
  53768. /**
  53769. * Returns a modified sample count from the given sample count value.
  53770. *
  53771. * That is required since WebGPU only supports either 1 or 4.
  53772. *
  53773. * @param {number} sampleCount - The input sample count.
  53774. * @return {number} The (potentially updated) output sample count.
  53775. */
  53776. getSampleCount( sampleCount ) {
  53777. return sampleCount >= 4 ? 4 : 1;
  53778. }
  53779. /**
  53780. * Returns the sample count of the given render context.
  53781. *
  53782. * @param {RenderContext} renderContext - The render context.
  53783. * @return {number} The sample count.
  53784. */
  53785. getSampleCountRenderContext( renderContext ) {
  53786. if ( renderContext.textures !== null ) {
  53787. return this.getSampleCount( renderContext.sampleCount );
  53788. }
  53789. return this.getSampleCount( this.backend.renderer.currentSamples );
  53790. }
  53791. /**
  53792. * Returns the preferred canvas format.
  53793. *
  53794. * There is a separate method for this so it's possible to
  53795. * honor edge cases for specific devices.
  53796. *
  53797. * @return {string} The GPU texture format of the canvas.
  53798. */
  53799. getPreferredCanvasFormat() {
  53800. const parameters = this.backend.parameters;
  53801. const bufferType = parameters.outputType;
  53802. if ( bufferType === undefined ) {
  53803. return navigator.gpu.getPreferredCanvasFormat();
  53804. } else if ( bufferType === UnsignedByteType ) {
  53805. return GPUTextureFormat.BGRA8Unorm;
  53806. } else if ( bufferType === HalfFloatType ) {
  53807. return GPUTextureFormat.RGBA16Float;
  53808. } else {
  53809. throw new Error( 'Unsupported output buffer type.' );
  53810. }
  53811. }
  53812. }
  53813. const typedArraysToVertexFormatPrefix = new Map( [
  53814. [ Int8Array, [ 'sint8', 'snorm8' ]],
  53815. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  53816. [ Int16Array, [ 'sint16', 'snorm16' ]],
  53817. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  53818. [ Int32Array, [ 'sint32', 'snorm32' ]],
  53819. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  53820. [ Float32Array, [ 'float32', ]],
  53821. ] );
  53822. if ( typeof Float16Array !== 'undefined' ) {
  53823. typedArraysToVertexFormatPrefix.set( Float16Array, [ 'float16' ] );
  53824. }
  53825. const typedAttributeToVertexFormatPrefix = new Map( [
  53826. [ Float16BufferAttribute, [ 'float16', ]],
  53827. ] );
  53828. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  53829. [ Int32Array, 'sint32' ],
  53830. [ Int16Array, 'sint32' ], // patch for INT16
  53831. [ Uint32Array, 'uint32' ],
  53832. [ Uint16Array, 'uint32' ], // patch for UINT16
  53833. [ Float32Array, 'float32' ]
  53834. ] );
  53835. /**
  53836. * A WebGPU backend utility module for managing shader attributes.
  53837. *
  53838. * @private
  53839. */
  53840. class WebGPUAttributeUtils {
  53841. /**
  53842. * Constructs a new utility object.
  53843. *
  53844. * @param {WebGPUBackend} backend - The WebGPU backend.
  53845. */
  53846. constructor( backend ) {
  53847. /**
  53848. * A reference to the WebGPU backend.
  53849. *
  53850. * @type {WebGPUBackend}
  53851. */
  53852. this.backend = backend;
  53853. }
  53854. /**
  53855. * Creates the GPU buffer for the given buffer attribute.
  53856. *
  53857. * @param {BufferAttribute} attribute - The buffer attribute.
  53858. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  53859. */
  53860. createAttribute( attribute, usage ) {
  53861. const bufferAttribute = this._getBufferAttribute( attribute );
  53862. const backend = this.backend;
  53863. const bufferData = backend.get( bufferAttribute );
  53864. let buffer = bufferData.buffer;
  53865. if ( buffer === undefined ) {
  53866. const device = backend.device;
  53867. let array = bufferAttribute.array;
  53868. // patch for INT16 and UINT16
  53869. if ( attribute.normalized === false ) {
  53870. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  53871. array = new Int32Array( array );
  53872. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  53873. array = new Uint32Array( array );
  53874. if ( usage & GPUBufferUsage.INDEX ) {
  53875. for ( let i = 0; i < array.length; i ++ ) {
  53876. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  53877. }
  53878. }
  53879. }
  53880. }
  53881. bufferAttribute.array = array;
  53882. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  53883. array = new array.constructor( bufferAttribute.count * 4 );
  53884. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  53885. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  53886. }
  53887. // Update BufferAttribute
  53888. bufferAttribute.itemSize = 4;
  53889. bufferAttribute.array = array;
  53890. bufferData._force3to4BytesAlignment = true;
  53891. }
  53892. // ensure 4 byte alignment
  53893. const byteLength = array.byteLength;
  53894. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  53895. buffer = device.createBuffer( {
  53896. label: bufferAttribute.name,
  53897. size: size,
  53898. usage: usage,
  53899. mappedAtCreation: true
  53900. } );
  53901. new array.constructor( buffer.getMappedRange() ).set( array );
  53902. buffer.unmap();
  53903. bufferData.buffer = buffer;
  53904. }
  53905. }
  53906. /**
  53907. * Updates the GPU buffer of the given buffer attribute.
  53908. *
  53909. * @param {BufferAttribute} attribute - The buffer attribute.
  53910. */
  53911. updateAttribute( attribute ) {
  53912. const bufferAttribute = this._getBufferAttribute( attribute );
  53913. const backend = this.backend;
  53914. const device = backend.device;
  53915. const bufferData = backend.get( bufferAttribute );
  53916. const buffer = backend.get( bufferAttribute ).buffer;
  53917. let array = bufferAttribute.array;
  53918. // if storage buffer ensure 4 byte alignment
  53919. if ( bufferData._force3to4BytesAlignment === true ) {
  53920. array = new array.constructor( bufferAttribute.count * 4 );
  53921. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  53922. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  53923. }
  53924. bufferAttribute.array = array;
  53925. }
  53926. const updateRanges = bufferAttribute.updateRanges;
  53927. if ( updateRanges.length === 0 ) {
  53928. // Not using update ranges
  53929. device.queue.writeBuffer(
  53930. buffer,
  53931. 0,
  53932. array,
  53933. 0
  53934. );
  53935. } else {
  53936. const isTyped = isTypedArray( array );
  53937. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  53938. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  53939. const range = updateRanges[ i ];
  53940. let dataOffset, size;
  53941. if ( bufferData._force3to4BytesAlignment === true ) {
  53942. const vertexStart = Math.floor( range.start / 3 );
  53943. const vertexCount = Math.ceil( range.count / 3 );
  53944. dataOffset = vertexStart * 4 * byteOffsetFactor;
  53945. size = vertexCount * 4 * byteOffsetFactor;
  53946. } else {
  53947. dataOffset = range.start * byteOffsetFactor;
  53948. size = range.count * byteOffsetFactor;
  53949. }
  53950. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  53951. device.queue.writeBuffer(
  53952. buffer,
  53953. bufferOffset,
  53954. array,
  53955. dataOffset,
  53956. size
  53957. );
  53958. }
  53959. bufferAttribute.clearUpdateRanges();
  53960. }
  53961. }
  53962. /**
  53963. * This method creates the vertex buffer layout data which are
  53964. * require when creating a render pipeline for the given render object.
  53965. *
  53966. * @param {RenderObject} renderObject - The render object.
  53967. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  53968. */
  53969. createShaderVertexBuffers( renderObject ) {
  53970. const attributes = renderObject.getAttributes();
  53971. const vertexBuffers = new Map();
  53972. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  53973. const geometryAttribute = attributes[ slot ];
  53974. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  53975. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  53976. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  53977. if ( vertexBufferLayout === undefined ) {
  53978. let arrayStride, stepMode;
  53979. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  53980. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  53981. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  53982. } else {
  53983. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  53984. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  53985. }
  53986. // patch for INT16 and UINT16
  53987. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  53988. arrayStride = 4;
  53989. }
  53990. vertexBufferLayout = {
  53991. arrayStride,
  53992. attributes: [],
  53993. stepMode
  53994. };
  53995. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  53996. }
  53997. const format = this._getVertexFormat( geometryAttribute );
  53998. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  53999. vertexBufferLayout.attributes.push( {
  54000. shaderLocation: slot,
  54001. offset,
  54002. format
  54003. } );
  54004. }
  54005. return Array.from( vertexBuffers.values() );
  54006. }
  54007. /**
  54008. * Destroys the GPU buffer of the given buffer attribute.
  54009. *
  54010. * @param {BufferAttribute} attribute - The buffer attribute.
  54011. */
  54012. destroyAttribute( attribute ) {
  54013. const backend = this.backend;
  54014. const data = backend.get( this._getBufferAttribute( attribute ) );
  54015. data.buffer.destroy();
  54016. backend.delete( attribute );
  54017. }
  54018. /**
  54019. * This method performs a readback operation by moving buffer data from
  54020. * a storage buffer attribute from the GPU to the CPU.
  54021. *
  54022. * @async
  54023. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  54024. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  54025. */
  54026. async getArrayBufferAsync( attribute ) {
  54027. const backend = this.backend;
  54028. const device = backend.device;
  54029. const data = backend.get( this._getBufferAttribute( attribute ) );
  54030. const bufferGPU = data.buffer;
  54031. const size = bufferGPU.size;
  54032. const readBufferGPU = device.createBuffer( {
  54033. label: `${ attribute.name }_readback`,
  54034. size,
  54035. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  54036. } );
  54037. const cmdEncoder = device.createCommandEncoder( {
  54038. label: `readback_encoder_${ attribute.name }`
  54039. } );
  54040. cmdEncoder.copyBufferToBuffer(
  54041. bufferGPU,
  54042. 0,
  54043. readBufferGPU,
  54044. 0,
  54045. size
  54046. );
  54047. const gpuCommands = cmdEncoder.finish();
  54048. device.queue.submit( [ gpuCommands ] );
  54049. await readBufferGPU.mapAsync( GPUMapMode.READ );
  54050. const arrayBuffer = readBufferGPU.getMappedRange();
  54051. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  54052. readBufferGPU.unmap();
  54053. return dstBuffer.buffer;
  54054. }
  54055. /**
  54056. * Returns the vertex format of the given buffer attribute.
  54057. *
  54058. * @private
  54059. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  54060. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  54061. */
  54062. _getVertexFormat( geometryAttribute ) {
  54063. const { itemSize, normalized } = geometryAttribute;
  54064. const ArrayType = geometryAttribute.array.constructor;
  54065. const AttributeType = geometryAttribute.constructor;
  54066. let format;
  54067. if ( itemSize === 1 ) {
  54068. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  54069. } else {
  54070. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  54071. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  54072. if ( prefix ) {
  54073. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  54074. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  54075. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  54076. if ( paddedItemSize % 1 ) {
  54077. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  54078. }
  54079. format = `${prefix}x${paddedItemSize}`;
  54080. }
  54081. }
  54082. if ( ! format ) {
  54083. error( 'WebGPUAttributeUtils: Vertex format not supported yet.' );
  54084. }
  54085. return format;
  54086. }
  54087. /**
  54088. * Utility method for handling interleaved buffer attributes correctly.
  54089. * To process them, their `InterleavedBuffer` is returned.
  54090. *
  54091. * @private
  54092. * @param {BufferAttribute} attribute - The attribute.
  54093. * @return {BufferAttribute|InterleavedBuffer}
  54094. */
  54095. _getBufferAttribute( attribute ) {
  54096. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  54097. return attribute;
  54098. }
  54099. }
  54100. /**
  54101. * Class representing a WebGPU bind group layout.
  54102. *
  54103. * @private
  54104. */
  54105. class BindGroupLayout {
  54106. /**
  54107. * Constructs a new layout.
  54108. *
  54109. * @param {GPUBindGroupLayout} layoutGPU - A GPU Bind Group Layout.
  54110. */
  54111. constructor( layoutGPU ) {
  54112. /**
  54113. * The current GPUBindGroupLayout.
  54114. *
  54115. * @type {GPUBindGroupLayout}
  54116. */
  54117. this.layoutGPU = layoutGPU;
  54118. /**
  54119. * The number of bind groups that use this layout.
  54120. *
  54121. * @type {number}
  54122. */
  54123. this.usedTimes = 0;
  54124. }
  54125. }
  54126. /**
  54127. * A WebGPU backend utility module for managing bindings.
  54128. *
  54129. * When reading the documentation it's helpful to keep in mind that
  54130. * all class definitions starting with 'GPU*' are modules from the
  54131. * WebGPU API. So for example `BindGroup` is a class from the engine
  54132. * whereas `GPUBindGroup` is a class from WebGPU.
  54133. *
  54134. * @private
  54135. */
  54136. class WebGPUBindingUtils {
  54137. /**
  54138. * Constructs a new utility object.
  54139. *
  54140. * @param {WebGPUBackend} backend - The WebGPU backend.
  54141. */
  54142. constructor( backend ) {
  54143. /**
  54144. * A reference to the WebGPU backend.
  54145. *
  54146. * @type {WebGPUBackend}
  54147. */
  54148. this.backend = backend;
  54149. /**
  54150. * A cache that maps combinations of layout entries to existing bind group layouts.
  54151. *
  54152. * @private
  54153. * @type {Map<string, BindGroupLayout>}
  54154. */
  54155. this._bindGroupLayoutCache = new Map();
  54156. }
  54157. /**
  54158. * Creates a GPU bind group layout for the given bind group.
  54159. *
  54160. * @param {BindGroup} bindGroup - The bind group.
  54161. * @return {GPUBindGroupLayout} The GPU bind group layout.
  54162. */
  54163. createBindingsLayout( bindGroup ) {
  54164. const backend = this.backend;
  54165. const device = backend.device;
  54166. const bindingsData = backend.get( bindGroup );
  54167. // check if the the bind group already has a layout
  54168. if ( bindingsData.layout ) {
  54169. return bindingsData.layout.layoutGPU;
  54170. }
  54171. // if not, assing one
  54172. const entries = this._createLayoutEntries( bindGroup );
  54173. const bindGroupLayoutKey = JSON.stringify( entries );
  54174. // try to find an existing layout in the cache
  54175. let bindGroupLayout = this._bindGroupLayoutCache.get( bindGroupLayoutKey );
  54176. // if not create a new one
  54177. if ( bindGroupLayout === undefined ) {
  54178. bindGroupLayout = new BindGroupLayout( device.createBindGroupLayout( { entries } ) );
  54179. this._bindGroupLayoutCache.set( bindGroupLayoutKey, bindGroupLayout );
  54180. }
  54181. bindGroupLayout.usedTimes ++;
  54182. bindingsData.layout = bindGroupLayout;
  54183. bindingsData.layoutKey = bindGroupLayoutKey;
  54184. return bindGroupLayout.layoutGPU;
  54185. }
  54186. /**
  54187. * Creates bindings from the given bind group definition.
  54188. *
  54189. * @param {BindGroup} bindGroup - The bind group.
  54190. * @param {Array<BindGroup>} bindings - Array of bind groups.
  54191. * @param {number} cacheIndex - The cache index.
  54192. * @param {number} version - The version.
  54193. */
  54194. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  54195. const { backend } = this;
  54196. const bindingsData = backend.get( bindGroup );
  54197. // setup (static) binding layout and (dynamic) binding group
  54198. const bindLayoutGPU = this.createBindingsLayout( bindGroup );
  54199. let bindGroupGPU;
  54200. if ( cacheIndex > 0 ) {
  54201. if ( bindingsData.groups === undefined ) {
  54202. bindingsData.groups = [];
  54203. bindingsData.versions = [];
  54204. }
  54205. if ( bindingsData.versions[ cacheIndex ] === version ) {
  54206. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  54207. }
  54208. }
  54209. if ( bindGroupGPU === undefined ) {
  54210. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  54211. if ( cacheIndex > 0 ) {
  54212. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  54213. bindingsData.versions[ cacheIndex ] = version;
  54214. }
  54215. }
  54216. bindingsData.group = bindGroupGPU;
  54217. }
  54218. /**
  54219. * Updates a buffer binding.
  54220. *
  54221. * @param {Buffer} binding - The buffer binding to update.
  54222. */
  54223. updateBinding( binding ) {
  54224. const backend = this.backend;
  54225. const device = backend.device;
  54226. const array = binding.buffer; // cpu
  54227. const buffer = backend.get( binding ).buffer; // gpu
  54228. const updateRanges = binding.updateRanges;
  54229. if ( updateRanges.length === 0 ) {
  54230. device.queue.writeBuffer(
  54231. buffer,
  54232. 0,
  54233. array,
  54234. 0
  54235. );
  54236. } else {
  54237. const isTyped = isTypedArray( array );
  54238. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  54239. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  54240. const range = updateRanges[ i ];
  54241. const dataOffset = range.start * byteOffsetFactor;
  54242. const size = range.count * byteOffsetFactor;
  54243. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  54244. device.queue.writeBuffer(
  54245. buffer,
  54246. bufferOffset,
  54247. array,
  54248. dataOffset,
  54249. size
  54250. );
  54251. }
  54252. binding.clearUpdateRanges();
  54253. }
  54254. }
  54255. /**
  54256. * Creates a GPU bind group for the camera index.
  54257. *
  54258. * @param {Uint32Array} data - The index data.
  54259. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  54260. * @return {GPUBindGroup} The GPU bind group.
  54261. */
  54262. createBindGroupIndex( data, layoutGPU ) {
  54263. const backend = this.backend;
  54264. const device = backend.device;
  54265. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  54266. const index = data[ 0 ];
  54267. const buffer = device.createBuffer( {
  54268. label: 'bindingCameraIndex_' + index,
  54269. size: 16, // uint(4) * 4
  54270. usage: usage
  54271. } );
  54272. device.queue.writeBuffer( buffer, 0, data, 0 );
  54273. const entries = [ { binding: 0, resource: { buffer } } ];
  54274. return device.createBindGroup( {
  54275. label: 'bindGroupCameraIndex_' + index,
  54276. layout: layoutGPU,
  54277. entries
  54278. } );
  54279. }
  54280. /**
  54281. * Creates a GPU bind group for the given bind group and GPU layout.
  54282. *
  54283. * @param {BindGroup} bindGroup - The bind group.
  54284. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  54285. * @return {GPUBindGroup} The GPU bind group.
  54286. */
  54287. createBindGroup( bindGroup, layoutGPU ) {
  54288. const backend = this.backend;
  54289. const device = backend.device;
  54290. let bindingPoint = 0;
  54291. const entriesGPU = [];
  54292. for ( const binding of bindGroup.bindings ) {
  54293. if ( binding.isUniformBuffer ) {
  54294. const bindingData = backend.get( binding );
  54295. if ( bindingData.buffer === undefined ) {
  54296. const byteLength = binding.byteLength;
  54297. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  54298. const visibilities = [];
  54299. if ( binding.visibility & GPUShaderStage.VERTEX ) {
  54300. visibilities.push( 'vertex' );
  54301. }
  54302. if ( binding.visibility & GPUShaderStage.FRAGMENT ) {
  54303. visibilities.push( 'fragment' );
  54304. }
  54305. if ( binding.visibility & GPUShaderStage.COMPUTE ) {
  54306. visibilities.push( 'compute' );
  54307. }
  54308. const bufferVisibility = `(${visibilities.join( ',' )})`;
  54309. const bufferGPU = device.createBuffer( {
  54310. label: `bindingBuffer${binding.id}_${binding.name}_${bufferVisibility}`,
  54311. size: byteLength,
  54312. usage: usage
  54313. } );
  54314. bindingData.buffer = bufferGPU;
  54315. }
  54316. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  54317. } else if ( binding.isStorageBuffer ) {
  54318. const bindingData = backend.get( binding );
  54319. if ( bindingData.buffer === undefined ) {
  54320. const attribute = binding.attribute;
  54321. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  54322. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  54323. bindingData.buffer = backend.get( attribute ).buffer;
  54324. }
  54325. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  54326. } else if ( binding.isSampledTexture ) {
  54327. const textureData = backend.get( binding.texture );
  54328. let resourceGPU;
  54329. if ( textureData.externalTexture !== undefined ) {
  54330. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  54331. } else {
  54332. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  54333. const baseMipLevel = binding.store ? binding.mipLevel : 0;
  54334. let propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }`;
  54335. if ( textureData.texture.depthOrArrayLayers > 1 ) {
  54336. propertyName += `-${ textureData.texture.depthOrArrayLayers }`;
  54337. }
  54338. propertyName += `-${ mipLevelCount }-${ baseMipLevel }`;
  54339. resourceGPU = textureData[ propertyName ];
  54340. if ( resourceGPU === undefined ) {
  54341. const aspectGPU = GPUTextureAspect.All;
  54342. let dimensionViewGPU;
  54343. if ( binding.isSampledCubeTexture ) {
  54344. dimensionViewGPU = GPUTextureViewDimension.Cube;
  54345. } else if ( binding.isSampledTexture3D ) {
  54346. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  54347. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  54348. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  54349. } else {
  54350. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  54351. }
  54352. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount, baseMipLevel } );
  54353. }
  54354. }
  54355. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  54356. } else if ( binding.isSampler ) {
  54357. const textureGPU = backend.get( binding.texture );
  54358. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  54359. }
  54360. bindingPoint ++;
  54361. }
  54362. return device.createBindGroup( {
  54363. label: 'bindGroup_' + bindGroup.name,
  54364. layout: layoutGPU,
  54365. entries: entriesGPU
  54366. } );
  54367. }
  54368. /**
  54369. * Creates a GPU bind group layout entries for the given bind group.
  54370. *
  54371. * @private
  54372. * @param {BindGroup} bindGroup - The bind group.
  54373. * @return {Array<GPUBindGroupLayoutEntry>} The GPU bind group layout entries.
  54374. */
  54375. _createLayoutEntries( bindGroup ) {
  54376. const entries = [];
  54377. let index = 0;
  54378. for ( const binding of bindGroup.bindings ) {
  54379. const backend = this.backend;
  54380. const bindingGPU = {
  54381. binding: index,
  54382. visibility: binding.visibility
  54383. };
  54384. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  54385. const buffer = {}; // GPUBufferBindingLayout
  54386. if ( binding.isStorageBuffer ) {
  54387. if ( binding.visibility & GPUShaderStage.COMPUTE ) {
  54388. // compute
  54389. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  54390. buffer.type = GPUBufferBindingType.Storage;
  54391. } else {
  54392. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  54393. }
  54394. } else {
  54395. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  54396. }
  54397. }
  54398. bindingGPU.buffer = buffer;
  54399. } else if ( binding.isSampledTexture && binding.store ) {
  54400. const storageTexture = {}; // GPUStorageTextureBindingLayout
  54401. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  54402. const access = binding.access;
  54403. if ( access === NodeAccess.READ_WRITE ) {
  54404. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  54405. } else if ( access === NodeAccess.WRITE_ONLY ) {
  54406. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  54407. } else {
  54408. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  54409. }
  54410. if ( binding.texture.isArrayTexture ) {
  54411. storageTexture.viewDimension = GPUTextureViewDimension.TwoDArray;
  54412. } else if ( binding.texture.is3DTexture ) {
  54413. storageTexture.viewDimension = GPUTextureViewDimension.ThreeD;
  54414. }
  54415. bindingGPU.storageTexture = storageTexture;
  54416. } else if ( binding.isSampledTexture ) {
  54417. const texture = {}; // GPUTextureBindingLayout
  54418. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  54419. if ( primarySamples > 1 ) {
  54420. texture.multisampled = true;
  54421. if ( ! binding.texture.isDepthTexture ) {
  54422. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  54423. }
  54424. }
  54425. if ( binding.texture.isDepthTexture ) {
  54426. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  54427. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  54428. } else {
  54429. texture.sampleType = GPUTextureSampleType.Depth;
  54430. }
  54431. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  54432. const type = binding.texture.type;
  54433. if ( type === IntType ) {
  54434. texture.sampleType = GPUTextureSampleType.SInt;
  54435. } else if ( type === UnsignedIntType ) {
  54436. texture.sampleType = GPUTextureSampleType.UInt;
  54437. } else if ( type === FloatType ) {
  54438. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  54439. texture.sampleType = GPUTextureSampleType.Float;
  54440. } else {
  54441. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  54442. }
  54443. }
  54444. }
  54445. if ( binding.isSampledCubeTexture ) {
  54446. texture.viewDimension = GPUTextureViewDimension.Cube;
  54447. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  54448. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  54449. } else if ( binding.isSampledTexture3D ) {
  54450. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  54451. }
  54452. bindingGPU.texture = texture;
  54453. } else if ( binding.isSampler ) {
  54454. const sampler = {}; // GPUSamplerBindingLayout
  54455. if ( binding.texture.isDepthTexture ) {
  54456. if ( binding.texture.compareFunction !== null ) {
  54457. sampler.type = GPUSamplerBindingType.Comparison;
  54458. } else if ( backend.compatibilityMode ) {
  54459. sampler.type = GPUSamplerBindingType.NonFiltering;
  54460. }
  54461. }
  54462. bindingGPU.sampler = sampler;
  54463. } else {
  54464. error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  54465. }
  54466. entries.push( bindingGPU );
  54467. index ++;
  54468. }
  54469. return entries;
  54470. }
  54471. /**
  54472. * Delete the data associated with a bind group.
  54473. *
  54474. * @param {BindGroup} bindGroup - The bind group.
  54475. */
  54476. deleteBindGroupData( bindGroup ) {
  54477. const { backend } = this;
  54478. const bindingsData = backend.get( bindGroup );
  54479. if ( bindingsData.layout ) {
  54480. bindingsData.layout.usedTimes --;
  54481. if ( bindingsData.layout.usedTimes === 0 ) {
  54482. this._bindGroupLayoutCache.delete( bindingsData.layoutKey );
  54483. }
  54484. bindingsData.layout = undefined;
  54485. bindingsData.layoutKey = undefined;
  54486. }
  54487. }
  54488. /**
  54489. * Frees internal resources.
  54490. */
  54491. dispose() {
  54492. this._bindGroupLayoutCache.clear();
  54493. }
  54494. }
  54495. /**
  54496. * A WebGPU backend utility module for managing pipelines.
  54497. *
  54498. * @private
  54499. */
  54500. class WebGPUPipelineUtils {
  54501. /**
  54502. * Constructs a new utility object.
  54503. *
  54504. * @param {WebGPUBackend} backend - The WebGPU backend.
  54505. */
  54506. constructor( backend ) {
  54507. /**
  54508. * A reference to the WebGPU backend.
  54509. *
  54510. * @type {WebGPUBackend}
  54511. */
  54512. this.backend = backend;
  54513. /**
  54514. * A Weak Map that tracks the active pipeline for render or compute passes.
  54515. *
  54516. * @private
  54517. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  54518. */
  54519. this._activePipelines = new WeakMap();
  54520. }
  54521. /**
  54522. * Sets the given pipeline for the given pass. The method makes sure to only set the
  54523. * pipeline when necessary.
  54524. *
  54525. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  54526. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  54527. */
  54528. setPipeline( pass, pipeline ) {
  54529. const currentPipeline = this._activePipelines.get( pass );
  54530. if ( currentPipeline !== pipeline ) {
  54531. pass.setPipeline( pipeline );
  54532. this._activePipelines.set( pass, pipeline );
  54533. }
  54534. }
  54535. /**
  54536. * Returns the sample count derived from the given render context.
  54537. *
  54538. * @private
  54539. * @param {RenderContext} renderContext - The render context.
  54540. * @return {number} The sample count.
  54541. */
  54542. _getSampleCount( renderContext ) {
  54543. return this.backend.utils.getSampleCountRenderContext( renderContext );
  54544. }
  54545. /**
  54546. * Creates a render pipeline for the given render object.
  54547. *
  54548. * @param {RenderObject} renderObject - The render object.
  54549. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  54550. */
  54551. createRenderPipeline( renderObject, promises ) {
  54552. const { object, material, geometry, pipeline } = renderObject;
  54553. const { vertexProgram, fragmentProgram } = pipeline;
  54554. const backend = this.backend;
  54555. const device = backend.device;
  54556. const utils = backend.utils;
  54557. const pipelineData = backend.get( pipeline );
  54558. // bind group layouts
  54559. const bindGroupLayouts = [];
  54560. for ( const bindGroup of renderObject.getBindings() ) {
  54561. const bindingsData = backend.get( bindGroup );
  54562. const { layoutGPU } = bindingsData.layout;
  54563. bindGroupLayouts.push( layoutGPU );
  54564. }
  54565. // vertex buffers
  54566. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  54567. // blending
  54568. let blending;
  54569. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  54570. blending = this._getBlending( material );
  54571. }
  54572. // stencil
  54573. let stencilFront = {};
  54574. if ( material.stencilWrite === true ) {
  54575. stencilFront = {
  54576. compare: this._getStencilCompare( material ),
  54577. failOp: this._getStencilOperation( material.stencilFail ),
  54578. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  54579. passOp: this._getStencilOperation( material.stencilZPass )
  54580. };
  54581. }
  54582. const colorWriteMask = this._getColorWriteMask( material );
  54583. const targets = [];
  54584. if ( renderObject.context.textures !== null ) {
  54585. const textures = renderObject.context.textures;
  54586. for ( let i = 0; i < textures.length; i ++ ) {
  54587. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  54588. if ( i === 0 ) {
  54589. targets.push( {
  54590. format: colorFormat,
  54591. blend: blending,
  54592. writeMask: colorWriteMask
  54593. } );
  54594. } else {
  54595. targets.push( {
  54596. format: colorFormat,
  54597. writeMask: colorWriteMask
  54598. } );
  54599. }
  54600. }
  54601. } else {
  54602. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  54603. targets.push( {
  54604. format: colorFormat,
  54605. blend: blending,
  54606. writeMask: colorWriteMask
  54607. } );
  54608. }
  54609. const vertexModule = backend.get( vertexProgram ).module;
  54610. const fragmentModule = backend.get( fragmentProgram ).module;
  54611. const primitiveState = this._getPrimitiveState( object, geometry, material );
  54612. const depthCompare = this._getDepthCompare( material );
  54613. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  54614. const sampleCount = this._getSampleCount( renderObject.context );
  54615. const pipelineDescriptor = {
  54616. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  54617. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  54618. fragment: Object.assign( {}, fragmentModule, { targets } ),
  54619. primitive: primitiveState,
  54620. multisample: {
  54621. count: sampleCount,
  54622. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  54623. },
  54624. layout: device.createPipelineLayout( {
  54625. bindGroupLayouts
  54626. } )
  54627. };
  54628. const depthStencil = {};
  54629. const renderDepth = renderObject.context.depth;
  54630. const renderStencil = renderObject.context.stencil;
  54631. if ( renderDepth === true || renderStencil === true ) {
  54632. if ( renderDepth === true ) {
  54633. depthStencil.format = depthStencilFormat;
  54634. depthStencil.depthWriteEnabled = material.depthWrite;
  54635. depthStencil.depthCompare = depthCompare;
  54636. }
  54637. if ( renderStencil === true ) {
  54638. depthStencil.stencilFront = stencilFront;
  54639. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  54640. depthStencil.stencilReadMask = material.stencilFuncMask;
  54641. depthStencil.stencilWriteMask = material.stencilWriteMask;
  54642. }
  54643. if ( material.polygonOffset === true ) {
  54644. depthStencil.depthBias = material.polygonOffsetUnits;
  54645. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  54646. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  54647. }
  54648. pipelineDescriptor.depthStencil = depthStencil;
  54649. }
  54650. // create pipeline
  54651. device.pushErrorScope( 'validation' );
  54652. if ( promises === null ) {
  54653. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  54654. device.popErrorScope().then( ( err ) => {
  54655. if ( err !== null ) {
  54656. pipelineData.error = true;
  54657. error( err.message );
  54658. }
  54659. } );
  54660. } else {
  54661. const p = new Promise( async ( resolve /*, reject*/ ) => {
  54662. try {
  54663. pipelineData.pipeline = await device.createRenderPipelineAsync( pipelineDescriptor );
  54664. } catch ( err ) { }
  54665. const errorScope = await device.popErrorScope();
  54666. if ( errorScope !== null ) {
  54667. pipelineData.error = true;
  54668. error( errorScope.message );
  54669. }
  54670. resolve();
  54671. } );
  54672. promises.push( p );
  54673. }
  54674. }
  54675. /**
  54676. * Creates GPU render bundle encoder for the given render context.
  54677. *
  54678. * @param {RenderContext} renderContext - The render context.
  54679. * @param {?string} [label='renderBundleEncoder'] - The label.
  54680. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  54681. */
  54682. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  54683. const backend = this.backend;
  54684. const { utils, device } = backend;
  54685. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  54686. const colorFormats = utils.getCurrentColorFormats( renderContext );
  54687. const sampleCount = this._getSampleCount( renderContext );
  54688. const descriptor = {
  54689. label,
  54690. colorFormats,
  54691. depthStencilFormat,
  54692. sampleCount
  54693. };
  54694. return device.createRenderBundleEncoder( descriptor );
  54695. }
  54696. /**
  54697. * Creates a compute pipeline for the given compute node.
  54698. *
  54699. * @param {ComputePipeline} pipeline - The compute pipeline.
  54700. * @param {Array<BindGroup>} bindings - The bindings.
  54701. */
  54702. createComputePipeline( pipeline, bindings ) {
  54703. const backend = this.backend;
  54704. const device = backend.device;
  54705. const computeProgram = backend.get( pipeline.computeProgram ).module;
  54706. const pipelineGPU = backend.get( pipeline );
  54707. // bind group layouts
  54708. const bindGroupLayouts = [];
  54709. for ( const bindingsGroup of bindings ) {
  54710. const bindingsData = backend.get( bindingsGroup );
  54711. const { layoutGPU } = bindingsData.layout;
  54712. bindGroupLayouts.push( layoutGPU );
  54713. }
  54714. pipelineGPU.pipeline = device.createComputePipeline( {
  54715. compute: computeProgram,
  54716. layout: device.createPipelineLayout( {
  54717. bindGroupLayouts
  54718. } )
  54719. } );
  54720. }
  54721. /**
  54722. * Returns the blending state as a descriptor object required
  54723. * for the pipeline creation.
  54724. *
  54725. * @private
  54726. * @param {Material} material - The material.
  54727. * @return {Object} The blending state.
  54728. */
  54729. _getBlending( material ) {
  54730. let color, alpha;
  54731. const blending = material.blending;
  54732. const blendSrc = material.blendSrc;
  54733. const blendDst = material.blendDst;
  54734. const blendEquation = material.blendEquation;
  54735. if ( blending === CustomBlending ) {
  54736. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  54737. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  54738. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  54739. color = {
  54740. srcFactor: this._getBlendFactor( blendSrc ),
  54741. dstFactor: this._getBlendFactor( blendDst ),
  54742. operation: this._getBlendOperation( blendEquation )
  54743. };
  54744. alpha = {
  54745. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  54746. dstFactor: this._getBlendFactor( blendDstAlpha ),
  54747. operation: this._getBlendOperation( blendEquationAlpha )
  54748. };
  54749. } else {
  54750. const premultipliedAlpha = material.premultipliedAlpha;
  54751. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  54752. color = {
  54753. srcFactor: srcRGB,
  54754. dstFactor: dstRGB,
  54755. operation: GPUBlendOperation.Add
  54756. };
  54757. alpha = {
  54758. srcFactor: srcAlpha,
  54759. dstFactor: dstAlpha,
  54760. operation: GPUBlendOperation.Add
  54761. };
  54762. };
  54763. if ( premultipliedAlpha ) {
  54764. switch ( blending ) {
  54765. case NormalBlending:
  54766. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  54767. break;
  54768. case AdditiveBlending:
  54769. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  54770. break;
  54771. case SubtractiveBlending:
  54772. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  54773. break;
  54774. case MultiplyBlending:
  54775. setBlend( GPUBlendFactor.Dst, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.Zero, GPUBlendFactor.One );
  54776. break;
  54777. }
  54778. } else {
  54779. switch ( blending ) {
  54780. case NormalBlending:
  54781. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  54782. break;
  54783. case AdditiveBlending:
  54784. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  54785. break;
  54786. case SubtractiveBlending:
  54787. error( 'WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true' );
  54788. break;
  54789. case MultiplyBlending:
  54790. error( 'WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true' );
  54791. break;
  54792. }
  54793. }
  54794. }
  54795. if ( color !== undefined && alpha !== undefined ) {
  54796. return { color, alpha };
  54797. } else {
  54798. error( 'WebGPURenderer: Invalid blending: ', blending );
  54799. }
  54800. }
  54801. /**
  54802. * Returns the GPU blend factor which is required for the pipeline creation.
  54803. *
  54804. * @private
  54805. * @param {number} blend - The blend factor as a three.js constant.
  54806. * @return {string} The GPU blend factor.
  54807. */
  54808. _getBlendFactor( blend ) {
  54809. let blendFactor;
  54810. switch ( blend ) {
  54811. case ZeroFactor:
  54812. blendFactor = GPUBlendFactor.Zero;
  54813. break;
  54814. case OneFactor:
  54815. blendFactor = GPUBlendFactor.One;
  54816. break;
  54817. case SrcColorFactor:
  54818. blendFactor = GPUBlendFactor.Src;
  54819. break;
  54820. case OneMinusSrcColorFactor:
  54821. blendFactor = GPUBlendFactor.OneMinusSrc;
  54822. break;
  54823. case SrcAlphaFactor:
  54824. blendFactor = GPUBlendFactor.SrcAlpha;
  54825. break;
  54826. case OneMinusSrcAlphaFactor:
  54827. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  54828. break;
  54829. case DstColorFactor:
  54830. blendFactor = GPUBlendFactor.Dst;
  54831. break;
  54832. case OneMinusDstColorFactor:
  54833. blendFactor = GPUBlendFactor.OneMinusDst;
  54834. break;
  54835. case DstAlphaFactor:
  54836. blendFactor = GPUBlendFactor.DstAlpha;
  54837. break;
  54838. case OneMinusDstAlphaFactor:
  54839. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  54840. break;
  54841. case SrcAlphaSaturateFactor:
  54842. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  54843. break;
  54844. case BlendColorFactor:
  54845. blendFactor = GPUBlendFactor.Constant;
  54846. break;
  54847. case OneMinusBlendColorFactor:
  54848. blendFactor = GPUBlendFactor.OneMinusConstant;
  54849. break;
  54850. default:
  54851. error( 'WebGPURenderer: Blend factor not supported.', blend );
  54852. }
  54853. return blendFactor;
  54854. }
  54855. /**
  54856. * Returns the GPU stencil compare function which is required for the pipeline creation.
  54857. *
  54858. * @private
  54859. * @param {Material} material - The material.
  54860. * @return {string} The GPU stencil compare function.
  54861. */
  54862. _getStencilCompare( material ) {
  54863. let stencilCompare;
  54864. const stencilFunc = material.stencilFunc;
  54865. switch ( stencilFunc ) {
  54866. case NeverStencilFunc:
  54867. stencilCompare = GPUCompareFunction.Never;
  54868. break;
  54869. case AlwaysStencilFunc:
  54870. stencilCompare = GPUCompareFunction.Always;
  54871. break;
  54872. case LessStencilFunc:
  54873. stencilCompare = GPUCompareFunction.Less;
  54874. break;
  54875. case LessEqualStencilFunc:
  54876. stencilCompare = GPUCompareFunction.LessEqual;
  54877. break;
  54878. case EqualStencilFunc:
  54879. stencilCompare = GPUCompareFunction.Equal;
  54880. break;
  54881. case GreaterEqualStencilFunc:
  54882. stencilCompare = GPUCompareFunction.GreaterEqual;
  54883. break;
  54884. case GreaterStencilFunc:
  54885. stencilCompare = GPUCompareFunction.Greater;
  54886. break;
  54887. case NotEqualStencilFunc:
  54888. stencilCompare = GPUCompareFunction.NotEqual;
  54889. break;
  54890. default:
  54891. error( 'WebGPURenderer: Invalid stencil function.', stencilFunc );
  54892. }
  54893. return stencilCompare;
  54894. }
  54895. /**
  54896. * Returns the GPU stencil operation which is required for the pipeline creation.
  54897. *
  54898. * @private
  54899. * @param {number} op - A three.js constant defining the stencil operation.
  54900. * @return {string} The GPU stencil operation.
  54901. */
  54902. _getStencilOperation( op ) {
  54903. let stencilOperation;
  54904. switch ( op ) {
  54905. case KeepStencilOp:
  54906. stencilOperation = GPUStencilOperation.Keep;
  54907. break;
  54908. case ZeroStencilOp:
  54909. stencilOperation = GPUStencilOperation.Zero;
  54910. break;
  54911. case ReplaceStencilOp:
  54912. stencilOperation = GPUStencilOperation.Replace;
  54913. break;
  54914. case InvertStencilOp:
  54915. stencilOperation = GPUStencilOperation.Invert;
  54916. break;
  54917. case IncrementStencilOp:
  54918. stencilOperation = GPUStencilOperation.IncrementClamp;
  54919. break;
  54920. case DecrementStencilOp:
  54921. stencilOperation = GPUStencilOperation.DecrementClamp;
  54922. break;
  54923. case IncrementWrapStencilOp:
  54924. stencilOperation = GPUStencilOperation.IncrementWrap;
  54925. break;
  54926. case DecrementWrapStencilOp:
  54927. stencilOperation = GPUStencilOperation.DecrementWrap;
  54928. break;
  54929. default:
  54930. error( 'WebGPURenderer: Invalid stencil operation.', stencilOperation );
  54931. }
  54932. return stencilOperation;
  54933. }
  54934. /**
  54935. * Returns the GPU blend operation which is required for the pipeline creation.
  54936. *
  54937. * @private
  54938. * @param {number} blendEquation - A three.js constant defining the blend equation.
  54939. * @return {string} The GPU blend operation.
  54940. */
  54941. _getBlendOperation( blendEquation ) {
  54942. let blendOperation;
  54943. switch ( blendEquation ) {
  54944. case AddEquation:
  54945. blendOperation = GPUBlendOperation.Add;
  54946. break;
  54947. case SubtractEquation:
  54948. blendOperation = GPUBlendOperation.Subtract;
  54949. break;
  54950. case ReverseSubtractEquation:
  54951. blendOperation = GPUBlendOperation.ReverseSubtract;
  54952. break;
  54953. case MinEquation:
  54954. blendOperation = GPUBlendOperation.Min;
  54955. break;
  54956. case MaxEquation:
  54957. blendOperation = GPUBlendOperation.Max;
  54958. break;
  54959. default:
  54960. error( 'WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  54961. }
  54962. return blendOperation;
  54963. }
  54964. /**
  54965. * Returns the primitive state as a descriptor object required
  54966. * for the pipeline creation.
  54967. *
  54968. * @private
  54969. * @param {Object3D} object - The 3D object.
  54970. * @param {BufferGeometry} geometry - The geometry.
  54971. * @param {Material} material - The material.
  54972. * @return {Object} The primitive state.
  54973. */
  54974. _getPrimitiveState( object, geometry, material ) {
  54975. const descriptor = {};
  54976. const utils = this.backend.utils;
  54977. //
  54978. descriptor.topology = utils.getPrimitiveTopology( object, material );
  54979. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  54980. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  54981. }
  54982. //
  54983. let flipSided = ( material.side === BackSide );
  54984. if ( object.isMesh && object.matrixWorld.determinant() < 0 ) flipSided = ! flipSided;
  54985. descriptor.frontFace = ( flipSided === true ) ? GPUFrontFace.CW : GPUFrontFace.CCW;
  54986. //
  54987. descriptor.cullMode = ( material.side === DoubleSide ) ? GPUCullMode.None : GPUCullMode.Back;
  54988. return descriptor;
  54989. }
  54990. /**
  54991. * Returns the GPU color write mask which is required for the pipeline creation.
  54992. *
  54993. * @private
  54994. * @param {Material} material - The material.
  54995. * @return {number} The GPU color write mask.
  54996. */
  54997. _getColorWriteMask( material ) {
  54998. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  54999. }
  55000. /**
  55001. * Returns the GPU depth compare function which is required for the pipeline creation.
  55002. *
  55003. * @private
  55004. * @param {Material} material - The material.
  55005. * @return {string} The GPU depth compare function.
  55006. */
  55007. _getDepthCompare( material ) {
  55008. let depthCompare;
  55009. if ( material.depthTest === false ) {
  55010. depthCompare = GPUCompareFunction.Always;
  55011. } else {
  55012. const depthFunc = material.depthFunc;
  55013. switch ( depthFunc ) {
  55014. case NeverDepth:
  55015. depthCompare = GPUCompareFunction.Never;
  55016. break;
  55017. case AlwaysDepth:
  55018. depthCompare = GPUCompareFunction.Always;
  55019. break;
  55020. case LessDepth:
  55021. depthCompare = GPUCompareFunction.Less;
  55022. break;
  55023. case LessEqualDepth:
  55024. depthCompare = GPUCompareFunction.LessEqual;
  55025. break;
  55026. case EqualDepth:
  55027. depthCompare = GPUCompareFunction.Equal;
  55028. break;
  55029. case GreaterEqualDepth:
  55030. depthCompare = GPUCompareFunction.GreaterEqual;
  55031. break;
  55032. case GreaterDepth:
  55033. depthCompare = GPUCompareFunction.Greater;
  55034. break;
  55035. case NotEqualDepth:
  55036. depthCompare = GPUCompareFunction.NotEqual;
  55037. break;
  55038. default:
  55039. error( 'WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  55040. }
  55041. }
  55042. return depthCompare;
  55043. }
  55044. }
  55045. /**
  55046. * Manages a pool of WebGPU timestamp queries for performance measurement.
  55047. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  55048. *
  55049. * @augments TimestampQueryPool
  55050. */
  55051. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  55052. /**
  55053. * Creates a new WebGPU timestamp query pool.
  55054. *
  55055. * @param {GPUDevice} device - The WebGPU device to create queries on.
  55056. * @param {string} type - The type identifier for this query pool.
  55057. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  55058. */
  55059. constructor( device, type, maxQueries = 2048 ) {
  55060. super( maxQueries );
  55061. this.device = device;
  55062. this.type = type;
  55063. this.querySet = this.device.createQuerySet( {
  55064. type: 'timestamp',
  55065. count: this.maxQueries,
  55066. label: `queryset_global_timestamp_${type}`
  55067. } );
  55068. const bufferSize = this.maxQueries * 8;
  55069. this.resolveBuffer = this.device.createBuffer( {
  55070. label: `buffer_timestamp_resolve_${type}`,
  55071. size: bufferSize,
  55072. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  55073. } );
  55074. this.resultBuffer = this.device.createBuffer( {
  55075. label: `buffer_timestamp_result_${type}`,
  55076. size: bufferSize,
  55077. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  55078. } );
  55079. }
  55080. /**
  55081. * Allocates a pair of queries for a given render context.
  55082. *
  55083. * @param {string} uid - A unique identifier for the render context.
  55084. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  55085. */
  55086. allocateQueriesForContext( uid ) {
  55087. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  55088. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  55089. 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() } ).` );
  55090. return null;
  55091. }
  55092. const baseOffset = this.currentQueryIndex;
  55093. this.currentQueryIndex += 2;
  55094. this.queryOffsets.set( uid, baseOffset );
  55095. return baseOffset;
  55096. }
  55097. /**
  55098. * Asynchronously resolves all pending queries and returns the total duration.
  55099. * If there's already a pending resolve operation, returns that promise instead.
  55100. *
  55101. * @async
  55102. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  55103. */
  55104. async resolveQueriesAsync() {
  55105. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  55106. return this.lastValue;
  55107. }
  55108. if ( this.pendingResolve ) {
  55109. return this.pendingResolve;
  55110. }
  55111. this.pendingResolve = this._resolveQueries();
  55112. try {
  55113. const result = await this.pendingResolve;
  55114. return result;
  55115. } finally {
  55116. this.pendingResolve = null;
  55117. }
  55118. }
  55119. /**
  55120. * Internal method to resolve queries and calculate total duration.
  55121. *
  55122. * @async
  55123. * @private
  55124. * @returns {Promise<number>} The total duration in milliseconds.
  55125. */
  55126. async _resolveQueries() {
  55127. if ( this.isDisposed ) {
  55128. return this.lastValue;
  55129. }
  55130. try {
  55131. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  55132. return this.lastValue;
  55133. }
  55134. const currentOffsets = new Map( this.queryOffsets );
  55135. const queryCount = this.currentQueryIndex;
  55136. const bytesUsed = queryCount * 8;
  55137. // Reset state before GPU work
  55138. this.currentQueryIndex = 0;
  55139. this.queryOffsets.clear();
  55140. const commandEncoder = this.device.createCommandEncoder();
  55141. commandEncoder.resolveQuerySet(
  55142. this.querySet,
  55143. 0,
  55144. queryCount,
  55145. this.resolveBuffer,
  55146. 0
  55147. );
  55148. commandEncoder.copyBufferToBuffer(
  55149. this.resolveBuffer,
  55150. 0,
  55151. this.resultBuffer,
  55152. 0,
  55153. bytesUsed
  55154. );
  55155. const commandBuffer = commandEncoder.finish();
  55156. this.device.queue.submit( [ commandBuffer ] );
  55157. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  55158. return this.lastValue;
  55159. }
  55160. // Create and track the mapping operation
  55161. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  55162. if ( this.isDisposed ) {
  55163. if ( this.resultBuffer.mapState === 'mapped' ) {
  55164. this.resultBuffer.unmap();
  55165. }
  55166. return this.lastValue;
  55167. }
  55168. //
  55169. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  55170. const framesDuration = {};
  55171. const frames = [];
  55172. for ( const [ uid, baseOffset ] of currentOffsets ) {
  55173. const match = uid.match( /^(.*):f(\d+)$/ );
  55174. const frame = parseInt( match[ 2 ] );
  55175. if ( frames.includes( frame ) === false ) {
  55176. frames.push( frame );
  55177. }
  55178. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  55179. const startTime = times[ baseOffset ];
  55180. const endTime = times[ baseOffset + 1 ];
  55181. const duration = Number( endTime - startTime ) / 1e6;
  55182. this.timestamps.set( uid, duration );
  55183. framesDuration[ frame ] += duration;
  55184. }
  55185. // Return the total duration of the last frame
  55186. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  55187. this.resultBuffer.unmap();
  55188. this.lastValue = totalDuration;
  55189. this.frames = frames;
  55190. return totalDuration;
  55191. } catch ( e ) {
  55192. error( 'Error resolving queries:', e );
  55193. if ( this.resultBuffer.mapState === 'mapped' ) {
  55194. this.resultBuffer.unmap();
  55195. }
  55196. return this.lastValue;
  55197. }
  55198. }
  55199. /**
  55200. * Dispose of the query pool.
  55201. *
  55202. * @async
  55203. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  55204. */
  55205. async dispose() {
  55206. if ( this.isDisposed ) {
  55207. return;
  55208. }
  55209. this.isDisposed = true;
  55210. // Wait for pending resolve operation
  55211. if ( this.pendingResolve ) {
  55212. try {
  55213. await this.pendingResolve;
  55214. } catch ( e ) {
  55215. error( 'Error waiting for pending resolve:', e );
  55216. }
  55217. }
  55218. // Ensure buffer is unmapped before destroying
  55219. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  55220. try {
  55221. this.resultBuffer.unmap();
  55222. } catch ( e ) {
  55223. error( 'Error unmapping buffer:', e );
  55224. }
  55225. }
  55226. // Destroy resources
  55227. if ( this.querySet ) {
  55228. this.querySet.destroy();
  55229. this.querySet = null;
  55230. }
  55231. if ( this.resolveBuffer ) {
  55232. this.resolveBuffer.destroy();
  55233. this.resolveBuffer = null;
  55234. }
  55235. if ( this.resultBuffer ) {
  55236. this.resultBuffer.destroy();
  55237. this.resultBuffer = null;
  55238. }
  55239. this.queryOffsets.clear();
  55240. this.pendingResolve = null;
  55241. }
  55242. }
  55243. /*// debugger tools
  55244. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  55245. //*/
  55246. /**
  55247. * A backend implementation targeting WebGPU.
  55248. *
  55249. * @private
  55250. * @augments Backend
  55251. */
  55252. class WebGPUBackend extends Backend {
  55253. /**
  55254. * WebGPUBackend options.
  55255. *
  55256. * @typedef {Object} WebGPUBackend~Options
  55257. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  55258. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  55259. * @property {boolean} [compatibilityMode=false] - Whether the backend should be in compatibility mode or not.
  55260. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  55261. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  55262. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  55263. * @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.
  55264. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  55265. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  55266. * @property {string} [powerPreference=undefined] - The power preference.
  55267. * @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.
  55268. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  55269. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  55270. */
  55271. /**
  55272. * Constructs a new WebGPU backend.
  55273. *
  55274. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  55275. */
  55276. constructor( parameters = {} ) {
  55277. super( parameters );
  55278. /**
  55279. * This flag can be used for type testing.
  55280. *
  55281. * @type {boolean}
  55282. * @readonly
  55283. * @default true
  55284. */
  55285. this.isWebGPUBackend = true;
  55286. // some parameters require default values other than "undefined"
  55287. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  55288. this.parameters.compatibilityMode = ( parameters.compatibilityMode === undefined ) ? false : parameters.compatibilityMode;
  55289. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  55290. /**
  55291. * Indicates whether the backend is in compatibility mode or not.
  55292. * @type {boolean}
  55293. * @default false
  55294. */
  55295. this.compatibilityMode = this.parameters.compatibilityMode;
  55296. /**
  55297. * A reference to the device.
  55298. *
  55299. * @type {?GPUDevice}
  55300. * @default null
  55301. */
  55302. this.device = null;
  55303. /**
  55304. * A reference to the default render pass descriptor.
  55305. *
  55306. * @type {?Object}
  55307. * @default null
  55308. */
  55309. this.defaultRenderPassdescriptor = null;
  55310. /**
  55311. * A reference to a backend module holding common utility functions.
  55312. *
  55313. * @type {WebGPUUtils}
  55314. */
  55315. this.utils = new WebGPUUtils( this );
  55316. /**
  55317. * A reference to a backend module holding shader attribute-related
  55318. * utility functions.
  55319. *
  55320. * @type {WebGPUAttributeUtils}
  55321. */
  55322. this.attributeUtils = new WebGPUAttributeUtils( this );
  55323. /**
  55324. * A reference to a backend module holding shader binding-related
  55325. * utility functions.
  55326. *
  55327. * @type {WebGPUBindingUtils}
  55328. */
  55329. this.bindingUtils = new WebGPUBindingUtils( this );
  55330. /**
  55331. * A reference to a backend module holding shader pipeline-related
  55332. * utility functions.
  55333. *
  55334. * @type {WebGPUPipelineUtils}
  55335. */
  55336. this.pipelineUtils = new WebGPUPipelineUtils( this );
  55337. /**
  55338. * A reference to a backend module holding shader texture-related
  55339. * utility functions.
  55340. *
  55341. * @type {WebGPUTextureUtils}
  55342. */
  55343. this.textureUtils = new WebGPUTextureUtils( this );
  55344. /**
  55345. * A map that manages the resolve buffers for occlusion queries.
  55346. *
  55347. * @type {Map<number,GPUBuffer>}
  55348. */
  55349. this.occludedResolveCache = new Map();
  55350. }
  55351. /**
  55352. * Initializes the backend so it is ready for usage.
  55353. *
  55354. * @async
  55355. * @param {Renderer} renderer - The renderer.
  55356. * @return {Promise} A Promise that resolves when the backend has been initialized.
  55357. */
  55358. async init( renderer ) {
  55359. await super.init( renderer );
  55360. //
  55361. const parameters = this.parameters;
  55362. // create the device if it is not passed with parameters
  55363. let device;
  55364. if ( parameters.device === undefined ) {
  55365. const adapterOptions = {
  55366. powerPreference: parameters.powerPreference,
  55367. featureLevel: parameters.compatibilityMode ? 'compatibility' : undefined
  55368. };
  55369. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  55370. if ( adapter === null ) {
  55371. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  55372. }
  55373. // feature support
  55374. const features = Object.values( GPUFeatureName );
  55375. const supportedFeatures = [];
  55376. for ( const name of features ) {
  55377. if ( adapter.features.has( name ) ) {
  55378. supportedFeatures.push( name );
  55379. }
  55380. }
  55381. const deviceDescriptor = {
  55382. requiredFeatures: supportedFeatures,
  55383. requiredLimits: parameters.requiredLimits
  55384. };
  55385. device = await adapter.requestDevice( deviceDescriptor );
  55386. } else {
  55387. device = parameters.device;
  55388. }
  55389. device.lost.then( ( info ) => {
  55390. if ( info.reason === 'destroyed' ) return;
  55391. const deviceLossInfo = {
  55392. api: 'WebGPU',
  55393. message: info.message || 'Unknown reason',
  55394. reason: info.reason || null,
  55395. originalEvent: info
  55396. };
  55397. renderer.onDeviceLost( deviceLossInfo );
  55398. } );
  55399. this.device = device;
  55400. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  55401. this.updateSize();
  55402. }
  55403. /**
  55404. * A reference to the context.
  55405. *
  55406. * @type {?GPUCanvasContext}
  55407. * @default null
  55408. */
  55409. get context() {
  55410. const canvasTarget = this.renderer.getCanvasTarget();
  55411. const canvasData = this.get( canvasTarget );
  55412. let context = canvasData.context;
  55413. if ( context === undefined ) {
  55414. const parameters = this.parameters;
  55415. if ( canvasTarget.isDefaultCanvasTarget === true && parameters.context !== undefined ) {
  55416. context = parameters.context;
  55417. } else {
  55418. context = canvasTarget.domElement.getContext( 'webgpu' );
  55419. }
  55420. // OffscreenCanvas does not have setAttribute, see #22811
  55421. if ( 'setAttribute' in canvasTarget.domElement ) canvasTarget.domElement.setAttribute( 'data-engine', `three.js r${ REVISION } webgpu` );
  55422. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  55423. const toneMappingMode = parameters.outputType === HalfFloatType ? 'extended' : 'standard';
  55424. context.configure( {
  55425. device: this.device,
  55426. format: this.utils.getPreferredCanvasFormat(),
  55427. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  55428. alphaMode: alphaMode,
  55429. toneMapping: {
  55430. mode: toneMappingMode
  55431. }
  55432. } );
  55433. canvasData.context = context;
  55434. }
  55435. return context;
  55436. }
  55437. /**
  55438. * The coordinate system of the backend.
  55439. *
  55440. * @type {number}
  55441. * @readonly
  55442. */
  55443. get coordinateSystem() {
  55444. return WebGPUCoordinateSystem;
  55445. }
  55446. /**
  55447. * This method performs a readback operation by moving buffer data from
  55448. * a storage buffer attribute from the GPU to the CPU.
  55449. *
  55450. * @async
  55451. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  55452. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  55453. */
  55454. async getArrayBufferAsync( attribute ) {
  55455. return await this.attributeUtils.getArrayBufferAsync( attribute );
  55456. }
  55457. /**
  55458. * Returns the backend's rendering context.
  55459. *
  55460. * @return {GPUCanvasContext} The rendering context.
  55461. */
  55462. getContext() {
  55463. return this.context;
  55464. }
  55465. /**
  55466. * Returns the default render pass descriptor.
  55467. *
  55468. * In WebGPU, the default framebuffer must be configured
  55469. * like custom framebuffers so the backend needs a render
  55470. * pass descriptor even when rendering directly to screen.
  55471. *
  55472. * @private
  55473. * @return {Object} The render pass descriptor.
  55474. */
  55475. _getDefaultRenderPassDescriptor() {
  55476. const renderer = this.renderer;
  55477. const canvasTarget = renderer.getCanvasTarget();
  55478. const canvasData = this.get( canvasTarget );
  55479. const samples = renderer.currentSamples;
  55480. let descriptor = canvasData.descriptor;
  55481. if ( descriptor === undefined || canvasData.samples !== samples ) {
  55482. descriptor = {
  55483. colorAttachments: [ {
  55484. view: null
  55485. } ]
  55486. };
  55487. if ( renderer.depth === true || renderer.stencil === true ) {
  55488. descriptor.depthStencilAttachment = {
  55489. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  55490. };
  55491. }
  55492. const colorAttachment = descriptor.colorAttachments[ 0 ];
  55493. if ( samples > 0 ) {
  55494. colorAttachment.view = this.textureUtils.getColorBuffer().createView();
  55495. } else {
  55496. colorAttachment.resolveTarget = undefined;
  55497. }
  55498. canvasData.descriptor = descriptor;
  55499. canvasData.samples = samples;
  55500. }
  55501. const colorAttachment = descriptor.colorAttachments[ 0 ];
  55502. if ( samples > 0 ) {
  55503. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  55504. } else {
  55505. colorAttachment.view = this.context.getCurrentTexture().createView();
  55506. }
  55507. return descriptor;
  55508. }
  55509. /**
  55510. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  55511. *
  55512. * @param {RenderContext} renderContext - The render context.
  55513. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  55514. *
  55515. * @private
  55516. */
  55517. _isRenderCameraDepthArray( renderContext ) {
  55518. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  55519. }
  55520. /**
  55521. * Returns the render pass descriptor for the given render context.
  55522. *
  55523. * @private
  55524. * @param {RenderContext} renderContext - The render context.
  55525. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  55526. * @return {Object} The render pass descriptor.
  55527. */
  55528. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  55529. const renderTarget = renderContext.renderTarget;
  55530. const renderTargetData = this.get( renderTarget );
  55531. let descriptors = renderTargetData.descriptors;
  55532. if ( descriptors === undefined ||
  55533. renderTargetData.width !== renderTarget.width ||
  55534. renderTargetData.height !== renderTarget.height ||
  55535. renderTargetData.samples !== renderTarget.samples
  55536. ) {
  55537. descriptors = {};
  55538. renderTargetData.descriptors = descriptors;
  55539. }
  55540. const cacheKey = renderContext.getCacheKey();
  55541. let descriptorBase = descriptors[ cacheKey ];
  55542. if ( descriptorBase === undefined ) {
  55543. const textures = renderContext.textures;
  55544. const textureViews = [];
  55545. let sliceIndex;
  55546. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  55547. for ( let i = 0; i < textures.length; i ++ ) {
  55548. const textureData = this.get( textures[ i ] );
  55549. const viewDescriptor = {
  55550. label: `colorAttachment_${ i }`,
  55551. baseMipLevel: renderContext.activeMipmapLevel,
  55552. mipLevelCount: 1,
  55553. baseArrayLayer: renderContext.activeCubeFace,
  55554. arrayLayerCount: 1,
  55555. dimension: GPUTextureViewDimension.TwoD
  55556. };
  55557. if ( renderTarget.isRenderTarget3D ) {
  55558. sliceIndex = renderContext.activeCubeFace;
  55559. viewDescriptor.baseArrayLayer = 0;
  55560. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  55561. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  55562. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  55563. if ( isRenderCameraDepthArray === true ) {
  55564. const cameras = renderContext.camera.cameras;
  55565. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  55566. const layerViewDescriptor = {
  55567. ...viewDescriptor,
  55568. baseArrayLayer: layer,
  55569. arrayLayerCount: 1,
  55570. dimension: GPUTextureViewDimension.TwoD
  55571. };
  55572. const textureView = textureData.texture.createView( layerViewDescriptor );
  55573. textureViews.push( {
  55574. view: textureView,
  55575. resolveTarget: undefined,
  55576. depthSlice: undefined
  55577. } );
  55578. }
  55579. } else {
  55580. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  55581. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  55582. }
  55583. }
  55584. if ( isRenderCameraDepthArray !== true ) {
  55585. const textureView = textureData.texture.createView( viewDescriptor );
  55586. let view, resolveTarget;
  55587. if ( textureData.msaaTexture !== undefined ) {
  55588. view = textureData.msaaTexture.createView();
  55589. resolveTarget = textureView;
  55590. } else {
  55591. view = textureView;
  55592. resolveTarget = undefined;
  55593. }
  55594. textureViews.push( {
  55595. view,
  55596. resolveTarget,
  55597. depthSlice: sliceIndex
  55598. } );
  55599. }
  55600. }
  55601. descriptorBase = { textureViews };
  55602. if ( renderContext.depth ) {
  55603. const depthTextureData = this.get( renderContext.depthTexture );
  55604. const options = {};
  55605. if ( renderContext.depthTexture.isArrayTexture || renderContext.depthTexture.isCubeTexture ) {
  55606. options.dimension = GPUTextureViewDimension.TwoD;
  55607. options.arrayLayerCount = 1;
  55608. options.baseArrayLayer = renderContext.activeCubeFace;
  55609. }
  55610. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  55611. }
  55612. descriptors[ cacheKey ] = descriptorBase;
  55613. renderTargetData.width = renderTarget.width;
  55614. renderTargetData.height = renderTarget.height;
  55615. renderTargetData.samples = renderTarget.samples;
  55616. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  55617. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  55618. }
  55619. const descriptor = {
  55620. colorAttachments: []
  55621. };
  55622. // Apply dynamic properties to cached views
  55623. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  55624. const viewInfo = descriptorBase.textureViews[ i ];
  55625. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  55626. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  55627. clearValue = colorAttachmentsConfig.clearValue;
  55628. }
  55629. descriptor.colorAttachments.push( {
  55630. view: viewInfo.view,
  55631. depthSlice: viewInfo.depthSlice,
  55632. resolveTarget: viewInfo.resolveTarget,
  55633. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  55634. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  55635. clearValue: clearValue
  55636. } );
  55637. }
  55638. if ( descriptorBase.depthStencilView ) {
  55639. descriptor.depthStencilAttachment = {
  55640. view: descriptorBase.depthStencilView
  55641. };
  55642. }
  55643. return descriptor;
  55644. }
  55645. /**
  55646. * This method is executed at the beginning of a render call and prepares
  55647. * the WebGPU state for upcoming render calls
  55648. *
  55649. * @param {RenderContext} renderContext - The render context.
  55650. */
  55651. beginRender( renderContext ) {
  55652. const renderContextData = this.get( renderContext );
  55653. //
  55654. const device = this.device;
  55655. const occlusionQueryCount = renderContext.occlusionQueryCount;
  55656. let occlusionQuerySet;
  55657. if ( occlusionQueryCount > 0 ) {
  55658. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  55659. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  55660. // Get a reference to the array of objects with queries. The renderContextData property
  55661. // can be changed by another render pass before the buffer.mapAsyc() completes.
  55662. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  55663. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  55664. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  55665. //
  55666. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  55667. renderContextData.occlusionQuerySet = occlusionQuerySet;
  55668. renderContextData.occlusionQueryIndex = 0;
  55669. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  55670. renderContextData.lastOcclusionObject = null;
  55671. }
  55672. let descriptor;
  55673. if ( renderContext.textures === null ) {
  55674. descriptor = this._getDefaultRenderPassDescriptor();
  55675. } else {
  55676. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  55677. }
  55678. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ), descriptor );
  55679. descriptor.occlusionQuerySet = occlusionQuerySet;
  55680. const depthStencilAttachment = descriptor.depthStencilAttachment;
  55681. if ( renderContext.textures !== null ) {
  55682. const colorAttachments = descriptor.colorAttachments;
  55683. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  55684. const colorAttachment = colorAttachments[ i ];
  55685. if ( renderContext.clearColor ) {
  55686. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  55687. colorAttachment.loadOp = GPULoadOp.Clear;
  55688. } else {
  55689. colorAttachment.loadOp = GPULoadOp.Load;
  55690. }
  55691. colorAttachment.storeOp = GPUStoreOp.Store;
  55692. }
  55693. } else {
  55694. const colorAttachment = descriptor.colorAttachments[ 0 ];
  55695. if ( renderContext.clearColor ) {
  55696. colorAttachment.clearValue = renderContext.clearColorValue;
  55697. colorAttachment.loadOp = GPULoadOp.Clear;
  55698. } else {
  55699. colorAttachment.loadOp = GPULoadOp.Load;
  55700. }
  55701. colorAttachment.storeOp = GPUStoreOp.Store;
  55702. }
  55703. //
  55704. if ( renderContext.depth ) {
  55705. if ( renderContext.clearDepth ) {
  55706. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  55707. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  55708. } else {
  55709. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  55710. }
  55711. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  55712. }
  55713. if ( renderContext.stencil ) {
  55714. if ( renderContext.clearStencil ) {
  55715. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  55716. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  55717. } else {
  55718. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  55719. }
  55720. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  55721. }
  55722. //
  55723. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  55724. // shadow arrays - prepare bundle encoders for each camera in an array camera
  55725. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  55726. const cameras = renderContext.camera.cameras;
  55727. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  55728. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  55729. } else {
  55730. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  55731. }
  55732. // Create bundle encoders for each layer
  55733. renderContextData.bundleEncoders = [];
  55734. renderContextData.bundleSets = [];
  55735. // Create separate bundle encoders for each camera in the array
  55736. for ( let i = 0; i < cameras.length; i ++ ) {
  55737. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  55738. renderContext,
  55739. 'renderBundleArrayCamera_' + i
  55740. );
  55741. // Initialize state tracking for this bundle
  55742. const bundleSets = {
  55743. attributes: {},
  55744. bindingGroups: [],
  55745. pipeline: null,
  55746. index: null
  55747. };
  55748. renderContextData.bundleEncoders.push( bundleEncoder );
  55749. renderContextData.bundleSets.push( bundleSets );
  55750. }
  55751. // We'll complete the bundles in finishRender
  55752. renderContextData.currentPass = null;
  55753. } else {
  55754. const currentPass = encoder.beginRenderPass( descriptor );
  55755. renderContextData.currentPass = currentPass;
  55756. if ( renderContext.viewport ) {
  55757. this.updateViewport( renderContext );
  55758. }
  55759. if ( renderContext.scissor ) {
  55760. this.updateScissor( renderContext );
  55761. }
  55762. }
  55763. //
  55764. renderContextData.descriptor = descriptor;
  55765. renderContextData.encoder = encoder;
  55766. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  55767. renderContextData.renderBundles = [];
  55768. }
  55769. /**
  55770. * This method creates layer descriptors for each camera in an array camera
  55771. * to prepare for rendering to a depth array texture.
  55772. *
  55773. * @param {RenderContext} renderContext - The render context.
  55774. * @param {Object} renderContextData - The render context data.
  55775. * @param {Object} descriptor - The render pass descriptor.
  55776. * @param {ArrayCamera} cameras - The array camera.
  55777. *
  55778. * @private
  55779. */
  55780. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  55781. const depthStencilAttachment = descriptor.depthStencilAttachment;
  55782. renderContextData.layerDescriptors = [];
  55783. const depthTextureData = this.get( renderContext.depthTexture );
  55784. if ( ! depthTextureData.viewCache ) {
  55785. depthTextureData.viewCache = [];
  55786. }
  55787. for ( let i = 0; i < cameras.length; i ++ ) {
  55788. const layerDescriptor = {
  55789. ...descriptor,
  55790. colorAttachments: [ {
  55791. ...descriptor.colorAttachments[ 0 ],
  55792. view: descriptor.colorAttachments[ i ].view
  55793. } ]
  55794. };
  55795. if ( descriptor.depthStencilAttachment ) {
  55796. const layerIndex = i;
  55797. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  55798. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  55799. dimension: GPUTextureViewDimension.TwoD,
  55800. baseArrayLayer: i,
  55801. arrayLayerCount: 1
  55802. } );
  55803. }
  55804. layerDescriptor.depthStencilAttachment = {
  55805. view: depthTextureData.viewCache[ layerIndex ],
  55806. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  55807. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  55808. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  55809. };
  55810. if ( renderContext.stencil ) {
  55811. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  55812. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  55813. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  55814. }
  55815. } else {
  55816. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  55817. }
  55818. renderContextData.layerDescriptors.push( layerDescriptor );
  55819. }
  55820. }
  55821. /**
  55822. * This method updates the layer descriptors for each camera in an array camera
  55823. * to prepare for rendering to a depth array texture.
  55824. *
  55825. * @param {RenderContext} renderContext - The render context.
  55826. * @param {Object} renderContextData - The render context data.
  55827. * @param {ArrayCamera} cameras - The array camera.
  55828. *
  55829. */
  55830. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  55831. for ( let i = 0; i < cameras.length; i ++ ) {
  55832. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  55833. if ( layerDescriptor.depthStencilAttachment ) {
  55834. const depthAttachment = layerDescriptor.depthStencilAttachment;
  55835. if ( renderContext.depth ) {
  55836. if ( renderContext.clearDepth ) {
  55837. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  55838. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  55839. } else {
  55840. depthAttachment.depthLoadOp = GPULoadOp.Load;
  55841. }
  55842. }
  55843. if ( renderContext.stencil ) {
  55844. if ( renderContext.clearStencil ) {
  55845. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  55846. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  55847. } else {
  55848. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  55849. }
  55850. }
  55851. }
  55852. }
  55853. }
  55854. /**
  55855. * This method is executed at the end of a render call and finalizes work
  55856. * after draw calls.
  55857. *
  55858. * @param {RenderContext} renderContext - The render context.
  55859. */
  55860. finishRender( renderContext ) {
  55861. const renderContextData = this.get( renderContext );
  55862. const occlusionQueryCount = renderContext.occlusionQueryCount;
  55863. if ( renderContextData.renderBundles.length > 0 ) {
  55864. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  55865. }
  55866. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  55867. renderContextData.currentPass.endOcclusionQuery();
  55868. }
  55869. // shadow arrays - Execute bundles for each layer
  55870. const encoder = renderContextData.encoder;
  55871. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  55872. const bundles = [];
  55873. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  55874. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  55875. bundles.push( bundleEncoder.finish() );
  55876. }
  55877. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  55878. if ( i < bundles.length ) {
  55879. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  55880. const renderPass = encoder.beginRenderPass( layerDescriptor );
  55881. if ( renderContext.viewport ) {
  55882. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  55883. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  55884. }
  55885. if ( renderContext.scissor ) {
  55886. const { x, y, width, height } = renderContext.scissorValue;
  55887. renderPass.setScissorRect( x, y, width, height );
  55888. }
  55889. renderPass.executeBundles( [ bundles[ i ] ] );
  55890. renderPass.end();
  55891. }
  55892. }
  55893. } else if ( renderContextData.currentPass ) {
  55894. renderContextData.currentPass.end();
  55895. }
  55896. if ( occlusionQueryCount > 0 ) {
  55897. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  55898. //
  55899. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  55900. if ( queryResolveBuffer === undefined ) {
  55901. queryResolveBuffer = this.device.createBuffer(
  55902. {
  55903. size: bufferSize,
  55904. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  55905. }
  55906. );
  55907. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  55908. }
  55909. //
  55910. const readBuffer = this.device.createBuffer(
  55911. {
  55912. size: bufferSize,
  55913. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  55914. }
  55915. );
  55916. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  55917. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  55918. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  55919. renderContextData.occlusionQueryBuffer = readBuffer;
  55920. //
  55921. this.resolveOccludedAsync( renderContext );
  55922. }
  55923. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  55924. //
  55925. if ( renderContext.textures !== null ) {
  55926. const textures = renderContext.textures;
  55927. for ( let i = 0; i < textures.length; i ++ ) {
  55928. const texture = textures[ i ];
  55929. if ( texture.generateMipmaps === true ) {
  55930. this.textureUtils.generateMipmaps( texture );
  55931. }
  55932. }
  55933. }
  55934. }
  55935. /**
  55936. * Returns `true` if the given 3D object is fully occluded by other
  55937. * 3D objects in the scene.
  55938. *
  55939. * @param {RenderContext} renderContext - The render context.
  55940. * @param {Object3D} object - The 3D object to test.
  55941. * @return {boolean} Whether the 3D object is fully occluded or not.
  55942. */
  55943. isOccluded( renderContext, object ) {
  55944. const renderContextData = this.get( renderContext );
  55945. return renderContextData.occluded && renderContextData.occluded.has( object );
  55946. }
  55947. /**
  55948. * This method processes the result of occlusion queries and writes it
  55949. * into render context data.
  55950. *
  55951. * @async
  55952. * @param {RenderContext} renderContext - The render context.
  55953. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  55954. */
  55955. async resolveOccludedAsync( renderContext ) {
  55956. const renderContextData = this.get( renderContext );
  55957. // handle occlusion query results
  55958. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  55959. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  55960. const occluded = new WeakSet();
  55961. renderContextData.currentOcclusionQueryObjects = null;
  55962. renderContextData.currentOcclusionQueryBuffer = null;
  55963. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  55964. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  55965. const results = new BigUint64Array( buffer );
  55966. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  55967. if ( results[ i ] === BigInt( 0 ) ) {
  55968. occluded.add( currentOcclusionQueryObjects[ i ] );
  55969. }
  55970. }
  55971. currentOcclusionQueryBuffer.destroy();
  55972. renderContextData.occluded = occluded;
  55973. }
  55974. }
  55975. /**
  55976. * Updates the viewport with the values from the given render context.
  55977. *
  55978. * @param {RenderContext} renderContext - The render context.
  55979. */
  55980. updateViewport( renderContext ) {
  55981. const { currentPass } = this.get( renderContext );
  55982. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  55983. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  55984. }
  55985. /**
  55986. * Updates the scissor with the values from the given render context.
  55987. *
  55988. * @param {RenderContext} renderContext - The render context.
  55989. */
  55990. updateScissor( renderContext ) {
  55991. const { currentPass } = this.get( renderContext );
  55992. const { x, y, width, height } = renderContext.scissorValue;
  55993. currentPass.setScissorRect( x, y, width, height );
  55994. }
  55995. /**
  55996. * Returns the clear color and alpha into a single
  55997. * color object.
  55998. *
  55999. * @return {Color4} The clear color.
  56000. */
  56001. getClearColor() {
  56002. const clearColor = super.getClearColor();
  56003. // only premultiply alpha when alphaMode is "premultiplied"
  56004. if ( this.renderer.alpha === true ) {
  56005. clearColor.r *= clearColor.a;
  56006. clearColor.g *= clearColor.a;
  56007. clearColor.b *= clearColor.a;
  56008. }
  56009. return clearColor;
  56010. }
  56011. /**
  56012. * Performs a clear operation.
  56013. *
  56014. * @param {boolean} color - Whether the color buffer should be cleared or not.
  56015. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  56016. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  56017. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  56018. */
  56019. clear( color, depth, stencil, renderTargetContext = null ) {
  56020. const device = this.device;
  56021. const renderer = this.renderer;
  56022. let colorAttachments = [];
  56023. let depthStencilAttachment;
  56024. let clearValue;
  56025. let supportsDepth;
  56026. let supportsStencil;
  56027. if ( color ) {
  56028. const clearColor = this.getClearColor();
  56029. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  56030. }
  56031. if ( renderTargetContext === null ) {
  56032. supportsDepth = renderer.depth;
  56033. supportsStencil = renderer.stencil;
  56034. const descriptor = this._getDefaultRenderPassDescriptor();
  56035. if ( color ) {
  56036. colorAttachments = descriptor.colorAttachments;
  56037. const colorAttachment = colorAttachments[ 0 ];
  56038. colorAttachment.clearValue = clearValue;
  56039. colorAttachment.loadOp = GPULoadOp.Clear;
  56040. colorAttachment.storeOp = GPUStoreOp.Store;
  56041. }
  56042. if ( supportsDepth || supportsStencil ) {
  56043. depthStencilAttachment = descriptor.depthStencilAttachment;
  56044. }
  56045. } else {
  56046. supportsDepth = renderTargetContext.depth;
  56047. supportsStencil = renderTargetContext.stencil;
  56048. const clearConfig = {
  56049. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  56050. clearValue: color ? clearValue : undefined
  56051. };
  56052. if ( supportsDepth ) {
  56053. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  56054. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  56055. clearConfig.depthStoreOp = GPUStoreOp.Store;
  56056. }
  56057. if ( supportsStencil ) {
  56058. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  56059. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  56060. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  56061. }
  56062. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  56063. colorAttachments = descriptor.colorAttachments;
  56064. depthStencilAttachment = descriptor.depthStencilAttachment;
  56065. }
  56066. if ( supportsDepth && depthStencilAttachment ) {
  56067. if ( depth ) {
  56068. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  56069. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  56070. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  56071. } else {
  56072. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  56073. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  56074. }
  56075. }
  56076. //
  56077. if ( supportsStencil && depthStencilAttachment ) {
  56078. if ( stencil ) {
  56079. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  56080. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  56081. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  56082. } else {
  56083. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  56084. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  56085. }
  56086. }
  56087. //
  56088. const encoder = device.createCommandEncoder( { label: 'clear' } );
  56089. const currentPass = encoder.beginRenderPass( {
  56090. colorAttachments,
  56091. depthStencilAttachment
  56092. } );
  56093. currentPass.end();
  56094. device.queue.submit( [ encoder.finish() ] );
  56095. }
  56096. // compute
  56097. /**
  56098. * This method is executed at the beginning of a compute call and
  56099. * prepares the state for upcoming compute tasks.
  56100. *
  56101. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  56102. */
  56103. beginCompute( computeGroup ) {
  56104. const groupGPU = this.get( computeGroup );
  56105. //
  56106. const descriptor = {
  56107. label: 'computeGroup_' + computeGroup.id
  56108. };
  56109. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ), descriptor );
  56110. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  56111. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  56112. }
  56113. /**
  56114. * Executes a compute command for the given compute node.
  56115. *
  56116. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  56117. * @param {Node} computeNode - The compute node.
  56118. * @param {Array<BindGroup>} bindings - The bindings.
  56119. * @param {ComputePipeline} pipeline - The compute pipeline.
  56120. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  56121. * - A single number representing count, or
  56122. * - An array [x, y, z] representing dispatch size, or
  56123. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  56124. */
  56125. compute( computeGroup, computeNode, bindings, pipeline, dispatchSize = null ) {
  56126. const computeNodeData = this.get( computeNode );
  56127. const { passEncoderGPU } = this.get( computeGroup );
  56128. // pipeline
  56129. const pipelineGPU = this.get( pipeline ).pipeline;
  56130. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  56131. // bind groups
  56132. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  56133. const bindGroup = bindings[ i ];
  56134. const bindingsData = this.get( bindGroup );
  56135. passEncoderGPU.setBindGroup( i, bindingsData.group );
  56136. }
  56137. if ( dispatchSize === null ) {
  56138. dispatchSize = computeNode.count;
  56139. }
  56140. // When the dispatchSize is set with a StorageBuffer from the GPU.
  56141. if ( dispatchSize && typeof dispatchSize === 'object' && dispatchSize.isIndirectStorageBufferAttribute ) {
  56142. const dispatchBuffer = this.get( dispatchSize ).buffer;
  56143. passEncoderGPU.dispatchWorkgroupsIndirect( dispatchBuffer, 0 );
  56144. return;
  56145. }
  56146. if ( typeof dispatchSize === 'number' ) {
  56147. // If a single number is given, we calculate the dispatch size based on the workgroup size
  56148. const count = dispatchSize;
  56149. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  56150. // cache dispatch size to avoid recalculating it every time
  56151. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  56152. computeNodeData.count = count;
  56153. const workgroupSize = computeNode.workgroupSize;
  56154. let size = workgroupSize[ 0 ];
  56155. for ( let i = 1; i < workgroupSize.length; i ++ )
  56156. size *= workgroupSize[ i ];
  56157. const dispatchCount = Math.ceil( count / size );
  56158. //
  56159. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  56160. dispatchSize = [ dispatchCount, 1, 1 ];
  56161. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  56162. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  56163. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  56164. }
  56165. computeNodeData.dispatchSize = dispatchSize;
  56166. }
  56167. dispatchSize = computeNodeData.dispatchSize;
  56168. }
  56169. //
  56170. passEncoderGPU.dispatchWorkgroups(
  56171. dispatchSize[ 0 ],
  56172. dispatchSize[ 1 ] || 1,
  56173. dispatchSize[ 2 ] || 1
  56174. );
  56175. }
  56176. /**
  56177. * This method is executed at the end of a compute call and
  56178. * finalizes work after compute tasks.
  56179. *
  56180. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  56181. */
  56182. finishCompute( computeGroup ) {
  56183. const groupData = this.get( computeGroup );
  56184. groupData.passEncoderGPU.end();
  56185. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  56186. }
  56187. // render object
  56188. /**
  56189. * Executes a draw command for the given render object.
  56190. *
  56191. * @param {RenderObject} renderObject - The render object to draw.
  56192. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  56193. */
  56194. draw( renderObject, info ) {
  56195. const { object, material, context, pipeline } = renderObject;
  56196. const bindings = renderObject.getBindings();
  56197. const renderContextData = this.get( context );
  56198. const pipelineData = this.get( pipeline );
  56199. const pipelineGPU = pipelineData.pipeline;
  56200. if ( pipelineData.error === true ) return;
  56201. const index = renderObject.getIndex();
  56202. const hasIndex = ( index !== null );
  56203. const drawParams = renderObject.getDrawParameters();
  56204. if ( drawParams === null ) return;
  56205. // pipeline
  56206. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  56207. // pipeline
  56208. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  56209. currentSets.pipeline = pipelineGPU;
  56210. // bind groups
  56211. const currentBindingGroups = currentSets.bindingGroups;
  56212. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  56213. const bindGroup = bindings[ i ];
  56214. const bindingsData = this.get( bindGroup );
  56215. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  56216. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  56217. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  56218. }
  56219. }
  56220. // attributes
  56221. // index
  56222. if ( hasIndex === true ) {
  56223. if ( currentSets.index !== index ) {
  56224. const buffer = this.get( index ).buffer;
  56225. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  56226. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  56227. currentSets.index = index;
  56228. }
  56229. }
  56230. // vertex buffers
  56231. const vertexBuffers = renderObject.getVertexBuffers();
  56232. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  56233. const vertexBuffer = vertexBuffers[ i ];
  56234. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  56235. const buffer = this.get( vertexBuffer ).buffer;
  56236. passEncoderGPU.setVertexBuffer( i, buffer );
  56237. currentSets.attributes[ i ] = vertexBuffer;
  56238. }
  56239. }
  56240. // stencil
  56241. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  56242. passEncoderGPU.setStencilReference( material.stencilRef );
  56243. renderContextData.currentStencilRef = material.stencilRef;
  56244. }
  56245. };
  56246. // Define draw function
  56247. const draw = ( passEncoderGPU, currentSets ) => {
  56248. setPipelineAndBindings( passEncoderGPU, currentSets );
  56249. if ( object.isBatchedMesh === true ) {
  56250. const starts = object._multiDrawStarts;
  56251. const counts = object._multiDrawCounts;
  56252. const drawCount = object._multiDrawCount;
  56253. const drawInstances = object._multiDrawInstances;
  56254. if ( drawInstances !== null ) {
  56255. // @deprecated, r174
  56256. warnOnce( 'WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  56257. }
  56258. for ( let i = 0; i < drawCount; i ++ ) {
  56259. const count = drawInstances ? drawInstances[ i ] : 1;
  56260. const firstInstance = count > 1 ? 0 : i;
  56261. if ( hasIndex === true ) {
  56262. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  56263. } else {
  56264. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  56265. }
  56266. info.update( object, counts[ i ], count );
  56267. }
  56268. } else if ( hasIndex === true ) {
  56269. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  56270. const indirect = renderObject.getIndirect();
  56271. if ( indirect !== null ) {
  56272. const buffer = this.get( indirect ).buffer;
  56273. const indirectOffset = renderObject.getIndirectOffset();
  56274. const indirectOffsets = Array.isArray( indirectOffset ) ? indirectOffset : [ indirectOffset ];
  56275. for ( let i = 0; i < indirectOffsets.length; i ++ ) {
  56276. passEncoderGPU.drawIndexedIndirect( buffer, indirectOffsets[ i ] );
  56277. }
  56278. } else {
  56279. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  56280. }
  56281. info.update( object, indexCount, instanceCount );
  56282. } else {
  56283. const { vertexCount, instanceCount, firstVertex } = drawParams;
  56284. const indirect = renderObject.getIndirect();
  56285. if ( indirect !== null ) {
  56286. const buffer = this.get( indirect ).buffer;
  56287. const indirectOffset = renderObject.getIndirectOffset();
  56288. const indirectOffsets = Array.isArray( indirectOffset ) ? indirectOffset : [ indirectOffset ];
  56289. for ( let i = 0; i < indirectOffsets.length; i ++ ) {
  56290. passEncoderGPU.drawIndirect( buffer, indirectOffsets[ i ] );
  56291. }
  56292. } else {
  56293. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  56294. }
  56295. info.update( object, vertexCount, instanceCount );
  56296. }
  56297. };
  56298. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  56299. const cameraData = this.get( renderObject.camera );
  56300. const cameras = renderObject.camera.cameras;
  56301. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  56302. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  56303. const bindingsData = this.get( cameraIndex );
  56304. const indexesGPU = [];
  56305. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  56306. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  56307. data[ 0 ] = i;
  56308. const { layoutGPU } = bindingsData.layout;
  56309. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, layoutGPU );
  56310. indexesGPU.push( bindGroupIndex );
  56311. }
  56312. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  56313. }
  56314. const pixelRatio = this.renderer.getPixelRatio();
  56315. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  56316. const subCamera = cameras[ i ];
  56317. if ( object.layers.test( subCamera.layers ) ) {
  56318. const vp = subCamera.viewport;
  56319. let pass = renderContextData.currentPass;
  56320. let sets = renderContextData.currentSets;
  56321. if ( renderContextData.bundleEncoders ) {
  56322. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  56323. const bundleSets = renderContextData.bundleSets[ i ];
  56324. pass = bundleEncoder;
  56325. sets = bundleSets;
  56326. }
  56327. if ( vp ) {
  56328. pass.setViewport(
  56329. Math.floor( vp.x * pixelRatio ),
  56330. Math.floor( vp.y * pixelRatio ),
  56331. Math.floor( vp.width * pixelRatio ),
  56332. Math.floor( vp.height * pixelRatio ),
  56333. context.viewportValue.minDepth,
  56334. context.viewportValue.maxDepth
  56335. );
  56336. }
  56337. // Set camera index binding for this layer
  56338. if ( cameraIndex && cameraData.indexesGPU ) {
  56339. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  56340. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  56341. }
  56342. draw( pass, sets );
  56343. }
  56344. }
  56345. } else {
  56346. // Regular single camera rendering
  56347. if ( renderContextData.currentPass ) {
  56348. // Handle occlusion queries
  56349. if ( renderContextData.occlusionQuerySet !== undefined ) {
  56350. const lastObject = renderContextData.lastOcclusionObject;
  56351. if ( lastObject !== object ) {
  56352. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  56353. renderContextData.currentPass.endOcclusionQuery();
  56354. renderContextData.occlusionQueryIndex ++;
  56355. }
  56356. if ( object.occlusionTest === true ) {
  56357. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  56358. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  56359. }
  56360. renderContextData.lastOcclusionObject = object;
  56361. }
  56362. }
  56363. draw( renderContextData.currentPass, renderContextData.currentSets );
  56364. }
  56365. }
  56366. }
  56367. // cache key
  56368. /**
  56369. * Returns `true` if the render pipeline requires an update.
  56370. *
  56371. * @param {RenderObject} renderObject - The render object.
  56372. * @return {boolean} Whether the render pipeline requires an update or not.
  56373. */
  56374. needsRenderUpdate( renderObject ) {
  56375. const data = this.get( renderObject );
  56376. const { object, material } = renderObject;
  56377. const utils = this.utils;
  56378. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  56379. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  56380. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  56381. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  56382. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  56383. let needsUpdate = false;
  56384. if ( data.material !== material || data.materialVersion !== material.version ||
  56385. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  56386. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  56387. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  56388. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  56389. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  56390. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  56391. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  56392. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  56393. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  56394. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  56395. data.primitiveTopology !== primitiveTopology ||
  56396. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  56397. ) {
  56398. data.material = material; data.materialVersion = material.version;
  56399. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  56400. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  56401. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  56402. data.colorWrite = material.colorWrite;
  56403. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  56404. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  56405. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  56406. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  56407. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  56408. data.sampleCount = sampleCount;
  56409. data.colorSpace = colorSpace;
  56410. data.colorFormat = colorFormat;
  56411. data.depthStencilFormat = depthStencilFormat;
  56412. data.primitiveTopology = primitiveTopology;
  56413. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  56414. needsUpdate = true;
  56415. }
  56416. return needsUpdate;
  56417. }
  56418. /**
  56419. * Returns a cache key that is used to identify render pipelines.
  56420. *
  56421. * @param {RenderObject} renderObject - The render object.
  56422. * @return {string} The cache key.
  56423. */
  56424. getRenderCacheKey( renderObject ) {
  56425. const { object, material } = renderObject;
  56426. const utils = this.utils;
  56427. const renderContext = renderObject.context;
  56428. // meshes with negative scale have a different frontFace render pipeline
  56429. // descriptor value so the following must be honored in the cache key
  56430. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  56431. return [
  56432. material.transparent, material.blending, material.premultipliedAlpha,
  56433. material.blendSrc, material.blendDst, material.blendEquation,
  56434. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  56435. material.colorWrite,
  56436. material.depthWrite, material.depthTest, material.depthFunc,
  56437. material.stencilWrite, material.stencilFunc,
  56438. material.stencilFail, material.stencilZFail, material.stencilZPass,
  56439. material.stencilFuncMask, material.stencilWriteMask,
  56440. material.side,
  56441. frontFaceCW,
  56442. utils.getSampleCountRenderContext( renderContext ),
  56443. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  56444. utils.getPrimitiveTopology( object, material ),
  56445. renderObject.getGeometryCacheKey(),
  56446. renderObject.clippingContextCacheKey
  56447. ].join();
  56448. }
  56449. // textures
  56450. /**
  56451. * Updates a GPU sampler for the given texture.
  56452. *
  56453. * @param {Texture} texture - The texture to update the sampler for.
  56454. * @return {string} The current sampler key.
  56455. */
  56456. updateSampler( texture ) {
  56457. return this.textureUtils.updateSampler( texture );
  56458. }
  56459. /**
  56460. * Creates a default texture for the given texture that can be used
  56461. * as a placeholder until the actual texture is ready for usage.
  56462. *
  56463. * @param {Texture} texture - The texture to create a default texture for.
  56464. * @return {boolean} Whether the sampler has been updated or not.
  56465. */
  56466. createDefaultTexture( texture ) {
  56467. return this.textureUtils.createDefaultTexture( texture );
  56468. }
  56469. /**
  56470. * Defines a texture on the GPU for the given texture object.
  56471. *
  56472. * @param {Texture} texture - The texture.
  56473. * @param {Object} [options={}] - Optional configuration parameter.
  56474. */
  56475. createTexture( texture, options ) {
  56476. this.textureUtils.createTexture( texture, options );
  56477. }
  56478. /**
  56479. * Uploads the updated texture data to the GPU.
  56480. *
  56481. * @param {Texture} texture - The texture.
  56482. * @param {Object} [options={}] - Optional configuration parameter.
  56483. */
  56484. updateTexture( texture, options ) {
  56485. this.textureUtils.updateTexture( texture, options );
  56486. }
  56487. /**
  56488. * Generates mipmaps for the given texture.
  56489. *
  56490. * @param {Texture} texture - The texture.
  56491. */
  56492. generateMipmaps( texture ) {
  56493. this.textureUtils.generateMipmaps( texture );
  56494. }
  56495. /**
  56496. * Destroys the GPU data for the given texture object.
  56497. *
  56498. * @param {Texture} texture - The texture.
  56499. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  56500. */
  56501. destroyTexture( texture, isDefaultTexture = false ) {
  56502. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  56503. }
  56504. /**
  56505. * Returns texture data as a typed array.
  56506. *
  56507. * @async
  56508. * @param {Texture} texture - The texture to copy.
  56509. * @param {number} x - The x coordinate of the copy origin.
  56510. * @param {number} y - The y coordinate of the copy origin.
  56511. * @param {number} width - The width of the copy.
  56512. * @param {number} height - The height of the copy.
  56513. * @param {number} faceIndex - The face index.
  56514. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  56515. */
  56516. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  56517. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  56518. }
  56519. /**
  56520. * Inits a time stamp query for the given render context.
  56521. *
  56522. * @param {string} type - The type of the timestamp query (e.g. 'render', 'compute').
  56523. * @param {number} uid - Unique id for the context (e.g. render context id).
  56524. * @param {Object} descriptor - The query descriptor.
  56525. */
  56526. initTimestampQuery( type, uid, descriptor ) {
  56527. if ( ! this.trackTimestamp ) return;
  56528. if ( ! this.timestampQueryPool[ type ] ) {
  56529. // TODO: Variable maxQueries?
  56530. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  56531. }
  56532. const timestampQueryPool = this.timestampQueryPool[ type ];
  56533. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  56534. descriptor.timestampWrites = {
  56535. querySet: timestampQueryPool.querySet,
  56536. beginningOfPassWriteIndex: baseOffset,
  56537. endOfPassWriteIndex: baseOffset + 1,
  56538. };
  56539. }
  56540. // node builder
  56541. /**
  56542. * Returns a node builder for the given render object.
  56543. *
  56544. * @param {RenderObject} object - The render object.
  56545. * @param {Renderer} renderer - The renderer.
  56546. * @return {WGSLNodeBuilder} The node builder.
  56547. */
  56548. createNodeBuilder( object, renderer ) {
  56549. return new WGSLNodeBuilder( object, renderer );
  56550. }
  56551. // program
  56552. /**
  56553. * Creates a shader program from the given programmable stage.
  56554. *
  56555. * @param {ProgrammableStage} program - The programmable stage.
  56556. */
  56557. createProgram( program ) {
  56558. const programGPU = this.get( program );
  56559. programGPU.module = {
  56560. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  56561. entryPoint: 'main'
  56562. };
  56563. }
  56564. /**
  56565. * Destroys the shader program of the given programmable stage.
  56566. *
  56567. * @param {ProgrammableStage} program - The programmable stage.
  56568. */
  56569. destroyProgram( program ) {
  56570. this.delete( program );
  56571. }
  56572. // pipelines
  56573. /**
  56574. * Creates a render pipeline for the given render object.
  56575. *
  56576. * @param {RenderObject} renderObject - The render object.
  56577. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  56578. */
  56579. createRenderPipeline( renderObject, promises ) {
  56580. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  56581. }
  56582. /**
  56583. * Creates a compute pipeline for the given compute node.
  56584. *
  56585. * @param {ComputePipeline} computePipeline - The compute pipeline.
  56586. * @param {Array<BindGroup>} bindings - The bindings.
  56587. */
  56588. createComputePipeline( computePipeline, bindings ) {
  56589. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  56590. }
  56591. /**
  56592. * Prepares the state for encoding render bundles.
  56593. *
  56594. * @param {RenderContext} renderContext - The render context.
  56595. */
  56596. beginBundle( renderContext ) {
  56597. const renderContextData = this.get( renderContext );
  56598. renderContextData._currentPass = renderContextData.currentPass;
  56599. renderContextData._currentSets = renderContextData.currentSets;
  56600. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  56601. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  56602. }
  56603. /**
  56604. * After processing render bundles this method finalizes related work.
  56605. *
  56606. * @param {RenderContext} renderContext - The render context.
  56607. * @param {RenderBundle} bundle - The render bundle.
  56608. */
  56609. finishBundle( renderContext, bundle ) {
  56610. const renderContextData = this.get( renderContext );
  56611. const bundleEncoder = renderContextData.currentPass;
  56612. const bundleGPU = bundleEncoder.finish();
  56613. this.get( bundle ).bundleGPU = bundleGPU;
  56614. // restore render pass state
  56615. renderContextData.currentSets = renderContextData._currentSets;
  56616. renderContextData.currentPass = renderContextData._currentPass;
  56617. }
  56618. /**
  56619. * Adds a render bundle to the render context data.
  56620. *
  56621. * @param {RenderContext} renderContext - The render context.
  56622. * @param {RenderBundle} bundle - The render bundle to add.
  56623. */
  56624. addBundle( renderContext, bundle ) {
  56625. const renderContextData = this.get( renderContext );
  56626. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  56627. }
  56628. // bindings
  56629. /**
  56630. * Creates bindings from the given bind group definition.
  56631. *
  56632. * @param {BindGroup} bindGroup - The bind group.
  56633. * @param {Array<BindGroup>} bindings - Array of bind groups.
  56634. * @param {number} cacheIndex - The cache index.
  56635. * @param {number} version - The version.
  56636. */
  56637. createBindings( bindGroup, bindings, cacheIndex, version ) {
  56638. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  56639. }
  56640. /**
  56641. * Updates the given bind group definition.
  56642. *
  56643. * @param {BindGroup} bindGroup - The bind group.
  56644. * @param {Array<BindGroup>} bindings - Array of bind groups.
  56645. * @param {number} cacheIndex - The cache index.
  56646. * @param {number} version - The version.
  56647. */
  56648. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  56649. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  56650. }
  56651. /**
  56652. * Updates a buffer binding.
  56653. *
  56654. * @param {Buffer} binding - The buffer binding to update.
  56655. */
  56656. updateBinding( binding ) {
  56657. this.bindingUtils.updateBinding( binding );
  56658. }
  56659. /**
  56660. * Delete data associated with the current bind group.
  56661. *
  56662. * @param {BindGroup} bindGroup - The bind group.
  56663. */
  56664. deleteBindGroupData( bindGroup ) {
  56665. this.bindingUtils.deleteBindGroupData( bindGroup );
  56666. }
  56667. // attributes
  56668. /**
  56669. * Creates the buffer of an indexed shader attribute.
  56670. *
  56671. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  56672. */
  56673. createIndexAttribute( attribute ) {
  56674. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  56675. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  56676. usage |= GPUBufferUsage.STORAGE;
  56677. }
  56678. this.attributeUtils.createAttribute( attribute, usage );
  56679. }
  56680. /**
  56681. * Creates the GPU buffer of a shader attribute.
  56682. *
  56683. * @param {BufferAttribute} attribute - The buffer attribute.
  56684. */
  56685. createAttribute( attribute ) {
  56686. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  56687. }
  56688. /**
  56689. * Creates the GPU buffer of a storage attribute.
  56690. *
  56691. * @param {BufferAttribute} attribute - The buffer attribute.
  56692. */
  56693. createStorageAttribute( attribute ) {
  56694. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  56695. }
  56696. /**
  56697. * Creates the GPU buffer of an indirect storage attribute.
  56698. *
  56699. * @param {BufferAttribute} attribute - The buffer attribute.
  56700. */
  56701. createIndirectStorageAttribute( attribute ) {
  56702. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  56703. }
  56704. /**
  56705. * Updates the GPU buffer of a shader attribute.
  56706. *
  56707. * @param {BufferAttribute} attribute - The buffer attribute to update.
  56708. */
  56709. updateAttribute( attribute ) {
  56710. this.attributeUtils.updateAttribute( attribute );
  56711. }
  56712. /**
  56713. * Destroys the GPU buffer of a shader attribute.
  56714. *
  56715. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  56716. */
  56717. destroyAttribute( attribute ) {
  56718. this.attributeUtils.destroyAttribute( attribute );
  56719. }
  56720. // canvas
  56721. /**
  56722. * Triggers an update of the default render pass descriptor.
  56723. */
  56724. updateSize() {
  56725. this.delete( this.renderer.getCanvasTarget() );
  56726. }
  56727. // utils public
  56728. /**
  56729. * Returns the maximum anisotropy texture filtering value.
  56730. *
  56731. * @return {number} The maximum anisotropy texture filtering value.
  56732. */
  56733. getMaxAnisotropy() {
  56734. return 16;
  56735. }
  56736. /**
  56737. * Checks if the given feature is supported by the backend.
  56738. *
  56739. * @param {string} name - The feature's name.
  56740. * @return {boolean} Whether the feature is supported or not.
  56741. */
  56742. hasFeature( name ) {
  56743. if ( GPUFeatureMap[ name ] !== undefined ) name = GPUFeatureMap[ name ];
  56744. return this.device.features.has( name );
  56745. }
  56746. /**
  56747. * Copies data of the given source texture to the given destination texture.
  56748. *
  56749. * @param {Texture} srcTexture - The source texture.
  56750. * @param {Texture} dstTexture - The destination texture.
  56751. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  56752. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  56753. * @param {number} [srcLevel=0] - The mipmap level to copy.
  56754. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  56755. */
  56756. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  56757. let dstX = 0;
  56758. let dstY = 0;
  56759. let dstZ = 0;
  56760. let srcX = 0;
  56761. let srcY = 0;
  56762. let srcZ = 0;
  56763. let srcWidth = srcTexture.image.width;
  56764. let srcHeight = srcTexture.image.height;
  56765. let srcDepth = 1;
  56766. if ( srcRegion !== null ) {
  56767. if ( srcRegion.isBox3 === true ) {
  56768. srcX = srcRegion.min.x;
  56769. srcY = srcRegion.min.y;
  56770. srcZ = srcRegion.min.z;
  56771. srcWidth = srcRegion.max.x - srcRegion.min.x;
  56772. srcHeight = srcRegion.max.y - srcRegion.min.y;
  56773. srcDepth = srcRegion.max.z - srcRegion.min.z;
  56774. } else {
  56775. // Assume it's a Box2
  56776. srcX = srcRegion.min.x;
  56777. srcY = srcRegion.min.y;
  56778. srcWidth = srcRegion.max.x - srcRegion.min.x;
  56779. srcHeight = srcRegion.max.y - srcRegion.min.y;
  56780. srcDepth = 1;
  56781. }
  56782. }
  56783. if ( dstPosition !== null ) {
  56784. dstX = dstPosition.x;
  56785. dstY = dstPosition.y;
  56786. dstZ = dstPosition.z || 0;
  56787. }
  56788. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  56789. const sourceGPU = this.get( srcTexture ).texture;
  56790. const destinationGPU = this.get( dstTexture ).texture;
  56791. encoder.copyTextureToTexture(
  56792. {
  56793. texture: sourceGPU,
  56794. mipLevel: srcLevel,
  56795. origin: { x: srcX, y: srcY, z: srcZ }
  56796. },
  56797. {
  56798. texture: destinationGPU,
  56799. mipLevel: dstLevel,
  56800. origin: { x: dstX, y: dstY, z: dstZ }
  56801. },
  56802. [
  56803. srcWidth,
  56804. srcHeight,
  56805. srcDepth
  56806. ]
  56807. );
  56808. this.device.queue.submit( [ encoder.finish() ] );
  56809. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  56810. this.textureUtils.generateMipmaps( dstTexture );
  56811. }
  56812. }
  56813. /**
  56814. * Copies the current bound framebuffer to the given texture.
  56815. *
  56816. * @param {Texture} texture - The destination texture.
  56817. * @param {RenderContext} renderContext - The render context.
  56818. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  56819. */
  56820. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  56821. const renderContextData = this.get( renderContext );
  56822. let sourceGPU = null;
  56823. if ( renderContext.renderTarget ) {
  56824. if ( texture.isDepthTexture ) {
  56825. sourceGPU = this.get( renderContext.depthTexture ).texture;
  56826. } else {
  56827. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  56828. }
  56829. } else {
  56830. if ( texture.isDepthTexture ) {
  56831. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  56832. } else {
  56833. sourceGPU = this.context.getCurrentTexture();
  56834. }
  56835. }
  56836. const destinationGPU = this.get( texture ).texture;
  56837. if ( sourceGPU.format !== destinationGPU.format ) {
  56838. error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  56839. return;
  56840. }
  56841. let encoder;
  56842. if ( renderContextData.currentPass ) {
  56843. renderContextData.currentPass.end();
  56844. encoder = renderContextData.encoder;
  56845. } else {
  56846. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  56847. }
  56848. encoder.copyTextureToTexture(
  56849. {
  56850. texture: sourceGPU,
  56851. origin: [ rectangle.x, rectangle.y, 0 ],
  56852. },
  56853. {
  56854. texture: destinationGPU
  56855. },
  56856. [
  56857. rectangle.z,
  56858. rectangle.w
  56859. ]
  56860. );
  56861. // mipmaps must be genereated with the same encoder otherwise the copied texture data
  56862. // might be out-of-sync, see #31768
  56863. if ( texture.generateMipmaps ) {
  56864. this.textureUtils.generateMipmaps( texture, encoder );
  56865. }
  56866. if ( renderContextData.currentPass ) {
  56867. const { descriptor } = renderContextData;
  56868. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  56869. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  56870. }
  56871. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  56872. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  56873. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  56874. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  56875. if ( renderContext.viewport ) {
  56876. this.updateViewport( renderContext );
  56877. }
  56878. if ( renderContext.scissor ) {
  56879. this.updateScissor( renderContext );
  56880. }
  56881. } else {
  56882. this.device.queue.submit( [ encoder.finish() ] );
  56883. }
  56884. }
  56885. dispose() {
  56886. this.bindingUtils.dispose();
  56887. this.textureUtils.dispose();
  56888. if ( this.occludedResolveCache ) {
  56889. for ( const buffer of this.occludedResolveCache.values() ) {
  56890. buffer.destroy();
  56891. }
  56892. this.occludedResolveCache.clear();
  56893. }
  56894. if ( this.timestampQueryPool ) {
  56895. for ( const queryPool of Object.values( this.timestampQueryPool ) ) {
  56896. if ( queryPool !== null ) queryPool.dispose();
  56897. }
  56898. }
  56899. if ( this.parameters.device === undefined && this.device !== null ) {
  56900. this.device.destroy();
  56901. }
  56902. }
  56903. }
  56904. /**
  56905. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  56906. *
  56907. * @augments SpotLight
  56908. */
  56909. class IESSpotLight extends SpotLight {
  56910. /**
  56911. * Constructs a new IES spot light.
  56912. *
  56913. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  56914. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  56915. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  56916. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  56917. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  56918. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  56919. */
  56920. constructor( color, intensity, distance, angle, penumbra, decay ) {
  56921. super( color, intensity, distance, angle, penumbra, decay );
  56922. /**
  56923. * TODO
  56924. *
  56925. * @type {?Texture}
  56926. * @default null
  56927. */
  56928. this.iesMap = null;
  56929. }
  56930. copy( source, recursive ) {
  56931. super.copy( source, recursive );
  56932. this.iesMap = source.iesMap;
  56933. return this;
  56934. }
  56935. }
  56936. /**
  56937. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  56938. *
  56939. * @augments SpotLight
  56940. */
  56941. class ProjectorLight extends SpotLight {
  56942. /**
  56943. * Constructs a new projector light.
  56944. *
  56945. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  56946. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  56947. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  56948. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  56949. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  56950. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  56951. */
  56952. constructor( color, intensity, distance, angle, penumbra, decay ) {
  56953. super( color, intensity, distance, angle, penumbra, decay );
  56954. /**
  56955. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  56956. *
  56957. * @type {?number}
  56958. * @default null
  56959. */
  56960. this.aspect = null;
  56961. }
  56962. copy( source, recursive ) {
  56963. super.copy( source, recursive );
  56964. this.aspect = source.aspect;
  56965. return this;
  56966. }
  56967. }
  56968. /**
  56969. * This version of a node library represents the standard version
  56970. * used in {@link WebGPURenderer}. It maps lights, tone mapping
  56971. * techniques and materials to node-based implementations.
  56972. *
  56973. * @private
  56974. * @augments NodeLibrary
  56975. */
  56976. class StandardNodeLibrary extends NodeLibrary {
  56977. /**
  56978. * Constructs a new standard node library.
  56979. */
  56980. constructor() {
  56981. super();
  56982. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  56983. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  56984. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  56985. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  56986. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  56987. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  56988. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  56989. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  56990. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  56991. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  56992. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  56993. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  56994. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  56995. this.addLight( PointLightNode, PointLight );
  56996. this.addLight( DirectionalLightNode, DirectionalLight );
  56997. this.addLight( RectAreaLightNode, RectAreaLight );
  56998. this.addLight( SpotLightNode, SpotLight );
  56999. this.addLight( AmbientLightNode, AmbientLight );
  57000. this.addLight( HemisphereLightNode, HemisphereLight );
  57001. this.addLight( LightProbeNode, LightProbe );
  57002. this.addLight( IESSpotLightNode, IESSpotLight );
  57003. this.addLight( ProjectorLightNode, ProjectorLight );
  57004. this.addToneMapping( linearToneMapping, LinearToneMapping );
  57005. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  57006. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  57007. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  57008. this.addToneMapping( agxToneMapping, AgXToneMapping );
  57009. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  57010. }
  57011. }
  57012. /*
  57013. const debugHandler = {
  57014. get: function ( target, name ) {
  57015. // Add |update
  57016. if ( /^(create|destroy)/.test( name ) ) log( 'WebGPUBackend.' + name );
  57017. return target[ name ];
  57018. }
  57019. };
  57020. */
  57021. /**
  57022. * This renderer is the new alternative of `WebGLRenderer`. `WebGPURenderer` has the ability
  57023. * to target different backends. By default, the renderer tries to use a WebGPU backend if the
  57024. * browser supports WebGPU. If not, `WebGPURenderer` falls backs to a WebGL 2 backend.
  57025. *
  57026. * @augments Renderer
  57027. */
  57028. class WebGPURenderer extends Renderer {
  57029. /**
  57030. * WebGPURenderer options.
  57031. *
  57032. * @typedef {Object} WebGPURenderer~Options
  57033. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  57034. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  57035. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  57036. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  57037. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  57038. * @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.
  57039. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  57040. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  57041. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  57042. * @property {number} [outputBufferType=HalfFloatType] - Defines the type of output buffers. The default `HalfFloatType` is recommend for best
  57043. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  57044. */
  57045. /**
  57046. * Constructs a new WebGPU renderer.
  57047. *
  57048. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  57049. */
  57050. constructor( parameters = {} ) {
  57051. let BackendClass;
  57052. if ( parameters.forceWebGL ) {
  57053. BackendClass = WebGLBackend;
  57054. } else {
  57055. BackendClass = WebGPUBackend;
  57056. parameters.getFallback = () => {
  57057. warn( 'WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  57058. return new WebGLBackend( parameters );
  57059. };
  57060. }
  57061. const backend = new BackendClass( parameters );
  57062. //super( new Proxy( backend, debugHandler ) );
  57063. super( backend, parameters );
  57064. /**
  57065. * The generic default value is overwritten with the
  57066. * standard node library for type mapping.
  57067. *
  57068. * @type {StandardNodeLibrary}
  57069. */
  57070. this.library = new StandardNodeLibrary();
  57071. /**
  57072. * This flag can be used for type testing.
  57073. *
  57074. * @type {boolean}
  57075. * @readonly
  57076. * @default true
  57077. */
  57078. this.isWebGPURenderer = true;
  57079. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  57080. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  57081. }
  57082. }
  57083. }
  57084. /**
  57085. * A specialized group which enables applications access to the
  57086. * Render Bundle API of WebGPU. The group with all its descendant nodes
  57087. * are considered as one render bundle and processed as such by
  57088. * the renderer.
  57089. *
  57090. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  57091. * With a WebGL backend, the group can technically be rendered but without
  57092. * any performance improvements.
  57093. *
  57094. * @augments Group
  57095. */
  57096. class BundleGroup extends Group {
  57097. /**
  57098. * Constructs a new bundle group.
  57099. */
  57100. constructor() {
  57101. super();
  57102. /**
  57103. * This flag can be used for type testing.
  57104. *
  57105. * @type {boolean}
  57106. * @readonly
  57107. * @default true
  57108. */
  57109. this.isBundleGroup = true;
  57110. /**
  57111. * This property is only relevant for detecting types
  57112. * during serialization/deserialization. It should always
  57113. * match the class name.
  57114. *
  57115. * @type {string}
  57116. * @readonly
  57117. * @default 'BundleGroup'
  57118. */
  57119. this.type = 'BundleGroup';
  57120. /**
  57121. * Whether the bundle is static or not. When set to `true`, the structure
  57122. * is assumed to be static and does not change. E.g. no new objects are
  57123. * added to the group
  57124. *
  57125. * If a change is required, an update can still be forced by setting the
  57126. * `needsUpdate` flag to `true`.
  57127. *
  57128. * @type {boolean}
  57129. * @default true
  57130. */
  57131. this.static = true;
  57132. /**
  57133. * The bundle group's version.
  57134. *
  57135. * @type {number}
  57136. * @readonly
  57137. * @default 0
  57138. */
  57139. this.version = 0;
  57140. }
  57141. /**
  57142. * Set this property to `true` when the bundle group has changed.
  57143. *
  57144. * @type {boolean}
  57145. * @default false
  57146. * @param {boolean} value
  57147. */
  57148. set needsUpdate( value ) {
  57149. if ( value === true ) this.version ++;
  57150. }
  57151. }
  57152. /**
  57153. * This module is responsible to manage the post processing setups in apps.
  57154. * You usually create a single instance of this class and use it to define
  57155. * the output of your post processing effect chain.
  57156. * ```js
  57157. * const postProcessing = new PostProcessing( renderer );
  57158. *
  57159. * const scenePass = pass( scene, camera );
  57160. *
  57161. * postProcessing.outputNode = scenePass;
  57162. * ```
  57163. *
  57164. * Note: This module can only be used with `WebGPURenderer`.
  57165. */
  57166. class PostProcessing {
  57167. /**
  57168. * Constructs a new post processing management module.
  57169. *
  57170. * @param {Renderer} renderer - A reference to the renderer.
  57171. * @param {Node<vec4>} outputNode - An optional output node.
  57172. */
  57173. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  57174. /**
  57175. * A reference to the renderer.
  57176. *
  57177. * @type {Renderer}
  57178. */
  57179. this.renderer = renderer;
  57180. /**
  57181. * A node which defines the final output of the post
  57182. * processing. This is usually the last node in a chain
  57183. * of effect nodes.
  57184. *
  57185. * @type {Node<vec4>}
  57186. */
  57187. this.outputNode = outputNode;
  57188. /**
  57189. * Whether the default output tone mapping and color
  57190. * space transformation should be enabled or not.
  57191. *
  57192. * It is enabled by default by it must be disabled when
  57193. * effects must be executed after tone mapping and color
  57194. * space conversion. A typical example is FXAA which
  57195. * requires sRGB input.
  57196. *
  57197. * When set to `false`, the app must control the output
  57198. * transformation with `RenderOutputNode`.
  57199. *
  57200. * ```js
  57201. * const outputPass = renderOutput( scenePass );
  57202. * ```
  57203. *
  57204. * @type {boolean}
  57205. */
  57206. this.outputColorTransform = true;
  57207. /**
  57208. * Must be set to `true` when the output node changes.
  57209. *
  57210. * @type {Node<vec4>}
  57211. */
  57212. this.needsUpdate = true;
  57213. const material = new NodeMaterial();
  57214. material.name = 'PostProcessing';
  57215. /**
  57216. * The full screen quad that is used to render
  57217. * the effects.
  57218. *
  57219. * @private
  57220. * @type {QuadMesh}
  57221. */
  57222. this._quadMesh = new QuadMesh( material );
  57223. this._quadMesh.name = 'Post-Processing';
  57224. /**
  57225. * The context of the post processing stack.
  57226. *
  57227. * @private
  57228. * @type {?Object}
  57229. * @default null
  57230. */
  57231. this._context = null;
  57232. }
  57233. /**
  57234. * When `PostProcessing` is used to apply post processing effects,
  57235. * the application must use this version of `render()` inside
  57236. * its animation loop (not the one from the renderer).
  57237. */
  57238. render() {
  57239. const renderer = this.renderer;
  57240. this._update();
  57241. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  57242. const toneMapping = renderer.toneMapping;
  57243. const outputColorSpace = renderer.outputColorSpace;
  57244. renderer.toneMapping = NoToneMapping;
  57245. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  57246. //
  57247. const currentXR = renderer.xr.enabled;
  57248. renderer.xr.enabled = false;
  57249. this._quadMesh.render( renderer );
  57250. renderer.xr.enabled = currentXR;
  57251. //
  57252. renderer.toneMapping = toneMapping;
  57253. renderer.outputColorSpace = outputColorSpace;
  57254. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  57255. }
  57256. /**
  57257. * Returns the current context of the post processing stack.
  57258. *
  57259. * @readonly
  57260. * @type {?Object}
  57261. */
  57262. get context() {
  57263. return this._context;
  57264. }
  57265. /**
  57266. * Frees internal resources.
  57267. */
  57268. dispose() {
  57269. this._quadMesh.material.dispose();
  57270. }
  57271. /**
  57272. * Updates the state of the module.
  57273. *
  57274. * @private
  57275. */
  57276. _update() {
  57277. if ( this.needsUpdate === true ) {
  57278. const renderer = this.renderer;
  57279. const toneMapping = renderer.toneMapping;
  57280. const outputColorSpace = renderer.outputColorSpace;
  57281. const context = {
  57282. postProcessing: this,
  57283. onBeforePostProcessing: null,
  57284. onAfterPostProcessing: null
  57285. };
  57286. let outputNode = this.outputNode;
  57287. if ( this.outputColorTransform === true ) {
  57288. outputNode = outputNode.context( context );
  57289. outputNode = renderOutput( outputNode, toneMapping, outputColorSpace );
  57290. } else {
  57291. context.toneMapping = toneMapping;
  57292. context.outputColorSpace = outputColorSpace;
  57293. outputNode = outputNode.context( context );
  57294. }
  57295. this._context = context;
  57296. this._quadMesh.material.fragmentNode = outputNode;
  57297. this._quadMesh.material.needsUpdate = true;
  57298. this.needsUpdate = false;
  57299. }
  57300. }
  57301. /**
  57302. * When `PostProcessing` is used to apply post processing effects,
  57303. * the application must use this version of `renderAsync()` inside
  57304. * its animation loop (not the one from the renderer).
  57305. *
  57306. * @async
  57307. * @deprecated
  57308. * @return {Promise} A Promise that resolves when the render has been finished.
  57309. */
  57310. async renderAsync() {
  57311. warnOnce( 'PostProcessing: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  57312. await this.renderer.init();
  57313. this.render();
  57314. }
  57315. }
  57316. /**
  57317. * This special type of texture is intended for compute shaders.
  57318. * It can be used to compute the data of a texture with a compute shader.
  57319. *
  57320. * Note: This type of texture can only be used with `WebGPURenderer`
  57321. * and a WebGPU backend.
  57322. *
  57323. * @augments Texture
  57324. */
  57325. class StorageTexture extends Texture {
  57326. /**
  57327. * Constructs a new storage texture.
  57328. *
  57329. * @param {number} [width=1] - The storage texture's width.
  57330. * @param {number} [height=1] - The storage texture's height.
  57331. */
  57332. constructor( width = 1, height = 1 ) {
  57333. super();
  57334. /**
  57335. * The image object which just represents the texture's dimension.
  57336. *
  57337. * @type {{width: number, height: number}}
  57338. */
  57339. this.image = { width, height };
  57340. /**
  57341. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  57342. *
  57343. * @type {number}
  57344. */
  57345. this.magFilter = LinearFilter;
  57346. /**
  57347. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  57348. *
  57349. * @type {number}
  57350. */
  57351. this.minFilter = LinearFilter;
  57352. /**
  57353. * This flag can be used for type testing.
  57354. *
  57355. * @type {boolean}
  57356. * @readonly
  57357. * @default true
  57358. */
  57359. this.isStorageTexture = true;
  57360. /**
  57361. * When `true`, mipmaps will be auto-generated after compute writes.
  57362. * When `false`, mipmaps must be written manually via compute shaders.
  57363. *
  57364. * @type {boolean}
  57365. * @default true
  57366. */
  57367. this.mipmapsAutoUpdate = true;
  57368. }
  57369. /**
  57370. * Sets the size of the storage texture.
  57371. *
  57372. * @param {number} width - The new width of the storage texture.
  57373. * @param {number} height - The new height of the storage texture.
  57374. */
  57375. setSize( width, height ) {
  57376. if ( this.image.width !== width || this.image.height !== height ) {
  57377. this.image.width = width;
  57378. this.image.height = height;
  57379. this.dispose();
  57380. }
  57381. }
  57382. }
  57383. /**
  57384. * This special type of texture is intended for compute shaders.
  57385. * It can be used to compute the data of a texture with a compute shader.
  57386. *
  57387. * Note: This type of texture can only be used with `WebGPURenderer`
  57388. * and a WebGPU backend.
  57389. *
  57390. * @augments Texture
  57391. */
  57392. class Storage3DTexture extends Texture {
  57393. /**
  57394. * Constructs a new storage texture.
  57395. *
  57396. * @param {number} [width=1] - The storage texture's width.
  57397. * @param {number} [height=1] - The storage texture's height.
  57398. * @param {number} [depth=1] - The storage texture's depth.
  57399. */
  57400. constructor( width = 1, height = 1, depth = 1 ) {
  57401. super();
  57402. //inherited from texture. Must be false for 3DTexture
  57403. this.isArrayTexture = false;
  57404. /**
  57405. * The image object which just represents the texture's dimension.
  57406. *
  57407. * @type {{width: number, height: number, depth: number}}
  57408. */
  57409. this.image = { width, height, depth };
  57410. /**
  57411. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  57412. *
  57413. * @type {number}
  57414. */
  57415. this.magFilter = LinearFilter;
  57416. /**
  57417. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  57418. *
  57419. * @type {number}
  57420. */
  57421. this.minFilter = LinearFilter;
  57422. /**
  57423. * This defines how the texture is wrapped in the depth direction and corresponds to
  57424. * *W* in UVW mapping.
  57425. *
  57426. * @type {number}
  57427. */
  57428. this.wrapR = ClampToEdgeWrapping;
  57429. /**
  57430. * This flag can be used for type testing.
  57431. *
  57432. * @type {boolean}
  57433. * @readonly
  57434. * @default true
  57435. */
  57436. this.isStorageTexture = true;
  57437. /**
  57438. * Indicates whether this texture is a 3D texture.
  57439. *
  57440. * @type {boolean}
  57441. *
  57442. */
  57443. this.is3DTexture = true;
  57444. }
  57445. /**
  57446. * Sets the size of the storage 3d texture.
  57447. *
  57448. * @param {number} width - The new width of the storage texture.
  57449. * @param {number} height - The new height of the storage texture.
  57450. * @param {number} depth - The new depth of the storage texture.
  57451. */
  57452. setSize( width, height, depth ) {
  57453. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  57454. this.image.width = width;
  57455. this.image.height = height;
  57456. this.image.depth = depth;
  57457. this.dispose();
  57458. }
  57459. }
  57460. }
  57461. /**
  57462. * This special type of texture is intended for compute shaders.
  57463. * It can be used to compute the data of a texture with a compute shader.
  57464. *
  57465. * Note: This type of texture can only be used with `WebGPURenderer`
  57466. * and a WebGPU backend.
  57467. *
  57468. * @augments Texture
  57469. */
  57470. class StorageArrayTexture extends Texture {
  57471. /**
  57472. * Constructs a new storage texture.
  57473. *
  57474. * @param {number} [width=1] - The storage texture's width.
  57475. * @param {number} [height=1] - The storage texture's height.
  57476. * @param {number} [depth=1] - The storage texture's depth.
  57477. */
  57478. constructor( width = 1, height = 1, depth = 1 ) {
  57479. super();
  57480. //inherited from texture
  57481. this.isArrayTexture = true;
  57482. /**
  57483. * The image object which just represents the texture's dimension.
  57484. *
  57485. * @type {{width: number, height: number, depth: number}}
  57486. */
  57487. this.image = { width, height, depth };
  57488. /**
  57489. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  57490. *
  57491. * @type {number}
  57492. */
  57493. this.magFilter = LinearFilter;
  57494. /**
  57495. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  57496. *
  57497. * @type {number}
  57498. */
  57499. this.minFilter = LinearFilter;
  57500. /**
  57501. * This flag can be used for type testing.
  57502. *
  57503. * @type {boolean}
  57504. * @readonly
  57505. * @default true
  57506. */
  57507. this.isStorageTexture = true;
  57508. }
  57509. /**
  57510. * Sets the size of the storage array texture.
  57511. *
  57512. * @param {number} width - The new width of the storage texture.
  57513. * @param {number} height - The new height of the storage texture.
  57514. * @param {number} depth - The new depth of the storage texture.
  57515. */
  57516. setSize( width, height, depth ) {
  57517. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  57518. this.image.width = width;
  57519. this.image.height = height;
  57520. this.image.depth = depth;
  57521. this.dispose();
  57522. }
  57523. }
  57524. }
  57525. /**
  57526. * This special type of buffer attribute is intended for compute shaders.
  57527. * It can be used to encode draw parameters for indirect draw calls.
  57528. *
  57529. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  57530. * and a WebGPU backend.
  57531. *
  57532. * @augments StorageBufferAttribute
  57533. */
  57534. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  57535. /**
  57536. * Constructs a new storage buffer attribute.
  57537. *
  57538. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  57539. * The subsequent parameter is then obsolete.
  57540. * @param {number} itemSize - The item size.
  57541. */
  57542. constructor( count, itemSize ) {
  57543. super( count, itemSize, Uint32Array );
  57544. /**
  57545. * This flag can be used for type testing.
  57546. *
  57547. * @type {boolean}
  57548. * @readonly
  57549. * @default true
  57550. */
  57551. this.isIndirectStorageBufferAttribute = true;
  57552. }
  57553. }
  57554. /**
  57555. * A loader for loading node objects in the three.js JSON Object/Scene format.
  57556. *
  57557. * @augments Loader
  57558. */
  57559. class NodeLoader extends Loader {
  57560. /**
  57561. * Constructs a new node loader.
  57562. *
  57563. * @param {LoadingManager} [manager] - A reference to a loading manager.
  57564. */
  57565. constructor( manager ) {
  57566. super( manager );
  57567. /**
  57568. * Represents a dictionary of textures.
  57569. *
  57570. * @type {Object<string,Texture>}
  57571. */
  57572. this.textures = {};
  57573. /**
  57574. * Represents a dictionary of node types.
  57575. *
  57576. * @type {Object<string,Node.constructor>}
  57577. */
  57578. this.nodes = {};
  57579. }
  57580. /**
  57581. * Loads the node definitions from the given URL.
  57582. *
  57583. * @param {string} url - The path/URL of the file to be loaded.
  57584. * @param {Function} onLoad - Will be called when load completes.
  57585. * @param {Function} onProgress - Will be called while load progresses.
  57586. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  57587. */
  57588. load( url, onLoad, onProgress, onError ) {
  57589. const loader = new FileLoader( this.manager );
  57590. loader.setPath( this.path );
  57591. loader.setRequestHeader( this.requestHeader );
  57592. loader.setWithCredentials( this.withCredentials );
  57593. loader.load( url, ( text ) => {
  57594. try {
  57595. onLoad( this.parse( JSON.parse( text ) ) );
  57596. } catch ( e ) {
  57597. if ( onError ) {
  57598. onError( e );
  57599. } else {
  57600. error( e );
  57601. }
  57602. this.manager.itemError( url );
  57603. }
  57604. }, onProgress, onError );
  57605. }
  57606. /**
  57607. * Parse the node dependencies for the loaded node.
  57608. *
  57609. * @param {Array<Object>} [json] - The JSON definition
  57610. * @return {Object<string,Node>} A dictionary with node dependencies.
  57611. */
  57612. parseNodes( json ) {
  57613. const nodes = {};
  57614. if ( json !== undefined ) {
  57615. for ( const nodeJSON of json ) {
  57616. const { uuid, type } = nodeJSON;
  57617. nodes[ uuid ] = this.createNodeFromType( type );
  57618. nodes[ uuid ].uuid = uuid;
  57619. }
  57620. const meta = { nodes, textures: this.textures };
  57621. for ( const nodeJSON of json ) {
  57622. nodeJSON.meta = meta;
  57623. const node = nodes[ nodeJSON.uuid ];
  57624. node.deserialize( nodeJSON );
  57625. delete nodeJSON.meta;
  57626. }
  57627. }
  57628. return nodes;
  57629. }
  57630. /**
  57631. * Parses the node from the given JSON.
  57632. *
  57633. * @param {Object} json - The JSON definition
  57634. * @param {string} json.type - The node type.
  57635. * @param {string} json.uuid - The node UUID.
  57636. * @param {Array<Object>} [json.nodes] - The node dependencies.
  57637. * @param {Object} [json.meta] - The meta data.
  57638. * @return {Node} The parsed node.
  57639. */
  57640. parse( json ) {
  57641. const node = this.createNodeFromType( json.type );
  57642. node.uuid = json.uuid;
  57643. const nodes = this.parseNodes( json.nodes );
  57644. const meta = { nodes, textures: this.textures };
  57645. json.meta = meta;
  57646. node.deserialize( json );
  57647. delete json.meta;
  57648. return node;
  57649. }
  57650. /**
  57651. * Defines the dictionary of textures.
  57652. *
  57653. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  57654. * @return {NodeLoader} A reference to this loader.
  57655. */
  57656. setTextures( value ) {
  57657. this.textures = value;
  57658. return this;
  57659. }
  57660. /**
  57661. * Defines the dictionary of node types.
  57662. *
  57663. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  57664. * @return {NodeLoader} A reference to this loader.
  57665. */
  57666. setNodes( value ) {
  57667. this.nodes = value;
  57668. return this;
  57669. }
  57670. /**
  57671. * Creates a node object from the given type.
  57672. *
  57673. * @param {string} type - The node type.
  57674. * @return {Node} The created node instance.
  57675. */
  57676. createNodeFromType( type ) {
  57677. if ( this.nodes[ type ] === undefined ) {
  57678. error( 'NodeLoader: Node type not found:', type );
  57679. return float();
  57680. }
  57681. return new this.nodes[ type ]();
  57682. }
  57683. }
  57684. /**
  57685. * A special type of material loader for loading node materials.
  57686. *
  57687. * @augments MaterialLoader
  57688. */
  57689. class NodeMaterialLoader extends MaterialLoader {
  57690. /**
  57691. * Constructs a new node material loader.
  57692. *
  57693. * @param {LoadingManager} [manager] - A reference to a loading manager.
  57694. */
  57695. constructor( manager ) {
  57696. super( manager );
  57697. /**
  57698. * Represents a dictionary of node types.
  57699. *
  57700. * @type {Object<string,Node.constructor>}
  57701. */
  57702. this.nodes = {};
  57703. /**
  57704. * Represents a dictionary of node material types.
  57705. *
  57706. * @type {Object<string,NodeMaterial.constructor>}
  57707. */
  57708. this.nodeMaterials = {};
  57709. }
  57710. /**
  57711. * Parses the node material from the given JSON.
  57712. *
  57713. * @param {Object} json - The JSON definition
  57714. * @return {NodeMaterial}. The parsed material.
  57715. */
  57716. parse( json ) {
  57717. const material = super.parse( json );
  57718. const nodes = this.nodes;
  57719. const inputNodes = json.inputNodes;
  57720. for ( const property in inputNodes ) {
  57721. const uuid = inputNodes[ property ];
  57722. material[ property ] = nodes[ uuid ];
  57723. }
  57724. return material;
  57725. }
  57726. /**
  57727. * Defines the dictionary of node types.
  57728. *
  57729. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  57730. * @return {NodeLoader} A reference to this loader.
  57731. */
  57732. setNodes( value ) {
  57733. this.nodes = value;
  57734. return this;
  57735. }
  57736. /**
  57737. * Defines the dictionary of node material types.
  57738. *
  57739. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  57740. * @return {NodeLoader} A reference to this loader.
  57741. */
  57742. setNodeMaterials( value ) {
  57743. this.nodeMaterials = value;
  57744. return this;
  57745. }
  57746. /**
  57747. * Creates a node material from the given type.
  57748. *
  57749. * @param {string} type - The node material type.
  57750. * @return {Node} The created node material instance.
  57751. */
  57752. createMaterialFromType( type ) {
  57753. const materialClass = this.nodeMaterials[ type ];
  57754. if ( materialClass !== undefined ) {
  57755. return new materialClass();
  57756. }
  57757. return super.createMaterialFromType( type );
  57758. }
  57759. }
  57760. /**
  57761. * A special type of object loader for loading 3D objects using
  57762. * node materials.
  57763. *
  57764. * @augments ObjectLoader
  57765. */
  57766. class NodeObjectLoader extends ObjectLoader {
  57767. /**
  57768. * Constructs a new node object loader.
  57769. *
  57770. * @param {LoadingManager} [manager] - A reference to a loading manager.
  57771. */
  57772. constructor( manager ) {
  57773. super( manager );
  57774. /**
  57775. * Represents a dictionary of node types.
  57776. *
  57777. * @type {Object<string,Node.constructor>}
  57778. */
  57779. this.nodes = {};
  57780. /**
  57781. * Represents a dictionary of node material types.
  57782. *
  57783. * @type {Object<string,NodeMaterial.constructor>}
  57784. */
  57785. this.nodeMaterials = {};
  57786. /**
  57787. * A reference to hold the `nodes` JSON property.
  57788. *
  57789. * @private
  57790. * @type {?Object[]}
  57791. */
  57792. this._nodesJSON = null;
  57793. }
  57794. /**
  57795. * Defines the dictionary of node types.
  57796. *
  57797. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  57798. * @return {NodeObjectLoader} A reference to this loader.
  57799. */
  57800. setNodes( value ) {
  57801. this.nodes = value;
  57802. return this;
  57803. }
  57804. /**
  57805. * Defines the dictionary of node material types.
  57806. *
  57807. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  57808. * @return {NodeObjectLoader} A reference to this loader.
  57809. */
  57810. setNodeMaterials( value ) {
  57811. this.nodeMaterials = value;
  57812. return this;
  57813. }
  57814. /**
  57815. * Parses the node objects from the given JSON.
  57816. *
  57817. * @param {Object} json - The JSON definition
  57818. * @param {Function} onLoad - The onLoad callback function.
  57819. * @return {Object3D}. The parsed 3D object.
  57820. */
  57821. parse( json, onLoad ) {
  57822. this._nodesJSON = json.nodes;
  57823. const data = super.parse( json, onLoad );
  57824. this._nodesJSON = null; // dispose
  57825. return data;
  57826. }
  57827. /**
  57828. * Parses the node objects from the given JSON and textures.
  57829. *
  57830. * @param {Object[]} json - The JSON definition
  57831. * @param {Object<string,Texture>} textures - The texture library.
  57832. * @return {Object<string,Node>}. The parsed nodes.
  57833. */
  57834. parseNodes( json, textures ) {
  57835. if ( json !== undefined ) {
  57836. const loader = new NodeLoader();
  57837. loader.setNodes( this.nodes );
  57838. loader.setTextures( textures );
  57839. return loader.parseNodes( json );
  57840. }
  57841. return {};
  57842. }
  57843. /**
  57844. * Parses the node objects from the given JSON and textures.
  57845. *
  57846. * @param {Object} json - The JSON definition
  57847. * @param {Object<string,Texture>} textures - The texture library.
  57848. * @return {Object<string,NodeMaterial>}. The parsed materials.
  57849. */
  57850. parseMaterials( json, textures ) {
  57851. const materials = {};
  57852. if ( json !== undefined ) {
  57853. const nodes = this.parseNodes( this._nodesJSON, textures );
  57854. const loader = new NodeMaterialLoader();
  57855. loader.setTextures( textures );
  57856. loader.setNodes( nodes );
  57857. loader.setNodeMaterials( this.nodeMaterials );
  57858. for ( let i = 0, l = json.length; i < l; i ++ ) {
  57859. const data = json[ i ];
  57860. materials[ data.uuid ] = loader.parse( data );
  57861. }
  57862. }
  57863. return materials;
  57864. }
  57865. }
  57866. /**
  57867. * In earlier three.js versions, clipping was defined globally
  57868. * on the renderer or on material level. This special version of
  57869. * `THREE.Group` allows to encode the clipping state into the scene
  57870. * graph. Meaning if you create an instance of this group, all
  57871. * descendant 3D objects will be affected by the respective clipping
  57872. * planes.
  57873. *
  57874. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  57875. *
  57876. * @augments Group
  57877. */
  57878. class ClippingGroup extends Group {
  57879. /**
  57880. * Constructs a new clipping group.
  57881. */
  57882. constructor() {
  57883. super();
  57884. /**
  57885. * This flag can be used for type testing.
  57886. *
  57887. * @type {boolean}
  57888. * @readonly
  57889. * @default true
  57890. */
  57891. this.isClippingGroup = true;
  57892. /**
  57893. * An array with clipping planes.
  57894. *
  57895. * @type {Array<Plane>}
  57896. */
  57897. this.clippingPlanes = [];
  57898. /**
  57899. * Whether clipping should be enabled or not.
  57900. *
  57901. * @type {boolean}
  57902. * @default true
  57903. */
  57904. this.enabled = true;
  57905. /**
  57906. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  57907. *
  57908. * @type {boolean}
  57909. * @default false
  57910. */
  57911. this.clipIntersection = false;
  57912. /**
  57913. * Whether shadows should be clipped or not.
  57914. *
  57915. * @type {boolean}
  57916. * @default false
  57917. */
  57918. this.clipShadows = false;
  57919. }
  57920. }
  57921. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BitcastNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, Camera, CanvasTarget, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeDepthTexture, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, CylinderGeometry, DataArrayTexture, DataTexture, DebugNode, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, EventNode, ExpressionNode, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FrustumArray, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InspectorBase, 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, MaterialLoader, MaterialNode, MaterialReferenceNode, 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, 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, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PosterizeNode, 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_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RendererUtils, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_R11_EAC_Format, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SIGNED_RG11_EAC_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, Sphere, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, Storage3DTexture, StorageArrayElementNode, StorageArrayTexture, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StructNode, StructTypeNode, SubBuildNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, TimestampQuery, ToneMappingNode, ToonOutlinePassNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt101111Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, error, log$1 as log, shaderStages, vectorComponents, warn, warnOnce };
粤ICP备19079148号