three.webgpu.js 1.9 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391
  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, IdentityDepthPacking, 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. generate( builder ) {
  1547. const indexType = this.indexNode.getNodeType( builder );
  1548. const nodeSnippet = this.node.build( builder );
  1549. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1550. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1551. }
  1552. }
  1553. /**
  1554. * This module is part of the TSL core and usually not used in app level code.
  1555. * It represents a convert operation during the shader generation process
  1556. * meaning it converts the data type of a node to a target data type.
  1557. *
  1558. * @augments Node
  1559. */
  1560. class ConvertNode extends Node {
  1561. static get type() {
  1562. return 'ConvertNode';
  1563. }
  1564. /**
  1565. * Constructs a new convert node.
  1566. *
  1567. * @param {Node} node - The node which type should be converted.
  1568. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1569. */
  1570. constructor( node, convertTo ) {
  1571. super();
  1572. /**
  1573. * The node which type should be converted.
  1574. *
  1575. * @type {Node}
  1576. */
  1577. this.node = node;
  1578. /**
  1579. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1580. *
  1581. * @type {string}
  1582. */
  1583. this.convertTo = convertTo;
  1584. }
  1585. /**
  1586. * This method is overwritten since the implementation tries to infer the best
  1587. * matching type from the {@link ConvertNode#convertTo} property.
  1588. *
  1589. * @param {NodeBuilder} builder - The current node builder.
  1590. * @return {string} The node type.
  1591. */
  1592. getNodeType( builder ) {
  1593. const requestType = this.node.getNodeType( builder );
  1594. let convertTo = null;
  1595. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1596. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1597. convertTo = overloadingType;
  1598. }
  1599. }
  1600. return convertTo;
  1601. }
  1602. serialize( data ) {
  1603. super.serialize( data );
  1604. data.convertTo = this.convertTo;
  1605. }
  1606. deserialize( data ) {
  1607. super.deserialize( data );
  1608. this.convertTo = data.convertTo;
  1609. }
  1610. generate( builder, output ) {
  1611. const node = this.node;
  1612. const type = this.getNodeType( builder );
  1613. const snippet = node.build( builder, type );
  1614. return builder.format( snippet, type, output );
  1615. }
  1616. }
  1617. /**
  1618. * This module uses cache management to create temporary variables
  1619. * if the node is used more than once to prevent duplicate calculations.
  1620. *
  1621. * The class acts as a base class for many other nodes types.
  1622. *
  1623. * @augments Node
  1624. */
  1625. class TempNode extends Node {
  1626. static get type() {
  1627. return 'TempNode';
  1628. }
  1629. /**
  1630. * Constructs a temp node.
  1631. *
  1632. * @param {?string} nodeType - The node type.
  1633. */
  1634. constructor( nodeType = null ) {
  1635. super( nodeType );
  1636. /**
  1637. * This flag can be used for type testing.
  1638. *
  1639. * @type {boolean}
  1640. * @readonly
  1641. * @default true
  1642. */
  1643. this.isTempNode = true;
  1644. }
  1645. /**
  1646. * Whether this node is used more than once in context of other nodes.
  1647. *
  1648. * @param {NodeBuilder} builder - The node builder.
  1649. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1650. */
  1651. hasDependencies( builder ) {
  1652. return builder.getDataFromNode( this ).usageCount > 1;
  1653. }
  1654. build( builder, output ) {
  1655. const buildStage = builder.getBuildStage();
  1656. if ( buildStage === 'generate' ) {
  1657. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1658. const nodeData = builder.getDataFromNode( this );
  1659. if ( nodeData.propertyName !== undefined ) {
  1660. return builder.format( nodeData.propertyName, type, output );
  1661. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1662. const snippet = super.build( builder, type );
  1663. const nodeVar = builder.getVarFromNode( this, null, type );
  1664. const propertyName = builder.getPropertyName( nodeVar );
  1665. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1666. nodeData.snippet = snippet;
  1667. nodeData.propertyName = propertyName;
  1668. return builder.format( nodeData.propertyName, type, output );
  1669. }
  1670. }
  1671. return super.build( builder, output );
  1672. }
  1673. }
  1674. /**
  1675. * This module is part of the TSL core and usually not used in app level code.
  1676. * It represents a join operation during the shader generation process.
  1677. * For example in can compose/join two single floats into a `vec2` type.
  1678. *
  1679. * @augments TempNode
  1680. */
  1681. class JoinNode extends TempNode {
  1682. static get type() {
  1683. return 'JoinNode';
  1684. }
  1685. /**
  1686. * Constructs a new join node.
  1687. *
  1688. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1689. * @param {?string} [nodeType=null] - The node type.
  1690. */
  1691. constructor( nodes = [], nodeType = null ) {
  1692. super( nodeType );
  1693. /**
  1694. * An array of nodes that should be joined.
  1695. *
  1696. * @type {Array<Node>}
  1697. */
  1698. this.nodes = nodes;
  1699. }
  1700. /**
  1701. * This method is overwritten since the node type must be inferred from the
  1702. * joined data length if not explicitly defined.
  1703. *
  1704. * @param {NodeBuilder} builder - The current node builder.
  1705. * @return {string} The node type.
  1706. */
  1707. getNodeType( builder ) {
  1708. if ( this.nodeType !== null ) {
  1709. return builder.getVectorType( this.nodeType );
  1710. }
  1711. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1712. }
  1713. generate( builder, output ) {
  1714. const type = this.getNodeType( builder );
  1715. const maxLength = builder.getTypeLength( type );
  1716. const nodes = this.nodes;
  1717. const primitiveType = builder.getComponentType( type );
  1718. const snippetValues = [];
  1719. let length = 0;
  1720. for ( const input of nodes ) {
  1721. if ( length >= maxLength ) {
  1722. error( `TSL: Length of parameters exceeds maximum length of function '${ type }()' type.` );
  1723. break;
  1724. }
  1725. let inputType = input.getNodeType( builder );
  1726. let inputTypeLength = builder.getTypeLength( inputType );
  1727. let inputSnippet;
  1728. if ( length + inputTypeLength > maxLength ) {
  1729. error( `TSL: Length of '${ type }()' data exceeds maximum length of output type.` );
  1730. inputTypeLength = maxLength - length;
  1731. inputType = builder.getTypeFromLength( inputTypeLength );
  1732. }
  1733. length += inputTypeLength;
  1734. inputSnippet = input.build( builder, inputType );
  1735. const inputPrimitiveType = builder.getComponentType( inputType );
  1736. if ( inputPrimitiveType !== primitiveType ) {
  1737. const targetType = builder.getTypeFromLength( inputTypeLength, primitiveType );
  1738. inputSnippet = builder.format( inputSnippet, inputType, targetType );
  1739. }
  1740. snippetValues.push( inputSnippet );
  1741. }
  1742. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1743. return builder.format( snippet, type, output );
  1744. }
  1745. }
  1746. const _stringVectorComponents = vectorComponents.join( '' );
  1747. /**
  1748. * This module is part of the TSL core and usually not used in app level code.
  1749. * `SplitNode` represents a property access operation which means it is
  1750. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1751. * For example:
  1752. * ```js
  1753. * const redValue = color.r;
  1754. * ```
  1755. *
  1756. * @augments Node
  1757. */
  1758. class SplitNode extends Node {
  1759. static get type() {
  1760. return 'SplitNode';
  1761. }
  1762. /**
  1763. * Constructs a new split node.
  1764. *
  1765. * @param {Node} node - The node that should be accessed.
  1766. * @param {string} [components='x'] - The components that should be accessed.
  1767. */
  1768. constructor( node, components = 'x' ) {
  1769. super();
  1770. /**
  1771. * The node that should be accessed.
  1772. *
  1773. * @type {Node}
  1774. */
  1775. this.node = node;
  1776. /**
  1777. * The components that should be accessed.
  1778. *
  1779. * @type {string}
  1780. */
  1781. this.components = components;
  1782. /**
  1783. * This flag can be used for type testing.
  1784. *
  1785. * @type {boolean}
  1786. * @readonly
  1787. * @default true
  1788. */
  1789. this.isSplitNode = true;
  1790. }
  1791. /**
  1792. * Returns the vector length which is computed based on the requested components.
  1793. *
  1794. * @return {number} The vector length.
  1795. */
  1796. getVectorLength() {
  1797. let vectorLength = this.components.length;
  1798. for ( const c of this.components ) {
  1799. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1800. }
  1801. return vectorLength;
  1802. }
  1803. /**
  1804. * Returns the component type of the node's type.
  1805. *
  1806. * @param {NodeBuilder} builder - The current node builder.
  1807. * @return {string} The component type.
  1808. */
  1809. getComponentType( builder ) {
  1810. return builder.getComponentType( this.node.getNodeType( builder ) );
  1811. }
  1812. /**
  1813. * This method is overwritten since the node type is inferred from requested components.
  1814. *
  1815. * @param {NodeBuilder} builder - The current node builder.
  1816. * @return {string} The node type.
  1817. */
  1818. getNodeType( builder ) {
  1819. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1820. }
  1821. /**
  1822. * Returns the scope of the node.
  1823. *
  1824. * @return {Node} The scope of the node.
  1825. */
  1826. getScope() {
  1827. return this.node.getScope();
  1828. }
  1829. generate( builder, output ) {
  1830. const node = this.node;
  1831. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1832. let snippet = null;
  1833. if ( nodeTypeLength > 1 ) {
  1834. let type = null;
  1835. const componentsLength = this.getVectorLength();
  1836. if ( componentsLength >= nodeTypeLength ) {
  1837. // needed expand the input node
  1838. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1839. }
  1840. const nodeSnippet = node.build( builder, type );
  1841. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1842. // unnecessary swizzle
  1843. snippet = builder.format( nodeSnippet, type, output );
  1844. } else {
  1845. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1846. }
  1847. } else {
  1848. // ignore .components if .node returns float/integer
  1849. snippet = node.build( builder, output );
  1850. }
  1851. return snippet;
  1852. }
  1853. serialize( data ) {
  1854. super.serialize( data );
  1855. data.components = this.components;
  1856. }
  1857. deserialize( data ) {
  1858. super.deserialize( data );
  1859. this.components = data.components;
  1860. }
  1861. }
  1862. /**
  1863. * This module is part of the TSL core and usually not used in app level code.
  1864. * `SetNode` represents a set operation which means it is used to implement any
  1865. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1866. * For example:
  1867. * ```js
  1868. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1869. * ```
  1870. *
  1871. * @augments TempNode
  1872. */
  1873. class SetNode extends TempNode {
  1874. static get type() {
  1875. return 'SetNode';
  1876. }
  1877. /**
  1878. * Constructs a new set node.
  1879. *
  1880. * @param {Node} sourceNode - The node that should be updated.
  1881. * @param {string} components - The components that should be updated.
  1882. * @param {Node} targetNode - The value node.
  1883. */
  1884. constructor( sourceNode, components, targetNode ) {
  1885. super();
  1886. /**
  1887. * The node that should be updated.
  1888. *
  1889. * @type {Node}
  1890. */
  1891. this.sourceNode = sourceNode;
  1892. /**
  1893. * The components that should be updated.
  1894. *
  1895. * @type {string}
  1896. */
  1897. this.components = components;
  1898. /**
  1899. * The value node.
  1900. *
  1901. * @type {Node}
  1902. */
  1903. this.targetNode = targetNode;
  1904. }
  1905. /**
  1906. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1907. *
  1908. * @param {NodeBuilder} builder - The current node builder.
  1909. * @return {string} The node type.
  1910. */
  1911. getNodeType( builder ) {
  1912. return this.sourceNode.getNodeType( builder );
  1913. }
  1914. generate( builder ) {
  1915. const { sourceNode, components, targetNode } = this;
  1916. const sourceType = this.getNodeType( builder );
  1917. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1918. const targetType = builder.getTypeFromLength( components.length, componentType );
  1919. const targetSnippet = targetNode.build( builder, targetType );
  1920. const sourceSnippet = sourceNode.build( builder, sourceType );
  1921. const length = builder.getTypeLength( sourceType );
  1922. const snippetValues = [];
  1923. for ( let i = 0; i < length; i ++ ) {
  1924. const component = vectorComponents[ i ];
  1925. if ( component === components[ 0 ] ) {
  1926. snippetValues.push( targetSnippet );
  1927. i += components.length - 1;
  1928. } else {
  1929. snippetValues.push( sourceSnippet + '.' + component );
  1930. }
  1931. }
  1932. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1933. }
  1934. }
  1935. /**
  1936. * This module is part of the TSL core and usually not used in app level code.
  1937. * It represents a flip operation during the shader generation process
  1938. * meaning it flips normalized values with the following formula:
  1939. * ```
  1940. * x = 1 - x;
  1941. * ```
  1942. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1943. * `flipSTPQ()` method invocations on node objects. For example:
  1944. * ```js
  1945. * uvNode = uvNode.flipY();
  1946. * ```
  1947. *
  1948. * @augments TempNode
  1949. */
  1950. class FlipNode extends TempNode {
  1951. static get type() {
  1952. return 'FlipNode';
  1953. }
  1954. /**
  1955. * Constructs a new flip node.
  1956. *
  1957. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1958. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1959. */
  1960. constructor( sourceNode, components ) {
  1961. super();
  1962. /**
  1963. * The node which component(s) should be flipped.
  1964. *
  1965. * @type {Node}
  1966. */
  1967. this.sourceNode = sourceNode;
  1968. /**
  1969. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1970. *
  1971. * @type {string}
  1972. */
  1973. this.components = components;
  1974. }
  1975. /**
  1976. * This method is overwritten since the node type is inferred from the source node.
  1977. *
  1978. * @param {NodeBuilder} builder - The current node builder.
  1979. * @return {string} The node type.
  1980. */
  1981. getNodeType( builder ) {
  1982. return this.sourceNode.getNodeType( builder );
  1983. }
  1984. generate( builder ) {
  1985. const { components, sourceNode } = this;
  1986. const sourceType = this.getNodeType( builder );
  1987. const sourceSnippet = sourceNode.build( builder );
  1988. const sourceCache = builder.getVarFromNode( this );
  1989. const sourceProperty = builder.getPropertyName( sourceCache );
  1990. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1991. const length = builder.getTypeLength( sourceType );
  1992. const snippetValues = [];
  1993. let componentIndex = 0;
  1994. for ( let i = 0; i < length; i ++ ) {
  1995. const component = vectorComponents[ i ];
  1996. if ( component === components[ componentIndex ] ) {
  1997. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1998. componentIndex ++;
  1999. } else {
  2000. snippetValues.push( sourceProperty + '.' + component );
  2001. }
  2002. }
  2003. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  2004. }
  2005. }
  2006. /**
  2007. * Base class for representing data input nodes.
  2008. *
  2009. * @augments Node
  2010. */
  2011. class InputNode extends Node {
  2012. static get type() {
  2013. return 'InputNode';
  2014. }
  2015. /**
  2016. * Constructs a new input node.
  2017. *
  2018. * @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).
  2019. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2020. */
  2021. constructor( value, nodeType = null ) {
  2022. super( nodeType );
  2023. /**
  2024. * This flag can be used for type testing.
  2025. *
  2026. * @type {boolean}
  2027. * @readonly
  2028. * @default true
  2029. */
  2030. this.isInputNode = true;
  2031. /**
  2032. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  2033. *
  2034. * @type {any}
  2035. */
  2036. this.value = value;
  2037. /**
  2038. * The precision of the value in the shader.
  2039. *
  2040. * @type {?('low'|'medium'|'high')}
  2041. * @default null
  2042. */
  2043. this.precision = null;
  2044. }
  2045. getNodeType( /*builder*/ ) {
  2046. if ( this.nodeType === null ) {
  2047. return getValueType( this.value );
  2048. }
  2049. return this.nodeType;
  2050. }
  2051. /**
  2052. * Returns the input type of the node which is by default the node type. Derived modules
  2053. * might overwrite this method and use a fixed type or compute one analytically.
  2054. *
  2055. * A typical example for different input and node types are textures. The input type of a
  2056. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  2057. *
  2058. * @param {NodeBuilder} builder - The current node builder.
  2059. * @return {string} The input type.
  2060. */
  2061. getInputType( builder ) {
  2062. return this.getNodeType( builder );
  2063. }
  2064. /**
  2065. * Sets the precision to the given value. The method can be
  2066. * overwritten in derived classes if the final precision must be computed
  2067. * analytically.
  2068. *
  2069. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  2070. * @return {InputNode} A reference to this node.
  2071. */
  2072. setPrecision( precision ) {
  2073. this.precision = precision;
  2074. return this;
  2075. }
  2076. serialize( data ) {
  2077. super.serialize( data );
  2078. data.value = this.value;
  2079. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  2080. data.valueType = getValueType( this.value );
  2081. data.nodeType = this.nodeType;
  2082. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  2083. data.precision = this.precision;
  2084. }
  2085. deserialize( data ) {
  2086. super.deserialize( data );
  2087. this.nodeType = data.nodeType;
  2088. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  2089. this.precision = data.precision || null;
  2090. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  2091. }
  2092. generate( /*builder, output*/ ) {
  2093. warn( 'Abstract function.' );
  2094. }
  2095. }
  2096. const _regNum = /float|u?int/;
  2097. /**
  2098. * Class for representing a constant value in the shader.
  2099. *
  2100. * @augments InputNode
  2101. */
  2102. class ConstNode extends InputNode {
  2103. static get type() {
  2104. return 'ConstNode';
  2105. }
  2106. /**
  2107. * Constructs a new input node.
  2108. *
  2109. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  2110. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2111. */
  2112. constructor( value, nodeType = null ) {
  2113. super( value, nodeType );
  2114. /**
  2115. * This flag can be used for type testing.
  2116. *
  2117. * @type {boolean}
  2118. * @readonly
  2119. * @default true
  2120. */
  2121. this.isConstNode = true;
  2122. }
  2123. /**
  2124. * Generates the shader string of the value with the current node builder.
  2125. *
  2126. * @param {NodeBuilder} builder - The current node builder.
  2127. * @return {string} The generated value as a shader string.
  2128. */
  2129. generateConst( builder ) {
  2130. return builder.generateConst( this.getNodeType( builder ), this.value );
  2131. }
  2132. generate( builder, output ) {
  2133. const type = this.getNodeType( builder );
  2134. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  2135. return builder.generateConst( output, this.value );
  2136. }
  2137. return builder.format( this.generateConst( builder ), type, output );
  2138. }
  2139. }
  2140. /**
  2141. * Base class for representing member access on an object-like
  2142. * node data structures.
  2143. *
  2144. * @augments Node
  2145. */
  2146. class MemberNode extends Node {
  2147. static get type() {
  2148. return 'MemberNode';
  2149. }
  2150. /**
  2151. * Constructs a member node.
  2152. *
  2153. * @param {Node} structNode - The struct node.
  2154. * @param {string} property - The property name.
  2155. */
  2156. constructor( structNode, property ) {
  2157. super();
  2158. /**
  2159. * The struct node.
  2160. *
  2161. * @type {Node}
  2162. */
  2163. this.structNode = structNode;
  2164. /**
  2165. * The property name.
  2166. *
  2167. * @type {Node}
  2168. */
  2169. this.property = property;
  2170. /**
  2171. * This flag can be used for type testing.
  2172. *
  2173. * @type {boolean}
  2174. * @readonly
  2175. * @default true
  2176. */
  2177. this.isMemberNode = true;
  2178. }
  2179. hasMember( builder ) {
  2180. if ( this.structNode.isMemberNode ) {
  2181. if ( this.structNode.hasMember( builder ) === false ) {
  2182. return false;
  2183. }
  2184. }
  2185. return this.structNode.getMemberType( builder, this.property ) !== 'void';
  2186. }
  2187. getNodeType( builder ) {
  2188. if ( this.hasMember( builder ) === false ) {
  2189. // default type if member does not exist
  2190. return 'float';
  2191. }
  2192. return this.structNode.getMemberType( builder, this.property );
  2193. }
  2194. getMemberType( builder, name ) {
  2195. if ( this.hasMember( builder ) === false ) {
  2196. // default type if member does not exist
  2197. return 'float';
  2198. }
  2199. const type = this.getNodeType( builder );
  2200. const struct = builder.getStructTypeNode( type );
  2201. return struct.getMemberType( builder, name );
  2202. }
  2203. generate( builder ) {
  2204. if ( this.hasMember( builder ) === false ) {
  2205. warn( `TSL: Member "${ this.property }" does not exist in struct.` );
  2206. const type = this.getNodeType( builder );
  2207. return builder.generateConst( type );
  2208. }
  2209. const propertyName = this.structNode.build( builder );
  2210. return propertyName + '.' + this.property;
  2211. }
  2212. }
  2213. let currentStack = null;
  2214. const NodeElements = new Map();
  2215. // Extend Node Class for TSL using prototype
  2216. function addMethodChaining( name, nodeElement ) {
  2217. if ( NodeElements.has( name ) ) {
  2218. warn( `TSL: Redefinition of method chaining '${ name }'.` );
  2219. return;
  2220. }
  2221. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2222. NodeElements.set( name, nodeElement );
  2223. if ( name !== 'assign' ) {
  2224. // Changing Node prototype to add method chaining
  2225. Node.prototype[ name ] = function ( ...params ) {
  2226. //if ( name === 'toVarIntent' ) return this;
  2227. return this.isStackNode ? this.addToStack( nodeElement( ...params ) ) : nodeElement( this, ...params );
  2228. };
  2229. // Adding assign method chaining
  2230. Node.prototype[ name + 'Assign' ] = function ( ...params ) {
  2231. return this.isStackNode ? this.assign( params[ 0 ], nodeElement( ...params ) ) : this.assign( nodeElement( this, ...params ) );
  2232. };
  2233. }
  2234. }
  2235. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2236. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2237. Node.prototype.assign = function ( ...params ) {
  2238. if ( this.isStackNode !== true ) {
  2239. if ( currentStack !== null ) {
  2240. currentStack.assign( this, ...params );
  2241. } else {
  2242. error( 'TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().' );
  2243. }
  2244. return this;
  2245. } else {
  2246. const nodeElement = NodeElements.get( 'assign' );
  2247. return this.addToStack( nodeElement( ...params ) );
  2248. }
  2249. };
  2250. Node.prototype.toVarIntent = function () {
  2251. return this;
  2252. };
  2253. Node.prototype.get = function ( value ) {
  2254. return new MemberNode( this, value );
  2255. };
  2256. // Cache prototype for TSL
  2257. const proto = {};
  2258. // Set swizzle properties for xyzw, rgba, and stpq.
  2259. function setProtoSwizzle( property, altA, altB ) {
  2260. // swizzle properties
  2261. proto[ property ] = proto[ altA ] = proto[ altB ] = {
  2262. get() {
  2263. this._cache = this._cache || {};
  2264. //
  2265. let split = this._cache[ property ];
  2266. if ( split === undefined ) {
  2267. split = new SplitNode( this, property );
  2268. this._cache[ property ] = split;
  2269. }
  2270. return split;
  2271. },
  2272. set( value ) {
  2273. this[ property ].assign( nodeObject( value ) );
  2274. }
  2275. };
  2276. // set properties ( swizzle ) and sort to xyzw sequence
  2277. const propUpper = property.toUpperCase();
  2278. const altAUpper = altA.toUpperCase();
  2279. const altBUpper = altB.toUpperCase();
  2280. // Set methods for swizzle properties
  2281. Node.prototype[ 'set' + propUpper ] = Node.prototype[ 'set' + altAUpper ] = Node.prototype[ 'set' + altBUpper ] = function ( value ) {
  2282. const swizzle = parseSwizzleAndSort( property );
  2283. return new SetNode( this, swizzle, nodeObject( value ) );
  2284. };
  2285. // Set methods for flip properties
  2286. Node.prototype[ 'flip' + propUpper ] = Node.prototype[ 'flip' + altAUpper ] = Node.prototype[ 'flip' + altBUpper ] = function () {
  2287. const swizzle = parseSwizzleAndSort( property );
  2288. return new FlipNode( this, swizzle );
  2289. };
  2290. }
  2291. const swizzleA = [ 'x', 'y', 'z', 'w' ];
  2292. const swizzleB = [ 'r', 'g', 'b', 'a' ];
  2293. const swizzleC = [ 's', 't', 'p', 'q' ];
  2294. for ( let a = 0; a < 4; a ++ ) {
  2295. let prop = swizzleA[ a ];
  2296. let altA = swizzleB[ a ];
  2297. let altB = swizzleC[ a ];
  2298. setProtoSwizzle( prop, altA, altB );
  2299. for ( let b = 0; b < 4; b ++ ) {
  2300. prop = swizzleA[ a ] + swizzleA[ b ];
  2301. altA = swizzleB[ a ] + swizzleB[ b ];
  2302. altB = swizzleC[ a ] + swizzleC[ b ];
  2303. setProtoSwizzle( prop, altA, altB );
  2304. for ( let c = 0; c < 4; c ++ ) {
  2305. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ];
  2306. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ];
  2307. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ];
  2308. setProtoSwizzle( prop, altA, altB );
  2309. for ( let d = 0; d < 4; d ++ ) {
  2310. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ] + swizzleA[ d ];
  2311. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ] + swizzleB[ d ];
  2312. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ] + swizzleC[ d ];
  2313. setProtoSwizzle( prop, altA, altB );
  2314. }
  2315. }
  2316. }
  2317. }
  2318. // Set/get static properties for array elements (0-31).
  2319. for ( let i = 0; i < 32; i ++ ) {
  2320. proto[ i ] = {
  2321. get() {
  2322. this._cache = this._cache || {};
  2323. //
  2324. let element = this._cache[ i ];
  2325. if ( element === undefined ) {
  2326. element = new ArrayElementNode( this, new ConstNode( i, 'uint' ) );
  2327. this._cache[ i ] = element;
  2328. }
  2329. return element;
  2330. },
  2331. set( value ) {
  2332. this[ i ].assign( nodeObject( value ) );
  2333. }
  2334. };
  2335. }
  2336. /*
  2337. // Set properties for width, height, and depth.
  2338. function setProtoProperty( property, target ) {
  2339. proto[ property ] = {
  2340. get() {
  2341. this._cache = this._cache || {};
  2342. //
  2343. let split = this._cache[ target ];
  2344. if ( split === undefined ) {
  2345. split = new SplitNode( this, target );
  2346. this._cache[ target ] = split;
  2347. }
  2348. return split;
  2349. },
  2350. set( value ) {
  2351. this[ target ].assign( nodeObject( value ) );
  2352. }
  2353. };
  2354. }
  2355. setProtoProperty( 'width', 'x' );
  2356. setProtoProperty( 'height', 'y' );
  2357. setProtoProperty( 'depth', 'z' );
  2358. */
  2359. Object.defineProperties( Node.prototype, proto );
  2360. // --- FINISH ---
  2361. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2362. const ShaderNodeObject = function ( obj, altType = null ) {
  2363. const type = getValueType( obj );
  2364. if ( type === 'node' ) {
  2365. return obj;
  2366. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2367. return nodeObject( getConstNode( obj, altType ) );
  2368. } else if ( type === 'shader' ) {
  2369. return obj.isFn ? obj : Fn( obj );
  2370. }
  2371. return obj;
  2372. };
  2373. const ShaderNodeObjects = function ( objects, altType = null ) {
  2374. for ( const name in objects ) {
  2375. objects[ name ] = nodeObject( objects[ name ], altType );
  2376. }
  2377. return objects;
  2378. };
  2379. const ShaderNodeArray = function ( array, altType = null ) {
  2380. const len = array.length;
  2381. for ( let i = 0; i < len; i ++ ) {
  2382. array[ i ] = nodeObject( array[ i ], altType );
  2383. }
  2384. return array;
  2385. };
  2386. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2387. function assignNode( node ) {
  2388. if ( settings !== null ) {
  2389. node = nodeObject( Object.assign( node, settings ) );
  2390. if ( settings.intent === true ) {
  2391. node = node.toVarIntent();
  2392. }
  2393. } else {
  2394. node = nodeObject( node );
  2395. }
  2396. return node;
  2397. }
  2398. let fn, name = scope, minParams, maxParams;
  2399. function verifyParamsLimit( params ) {
  2400. let tslName;
  2401. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2402. else tslName = NodeClass.type;
  2403. if ( minParams !== undefined && params.length < minParams ) {
  2404. error( `TSL: "${ tslName }" parameter length is less than minimum required.` );
  2405. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2406. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2407. error( `TSL: "${ tslName }" parameter length exceeds limit.` );
  2408. return params.slice( 0, maxParams );
  2409. }
  2410. return params;
  2411. }
  2412. if ( scope === null ) {
  2413. fn = ( ...params ) => {
  2414. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2415. };
  2416. } else if ( factor !== null ) {
  2417. factor = nodeObject( factor );
  2418. fn = ( ...params ) => {
  2419. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2420. };
  2421. } else {
  2422. fn = ( ...params ) => {
  2423. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2424. };
  2425. }
  2426. fn.setParameterLength = ( ...params ) => {
  2427. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2428. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2429. return fn;
  2430. };
  2431. fn.setName = ( value ) => {
  2432. name = value;
  2433. return fn;
  2434. };
  2435. return fn;
  2436. };
  2437. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2438. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2439. };
  2440. class ShaderCallNodeInternal extends Node {
  2441. constructor( shaderNode, rawInputs ) {
  2442. super();
  2443. this.shaderNode = shaderNode;
  2444. this.rawInputs = rawInputs;
  2445. this.isShaderCallNodeInternal = true;
  2446. }
  2447. getNodeType( builder ) {
  2448. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2449. }
  2450. getElementType( builder ) {
  2451. return this.getOutputNode( builder ).getElementType( builder );
  2452. }
  2453. getMemberType( builder, name ) {
  2454. return this.getOutputNode( builder ).getMemberType( builder, name );
  2455. }
  2456. call( builder ) {
  2457. const { shaderNode, rawInputs } = this;
  2458. const properties = builder.getNodeProperties( shaderNode );
  2459. const subBuild = builder.getClosestSubBuild( shaderNode.subBuilds ) || '';
  2460. const subBuildProperty = subBuild || 'default';
  2461. if ( properties[ subBuildProperty ] ) {
  2462. return properties[ subBuildProperty ];
  2463. }
  2464. //
  2465. const previousSubBuildFn = builder.subBuildFn;
  2466. const previousFnCall = builder.fnCall;
  2467. builder.subBuildFn = subBuild;
  2468. builder.fnCall = this;
  2469. let result = null;
  2470. if ( shaderNode.layout ) {
  2471. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2472. if ( functionNodesCacheMap === undefined ) {
  2473. functionNodesCacheMap = new WeakMap();
  2474. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2475. }
  2476. let functionNode = functionNodesCacheMap.get( shaderNode );
  2477. if ( functionNode === undefined ) {
  2478. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2479. functionNodesCacheMap.set( shaderNode, functionNode );
  2480. }
  2481. builder.addInclude( functionNode );
  2482. //
  2483. const inputs = rawInputs ? getLayoutParameters( rawInputs ) : null;
  2484. result = nodeObject( functionNode.call( inputs ) );
  2485. } else {
  2486. const secureNodeBuilder = new Proxy( builder, {
  2487. get: ( target, property, receiver ) => {
  2488. let value;
  2489. if ( Symbol.iterator === property ) {
  2490. value = function* () {
  2491. yield undefined;
  2492. };
  2493. } else {
  2494. value = Reflect.get( target, property, receiver );
  2495. }
  2496. return value;
  2497. }
  2498. } );
  2499. //
  2500. const inputs = rawInputs ? getProxyParameters( rawInputs ) : null;
  2501. const hasParameters = Array.isArray( rawInputs ) ? rawInputs.length > 0 : rawInputs !== null;
  2502. const jsFunc = shaderNode.jsFunc;
  2503. const outputNode = hasParameters || jsFunc.length > 1 ? jsFunc( inputs, secureNodeBuilder ) : jsFunc( secureNodeBuilder );
  2504. result = nodeObject( outputNode );
  2505. }
  2506. builder.subBuildFn = previousSubBuildFn;
  2507. builder.fnCall = previousFnCall;
  2508. if ( shaderNode.once ) {
  2509. properties[ subBuildProperty ] = result;
  2510. }
  2511. return result;
  2512. }
  2513. setupOutput( builder ) {
  2514. builder.addStack();
  2515. builder.stack.outputNode = this.call( builder );
  2516. return builder.removeStack();
  2517. }
  2518. getOutputNode( builder ) {
  2519. const properties = builder.getNodeProperties( this );
  2520. const subBuildOutput = builder.getSubBuildOutput( this );
  2521. properties[ subBuildOutput ] = properties[ subBuildOutput ] || this.setupOutput( builder );
  2522. properties[ subBuildOutput ].subBuild = builder.getClosestSubBuild( this );
  2523. return properties[ subBuildOutput ];
  2524. }
  2525. build( builder, output = null ) {
  2526. let result = null;
  2527. const buildStage = builder.getBuildStage();
  2528. const properties = builder.getNodeProperties( this );
  2529. const subBuildOutput = builder.getSubBuildOutput( this );
  2530. const outputNode = this.getOutputNode( builder );
  2531. const previousFnCall = builder.fnCall;
  2532. builder.fnCall = this;
  2533. if ( buildStage === 'setup' ) {
  2534. const subBuildInitialized = builder.getSubBuildProperty( 'initialized', this );
  2535. if ( properties[ subBuildInitialized ] !== true ) {
  2536. properties[ subBuildInitialized ] = true;
  2537. properties[ subBuildOutput ] = this.getOutputNode( builder );
  2538. properties[ subBuildOutput ].build( builder );
  2539. // If the shaderNode has subBuilds, add them to the chaining nodes
  2540. // so they can be built later in the build process.
  2541. if ( this.shaderNode.subBuilds ) {
  2542. for ( const node of builder.chaining ) {
  2543. const nodeData = builder.getDataFromNode( node, 'any' );
  2544. nodeData.subBuilds = nodeData.subBuilds || new Set();
  2545. for ( const subBuild of this.shaderNode.subBuilds ) {
  2546. nodeData.subBuilds.add( subBuild );
  2547. }
  2548. //builder.getDataFromNode( node ).subBuilds = nodeData.subBuilds;
  2549. }
  2550. }
  2551. }
  2552. result = properties[ subBuildOutput ];
  2553. } else if ( buildStage === 'analyze' ) {
  2554. outputNode.build( builder, output );
  2555. } else if ( buildStage === 'generate' ) {
  2556. result = outputNode.build( builder, output ) || '';
  2557. }
  2558. builder.fnCall = previousFnCall;
  2559. return result;
  2560. }
  2561. }
  2562. function getLayoutParameters( params ) {
  2563. let output;
  2564. nodeObjects( params );
  2565. const isArrayAsParameter = params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2566. if ( isArrayAsParameter ) {
  2567. output = [ ...params ];
  2568. } else {
  2569. output = params[ 0 ];
  2570. }
  2571. return output;
  2572. }
  2573. function getProxyParameters( params ) {
  2574. let index = 0;
  2575. nodeObjects( params );
  2576. return new Proxy( params, {
  2577. get: ( target, property, receiver ) => {
  2578. let value;
  2579. if ( property === 'length' ) {
  2580. value = params.length;
  2581. return value;
  2582. }
  2583. if ( Symbol.iterator === property ) {
  2584. value = function* () {
  2585. for ( const inputNode of params ) {
  2586. yield nodeObject( inputNode );
  2587. }
  2588. };
  2589. } else {
  2590. if ( params.length > 0 ) {
  2591. if ( Object.getPrototypeOf( params[ 0 ] ) === Object.prototype ) {
  2592. const objectTarget = params[ 0 ];
  2593. if ( objectTarget[ property ] === undefined ) {
  2594. value = objectTarget[ index ++ ];
  2595. } else {
  2596. value = Reflect.get( objectTarget, property, receiver );
  2597. }
  2598. } else if ( params[ 0 ] instanceof Node ) {
  2599. if ( params[ property ] === undefined ) {
  2600. value = params[ index ++ ];
  2601. } else {
  2602. value = Reflect.get( params, property, receiver );
  2603. }
  2604. }
  2605. } else {
  2606. value = Reflect.get( target, property, receiver );
  2607. }
  2608. value = nodeObject( value );
  2609. }
  2610. return value;
  2611. }
  2612. } );
  2613. }
  2614. class ShaderNodeInternal extends Node {
  2615. constructor( jsFunc, nodeType ) {
  2616. super( nodeType );
  2617. this.jsFunc = jsFunc;
  2618. this.layout = null;
  2619. this.global = true;
  2620. this.once = false;
  2621. }
  2622. setLayout( layout ) {
  2623. this.layout = layout;
  2624. return this;
  2625. }
  2626. getLayout() {
  2627. return this.layout;
  2628. }
  2629. call( rawInputs = null ) {
  2630. return new ShaderCallNodeInternal( this, rawInputs );
  2631. }
  2632. setup() {
  2633. return this.call();
  2634. }
  2635. }
  2636. const bools = [ false, true ];
  2637. const uints = [ 0, 1, 2, 3 ];
  2638. const ints = [ -1, -2 ];
  2639. 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 ];
  2640. const boolsCacheMap = new Map();
  2641. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2642. const uintsCacheMap = new Map();
  2643. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2644. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2645. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2646. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2647. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2648. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2649. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2650. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2651. const getConstNode = ( value, type ) => {
  2652. if ( constNodesCacheMap.has( value ) ) {
  2653. return constNodesCacheMap.get( value );
  2654. } else if ( value.isNode === true ) {
  2655. return value;
  2656. } else {
  2657. return new ConstNode( value, type );
  2658. }
  2659. };
  2660. const ConvertType = function ( type, cacheMap = null ) {
  2661. return ( ...params ) => {
  2662. for ( const param of params ) {
  2663. if ( param === undefined ) {
  2664. error( `TSL: Invalid parameter for the type "${ type }".` );
  2665. return nodeObject( new ConstNode( 0, type ) );
  2666. }
  2667. }
  2668. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => {
  2669. const paramType = typeof param;
  2670. return paramType !== 'object' && paramType !== 'function';
  2671. } ) ) ) {
  2672. params = [ getValueFromType( type, ...params ) ];
  2673. }
  2674. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2675. return nodeObjectIntent( cacheMap.get( params[ 0 ] ) );
  2676. }
  2677. if ( params.length === 1 ) {
  2678. const node = getConstNode( params[ 0 ], type );
  2679. if ( node.nodeType === type ) return nodeObjectIntent( node );
  2680. return nodeObjectIntent( new ConvertNode( node, type ) );
  2681. }
  2682. const nodes = params.map( param => getConstNode( param ) );
  2683. return nodeObjectIntent( new JoinNode( nodes, type ) );
  2684. };
  2685. };
  2686. // exports
  2687. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2688. // utils
  2689. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2690. // shader node base
  2691. function ShaderNode( jsFunc, nodeType ) {
  2692. return new ShaderNodeInternal( jsFunc, nodeType );
  2693. }
  2694. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2695. const nodeObjectIntent = ( val, altType = null ) => /* new */ nodeObject( val, altType ).toVarIntent();
  2696. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2697. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2698. const nodeProxy = ( NodeClass, scope = null, factor = null, settings = null ) => new ShaderNodeProxy( NodeClass, scope, factor, settings );
  2699. const nodeImmutable = ( NodeClass, ...params ) => new ShaderNodeImmutable( NodeClass, ...params );
  2700. const nodeProxyIntent = ( NodeClass, scope = null, factor = null, settings = {} ) => new ShaderNodeProxy( NodeClass, scope, factor, { ...settings, intent: true } );
  2701. let fnId = 0;
  2702. class FnNode extends Node {
  2703. constructor( jsFunc, layout = null ) {
  2704. super();
  2705. let nodeType = null;
  2706. if ( layout !== null ) {
  2707. if ( typeof layout === 'object' ) {
  2708. nodeType = layout.return;
  2709. } else {
  2710. if ( typeof layout === 'string' ) {
  2711. nodeType = layout;
  2712. } else {
  2713. error( 'TSL: Invalid layout type.' );
  2714. }
  2715. layout = null;
  2716. }
  2717. }
  2718. this.shaderNode = new ShaderNode( jsFunc, nodeType );
  2719. if ( layout !== null ) {
  2720. this.setLayout( layout );
  2721. }
  2722. this.isFn = true;
  2723. }
  2724. setLayout( layout ) {
  2725. const nodeType = this.shaderNode.nodeType;
  2726. if ( typeof layout.inputs !== 'object' ) {
  2727. const fullLayout = {
  2728. name: 'fn' + fnId ++,
  2729. type: nodeType,
  2730. inputs: []
  2731. };
  2732. for ( const name in layout ) {
  2733. if ( name === 'return' ) continue;
  2734. fullLayout.inputs.push( {
  2735. name: name,
  2736. type: layout[ name ]
  2737. } );
  2738. }
  2739. layout = fullLayout;
  2740. }
  2741. this.shaderNode.setLayout( layout );
  2742. return this;
  2743. }
  2744. getNodeType( builder ) {
  2745. return this.shaderNode.getNodeType( builder ) || 'float';
  2746. }
  2747. call( ...params ) {
  2748. const fnCall = this.shaderNode.call( params );
  2749. if ( this.shaderNode.nodeType === 'void' ) fnCall.toStack();
  2750. return fnCall.toVarIntent();
  2751. }
  2752. once( subBuilds = null ) {
  2753. this.shaderNode.once = true;
  2754. this.shaderNode.subBuilds = subBuilds;
  2755. return this;
  2756. }
  2757. generate( builder ) {
  2758. const type = this.getNodeType( builder );
  2759. error( 'TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".' );
  2760. return builder.generateConst( type );
  2761. }
  2762. }
  2763. function Fn( jsFunc, layout = null ) {
  2764. const instance = new FnNode( jsFunc, layout );
  2765. return new Proxy( () => {}, {
  2766. apply( target, thisArg, params ) {
  2767. return instance.call( ...params );
  2768. },
  2769. get( target, prop, receiver ) {
  2770. return Reflect.get( instance, prop, receiver );
  2771. },
  2772. set( target, prop, value, receiver ) {
  2773. return Reflect.set( instance, prop, value, receiver );
  2774. }
  2775. } );
  2776. }
  2777. //
  2778. const setCurrentStack = ( stack ) => {
  2779. currentStack = stack;
  2780. };
  2781. const getCurrentStack = () => currentStack;
  2782. /**
  2783. * Represent a conditional node using if/else statements.
  2784. *
  2785. * ```js
  2786. * If( condition, function )
  2787. * .ElseIf( condition, function )
  2788. * .Else( function )
  2789. * ```
  2790. * @tsl
  2791. * @function
  2792. * @param {...any} params - The parameters for the conditional node.
  2793. * @returns {StackNode} The conditional node.
  2794. */
  2795. const If = ( ...params ) => currentStack.If( ...params );
  2796. /**
  2797. * Represent a conditional node using switch/case statements.
  2798. *
  2799. * ```js
  2800. * Switch( value )
  2801. * .Case( 1, function )
  2802. * .Case( 2, 3, 4, function )
  2803. * .Default( function )
  2804. * ```
  2805. * @tsl
  2806. * @function
  2807. * @param {...any} params - The parameters for the conditional node.
  2808. * @returns {StackNode} The conditional node.
  2809. */
  2810. const Switch = ( ...params ) => currentStack.Switch( ...params );
  2811. /**
  2812. * Add the given node to the current stack.
  2813. *
  2814. * @param {Node} node - The node to add.
  2815. * @returns {Node} The node that was added to the stack.
  2816. */
  2817. function Stack( node ) {
  2818. if ( currentStack ) currentStack.addToStack( node );
  2819. return node;
  2820. }
  2821. addMethodChaining( 'toStack', Stack );
  2822. // types
  2823. const color = new ConvertType( 'color' );
  2824. const float = new ConvertType( 'float', cacheMaps.float );
  2825. const int = new ConvertType( 'int', cacheMaps.ints );
  2826. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2827. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2828. const vec2 = new ConvertType( 'vec2' );
  2829. const ivec2 = new ConvertType( 'ivec2' );
  2830. const uvec2 = new ConvertType( 'uvec2' );
  2831. const bvec2 = new ConvertType( 'bvec2' );
  2832. const vec3 = new ConvertType( 'vec3' );
  2833. const ivec3 = new ConvertType( 'ivec3' );
  2834. const uvec3 = new ConvertType( 'uvec3' );
  2835. const bvec3 = new ConvertType( 'bvec3' );
  2836. const vec4 = new ConvertType( 'vec4' );
  2837. const ivec4 = new ConvertType( 'ivec4' );
  2838. const uvec4 = new ConvertType( 'uvec4' );
  2839. const bvec4 = new ConvertType( 'bvec4' );
  2840. const mat2 = new ConvertType( 'mat2' );
  2841. const mat3 = new ConvertType( 'mat3' );
  2842. const mat4 = new ConvertType( 'mat4' );
  2843. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2844. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2845. addMethodChaining( 'toColor', color );
  2846. addMethodChaining( 'toFloat', float );
  2847. addMethodChaining( 'toInt', int );
  2848. addMethodChaining( 'toUint', uint );
  2849. addMethodChaining( 'toBool', bool );
  2850. addMethodChaining( 'toVec2', vec2 );
  2851. addMethodChaining( 'toIVec2', ivec2 );
  2852. addMethodChaining( 'toUVec2', uvec2 );
  2853. addMethodChaining( 'toBVec2', bvec2 );
  2854. addMethodChaining( 'toVec3', vec3 );
  2855. addMethodChaining( 'toIVec3', ivec3 );
  2856. addMethodChaining( 'toUVec3', uvec3 );
  2857. addMethodChaining( 'toBVec3', bvec3 );
  2858. addMethodChaining( 'toVec4', vec4 );
  2859. addMethodChaining( 'toIVec4', ivec4 );
  2860. addMethodChaining( 'toUVec4', uvec4 );
  2861. addMethodChaining( 'toBVec4', bvec4 );
  2862. addMethodChaining( 'toMat2', mat2 );
  2863. addMethodChaining( 'toMat3', mat3 );
  2864. addMethodChaining( 'toMat4', mat4 );
  2865. // basic nodes
  2866. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  2867. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2868. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2869. addMethodChaining( 'element', element );
  2870. addMethodChaining( 'convert', convert );
  2871. // deprecated
  2872. /**
  2873. * @tsl
  2874. * @function
  2875. * @deprecated since r176. Use {@link Stack} instead.
  2876. *
  2877. * @param {Node} node - The node to add.
  2878. * @returns {Function}
  2879. */
  2880. const append = ( node ) => { // @deprecated, r176
  2881. warn( 'TSL: append() has been renamed to Stack().' );
  2882. return Stack( node );
  2883. };
  2884. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  2885. warn( 'TSL: .append() has been renamed to .toStack().' );
  2886. return Stack( node );
  2887. } );
  2888. /**
  2889. * This class represents a shader property. It can be used
  2890. * to explicitly define a property and assign a value to it.
  2891. *
  2892. * ```js
  2893. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2894. *```
  2895. * `PropertyNode` is used by the engine to predefined common material properties
  2896. * for TSL code.
  2897. *
  2898. * @augments Node
  2899. */
  2900. class PropertyNode extends Node {
  2901. static get type() {
  2902. return 'PropertyNode';
  2903. }
  2904. /**
  2905. * Constructs a new property node.
  2906. *
  2907. * @param {string} nodeType - The type of the node.
  2908. * @param {?string} [name=null] - The name of the property in the shader.
  2909. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2910. */
  2911. constructor( nodeType, name = null, varying = false ) {
  2912. super( nodeType );
  2913. /**
  2914. * The name of the property in the shader. If no name is defined,
  2915. * the node system auto-generates one.
  2916. *
  2917. * @type {?string}
  2918. * @default null
  2919. */
  2920. this.name = name;
  2921. /**
  2922. * Whether this property is a varying or not.
  2923. *
  2924. * @type {boolean}
  2925. * @default false
  2926. */
  2927. this.varying = varying;
  2928. /**
  2929. * This flag can be used for type testing.
  2930. *
  2931. * @type {boolean}
  2932. * @readonly
  2933. * @default true
  2934. */
  2935. this.isPropertyNode = true;
  2936. /**
  2937. * This flag is used for global cache.
  2938. *
  2939. * @type {boolean}
  2940. * @default true
  2941. */
  2942. this.global = true;
  2943. }
  2944. customCacheKey() {
  2945. return hashString( this.type + ':' + ( this.name || '' ) + ':' + ( this.varying ? '1' : '0' ) );
  2946. }
  2947. getHash( builder ) {
  2948. return this.name || super.getHash( builder );
  2949. }
  2950. generate( builder ) {
  2951. let nodeVar;
  2952. if ( this.varying === true ) {
  2953. nodeVar = builder.getVaryingFromNode( this, this.name );
  2954. nodeVar.needsInterpolation = true;
  2955. } else {
  2956. nodeVar = builder.getVarFromNode( this, this.name );
  2957. }
  2958. return builder.getPropertyName( nodeVar );
  2959. }
  2960. }
  2961. /**
  2962. * TSL function for creating a property node.
  2963. *
  2964. * @tsl
  2965. * @function
  2966. * @param {string} type - The type of the node.
  2967. * @param {?string} [name=null] - The name of the property in the shader.
  2968. * @returns {PropertyNode}
  2969. */
  2970. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2971. /**
  2972. * TSL function for creating a varying 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 varying in the shader.
  2978. * @returns {PropertyNode}
  2979. */
  2980. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2981. /**
  2982. * TSL object that represents the shader variable `DiffuseColor`.
  2983. *
  2984. * @tsl
  2985. * @type {PropertyNode<vec4>}
  2986. */
  2987. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2988. /**
  2989. * TSL object that represents the shader variable `DiffuseContribution`.
  2990. *
  2991. * @tsl
  2992. * @type {PropertyNode<vec3>}
  2993. */
  2994. const diffuseContribution = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'DiffuseContribution' );
  2995. /**
  2996. * TSL object that represents the shader variable `EmissiveColor`.
  2997. *
  2998. * @tsl
  2999. * @type {PropertyNode<vec3>}
  3000. */
  3001. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  3002. /**
  3003. * TSL object that represents the shader variable `Roughness`.
  3004. *
  3005. * @tsl
  3006. * @type {PropertyNode<float>}
  3007. */
  3008. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  3009. /**
  3010. * TSL object that represents the shader variable `Metalness`.
  3011. *
  3012. * @tsl
  3013. * @type {PropertyNode<float>}
  3014. */
  3015. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  3016. /**
  3017. * TSL object that represents the shader variable `Clearcoat`.
  3018. *
  3019. * @tsl
  3020. * @type {PropertyNode<float>}
  3021. */
  3022. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  3023. /**
  3024. * TSL object that represents the shader variable `ClearcoatRoughness`.
  3025. *
  3026. * @tsl
  3027. * @type {PropertyNode<float>}
  3028. */
  3029. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  3030. /**
  3031. * TSL object that represents the shader variable `Sheen`.
  3032. *
  3033. * @tsl
  3034. * @type {PropertyNode<vec3>}
  3035. */
  3036. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  3037. /**
  3038. * TSL object that represents the shader variable `SheenRoughness`.
  3039. *
  3040. * @tsl
  3041. * @type {PropertyNode<float>}
  3042. */
  3043. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  3044. /**
  3045. * TSL object that represents the shader variable `Iridescence`.
  3046. *
  3047. * @tsl
  3048. * @type {PropertyNode<float>}
  3049. */
  3050. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  3051. /**
  3052. * TSL object that represents the shader variable `IridescenceIOR`.
  3053. *
  3054. * @tsl
  3055. * @type {PropertyNode<float>}
  3056. */
  3057. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  3058. /**
  3059. * TSL object that represents the shader variable `IridescenceThickness`.
  3060. *
  3061. * @tsl
  3062. * @type {PropertyNode<float>}
  3063. */
  3064. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  3065. /**
  3066. * TSL object that represents the shader variable `AlphaT`.
  3067. *
  3068. * @tsl
  3069. * @type {PropertyNode<float>}
  3070. */
  3071. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  3072. /**
  3073. * TSL object that represents the shader variable `Anisotropy`.
  3074. *
  3075. * @tsl
  3076. * @type {PropertyNode<float>}
  3077. */
  3078. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  3079. /**
  3080. * TSL object that represents the shader variable `AnisotropyT`.
  3081. *
  3082. * @tsl
  3083. * @type {PropertyNode<vec3>}
  3084. */
  3085. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  3086. /**
  3087. * TSL object that represents the shader variable `AnisotropyB`.
  3088. *
  3089. * @tsl
  3090. * @type {PropertyNode<vec3>}
  3091. */
  3092. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  3093. /**
  3094. * TSL object that represents the shader variable `SpecularColor`.
  3095. *
  3096. * @tsl
  3097. * @type {PropertyNode<color>}
  3098. */
  3099. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  3100. /**
  3101. * TSL object that represents the shader variable `SpecularColorBlended`.
  3102. *
  3103. * @tsl
  3104. * @type {PropertyNode<color>}
  3105. */
  3106. const specularColorBlended = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColorBlended' );
  3107. /**
  3108. * TSL object that represents the shader variable `SpecularF90`.
  3109. *
  3110. * @tsl
  3111. * @type {PropertyNode<float>}
  3112. */
  3113. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  3114. /**
  3115. * TSL object that represents the shader variable `Shininess`.
  3116. *
  3117. * @tsl
  3118. * @type {PropertyNode<float>}
  3119. */
  3120. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  3121. /**
  3122. * TSL object that represents the shader variable `Output`.
  3123. *
  3124. * @tsl
  3125. * @type {PropertyNode<vec4>}
  3126. */
  3127. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  3128. /**
  3129. * TSL object that represents the shader variable `dashSize`.
  3130. *
  3131. * @tsl
  3132. * @type {PropertyNode<float>}
  3133. */
  3134. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  3135. /**
  3136. * TSL object that represents the shader variable `gapSize`.
  3137. *
  3138. * @tsl
  3139. * @type {PropertyNode<float>}
  3140. */
  3141. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  3142. /**
  3143. * TSL object that represents the shader variable `pointWidth`.
  3144. *
  3145. * @tsl
  3146. * @type {PropertyNode<float>}
  3147. */
  3148. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  3149. /**
  3150. * TSL object that represents the shader variable `IOR`.
  3151. *
  3152. * @tsl
  3153. * @type {PropertyNode<float>}
  3154. */
  3155. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  3156. /**
  3157. * TSL object that represents the shader variable `Transmission`.
  3158. *
  3159. * @tsl
  3160. * @type {PropertyNode<float>}
  3161. */
  3162. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  3163. /**
  3164. * TSL object that represents the shader variable `Thickness`.
  3165. *
  3166. * @tsl
  3167. * @type {PropertyNode<float>}
  3168. */
  3169. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  3170. /**
  3171. * TSL object that represents the shader variable `AttenuationDistance`.
  3172. *
  3173. * @tsl
  3174. * @type {PropertyNode<float>}
  3175. */
  3176. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  3177. /**
  3178. * TSL object that represents the shader variable `AttenuationColor`.
  3179. *
  3180. * @tsl
  3181. * @type {PropertyNode<color>}
  3182. */
  3183. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  3184. /**
  3185. * TSL object that represents the shader variable `Dispersion`.
  3186. *
  3187. * @tsl
  3188. * @type {PropertyNode<float>}
  3189. */
  3190. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  3191. /**
  3192. * This node can be used to group single instances of {@link UniformNode}
  3193. * and manage them as a uniform buffer.
  3194. *
  3195. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  3196. * will be used when defining the {@link UniformNode#groupNode} property.
  3197. *
  3198. * - `objectGroup`: Uniform buffer per object.
  3199. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  3200. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  3201. *
  3202. * @augments Node
  3203. */
  3204. class UniformGroupNode extends Node {
  3205. static get type() {
  3206. return 'UniformGroupNode';
  3207. }
  3208. /**
  3209. * Constructs a new uniform group node.
  3210. *
  3211. * @param {string} name - The name of the uniform group node.
  3212. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  3213. * @param {number} [order=1] - Influences the internal sorting.
  3214. */
  3215. constructor( name, shared = false, order = 1 ) {
  3216. super( 'string' );
  3217. /**
  3218. * The name of the uniform group node.
  3219. *
  3220. * @type {string}
  3221. */
  3222. this.name = name;
  3223. /**
  3224. * Whether this uniform group node is shared or not.
  3225. *
  3226. * @type {boolean}
  3227. * @default false
  3228. */
  3229. this.shared = shared;
  3230. /**
  3231. * Influences the internal sorting.
  3232. * TODO: Add details when this property should be changed.
  3233. *
  3234. * @type {number}
  3235. * @default 1
  3236. */
  3237. this.order = order;
  3238. /**
  3239. * This flag can be used for type testing.
  3240. *
  3241. * @type {boolean}
  3242. * @readonly
  3243. * @default true
  3244. */
  3245. this.isUniformGroup = true;
  3246. }
  3247. serialize( data ) {
  3248. super.serialize( data );
  3249. data.name = this.name;
  3250. data.version = this.version;
  3251. data.shared = this.shared;
  3252. }
  3253. deserialize( data ) {
  3254. super.deserialize( data );
  3255. this.name = data.name;
  3256. this.version = data.version;
  3257. this.shared = data.shared;
  3258. }
  3259. }
  3260. /**
  3261. * TSL function for creating a uniform group node with the given name.
  3262. *
  3263. * @tsl
  3264. * @function
  3265. * @param {string} name - The name of the uniform group node.
  3266. * @returns {UniformGroupNode}
  3267. */
  3268. const uniformGroup = ( name ) => new UniformGroupNode( name );
  3269. /**
  3270. * TSL function for creating a shared uniform group node with the given name and order.
  3271. *
  3272. * @tsl
  3273. * @function
  3274. * @param {string} name - The name of the uniform group node.
  3275. * @param {number} [order=0] - Influences the internal sorting.
  3276. * @returns {UniformGroupNode}
  3277. */
  3278. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  3279. /**
  3280. * TSL object that represents a shared uniform group node which is updated once per frame.
  3281. *
  3282. * @tsl
  3283. * @type {UniformGroupNode}
  3284. */
  3285. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  3286. /**
  3287. * TSL object that represents a shared uniform group node which is updated once per render.
  3288. *
  3289. * @tsl
  3290. * @type {UniformGroupNode}
  3291. */
  3292. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  3293. /**
  3294. * TSL object that represents a uniform group node which is updated once per object.
  3295. *
  3296. * @tsl
  3297. * @type {UniformGroupNode}
  3298. */
  3299. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  3300. /**
  3301. * Class for representing a uniform.
  3302. *
  3303. * @augments InputNode
  3304. */
  3305. class UniformNode extends InputNode {
  3306. static get type() {
  3307. return 'UniformNode';
  3308. }
  3309. /**
  3310. * Constructs a new uniform node.
  3311. *
  3312. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3313. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3314. */
  3315. constructor( value, nodeType = null ) {
  3316. super( value, nodeType );
  3317. /**
  3318. * This flag can be used for type testing.
  3319. *
  3320. * @type {boolean}
  3321. * @readonly
  3322. * @default true
  3323. */
  3324. this.isUniformNode = true;
  3325. /**
  3326. * The name or label of the uniform.
  3327. *
  3328. * @type {string}
  3329. * @default ''
  3330. */
  3331. this.name = '';
  3332. /**
  3333. * The uniform group of this uniform. By default, uniforms are
  3334. * managed per object but they might belong to a shared group
  3335. * which is updated per frame or render call.
  3336. *
  3337. * @type {UniformGroupNode}
  3338. */
  3339. this.groupNode = objectGroup;
  3340. }
  3341. /**
  3342. * Sets the {@link UniformNode#name} property.
  3343. *
  3344. * @param {string} name - The name of the uniform.
  3345. * @return {UniformNode} A reference to this node.
  3346. */
  3347. setName( name ) {
  3348. this.name = name;
  3349. return this;
  3350. }
  3351. /**
  3352. * Sets the {@link UniformNode#name} property.
  3353. *
  3354. * @deprecated
  3355. * @param {string} name - The name of the uniform.
  3356. * @return {UniformNode} A reference to this node.
  3357. */
  3358. label( name ) {
  3359. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  3360. return this.setName( name );
  3361. }
  3362. /**
  3363. * Sets the {@link UniformNode#groupNode} property.
  3364. *
  3365. * @param {UniformGroupNode} group - The uniform group.
  3366. * @return {UniformNode} A reference to this node.
  3367. */
  3368. setGroup( group ) {
  3369. this.groupNode = group;
  3370. return this;
  3371. }
  3372. /**
  3373. * Returns the {@link UniformNode#groupNode}.
  3374. *
  3375. * @return {UniformGroupNode} The uniform group.
  3376. */
  3377. getGroup() {
  3378. return this.groupNode;
  3379. }
  3380. /**
  3381. * By default, this method returns the result of {@link Node#getHash} but derived
  3382. * classes might overwrite this method with a different implementation.
  3383. *
  3384. * @param {NodeBuilder} builder - The current node builder.
  3385. * @return {string} The uniform hash.
  3386. */
  3387. getUniformHash( builder ) {
  3388. return this.getHash( builder );
  3389. }
  3390. onUpdate( callback, updateType ) {
  3391. callback = callback.bind( this );
  3392. return super.onUpdate( ( frame ) => {
  3393. const value = callback( frame, this );
  3394. if ( value !== undefined ) {
  3395. this.value = value;
  3396. }
  3397. }, updateType );
  3398. }
  3399. getInputType( builder ) {
  3400. let type = super.getInputType( builder );
  3401. if ( type === 'bool' ) {
  3402. type = 'uint';
  3403. }
  3404. return type;
  3405. }
  3406. generate( builder, output ) {
  3407. const type = this.getNodeType( builder );
  3408. const hash = this.getUniformHash( builder );
  3409. let sharedNode = builder.getNodeFromHash( hash );
  3410. if ( sharedNode === undefined ) {
  3411. builder.setHashNode( this, hash );
  3412. sharedNode = this;
  3413. }
  3414. const sharedNodeType = sharedNode.getInputType( builder );
  3415. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.nodeName );
  3416. const uniformName = builder.getPropertyName( nodeUniform );
  3417. if ( builder.context.nodeName !== undefined ) delete builder.context.nodeName;
  3418. //
  3419. let snippet = uniformName;
  3420. if ( type === 'bool' ) {
  3421. // cache to variable
  3422. const nodeData = builder.getDataFromNode( this );
  3423. let propertyName = nodeData.propertyName;
  3424. if ( propertyName === undefined ) {
  3425. const nodeVar = builder.getVarFromNode( this, null, 'bool' );
  3426. propertyName = builder.getPropertyName( nodeVar );
  3427. nodeData.propertyName = propertyName;
  3428. snippet = builder.format( uniformName, sharedNodeType, type );
  3429. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  3430. }
  3431. snippet = propertyName;
  3432. }
  3433. return builder.format( snippet, type, output );
  3434. }
  3435. }
  3436. /**
  3437. * TSL function for creating a uniform node.
  3438. *
  3439. * @tsl
  3440. * @function
  3441. * @param {any|string} value - The value of this uniform or your type. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3442. * @param {string} [type] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3443. * @returns {UniformNode}
  3444. */
  3445. const uniform = ( value, type ) => {
  3446. const nodeType = getConstNodeType( type || value );
  3447. if ( nodeType === value ) {
  3448. // if the value is a type but no having a value
  3449. value = getValueFromType( nodeType );
  3450. }
  3451. if ( value && value.isNode === true ) {
  3452. let v = value.value;
  3453. value.traverse( n => {
  3454. if ( n.isConstNode === true ) {
  3455. v = n.value;
  3456. }
  3457. } );
  3458. value = v;
  3459. }
  3460. return nodeObject( new UniformNode( value, nodeType ) );
  3461. };
  3462. /**
  3463. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3464. * ```js
  3465. * const colors = array( [
  3466. * vec3( 1, 0, 0 ),
  3467. * vec3( 0, 1, 0 ),
  3468. * vec3( 0, 0, 1 )
  3469. * ] );
  3470. *
  3471. * const redColor = tintColors.element( 0 );
  3472. * ```
  3473. *
  3474. * @augments TempNode
  3475. */
  3476. class ArrayNode extends TempNode {
  3477. static get type() {
  3478. return 'ArrayNode';
  3479. }
  3480. /**
  3481. * Constructs a new array node.
  3482. *
  3483. * @param {?string} nodeType - The data type of the elements.
  3484. * @param {number} count - Size of the array.
  3485. * @param {?Array<Node>} [values=null] - Array default values.
  3486. */
  3487. constructor( nodeType, count, values = null ) {
  3488. super( nodeType );
  3489. /**
  3490. * Array size.
  3491. *
  3492. * @type {number}
  3493. */
  3494. this.count = count;
  3495. /**
  3496. * Array default values.
  3497. *
  3498. * @type {?Array<Node>}
  3499. */
  3500. this.values = values;
  3501. /**
  3502. * This flag can be used for type testing.
  3503. *
  3504. * @type {boolean}
  3505. * @readonly
  3506. * @default true
  3507. */
  3508. this.isArrayNode = true;
  3509. }
  3510. /**
  3511. * Returns the number of elements in the node array.
  3512. *
  3513. * @param {NodeBuilder} builder - The current node builder.
  3514. * @return {number} The number of elements in the node array.
  3515. */
  3516. getArrayCount( /*builder*/ ) {
  3517. return this.count;
  3518. }
  3519. /**
  3520. * Returns the node's type.
  3521. *
  3522. * @param {NodeBuilder} builder - The current node builder.
  3523. * @return {string} The type of the node.
  3524. */
  3525. getNodeType( builder ) {
  3526. if ( this.nodeType === null ) {
  3527. this.nodeType = this.values[ 0 ].getNodeType( builder );
  3528. }
  3529. return this.nodeType;
  3530. }
  3531. /**
  3532. * Returns the node's type.
  3533. *
  3534. * @param {NodeBuilder} builder - The current node builder.
  3535. * @return {string} The type of the node.
  3536. */
  3537. getElementType( builder ) {
  3538. return this.getNodeType( builder );
  3539. }
  3540. /**
  3541. * This method builds the output node and returns the resulting array as a shader string.
  3542. *
  3543. * @param {NodeBuilder} builder - The current node builder.
  3544. * @return {string} The generated shader string.
  3545. */
  3546. generate( builder ) {
  3547. const type = this.getNodeType( builder );
  3548. return builder.generateArray( type, this.count, this.values );
  3549. }
  3550. }
  3551. /**
  3552. * TSL function for creating an array node.
  3553. *
  3554. * @tsl
  3555. * @function
  3556. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3557. * or an array containing the default values (e.g., [ vec3() ]).
  3558. * @param {?number} [count] - Size of the array.
  3559. * @returns {ArrayNode}
  3560. */
  3561. const array = ( ...params ) => {
  3562. let node;
  3563. if ( params.length === 1 ) {
  3564. const values = params[ 0 ];
  3565. node = new ArrayNode( null, values.length, values );
  3566. } else {
  3567. const nodeType = params[ 0 ];
  3568. const count = params[ 1 ];
  3569. node = new ArrayNode( nodeType, count );
  3570. }
  3571. return nodeObject( node );
  3572. };
  3573. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3574. /**
  3575. * These node represents an assign operation. Meaning a node is assigned
  3576. * to another node.
  3577. *
  3578. * @augments TempNode
  3579. */
  3580. class AssignNode extends TempNode {
  3581. static get type() {
  3582. return 'AssignNode';
  3583. }
  3584. /**
  3585. * Constructs a new assign node.
  3586. *
  3587. * @param {Node} targetNode - The target node.
  3588. * @param {Node} sourceNode - The source type.
  3589. */
  3590. constructor( targetNode, sourceNode ) {
  3591. super();
  3592. /**
  3593. * The target node.
  3594. *
  3595. * @type {Node}
  3596. */
  3597. this.targetNode = targetNode;
  3598. /**
  3599. * The source node.
  3600. *
  3601. * @type {Node}
  3602. */
  3603. this.sourceNode = sourceNode;
  3604. /**
  3605. * This flag can be used for type testing.
  3606. *
  3607. * @type {boolean}
  3608. * @readonly
  3609. * @default true
  3610. */
  3611. this.isAssignNode = true;
  3612. }
  3613. /**
  3614. * Whether this node is used more than once in context of other nodes. This method
  3615. * is overwritten since it always returns `false` (assigns are unique).
  3616. *
  3617. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3618. */
  3619. hasDependencies() {
  3620. return false;
  3621. }
  3622. getNodeType( builder, output ) {
  3623. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3624. }
  3625. /**
  3626. * Whether a split is required when assigning source to target. This can happen when the component length of
  3627. * target and source data type does not match.
  3628. *
  3629. * @param {NodeBuilder} builder - The current node builder.
  3630. * @return {boolean} Whether a split is required when assigning source to target.
  3631. */
  3632. needsSplitAssign( builder ) {
  3633. const { targetNode } = this;
  3634. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3635. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3636. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3637. return assignDifferentVector;
  3638. }
  3639. return false;
  3640. }
  3641. setup( builder ) {
  3642. const { targetNode, sourceNode } = this;
  3643. const scope = targetNode.getScope();
  3644. const targetProperties = builder.getNodeProperties( scope );
  3645. targetProperties.assign = true;
  3646. const properties = builder.getNodeProperties( this );
  3647. properties.sourceNode = sourceNode;
  3648. properties.targetNode = targetNode.context( { assign: true } );
  3649. }
  3650. generate( builder, output ) {
  3651. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  3652. const needsSplitAssign = this.needsSplitAssign( builder );
  3653. const target = targetNode.build( builder );
  3654. const targetType = targetNode.getNodeType( builder );
  3655. const source = sourceNode.build( builder, targetType );
  3656. const sourceType = sourceNode.getNodeType( builder );
  3657. const nodeData = builder.getDataFromNode( this );
  3658. //
  3659. let snippet;
  3660. if ( nodeData.initialized === true ) {
  3661. if ( output !== 'void' ) {
  3662. snippet = target;
  3663. }
  3664. } else if ( needsSplitAssign ) {
  3665. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3666. const sourceProperty = builder.getPropertyName( sourceVar );
  3667. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3668. const splitNode = targetNode.node;
  3669. const splitTargetNode = splitNode.node.context( { assign: true } );
  3670. const targetRoot = splitTargetNode.build( builder );
  3671. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  3672. const component = splitNode.components[ i ];
  3673. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3674. }
  3675. if ( output !== 'void' ) {
  3676. snippet = target;
  3677. }
  3678. } else {
  3679. snippet = `${ target } = ${ source }`;
  3680. if ( output === 'void' || sourceType === 'void' ) {
  3681. builder.addLineFlowCode( snippet, this );
  3682. if ( output !== 'void' ) {
  3683. snippet = target;
  3684. }
  3685. }
  3686. }
  3687. nodeData.initialized = true;
  3688. return builder.format( snippet, targetType, output );
  3689. }
  3690. }
  3691. /**
  3692. * TSL function for creating an assign node.
  3693. *
  3694. * @tsl
  3695. * @function
  3696. * @param {Node} targetNode - The target node.
  3697. * @param {Node} sourceNode - The source type.
  3698. * @returns {AssignNode}
  3699. */
  3700. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  3701. addMethodChaining( 'assign', assign );
  3702. /**
  3703. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3704. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3705. * this logic.
  3706. *
  3707. * @augments TempNode
  3708. */
  3709. class FunctionCallNode extends TempNode {
  3710. static get type() {
  3711. return 'FunctionCallNode';
  3712. }
  3713. /**
  3714. * Constructs a new function call node.
  3715. *
  3716. * @param {?FunctionNode} functionNode - The function node.
  3717. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3718. */
  3719. constructor( functionNode = null, parameters = {} ) {
  3720. super();
  3721. /**
  3722. * The function node.
  3723. *
  3724. * @type {?FunctionNode}
  3725. * @default null
  3726. */
  3727. this.functionNode = functionNode;
  3728. /**
  3729. * The parameters of the function call.
  3730. *
  3731. * @type {Object<string, Node>}
  3732. * @default {}
  3733. */
  3734. this.parameters = parameters;
  3735. }
  3736. /**
  3737. * Sets the parameters of the function call node.
  3738. *
  3739. * @param {Object<string, Node>} parameters - The parameters to set.
  3740. * @return {FunctionCallNode} A reference to this node.
  3741. */
  3742. setParameters( parameters ) {
  3743. this.parameters = parameters;
  3744. return this;
  3745. }
  3746. /**
  3747. * Returns the parameters of the function call node.
  3748. *
  3749. * @return {Object<string, Node>} The parameters of this node.
  3750. */
  3751. getParameters() {
  3752. return this.parameters;
  3753. }
  3754. /**
  3755. * Returns the type of this function call node.
  3756. *
  3757. * @param {NodeBuilder} builder - The current node builder.
  3758. * @returns {string} The type of this node.
  3759. */
  3760. getNodeType( builder ) {
  3761. return this.functionNode.getNodeType( builder );
  3762. }
  3763. /**
  3764. * Returns the function node of this function call node.
  3765. *
  3766. * @param {NodeBuilder} builder - The current node builder.
  3767. * @param {string} [name] - The name of the member.
  3768. * @returns {string} The type of the member.
  3769. */
  3770. getMemberType( builder, name ) {
  3771. return this.functionNode.getMemberType( builder, name );
  3772. }
  3773. generate( builder ) {
  3774. const params = [];
  3775. const functionNode = this.functionNode;
  3776. const inputs = functionNode.getInputs( builder );
  3777. const parameters = this.parameters;
  3778. const generateInput = ( node, inputNode ) => {
  3779. const type = inputNode.type;
  3780. const pointer = type === 'pointer';
  3781. let output;
  3782. if ( pointer ) output = '&' + node.build( builder );
  3783. else output = node.build( builder, type );
  3784. return output;
  3785. };
  3786. if ( Array.isArray( parameters ) ) {
  3787. if ( parameters.length > inputs.length ) {
  3788. error( 'TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  3789. parameters.length = inputs.length;
  3790. } else if ( parameters.length < inputs.length ) {
  3791. error( 'TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  3792. while ( parameters.length < inputs.length ) {
  3793. parameters.push( float( 0 ) );
  3794. }
  3795. }
  3796. for ( let i = 0; i < parameters.length; i ++ ) {
  3797. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3798. }
  3799. } else {
  3800. for ( const inputNode of inputs ) {
  3801. const node = parameters[ inputNode.name ];
  3802. if ( node !== undefined ) {
  3803. params.push( generateInput( node, inputNode ) );
  3804. } else {
  3805. error( `TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  3806. params.push( generateInput( float( 0 ), inputNode ) );
  3807. }
  3808. }
  3809. }
  3810. const functionName = functionNode.build( builder, 'property' );
  3811. return `${ functionName }( ${ params.join( ', ' ) } )`;
  3812. }
  3813. }
  3814. const call = ( func, ...params ) => {
  3815. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3816. return new FunctionCallNode( nodeObject( func ), params );
  3817. };
  3818. addMethodChaining( 'call', call );
  3819. const _vectorOperators = {
  3820. '==': 'equal',
  3821. '!=': 'notEqual',
  3822. '<': 'lessThan',
  3823. '>': 'greaterThan',
  3824. '<=': 'lessThanEqual',
  3825. '>=': 'greaterThanEqual',
  3826. '%': 'mod'
  3827. };
  3828. /**
  3829. * This node represents basic mathematical and logical operations like addition,
  3830. * subtraction or comparisons (e.g. `equal()`).
  3831. *
  3832. * @augments TempNode
  3833. */
  3834. class OperatorNode extends TempNode {
  3835. static get type() {
  3836. return 'OperatorNode';
  3837. }
  3838. /**
  3839. * Constructs a new operator node.
  3840. *
  3841. * @param {string} op - The operator.
  3842. * @param {Node} aNode - The first input.
  3843. * @param {Node} bNode - The second input.
  3844. * @param {...Node} params - Additional input parameters.
  3845. */
  3846. constructor( op, aNode, bNode, ...params ) {
  3847. super();
  3848. if ( params.length > 0 ) {
  3849. let finalOp = new OperatorNode( op, aNode, bNode );
  3850. for ( let i = 0; i < params.length - 1; i ++ ) {
  3851. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3852. }
  3853. aNode = finalOp;
  3854. bNode = params[ params.length - 1 ];
  3855. }
  3856. /**
  3857. * The operator.
  3858. *
  3859. * @type {string}
  3860. */
  3861. this.op = op;
  3862. /**
  3863. * The first input.
  3864. *
  3865. * @type {Node}
  3866. */
  3867. this.aNode = aNode;
  3868. /**
  3869. * The second input.
  3870. *
  3871. * @type {Node}
  3872. */
  3873. this.bNode = bNode;
  3874. /**
  3875. * This flag can be used for type testing.
  3876. *
  3877. * @type {boolean}
  3878. * @readonly
  3879. * @default true
  3880. */
  3881. this.isOperatorNode = true;
  3882. }
  3883. /**
  3884. * Returns the operator method name.
  3885. *
  3886. * @param {NodeBuilder} builder - The current node builder.
  3887. * @param {string} output - The output type.
  3888. * @returns {string} The operator method name.
  3889. */
  3890. getOperatorMethod( builder, output ) {
  3891. return builder.getMethod( _vectorOperators[ this.op ], output );
  3892. }
  3893. /**
  3894. * This method is overwritten since the node type is inferred from the operator
  3895. * and the input node types.
  3896. *
  3897. * @param {NodeBuilder} builder - The current node builder.
  3898. * @param {?string} [output=null] - The output type.
  3899. * @return {string} The node type.
  3900. */
  3901. getNodeType( builder, output = null ) {
  3902. const op = this.op;
  3903. const aNode = this.aNode;
  3904. const bNode = this.bNode;
  3905. const typeA = aNode.getNodeType( builder );
  3906. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  3907. if ( typeA === 'void' || typeB === 'void' ) {
  3908. return output || 'void';
  3909. } else if ( op === '%' ) {
  3910. return typeA;
  3911. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3912. return builder.getIntegerType( typeA );
  3913. } else if ( op === '!' || op === '&&' || op === '||' || op === '^^' ) {
  3914. return 'bool';
  3915. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3916. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3917. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3918. } else {
  3919. // Handle matrix operations
  3920. if ( builder.isMatrix( typeA ) ) {
  3921. if ( typeB === 'float' ) {
  3922. return typeA; // matrix * scalar = matrix
  3923. } else if ( builder.isVector( typeB ) ) {
  3924. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3925. } else if ( builder.isMatrix( typeB ) ) {
  3926. return typeA; // matrix * matrix
  3927. }
  3928. } else if ( builder.isMatrix( typeB ) ) {
  3929. if ( typeA === 'float' ) {
  3930. return typeB; // scalar * matrix = matrix
  3931. } else if ( builder.isVector( typeA ) ) {
  3932. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3933. }
  3934. }
  3935. // Handle non-matrix cases
  3936. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3937. // anytype x anytype: use the greater length vector
  3938. return typeB;
  3939. }
  3940. return typeA;
  3941. }
  3942. }
  3943. generate( builder, output ) {
  3944. const op = this.op;
  3945. const { aNode, bNode } = this;
  3946. const type = this.getNodeType( builder, output );
  3947. let typeA = null;
  3948. let typeB = null;
  3949. if ( type !== 'void' ) {
  3950. typeA = aNode.getNodeType( builder );
  3951. typeB = bNode ? bNode.getNodeType( builder ) : null;
  3952. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  3953. if ( builder.isVector( typeA ) ) {
  3954. typeB = typeA;
  3955. } else if ( builder.isVector( typeB ) ) {
  3956. typeA = typeB;
  3957. } else if ( typeA !== typeB ) {
  3958. typeA = typeB = 'float';
  3959. }
  3960. } else if ( op === '>>' || op === '<<' ) {
  3961. typeA = type;
  3962. typeB = builder.changeComponentType( typeB, 'uint' );
  3963. } else if ( op === '%' ) {
  3964. typeA = type;
  3965. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  3966. } else if ( builder.isMatrix( typeA ) ) {
  3967. if ( typeB === 'float' ) {
  3968. // Keep matrix type for typeA, but ensure typeB stays float
  3969. typeB = 'float';
  3970. } else if ( builder.isVector( typeB ) ) {
  3971. // matrix x vector
  3972. typeB = builder.getVectorFromMatrix( typeA );
  3973. } else if ( builder.isMatrix( typeB ) ) ; else {
  3974. typeA = typeB = type;
  3975. }
  3976. } else if ( builder.isMatrix( typeB ) ) {
  3977. if ( typeA === 'float' ) {
  3978. // Keep matrix type for typeB, but ensure typeA stays float
  3979. typeA = 'float';
  3980. } else if ( builder.isVector( typeA ) ) {
  3981. // vector x matrix
  3982. typeA = builder.getVectorFromMatrix( typeB );
  3983. } else {
  3984. typeA = typeB = type;
  3985. }
  3986. } else {
  3987. // anytype x anytype
  3988. typeA = typeB = type;
  3989. }
  3990. } else {
  3991. typeA = typeB = type;
  3992. }
  3993. const a = aNode.build( builder, typeA );
  3994. const b = bNode ? bNode.build( builder, typeB ) : null;
  3995. const fnOpSnippet = builder.getFunctionOperator( op );
  3996. if ( output !== 'void' ) {
  3997. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  3998. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3999. if ( isGLSL ) {
  4000. if ( builder.isVector( typeA ) ) {
  4001. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  4002. } else {
  4003. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  4004. }
  4005. } else {
  4006. // WGSL
  4007. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  4008. }
  4009. } else if ( op === '%' ) {
  4010. if ( builder.isInteger( typeB ) ) {
  4011. return builder.format( `( ${ a } % ${ b } )`, type, output );
  4012. } else {
  4013. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  4014. }
  4015. } else if ( op === '!' || op === '~' ) {
  4016. return builder.format( `(${op}${a})`, typeA, output );
  4017. } else if ( fnOpSnippet ) {
  4018. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4019. } else {
  4020. // Handle matrix operations
  4021. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4022. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  4023. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  4024. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4025. } else {
  4026. let snippet = `( ${ a } ${ op } ${ b } )`;
  4027. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  4028. snippet = `all${ snippet }`;
  4029. }
  4030. return builder.format( snippet, type, output );
  4031. }
  4032. }
  4033. } else if ( typeA !== 'void' ) {
  4034. if ( fnOpSnippet ) {
  4035. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4036. } else {
  4037. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4038. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  4039. } else {
  4040. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4041. }
  4042. }
  4043. }
  4044. }
  4045. serialize( data ) {
  4046. super.serialize( data );
  4047. data.op = this.op;
  4048. }
  4049. deserialize( data ) {
  4050. super.deserialize( data );
  4051. this.op = data.op;
  4052. }
  4053. }
  4054. /**
  4055. * Returns the addition of two or more value.
  4056. *
  4057. * @tsl
  4058. * @function
  4059. * @param {Node} a - The first input.
  4060. * @param {Node} b - The second input.
  4061. * @param {...Node} params - Additional input parameters.
  4062. * @returns {OperatorNode}
  4063. */
  4064. const add = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  4065. /**
  4066. * Returns the subtraction of two or more value.
  4067. *
  4068. * @tsl
  4069. * @function
  4070. * @param {Node} a - The first input.
  4071. * @param {Node} b - The second input.
  4072. * @param {...Node} params - Additional input parameters.
  4073. * @returns {OperatorNode}
  4074. */
  4075. const sub = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  4076. /**
  4077. * Returns the multiplication of two or more value.
  4078. *
  4079. * @tsl
  4080. * @function
  4081. * @param {Node} a - The first input.
  4082. * @param {Node} b - The second input.
  4083. * @param {...Node} params - Additional input parameters.
  4084. * @returns {OperatorNode}
  4085. */
  4086. const mul = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  4087. /**
  4088. * Returns the division of two or more value.
  4089. *
  4090. * @tsl
  4091. * @function
  4092. * @param {Node} a - The first input.
  4093. * @param {Node} b - The second input.
  4094. * @param {...Node} params - Additional input parameters.
  4095. * @returns {OperatorNode}
  4096. */
  4097. const div = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  4098. /**
  4099. * Computes the remainder of dividing the first node by the second one.
  4100. *
  4101. * @tsl
  4102. * @function
  4103. * @param {Node} a - The first input.
  4104. * @param {Node} b - The second input.
  4105. * @returns {OperatorNode}
  4106. */
  4107. const mod = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  4108. /**
  4109. * Checks if two nodes are equal.
  4110. *
  4111. * @tsl
  4112. * @function
  4113. * @param {Node} a - The first input.
  4114. * @param {Node} b - The second input.
  4115. * @returns {OperatorNode}
  4116. */
  4117. const equal = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  4118. /**
  4119. * Checks if two nodes are not equal.
  4120. *
  4121. * @tsl
  4122. * @function
  4123. * @param {Node} a - The first input.
  4124. * @param {Node} b - The second input.
  4125. * @returns {OperatorNode}
  4126. */
  4127. const notEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  4128. /**
  4129. * Checks if the first node is less than the second.
  4130. *
  4131. * @tsl
  4132. * @function
  4133. * @param {Node} a - The first input.
  4134. * @param {Node} b - The second input.
  4135. * @returns {OperatorNode}
  4136. */
  4137. const lessThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  4138. /**
  4139. * Checks if the first node is greater than the second.
  4140. *
  4141. * @tsl
  4142. * @function
  4143. * @param {Node} a - The first input.
  4144. * @param {Node} b - The second input.
  4145. * @returns {OperatorNode}
  4146. */
  4147. const greaterThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  4148. /**
  4149. * Checks if the first node is less than or equal to the second.
  4150. *
  4151. * @tsl
  4152. * @function
  4153. * @param {Node} a - The first input.
  4154. * @param {Node} b - The second input.
  4155. * @returns {OperatorNode}
  4156. */
  4157. const lessThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  4158. /**
  4159. * Checks if the first node is greater than or equal to the second.
  4160. *
  4161. * @tsl
  4162. * @function
  4163. * @param {Node} a - The first input.
  4164. * @param {Node} b - The second input.
  4165. * @returns {OperatorNode}
  4166. */
  4167. const greaterThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  4168. /**
  4169. * Performs a logical AND operation on multiple nodes.
  4170. *
  4171. * @tsl
  4172. * @function
  4173. * @param {...Node} nodes - The input nodes to be combined using AND.
  4174. * @returns {OperatorNode}
  4175. */
  4176. const and = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  4177. /**
  4178. * Performs a logical OR operation on multiple nodes.
  4179. *
  4180. * @tsl
  4181. * @function
  4182. * @param {...Node} nodes - The input nodes to be combined using OR.
  4183. * @returns {OperatorNode}
  4184. */
  4185. const or = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  4186. /**
  4187. * Performs logical NOT on a node.
  4188. *
  4189. * @tsl
  4190. * @function
  4191. * @param {Node} value - The value.
  4192. * @returns {OperatorNode}
  4193. */
  4194. const not = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  4195. /**
  4196. * Performs logical XOR on two nodes.
  4197. *
  4198. * @tsl
  4199. * @function
  4200. * @param {Node} a - The first input.
  4201. * @param {Node} b - The second input.
  4202. * @returns {OperatorNode}
  4203. */
  4204. const xor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  4205. /**
  4206. * Performs bitwise AND on two nodes.
  4207. *
  4208. * @tsl
  4209. * @function
  4210. * @param {Node} a - The first input.
  4211. * @param {Node} b - The second input.
  4212. * @returns {OperatorNode}
  4213. */
  4214. const bitAnd = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  4215. /**
  4216. * Performs bitwise NOT on a node.
  4217. *
  4218. * @tsl
  4219. * @function
  4220. * @param {Node} a - The first input.
  4221. * @param {Node} b - The second input.
  4222. * @returns {OperatorNode}
  4223. */
  4224. const bitNot = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '~' ).setParameterLength( 1 ).setName( 'bitNot' );
  4225. /**
  4226. * Performs bitwise OR on two nodes.
  4227. *
  4228. * @tsl
  4229. * @function
  4230. * @param {Node} a - The first input.
  4231. * @param {Node} b - The second input.
  4232. * @returns {OperatorNode}
  4233. */
  4234. const bitOr = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  4235. /**
  4236. * Performs bitwise XOR on two nodes.
  4237. *
  4238. * @tsl
  4239. * @function
  4240. * @param {Node} a - The first input.
  4241. * @param {Node} b - The second input.
  4242. * @returns {OperatorNode}
  4243. */
  4244. const bitXor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  4245. /**
  4246. * Shifts a node to the left.
  4247. *
  4248. * @tsl
  4249. * @function
  4250. * @param {Node} a - The node to shift.
  4251. * @param {Node} b - The value to shift.
  4252. * @returns {OperatorNode}
  4253. */
  4254. const shiftLeft = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  4255. /**
  4256. * Shifts a node to the right.
  4257. *
  4258. * @tsl
  4259. * @function
  4260. * @param {Node} a - The node to shift.
  4261. * @param {Node} b - The value to shift.
  4262. * @returns {OperatorNode}
  4263. */
  4264. const shiftRight = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  4265. /**
  4266. * Increments a node by 1.
  4267. *
  4268. * @tsl
  4269. * @function
  4270. * @param {Node} a - The node to increment.
  4271. * @returns {OperatorNode}
  4272. */
  4273. const incrementBefore = Fn( ( [ a ] ) => {
  4274. a.addAssign( 1 );
  4275. return a;
  4276. } );
  4277. /**
  4278. * Decrements a node by 1.
  4279. *
  4280. * @tsl
  4281. * @function
  4282. * @param {Node} a - The node to decrement.
  4283. * @returns {OperatorNode}
  4284. */
  4285. const decrementBefore = Fn( ( [ a ] ) => {
  4286. a.subAssign( 1 );
  4287. return a;
  4288. } );
  4289. /**
  4290. * Increments a node by 1 and returns the previous value.
  4291. *
  4292. * @tsl
  4293. * @function
  4294. * @param {Node} a - The node to increment.
  4295. * @returns {OperatorNode}
  4296. */
  4297. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4298. const temp = int( a ).toConst();
  4299. a.addAssign( 1 );
  4300. return temp;
  4301. } );
  4302. /**
  4303. * Decrements a node by 1 and returns the previous value.
  4304. *
  4305. * @tsl
  4306. * @function
  4307. * @param {Node} a - The node to decrement.
  4308. * @returns {OperatorNode}
  4309. */
  4310. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4311. const temp = int( a ).toConst();
  4312. a.subAssign( 1 );
  4313. return temp;
  4314. } );
  4315. addMethodChaining( 'add', add );
  4316. addMethodChaining( 'sub', sub );
  4317. addMethodChaining( 'mul', mul );
  4318. addMethodChaining( 'div', div );
  4319. addMethodChaining( 'mod', mod );
  4320. addMethodChaining( 'equal', equal );
  4321. addMethodChaining( 'notEqual', notEqual );
  4322. addMethodChaining( 'lessThan', lessThan );
  4323. addMethodChaining( 'greaterThan', greaterThan );
  4324. addMethodChaining( 'lessThanEqual', lessThanEqual );
  4325. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  4326. addMethodChaining( 'and', and );
  4327. addMethodChaining( 'or', or );
  4328. addMethodChaining( 'not', not );
  4329. addMethodChaining( 'xor', xor );
  4330. addMethodChaining( 'bitAnd', bitAnd );
  4331. addMethodChaining( 'bitNot', bitNot );
  4332. addMethodChaining( 'bitOr', bitOr );
  4333. addMethodChaining( 'bitXor', bitXor );
  4334. addMethodChaining( 'shiftLeft', shiftLeft );
  4335. addMethodChaining( 'shiftRight', shiftRight );
  4336. addMethodChaining( 'incrementBefore', incrementBefore );
  4337. addMethodChaining( 'decrementBefore', decrementBefore );
  4338. addMethodChaining( 'increment', increment );
  4339. addMethodChaining( 'decrement', decrement );
  4340. /**
  4341. * @tsl
  4342. * @function
  4343. * @deprecated since r175. Use {@link mod} instead.
  4344. *
  4345. * @param {Node} a - The first input.
  4346. * @param {Node} b - The second input.
  4347. * @returns {OperatorNode}
  4348. */
  4349. const modInt = ( a, b ) => { // @deprecated, r175
  4350. warn( 'TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.' );
  4351. return mod( int( a ), int( b ) );
  4352. };
  4353. addMethodChaining( 'modInt', modInt );
  4354. /**
  4355. * This node represents a variety of mathematical methods available in shaders.
  4356. * They are divided into three categories:
  4357. *
  4358. * - Methods with one input like `sin`, `cos` or `normalize`.
  4359. * - Methods with two inputs like `dot`, `cross` or `pow`.
  4360. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  4361. *
  4362. * @augments TempNode
  4363. */
  4364. class MathNode extends TempNode {
  4365. static get type() {
  4366. return 'MathNode';
  4367. }
  4368. /**
  4369. * Constructs a new math node.
  4370. *
  4371. * @param {string} method - The method name.
  4372. * @param {Node} aNode - The first input.
  4373. * @param {?Node} [bNode=null] - The second input.
  4374. * @param {?Node} [cNode=null] - The third input.
  4375. */
  4376. constructor( method, aNode, bNode = null, cNode = null ) {
  4377. super();
  4378. // Allow the max() and min() functions to take an arbitrary number of arguments.
  4379. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  4380. let finalOp = new MathNode( method, aNode, bNode );
  4381. for ( let i = 2; i < arguments.length - 1; i ++ ) {
  4382. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4383. }
  4384. aNode = finalOp;
  4385. bNode = arguments[ arguments.length - 1 ];
  4386. cNode = null;
  4387. }
  4388. /**
  4389. * The method name.
  4390. *
  4391. * @type {string}
  4392. */
  4393. this.method = method;
  4394. /**
  4395. * The first input.
  4396. *
  4397. * @type {Node}
  4398. */
  4399. this.aNode = aNode;
  4400. /**
  4401. * The second input.
  4402. *
  4403. * @type {?Node}
  4404. * @default null
  4405. */
  4406. this.bNode = bNode;
  4407. /**
  4408. * The third input.
  4409. *
  4410. * @type {?Node}
  4411. * @default null
  4412. */
  4413. this.cNode = cNode;
  4414. /**
  4415. * This flag can be used for type testing.
  4416. *
  4417. * @type {boolean}
  4418. * @readonly
  4419. * @default true
  4420. */
  4421. this.isMathNode = true;
  4422. }
  4423. /**
  4424. * The input type is inferred from the node types of the input nodes.
  4425. *
  4426. * @param {NodeBuilder} builder - The current node builder.
  4427. * @return {string} The input type.
  4428. */
  4429. getInputType( builder ) {
  4430. const aType = this.aNode.getNodeType( builder );
  4431. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4432. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4433. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4434. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4435. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4436. if ( aLen > bLen && aLen > cLen ) {
  4437. return aType;
  4438. } else if ( bLen > cLen ) {
  4439. return bType;
  4440. } else if ( cLen > aLen ) {
  4441. return cType;
  4442. }
  4443. return aType;
  4444. }
  4445. /**
  4446. * The selected method as well as the input type determine the node type of this node.
  4447. *
  4448. * @param {NodeBuilder} builder - The current node builder.
  4449. * @return {string} The node type.
  4450. */
  4451. getNodeType( builder ) {
  4452. const method = this.method;
  4453. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4454. return 'float';
  4455. } else if ( method === MathNode.CROSS ) {
  4456. return 'vec3';
  4457. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4458. return 'bool';
  4459. } else if ( method === MathNode.EQUALS ) {
  4460. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4461. } else {
  4462. return this.getInputType( builder );
  4463. }
  4464. }
  4465. setup( builder ) {
  4466. const { aNode, bNode, method } = this;
  4467. let outputNode = null;
  4468. if ( method === MathNode.ONE_MINUS ) {
  4469. outputNode = sub( 1.0, aNode );
  4470. } else if ( method === MathNode.RECIPROCAL ) {
  4471. outputNode = div( 1.0, aNode );
  4472. } else if ( method === MathNode.DIFFERENCE ) {
  4473. outputNode = abs( sub( aNode, bNode ) );
  4474. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4475. // dir can be either a direction vector or a normal vector
  4476. // upper-left 3x3 of matrix is assumed to be orthogonal
  4477. let tA = aNode;
  4478. let tB = bNode;
  4479. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4480. tB = vec4( vec3( tB ), 0.0 );
  4481. } else {
  4482. tA = vec4( vec3( tA ), 0.0 );
  4483. }
  4484. const mulNode = mul( tA, tB ).xyz;
  4485. outputNode = normalize( mulNode );
  4486. }
  4487. if ( outputNode !== null ) {
  4488. return outputNode;
  4489. } else {
  4490. return super.setup( builder );
  4491. }
  4492. }
  4493. generate( builder, output ) {
  4494. const properties = builder.getNodeProperties( this );
  4495. if ( properties.outputNode ) {
  4496. return super.generate( builder, output );
  4497. }
  4498. let method = this.method;
  4499. const type = this.getNodeType( builder );
  4500. const inputType = this.getInputType( builder );
  4501. const a = this.aNode;
  4502. const b = this.bNode;
  4503. const c = this.cNode;
  4504. const coordinateSystem = builder.renderer.coordinateSystem;
  4505. if ( method === MathNode.NEGATE ) {
  4506. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4507. } else {
  4508. const params = [];
  4509. if ( method === MathNode.CROSS ) {
  4510. params.push(
  4511. a.build( builder, type ),
  4512. b.build( builder, type )
  4513. );
  4514. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4515. params.push(
  4516. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4517. b.build( builder, inputType )
  4518. );
  4519. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4520. params.push(
  4521. a.build( builder, inputType ),
  4522. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4523. );
  4524. } else if ( method === MathNode.REFRACT ) {
  4525. params.push(
  4526. a.build( builder, inputType ),
  4527. b.build( builder, inputType ),
  4528. c.build( builder, 'float' )
  4529. );
  4530. } else if ( method === MathNode.MIX ) {
  4531. params.push(
  4532. a.build( builder, inputType ),
  4533. b.build( builder, inputType ),
  4534. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4535. );
  4536. } else {
  4537. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4538. method = 'atan2';
  4539. }
  4540. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4541. warn( `TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.` );
  4542. method = '/*' + method + '*/';
  4543. }
  4544. params.push( a.build( builder, inputType ) );
  4545. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4546. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4547. }
  4548. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4549. }
  4550. }
  4551. serialize( data ) {
  4552. super.serialize( data );
  4553. data.method = this.method;
  4554. }
  4555. deserialize( data ) {
  4556. super.deserialize( data );
  4557. this.method = data.method;
  4558. }
  4559. }
  4560. // 1 input
  4561. MathNode.ALL = 'all';
  4562. MathNode.ANY = 'any';
  4563. MathNode.RADIANS = 'radians';
  4564. MathNode.DEGREES = 'degrees';
  4565. MathNode.EXP = 'exp';
  4566. MathNode.EXP2 = 'exp2';
  4567. MathNode.LOG = 'log';
  4568. MathNode.LOG2 = 'log2';
  4569. MathNode.SQRT = 'sqrt';
  4570. MathNode.INVERSE_SQRT = 'inversesqrt';
  4571. MathNode.FLOOR = 'floor';
  4572. MathNode.CEIL = 'ceil';
  4573. MathNode.NORMALIZE = 'normalize';
  4574. MathNode.FRACT = 'fract';
  4575. MathNode.SIN = 'sin';
  4576. MathNode.COS = 'cos';
  4577. MathNode.TAN = 'tan';
  4578. MathNode.ASIN = 'asin';
  4579. MathNode.ACOS = 'acos';
  4580. MathNode.ATAN = 'atan';
  4581. MathNode.ABS = 'abs';
  4582. MathNode.SIGN = 'sign';
  4583. MathNode.LENGTH = 'length';
  4584. MathNode.NEGATE = 'negate';
  4585. MathNode.ONE_MINUS = 'oneMinus';
  4586. MathNode.DFDX = 'dFdx';
  4587. MathNode.DFDY = 'dFdy';
  4588. MathNode.ROUND = 'round';
  4589. MathNode.RECIPROCAL = 'reciprocal';
  4590. MathNode.TRUNC = 'trunc';
  4591. MathNode.FWIDTH = 'fwidth';
  4592. MathNode.TRANSPOSE = 'transpose';
  4593. MathNode.DETERMINANT = 'determinant';
  4594. MathNode.INVERSE = 'inverse';
  4595. // 2 inputs
  4596. MathNode.EQUALS = 'equals';
  4597. MathNode.MIN = 'min';
  4598. MathNode.MAX = 'max';
  4599. MathNode.STEP = 'step';
  4600. MathNode.REFLECT = 'reflect';
  4601. MathNode.DISTANCE = 'distance';
  4602. MathNode.DIFFERENCE = 'difference';
  4603. MathNode.DOT = 'dot';
  4604. MathNode.CROSS = 'cross';
  4605. MathNode.POW = 'pow';
  4606. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4607. // 3 inputs
  4608. MathNode.MIX = 'mix';
  4609. MathNode.CLAMP = 'clamp';
  4610. MathNode.REFRACT = 'refract';
  4611. MathNode.SMOOTHSTEP = 'smoothstep';
  4612. MathNode.FACEFORWARD = 'faceforward';
  4613. // 1 inputs
  4614. /**
  4615. * A small value used to handle floating-point precision errors.
  4616. *
  4617. * @tsl
  4618. * @type {Node<float>}
  4619. */
  4620. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4621. /**
  4622. * Represents infinity.
  4623. *
  4624. * @tsl
  4625. * @type {Node<float>}
  4626. */
  4627. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4628. /**
  4629. * Represents PI.
  4630. *
  4631. * @tsl
  4632. * @type {Node<float>}
  4633. */
  4634. const PI = /*@__PURE__*/ float( Math.PI );
  4635. /**
  4636. * Represents PI * 2. Please use the non-deprecated version `TWO_PI`.
  4637. *
  4638. * @tsl
  4639. * @deprecated
  4640. * @type {Node<float>}
  4641. */
  4642. const PI2 = /*@__PURE__*/ float( Math.PI * 2 ); // @deprecated r181
  4643. /**
  4644. * Represents PI * 2.
  4645. *
  4646. * @tsl
  4647. * @type {Node<float>}
  4648. */
  4649. const TWO_PI = /*@__PURE__*/ float( Math.PI * 2 );
  4650. /**
  4651. * Represents PI / 2.
  4652. *
  4653. * @tsl
  4654. * @type {Node<float>}
  4655. */
  4656. const HALF_PI = /*@__PURE__*/ float( Math.PI * 0.5 );
  4657. /**
  4658. * Returns `true` if all components of `x` are `true`.
  4659. *
  4660. * @tsl
  4661. * @function
  4662. * @param {Node | number} x - The parameter.
  4663. * @returns {Node<bool>}
  4664. */
  4665. const all = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4666. /**
  4667. * Returns `true` if any components of `x` are `true`.
  4668. *
  4669. * @tsl
  4670. * @function
  4671. * @param {Node | number} x - The parameter.
  4672. * @returns {Node<bool>}
  4673. */
  4674. const any = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4675. /**
  4676. * Converts a quantity in degrees to radians.
  4677. *
  4678. * @tsl
  4679. * @function
  4680. * @param {Node | number} x - The input in degrees.
  4681. * @returns {Node}
  4682. */
  4683. const radians = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4684. /**
  4685. * Convert a quantity in radians to degrees.
  4686. *
  4687. * @tsl
  4688. * @function
  4689. * @param {Node | number} x - The input in radians.
  4690. * @returns {Node}
  4691. */
  4692. const degrees = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4693. /**
  4694. * Returns the natural exponentiation of the parameter.
  4695. *
  4696. * @tsl
  4697. * @function
  4698. * @param {Node | number} x - The parameter.
  4699. * @returns {Node}
  4700. */
  4701. const exp = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP ).setParameterLength( 1 );
  4702. /**
  4703. * Returns 2 raised to the power of the parameter.
  4704. *
  4705. * @tsl
  4706. * @function
  4707. * @param {Node | number} x - The parameter.
  4708. * @returns {Node}
  4709. */
  4710. const exp2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  4711. /**
  4712. * Returns the natural logarithm of the parameter.
  4713. *
  4714. * @tsl
  4715. * @function
  4716. * @param {Node | number} x - The parameter.
  4717. * @returns {Node}
  4718. */
  4719. const log = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG ).setParameterLength( 1 );
  4720. /**
  4721. * Returns the base 2 logarithm of the parameter.
  4722. *
  4723. * @tsl
  4724. * @function
  4725. * @param {Node | number} x - The parameter.
  4726. * @returns {Node}
  4727. */
  4728. const log2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  4729. /**
  4730. * Returns the square root of the parameter.
  4731. *
  4732. * @tsl
  4733. * @function
  4734. * @param {Node | number} x - The parameter.
  4735. * @returns {Node}
  4736. */
  4737. const sqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  4738. /**
  4739. * Returns the inverse of the square root of the parameter.
  4740. *
  4741. * @tsl
  4742. * @function
  4743. * @param {Node | number} x - The parameter.
  4744. * @returns {Node}
  4745. */
  4746. const inverseSqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  4747. /**
  4748. * Finds the nearest integer less than or equal to the parameter.
  4749. *
  4750. * @tsl
  4751. * @function
  4752. * @param {Node | number} x - The parameter.
  4753. * @returns {Node}
  4754. */
  4755. const floor = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  4756. /**
  4757. * Finds the nearest integer that is greater than or equal to the parameter.
  4758. *
  4759. * @tsl
  4760. * @function
  4761. * @param {Node | number} x - The parameter.
  4762. * @returns {Node}
  4763. */
  4764. const ceil = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  4765. /**
  4766. * Calculates the unit vector in the same direction as the original vector.
  4767. *
  4768. * @tsl
  4769. * @function
  4770. * @param {Node} x - The input vector.
  4771. * @returns {Node}
  4772. */
  4773. const normalize = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  4774. /**
  4775. * Computes the fractional part of the parameter.
  4776. *
  4777. * @tsl
  4778. * @function
  4779. * @param {Node | number} x - The parameter.
  4780. * @returns {Node}
  4781. */
  4782. const fract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  4783. /**
  4784. * Returns the sine of the parameter.
  4785. *
  4786. * @tsl
  4787. * @function
  4788. * @param {Node | number} x - The parameter.
  4789. * @returns {Node}
  4790. */
  4791. const sin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIN ).setParameterLength( 1 );
  4792. /**
  4793. * Returns the cosine of the parameter.
  4794. *
  4795. * @tsl
  4796. * @function
  4797. * @param {Node | number} x - The parameter.
  4798. * @returns {Node}
  4799. */
  4800. const cos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COS ).setParameterLength( 1 );
  4801. /**
  4802. * Returns the tangent of the parameter.
  4803. *
  4804. * @tsl
  4805. * @function
  4806. * @param {Node | number} x - The parameter.
  4807. * @returns {Node}
  4808. */
  4809. const tan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TAN ).setParameterLength( 1 );
  4810. /**
  4811. * Returns the arcsine of the parameter.
  4812. *
  4813. * @tsl
  4814. * @function
  4815. * @param {Node | number} x - The parameter.
  4816. * @returns {Node}
  4817. */
  4818. const asin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  4819. /**
  4820. * Returns the arccosine of the parameter.
  4821. *
  4822. * @tsl
  4823. * @function
  4824. * @param {Node | number} x - The parameter.
  4825. * @returns {Node}
  4826. */
  4827. const acos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  4828. /**
  4829. * Returns the arc-tangent of the parameter.
  4830. * If two parameters are provided, the result is `atan2(y/x)`.
  4831. *
  4832. * @tsl
  4833. * @function
  4834. * @param {Node | number} y - The y parameter.
  4835. * @param {?(Node | number)} x - The x parameter.
  4836. * @returns {Node}
  4837. */
  4838. const atan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  4839. /**
  4840. * Returns the absolute value of the parameter.
  4841. *
  4842. * @tsl
  4843. * @function
  4844. * @param {Node | number} x - The parameter.
  4845. * @returns {Node}
  4846. */
  4847. const abs = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ABS ).setParameterLength( 1 );
  4848. /**
  4849. * Extracts the sign of the parameter.
  4850. *
  4851. * @tsl
  4852. * @function
  4853. * @param {Node | number} x - The parameter.
  4854. * @returns {Node}
  4855. */
  4856. const sign = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  4857. /**
  4858. * Calculates the length of a vector.
  4859. *
  4860. * @tsl
  4861. * @function
  4862. * @param {Node} x - The parameter.
  4863. * @returns {Node<float>}
  4864. */
  4865. const length = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  4866. /**
  4867. * Negates the value of the parameter (-x).
  4868. *
  4869. * @tsl
  4870. * @function
  4871. * @param {Node | number} x - The parameter.
  4872. * @returns {Node}
  4873. */
  4874. const negate = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  4875. /**
  4876. * Return `1` minus the parameter.
  4877. *
  4878. * @tsl
  4879. * @function
  4880. * @param {Node | number} x - The parameter.
  4881. * @returns {Node}
  4882. */
  4883. const oneMinus = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  4884. /**
  4885. * Returns the partial derivative of the parameter with respect to x.
  4886. *
  4887. * @tsl
  4888. * @function
  4889. * @param {Node | number} x - The parameter.
  4890. * @returns {Node}
  4891. */
  4892. const dFdx = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  4893. /**
  4894. * Returns the partial derivative of the parameter with respect to y.
  4895. *
  4896. * @tsl
  4897. * @function
  4898. * @param {Node | number} x - The parameter.
  4899. * @returns {Node}
  4900. */
  4901. const dFdy = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  4902. /**
  4903. * Rounds the parameter to the nearest integer.
  4904. *
  4905. * @tsl
  4906. * @function
  4907. * @param {Node | number} x - The parameter.
  4908. * @returns {Node}
  4909. */
  4910. const round = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  4911. /**
  4912. * Returns the reciprocal of the parameter `(1/x)`.
  4913. *
  4914. * @tsl
  4915. * @function
  4916. * @param {Node | number} x - The parameter.
  4917. * @returns {Node}
  4918. */
  4919. const reciprocal = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  4920. /**
  4921. * Truncates the parameter, removing the fractional part.
  4922. *
  4923. * @tsl
  4924. * @function
  4925. * @param {Node | number} x - The parameter.
  4926. * @returns {Node}
  4927. */
  4928. const trunc = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  4929. /**
  4930. * Returns the sum of the absolute derivatives in x and y.
  4931. *
  4932. * @tsl
  4933. * @function
  4934. * @param {Node | number} x - The parameter.
  4935. * @returns {Node}
  4936. */
  4937. const fwidth = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  4938. /**
  4939. * Returns the transpose of a matrix.
  4940. *
  4941. * @tsl
  4942. * @function
  4943. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4944. * @returns {Node}
  4945. */
  4946. const transpose = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  4947. /**
  4948. * Returns the determinant of a matrix.
  4949. *
  4950. * @tsl
  4951. * @function
  4952. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4953. * @returns {Node<float>}
  4954. */
  4955. const determinant = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DETERMINANT ).setParameterLength( 1 );
  4956. /**
  4957. * Returns the inverse of a matrix.
  4958. *
  4959. * @tsl
  4960. * @function
  4961. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4962. * @returns {Node<mat2|mat3|mat4>}
  4963. */
  4964. const inverse = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE ).setParameterLength( 1 );
  4965. // 2 inputs
  4966. /**
  4967. * Returns `true` if `x` equals `y`.
  4968. *
  4969. * @tsl
  4970. * @function
  4971. * @param {Node | number} x - The first parameter.
  4972. * @param {Node | number} y - The second parameter.
  4973. * @deprecated since r175. Use {@link equal} instead.
  4974. * @returns {Node<bool>}
  4975. */
  4976. const equals = ( x, y ) => { // @deprecated, r172
  4977. warn( 'TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"' );
  4978. return equal( x, y );
  4979. };
  4980. /**
  4981. * Returns the least of the given values.
  4982. *
  4983. * @tsl
  4984. * @function
  4985. * @param {...(Node | number)} values - The values to compare.
  4986. * @returns {Node}
  4987. */
  4988. const min$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  4989. /**
  4990. * Returns the greatest of the given values.
  4991. *
  4992. * @tsl
  4993. * @function
  4994. * @param {...(Node | number)} values - The values to compare.
  4995. * @returns {Node}
  4996. */
  4997. const max$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  4998. /**
  4999. * Generate a step function by comparing two values.
  5000. *
  5001. * @tsl
  5002. * @function
  5003. * @param {Node | number} x - The y parameter.
  5004. * @param {Node | number} y - The x parameter.
  5005. * @returns {Node}
  5006. */
  5007. const step = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.STEP ).setParameterLength( 2 );
  5008. /**
  5009. * Calculates the reflection direction for an incident vector.
  5010. *
  5011. * @tsl
  5012. * @function
  5013. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5014. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5015. * @returns {Node<vec2|vec3|vec4>}
  5016. */
  5017. const reflect = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  5018. /**
  5019. * Calculates the distance between two points.
  5020. *
  5021. * @tsl
  5022. * @function
  5023. * @param {Node<vec2|vec3|vec4>} x - The first point.
  5024. * @param {Node<vec2|vec3|vec4>} y - The second point.
  5025. * @returns {Node<float>}
  5026. */
  5027. const distance = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  5028. /**
  5029. * Calculates the absolute difference between two values.
  5030. *
  5031. * @tsl
  5032. * @function
  5033. * @param {Node | number} x - The first parameter.
  5034. * @param {Node | number} y - The second parameter.
  5035. * @returns {Node}
  5036. */
  5037. const difference = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  5038. /**
  5039. * Calculates the dot product of two vectors.
  5040. *
  5041. * @tsl
  5042. * @function
  5043. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  5044. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  5045. * @returns {Node<float>}
  5046. */
  5047. const dot = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DOT ).setParameterLength( 2 );
  5048. /**
  5049. * Calculates the cross product of two vectors.
  5050. *
  5051. * @tsl
  5052. * @function
  5053. * @param {Node<vec2|vec3>} x - The first vector.
  5054. * @param {Node<vec2|vec3>} y - The second vector.
  5055. * @returns {Node<float|vec3>}
  5056. */
  5057. const cross = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  5058. /**
  5059. * Return the value of the first parameter raised to the power of the second one.
  5060. *
  5061. * @tsl
  5062. * @function
  5063. * @param {Node | number} x - The first parameter.
  5064. * @param {Node | number} y - The second parameter.
  5065. * @returns {Node}
  5066. */
  5067. const pow = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW ).setParameterLength( 2 );
  5068. /**
  5069. * Returns the square of the parameter.
  5070. *
  5071. * @tsl
  5072. * @function
  5073. * @param {Node | number} x - The first parameter.
  5074. * @returns {Node}
  5075. */
  5076. const pow2 = ( x ) => mul( x, x );
  5077. /**
  5078. * Returns the cube of the parameter.
  5079. *
  5080. * @tsl
  5081. * @function
  5082. * @param {Node | number} x - The first parameter.
  5083. * @returns {Node}
  5084. */
  5085. const pow3 = ( x ) => mul( x, x, x );
  5086. /**
  5087. * Returns the fourth power of the parameter.
  5088. *
  5089. * @tsl
  5090. * @function
  5091. * @param {Node | number} x - The first parameter.
  5092. * @returns {Node}
  5093. */
  5094. const pow4 = ( x ) => mul( x, x, x, x );
  5095. /**
  5096. * Transforms the direction of a vector by a matrix and then normalizes the result.
  5097. *
  5098. * @tsl
  5099. * @function
  5100. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  5101. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  5102. * @returns {Node}
  5103. */
  5104. const transformDirection = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  5105. /**
  5106. * Returns the cube root of a number.
  5107. *
  5108. * @tsl
  5109. * @function
  5110. * @param {Node | number} a - The first parameter.
  5111. * @returns {Node}
  5112. */
  5113. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  5114. /**
  5115. * Calculate the squared length of a vector.
  5116. *
  5117. * @tsl
  5118. * @function
  5119. * @param {Node<vec2|vec3|vec4>} a - The vector.
  5120. * @returns {Node<float>}
  5121. */
  5122. const lengthSq = ( a ) => dot( a, a );
  5123. /**
  5124. * Linearly interpolates between two values.
  5125. *
  5126. * @tsl
  5127. * @function
  5128. * @param {Node | number} a - The first parameter.
  5129. * @param {Node | number} b - The second parameter.
  5130. * @param {Node | number} t - The interpolation value.
  5131. * @returns {Node}
  5132. */
  5133. const mix = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIX ).setParameterLength( 3 );
  5134. /**
  5135. * Constrains a value to lie between two further values.
  5136. *
  5137. * @tsl
  5138. * @function
  5139. * @param {Node | number} value - The value to constrain.
  5140. * @param {Node | number} [low=0] - The lower bound.
  5141. * @param {Node | number} [high=1] - The upper bound.
  5142. * @returns {Node}
  5143. */
  5144. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  5145. /**
  5146. * Constrains a value between `0` and `1`.
  5147. *
  5148. * @tsl
  5149. * @function
  5150. * @param {Node | number} value - The value to constrain.
  5151. * @returns {Node}
  5152. */
  5153. const saturate = ( value ) => clamp( value );
  5154. /**
  5155. * Calculates the refraction direction for an incident vector.
  5156. *
  5157. * @tsl
  5158. * @function
  5159. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5160. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5161. * @param {Node<float>} eta - The ratio of indices of refraction.
  5162. * @returns {Node<vec2|vec3|vec4>}
  5163. */
  5164. const refract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  5165. /**
  5166. * Performs a Hermite interpolation between two values.
  5167. *
  5168. * @tsl
  5169. * @function
  5170. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5171. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5172. * @param {Node | number} x - The source value for interpolation.
  5173. * @returns {Node}
  5174. */
  5175. const smoothstep = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  5176. /**
  5177. * Returns a vector pointing in the same direction as another.
  5178. *
  5179. * @tsl
  5180. * @function
  5181. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  5182. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5183. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  5184. * @returns {Node<vec2|vec3|vec4>}
  5185. */
  5186. const faceForward = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  5187. /**
  5188. * Returns a random value for the given uv.
  5189. *
  5190. * @tsl
  5191. * @function
  5192. * @param {Node<vec2>} uv - The uv node.
  5193. * @returns {Node<float>}
  5194. */
  5195. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  5196. const a = 12.9898, b = 78.233, c = 43758.5453;
  5197. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  5198. return fract( sin( sn ).mul( c ) );
  5199. } );
  5200. /**
  5201. * Alias for `mix()` with a different parameter order.
  5202. *
  5203. * @tsl
  5204. * @function
  5205. * @param {Node | number} t - The interpolation value.
  5206. * @param {Node | number} e1 - The first parameter.
  5207. * @param {Node | number} e2 - The second parameter.
  5208. * @returns {Node}
  5209. */
  5210. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  5211. /**
  5212. * Alias for `smoothstep()` with a different parameter order.
  5213. *
  5214. * @tsl
  5215. * @function
  5216. * @param {Node | number} x - The source value for interpolation.
  5217. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5218. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5219. * @returns {Node}
  5220. */
  5221. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  5222. /**
  5223. * Alias for `step()` with a different parameter order.
  5224. *
  5225. * @tsl
  5226. * @function
  5227. * @param {Node | number} x - The source value for interpolation.
  5228. * @param {Node | number} edge - The edge value.
  5229. * @returns {Node}
  5230. */
  5231. const stepElement = ( x, edge ) => step( edge, x );
  5232. /**
  5233. * Returns the arc-tangent of the quotient of its parameters.
  5234. *
  5235. * @tsl
  5236. * @function
  5237. * @deprecated since r172. Use {@link atan} instead.
  5238. *
  5239. * @param {Node | number} y - The y parameter.
  5240. * @param {Node | number} x - The x parameter.
  5241. * @returns {Node}
  5242. */
  5243. const atan2 = ( y, x ) => { // @deprecated, r172
  5244. warn( 'TSL: "atan2" is overloaded. Use "atan" instead.' );
  5245. return atan( y, x );
  5246. };
  5247. // GLSL alias function
  5248. const faceforward = faceForward;
  5249. const inversesqrt = inverseSqrt;
  5250. // Method chaining
  5251. addMethodChaining( 'all', all );
  5252. addMethodChaining( 'any', any );
  5253. addMethodChaining( 'equals', equals );
  5254. addMethodChaining( 'radians', radians );
  5255. addMethodChaining( 'degrees', degrees );
  5256. addMethodChaining( 'exp', exp );
  5257. addMethodChaining( 'exp2', exp2 );
  5258. addMethodChaining( 'log', log );
  5259. addMethodChaining( 'log2', log2 );
  5260. addMethodChaining( 'sqrt', sqrt );
  5261. addMethodChaining( 'inverseSqrt', inverseSqrt );
  5262. addMethodChaining( 'floor', floor );
  5263. addMethodChaining( 'ceil', ceil );
  5264. addMethodChaining( 'normalize', normalize );
  5265. addMethodChaining( 'fract', fract );
  5266. addMethodChaining( 'sin', sin );
  5267. addMethodChaining( 'cos', cos );
  5268. addMethodChaining( 'tan', tan );
  5269. addMethodChaining( 'asin', asin );
  5270. addMethodChaining( 'acos', acos );
  5271. addMethodChaining( 'atan', atan );
  5272. addMethodChaining( 'abs', abs );
  5273. addMethodChaining( 'sign', sign );
  5274. addMethodChaining( 'length', length );
  5275. addMethodChaining( 'lengthSq', lengthSq );
  5276. addMethodChaining( 'negate', negate );
  5277. addMethodChaining( 'oneMinus', oneMinus );
  5278. addMethodChaining( 'dFdx', dFdx );
  5279. addMethodChaining( 'dFdy', dFdy );
  5280. addMethodChaining( 'round', round );
  5281. addMethodChaining( 'reciprocal', reciprocal );
  5282. addMethodChaining( 'trunc', trunc );
  5283. addMethodChaining( 'fwidth', fwidth );
  5284. addMethodChaining( 'atan2', atan2 );
  5285. addMethodChaining( 'min', min$1 );
  5286. addMethodChaining( 'max', max$1 );
  5287. addMethodChaining( 'step', stepElement );
  5288. addMethodChaining( 'reflect', reflect );
  5289. addMethodChaining( 'distance', distance );
  5290. addMethodChaining( 'dot', dot );
  5291. addMethodChaining( 'cross', cross );
  5292. addMethodChaining( 'pow', pow );
  5293. addMethodChaining( 'pow2', pow2 );
  5294. addMethodChaining( 'pow3', pow3 );
  5295. addMethodChaining( 'pow4', pow4 );
  5296. addMethodChaining( 'transformDirection', transformDirection );
  5297. addMethodChaining( 'mix', mixElement );
  5298. addMethodChaining( 'clamp', clamp );
  5299. addMethodChaining( 'refract', refract );
  5300. addMethodChaining( 'smoothstep', smoothstepElement );
  5301. addMethodChaining( 'faceForward', faceForward );
  5302. addMethodChaining( 'difference', difference );
  5303. addMethodChaining( 'saturate', saturate );
  5304. addMethodChaining( 'cbrt', cbrt );
  5305. addMethodChaining( 'transpose', transpose );
  5306. addMethodChaining( 'determinant', determinant );
  5307. addMethodChaining( 'inverse', inverse );
  5308. addMethodChaining( 'rand', rand );
  5309. /**
  5310. * Represents a logical `if/else` statement. Can be used as an alternative
  5311. * to the `If()`/`Else()` syntax.
  5312. *
  5313. * The corresponding TSL `select()` looks like so:
  5314. * ```js
  5315. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  5316. * ```
  5317. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  5318. * determine the outcome of the entire statement.
  5319. *
  5320. * @augments Node
  5321. */
  5322. class ConditionalNode extends Node {
  5323. static get type() {
  5324. return 'ConditionalNode';
  5325. }
  5326. /**
  5327. * Constructs a new conditional node.
  5328. *
  5329. * @param {Node} condNode - The node that defines the condition.
  5330. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5331. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5332. */
  5333. constructor( condNode, ifNode, elseNode = null ) {
  5334. super();
  5335. /**
  5336. * The node that defines the condition.
  5337. *
  5338. * @type {Node}
  5339. */
  5340. this.condNode = condNode;
  5341. /**
  5342. * The node that is evaluate when the condition ends up `true`.
  5343. *
  5344. * @type {Node}
  5345. */
  5346. this.ifNode = ifNode;
  5347. /**
  5348. * The node that is evaluate when the condition ends up `false`.
  5349. *
  5350. * @type {?Node}
  5351. * @default null
  5352. */
  5353. this.elseNode = elseNode;
  5354. }
  5355. /**
  5356. * This method is overwritten since the node type is inferred from the if/else
  5357. * nodes.
  5358. *
  5359. * @param {NodeBuilder} builder - The current node builder.
  5360. * @return {string} The node type.
  5361. */
  5362. getNodeType( builder ) {
  5363. const { ifNode, elseNode } = builder.getNodeProperties( this );
  5364. if ( ifNode === undefined ) {
  5365. // fallback setup
  5366. builder.flowBuildStage( this, 'setup' );
  5367. return this.getNodeType( builder );
  5368. }
  5369. const ifType = ifNode.getNodeType( builder );
  5370. if ( elseNode !== null ) {
  5371. const elseType = elseNode.getNodeType( builder );
  5372. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  5373. return elseType;
  5374. }
  5375. }
  5376. return ifType;
  5377. }
  5378. setup( builder ) {
  5379. const condNode = this.condNode;
  5380. const ifNode = this.ifNode.isolate();
  5381. const elseNode = this.elseNode ? this.elseNode.isolate() : null;
  5382. //
  5383. const currentNodeBlock = builder.context.nodeBlock;
  5384. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  5385. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  5386. //
  5387. const isUniformFlow = builder.context.uniformFlow;
  5388. const properties = builder.getNodeProperties( this );
  5389. properties.condNode = condNode;
  5390. properties.ifNode = isUniformFlow ? ifNode : ifNode.context( { nodeBlock: ifNode } );
  5391. properties.elseNode = elseNode ? ( isUniformFlow ? elseNode : elseNode.context( { nodeBlock: elseNode } ) ) : null;
  5392. }
  5393. generate( builder, output ) {
  5394. const type = this.getNodeType( builder );
  5395. const nodeData = builder.getDataFromNode( this );
  5396. if ( nodeData.nodeProperty !== undefined ) {
  5397. return nodeData.nodeProperty;
  5398. }
  5399. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  5400. const functionNode = builder.currentFunctionNode;
  5401. const needsOutput = output !== 'void';
  5402. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  5403. nodeData.nodeProperty = nodeProperty;
  5404. const nodeSnippet = condNode.build( builder, 'bool' );
  5405. const isUniformFlow = builder.context.uniformFlow;
  5406. if ( isUniformFlow && elseNode !== null ) {
  5407. const ifSnippet = ifNode.build( builder, type );
  5408. const elseSnippet = elseNode.build( builder, type );
  5409. const mathSnippet = builder.getTernary( nodeSnippet, ifSnippet, elseSnippet );
  5410. // TODO: If node property already exists return something else
  5411. return builder.format( mathSnippet, type, output );
  5412. }
  5413. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  5414. let ifSnippet = ifNode.build( builder, type );
  5415. if ( ifSnippet ) {
  5416. if ( needsOutput ) {
  5417. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  5418. } else {
  5419. ifSnippet = 'return ' + ifSnippet + ';';
  5420. if ( functionNode === null ) {
  5421. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5422. ifSnippet = '// ' + ifSnippet;
  5423. }
  5424. }
  5425. }
  5426. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  5427. if ( elseNode !== null ) {
  5428. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5429. let elseSnippet = elseNode.build( builder, type );
  5430. if ( elseSnippet ) {
  5431. if ( needsOutput ) {
  5432. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5433. } else {
  5434. elseSnippet = 'return ' + elseSnippet + ';';
  5435. if ( functionNode === null ) {
  5436. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5437. elseSnippet = '// ' + elseSnippet;
  5438. }
  5439. }
  5440. }
  5441. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5442. } else {
  5443. builder.addFlowCode( '\n\n' );
  5444. }
  5445. return builder.format( nodeProperty, type, output );
  5446. }
  5447. }
  5448. /**
  5449. * TSL function for creating a conditional node.
  5450. *
  5451. * @tsl
  5452. * @function
  5453. * @param {Node} condNode - The node that defines the condition.
  5454. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5455. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5456. * @returns {ConditionalNode}
  5457. */
  5458. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5459. addMethodChaining( 'select', select );
  5460. /**
  5461. * This node can be used as a context management component for another node.
  5462. * {@link NodeBuilder} performs its node building process in a specific context and
  5463. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5464. *
  5465. * ```js
  5466. *node.context( { getUV: () => customCoord } );
  5467. *\// or
  5468. *material.contextNode = context( { getUV: () => customCoord } );
  5469. *\// or
  5470. *renderer.contextNode = context( { getUV: () => customCoord } );
  5471. *\// or
  5472. *scenePass.contextNode = context( { getUV: () => customCoord } );
  5473. *```
  5474. * @augments Node
  5475. */
  5476. class ContextNode extends Node {
  5477. static get type() {
  5478. return 'ContextNode';
  5479. }
  5480. /**
  5481. * Constructs a new context node.
  5482. *
  5483. * @param {Node} node - The node whose context should be modified.
  5484. * @param {Object} [value={}] - The modified context data.
  5485. */
  5486. constructor( node = null, value = {} ) {
  5487. super();
  5488. /**
  5489. * This flag can be used for type testing.
  5490. *
  5491. * @type {boolean}
  5492. * @readonly
  5493. * @default true
  5494. */
  5495. this.isContextNode = true;
  5496. /**
  5497. * The node whose context should be modified.
  5498. *
  5499. * @type {Node}
  5500. */
  5501. this.node = node;
  5502. /**
  5503. * The modified context data.
  5504. *
  5505. * @type {Object}
  5506. * @default {}
  5507. */
  5508. this.value = value;
  5509. }
  5510. /**
  5511. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5512. *
  5513. * @return {Node} A reference to {@link ContextNode#node}.
  5514. */
  5515. getScope() {
  5516. return this.node.getScope();
  5517. }
  5518. /**
  5519. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5520. *
  5521. * @param {NodeBuilder} builder - The current node builder.
  5522. * @return {string} The node type.
  5523. */
  5524. getNodeType( builder ) {
  5525. return this.node.getNodeType( builder );
  5526. }
  5527. /**
  5528. * Gathers the context data from all parent context nodes.
  5529. *
  5530. * @return {Object} The gathered context data.
  5531. */
  5532. getFlowContextData() {
  5533. const children = [];
  5534. this.traverse( ( node ) => {
  5535. if ( node.isContextNode === true ) {
  5536. children.push( node.value );
  5537. }
  5538. } );
  5539. return Object.assign( {}, ...children );
  5540. }
  5541. /**
  5542. * This method is overwritten to ensure it returns the member type of {@link ContextNode#node}.
  5543. *
  5544. * @param {NodeBuilder} builder - The current node builder.
  5545. * @param {string} name - The member name.
  5546. * @returns {string} The member type.
  5547. */
  5548. getMemberType( builder, name ) {
  5549. return this.node.getMemberType( builder, name );
  5550. }
  5551. analyze( builder ) {
  5552. const previousContext = builder.addContext( this.value );
  5553. this.node.build( builder );
  5554. builder.setContext( previousContext );
  5555. }
  5556. setup( builder ) {
  5557. const previousContext = builder.addContext( this.value );
  5558. this.node.build( builder );
  5559. builder.setContext( previousContext );
  5560. }
  5561. generate( builder, output ) {
  5562. const previousContext = builder.addContext( this.value );
  5563. const snippet = this.node.build( builder, output );
  5564. builder.setContext( previousContext );
  5565. return snippet;
  5566. }
  5567. }
  5568. /**
  5569. * TSL function for creating a context node.
  5570. *
  5571. * @tsl
  5572. * @function
  5573. * @param {Node|Object} [nodeOrValue={}] - The node whose context should be modified or the modified context data.
  5574. * @param {Object} [value={}] - The modified context data.
  5575. * @returns {ContextNode}
  5576. */
  5577. const context = ( nodeOrValue = null, value = {} ) => {
  5578. let node = nodeOrValue;
  5579. if ( node === null || node.isNode !== true ) {
  5580. value = node || value;
  5581. node = null;
  5582. }
  5583. return new ContextNode( node, value );
  5584. };
  5585. /**
  5586. * TSL function for defining a uniformFlow context value for a given node.
  5587. *
  5588. * @tsl
  5589. * @function
  5590. * @param {Node} node - The node whose dependencies should all execute within a uniform control-flow path.
  5591. * @returns {ContextNode}
  5592. */
  5593. const uniformFlow = ( node ) => context( node, { uniformFlow: true } );
  5594. /**
  5595. * TSL function for defining a name for the context value for a given node.
  5596. *
  5597. * @tsl
  5598. * @function
  5599. * @param {Node} node - The node whose context should be modified.
  5600. * @param {string} name - The name to set.
  5601. * @returns {ContextNode}
  5602. */
  5603. const setName = ( node, name ) => context( node, { nodeName: name } );
  5604. /**
  5605. * TSL function for defining a built-in shadow context for a given node.
  5606. *
  5607. * @tsl
  5608. * @function
  5609. * @param {ShadowNode} shadowNode - The shadow node representing the light's shadow.
  5610. * @param {Light} light - The light associated with the shadow.
  5611. * @param {Node} [node=null] - The node whose context should be modified.
  5612. * @returns {ContextNode}
  5613. */
  5614. function builtinShadowContext( shadowNode, light, node = null ) {
  5615. return context( node, {
  5616. getShadow: ( { light: shadowLight, shadowColorNode } ) => {
  5617. if ( light === shadowLight ) {
  5618. return shadowColorNode.mul( shadowNode );
  5619. }
  5620. return shadowColorNode;
  5621. }
  5622. } );
  5623. }
  5624. /**
  5625. * TSL function for defining a built-in ambient occlusion context for a given node.
  5626. *
  5627. * @tsl
  5628. * @function
  5629. * @param {Node} aoNode - The ambient occlusion value node to apply.
  5630. * @param {Node} [node=null] - The node whose context should be modified.
  5631. * @returns {ContextNode}
  5632. */
  5633. function builtinAOContext( aoNode, node = null ) {
  5634. return context( node, {
  5635. getAO: ( inputNode, { material } ) => {
  5636. if ( material.transparent === true ) return inputNode;
  5637. return inputNode !== null ? inputNode.mul( aoNode ) : aoNode;
  5638. }
  5639. } );
  5640. }
  5641. /**
  5642. * TSL function for defining a label context value for a given node.
  5643. *
  5644. * @tsl
  5645. * @function
  5646. * @deprecated
  5647. * @param {Node} node - The node whose context should be modified.
  5648. * @param {string} name - The name/label to set.
  5649. * @returns {ContextNode}
  5650. */
  5651. function label( node, name ) {
  5652. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  5653. return setName( node, name );
  5654. }
  5655. addMethodChaining( 'context', context );
  5656. addMethodChaining( 'label', label );
  5657. addMethodChaining( 'uniformFlow', uniformFlow );
  5658. addMethodChaining( 'setName', setName );
  5659. addMethodChaining( 'builtinShadowContext', ( node, shadowNode, light ) => builtinShadowContext( shadowNode, light, node ) );
  5660. addMethodChaining( 'builtinAOContext', ( node, aoValue ) => builtinAOContext( aoValue, node ) );
  5661. /**
  5662. * Class for representing shader variables as nodes. Variables are created from
  5663. * existing nodes like the following:
  5664. *
  5665. * ```js
  5666. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5667. * ```
  5668. *
  5669. * @augments Node
  5670. */
  5671. class VarNode extends Node {
  5672. static get type() {
  5673. return 'VarNode';
  5674. }
  5675. /**
  5676. * Constructs a new variable node.
  5677. *
  5678. * @param {Node} node - The node for which a variable should be created.
  5679. * @param {?string} [name=null] - The name of the variable in the shader.
  5680. * @param {boolean} [readOnly=false] - The read-only flag.
  5681. */
  5682. constructor( node, name = null, readOnly = false ) {
  5683. super();
  5684. /**
  5685. * The node for which a variable should be created.
  5686. *
  5687. * @type {Node}
  5688. */
  5689. this.node = node;
  5690. /**
  5691. * The name of the variable in the shader. If no name is defined,
  5692. * the node system auto-generates one.
  5693. *
  5694. * @type {?string}
  5695. * @default null
  5696. */
  5697. this.name = name;
  5698. /**
  5699. * `VarNode` sets this property to `true` by default.
  5700. *
  5701. * @type {boolean}
  5702. * @default true
  5703. */
  5704. this.global = true;
  5705. /**
  5706. * This flag can be used for type testing.
  5707. *
  5708. * @type {boolean}
  5709. * @readonly
  5710. * @default true
  5711. */
  5712. this.isVarNode = true;
  5713. /**
  5714. *
  5715. * The read-only flag.
  5716. *
  5717. * @type {boolean}
  5718. * @default false
  5719. */
  5720. this.readOnly = readOnly;
  5721. /**
  5722. *
  5723. * Add this flag to the node system to indicate that this node require parents.
  5724. *
  5725. * @type {boolean}
  5726. * @default true
  5727. */
  5728. this.parents = true;
  5729. /**
  5730. * This flag is used to indicate that this node is used for intent.
  5731. *
  5732. * @type {boolean}
  5733. * @default false
  5734. */
  5735. this.intent = false;
  5736. }
  5737. /**
  5738. * Sets the intent flag for this node.
  5739. *
  5740. * This flag is used to indicate that this node is used for intent
  5741. * and should not be built directly. Instead, it is used to indicate that
  5742. * the node should be treated as a variable intent.
  5743. *
  5744. * It's useful for assigning variables without needing creating a new variable node.
  5745. *
  5746. * @param {boolean} value - The value to set for the intent flag.
  5747. * @returns {VarNode} This node.
  5748. */
  5749. setIntent( value ) {
  5750. this.intent = value;
  5751. return this;
  5752. }
  5753. /**
  5754. * Returns the intent flag of this node.
  5755. *
  5756. * @return {boolean} The intent flag.
  5757. */
  5758. getIntent() {
  5759. return this.intent;
  5760. }
  5761. getMemberType( builder, name ) {
  5762. return this.node.getMemberType( builder, name );
  5763. }
  5764. getElementType( builder ) {
  5765. return this.node.getElementType( builder );
  5766. }
  5767. getNodeType( builder ) {
  5768. return this.node.getNodeType( builder );
  5769. }
  5770. getArrayCount( builder ) {
  5771. return this.node.getArrayCount( builder );
  5772. }
  5773. isAssign( builder ) {
  5774. const properties = builder.getNodeProperties( this );
  5775. let assign = properties.assign;
  5776. if ( assign !== true ) {
  5777. if ( this.node.isShaderCallNodeInternal && this.node.shaderNode.getLayout() === null ) {
  5778. if ( builder.fnCall && builder.fnCall.shaderNode ) {
  5779. const shaderNodeData = builder.getDataFromNode( this.node.shaderNode );
  5780. if ( shaderNodeData.hasLoop ) {
  5781. assign = true;
  5782. }
  5783. }
  5784. }
  5785. }
  5786. return assign;
  5787. }
  5788. build( ...params ) {
  5789. const builder = params[ 0 ];
  5790. if ( this._hasStack( builder ) === false && builder.buildStage === 'setup' ) {
  5791. if ( builder.context.nodeLoop || builder.context.nodeBlock ) {
  5792. builder.getBaseStack().addToStack( this );
  5793. }
  5794. }
  5795. if ( this.intent === true ) {
  5796. if ( this.isAssign( builder ) !== true ) {
  5797. return this.node.build( ...params );
  5798. }
  5799. }
  5800. return super.build( ...params );
  5801. }
  5802. generate( builder ) {
  5803. const { node, name, readOnly } = this;
  5804. const { renderer } = builder;
  5805. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5806. let isDeterministic = false;
  5807. let shouldTreatAsReadOnly = false;
  5808. if ( readOnly ) {
  5809. isDeterministic = builder.isDeterministic( node );
  5810. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5811. }
  5812. const nodeType = this.getNodeType( builder );
  5813. if ( nodeType == 'void' ) {
  5814. if ( this.intent !== true ) {
  5815. error( 'TSL: ".toVar()" can not be used with void type.' );
  5816. }
  5817. const snippet = node.build( builder );
  5818. return snippet;
  5819. }
  5820. const vectorType = builder.getVectorType( nodeType );
  5821. const snippet = node.build( builder, vectorType );
  5822. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5823. const propertyName = builder.getPropertyName( nodeVar );
  5824. let declarationPrefix = propertyName;
  5825. if ( shouldTreatAsReadOnly ) {
  5826. if ( isWebGPUBackend ) {
  5827. declarationPrefix = isDeterministic
  5828. ? `const ${ propertyName }`
  5829. : `let ${ propertyName }`;
  5830. } else {
  5831. const count = node.getArrayCount( builder );
  5832. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5833. }
  5834. }
  5835. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5836. return propertyName;
  5837. }
  5838. _hasStack( builder ) {
  5839. const nodeData = builder.getDataFromNode( this );
  5840. return nodeData.stack !== undefined;
  5841. }
  5842. }
  5843. /**
  5844. * TSL function for creating a var node.
  5845. *
  5846. * @tsl
  5847. * @function
  5848. * @param {Node} node - The node for which a variable should be created.
  5849. * @param {?string} name - The name of the variable in the shader.
  5850. * @returns {VarNode}
  5851. */
  5852. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5853. /**
  5854. * TSL function for creating a var node.
  5855. *
  5856. * @tsl
  5857. * @function
  5858. * @param {Node} node - The node for which a variable should be created.
  5859. * @param {?string} name - The name of the variable in the shader.
  5860. * @returns {VarNode}
  5861. */
  5862. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5863. /**
  5864. * TSL function for creating a const node.
  5865. *
  5866. * @tsl
  5867. * @function
  5868. * @param {Node} node - The node for which a constant should be created.
  5869. * @param {?string} name - The name of the constant in the shader.
  5870. * @returns {VarNode}
  5871. */
  5872. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  5873. //
  5874. //
  5875. /**
  5876. * TSL function for creating a var intent node.
  5877. *
  5878. * @tsl
  5879. * @function
  5880. * @param {Node} node - The node for which a variable should be created.
  5881. * @param {?string} name - The name of the variable in the shader.
  5882. * @returns {VarNode}
  5883. */
  5884. const VarIntent = ( node ) => {
  5885. return createVar( node ).setIntent( true ).toStack();
  5886. };
  5887. // Method chaining
  5888. addMethodChaining( 'toVar', Var );
  5889. addMethodChaining( 'toConst', Const );
  5890. addMethodChaining( 'toVarIntent', VarIntent );
  5891. /**
  5892. * This node is used to build a sub-build in the node system.
  5893. *
  5894. * @augments Node
  5895. * @param {Node} node - The node to be built in the sub-build.
  5896. * @param {string} name - The name of the sub-build.
  5897. * @param {?string} [nodeType=null] - The type of the node, if known.
  5898. */
  5899. class SubBuildNode extends Node {
  5900. static get type() {
  5901. return 'SubBuild';
  5902. }
  5903. constructor( node, name, nodeType = null ) {
  5904. super( nodeType );
  5905. /**
  5906. * The node to be built in the sub-build.
  5907. *
  5908. * @type {Node}
  5909. */
  5910. this.node = node;
  5911. /**
  5912. * The name of the sub-build.
  5913. *
  5914. * @type {string}
  5915. */
  5916. this.name = name;
  5917. /**
  5918. * This flag can be used for type testing.
  5919. *
  5920. * @type {boolean}
  5921. * @readonly
  5922. * @default true
  5923. */
  5924. this.isSubBuildNode = true;
  5925. }
  5926. getNodeType( builder ) {
  5927. if ( this.nodeType !== null ) return this.nodeType;
  5928. builder.addSubBuild( this.name );
  5929. const nodeType = this.node.getNodeType( builder );
  5930. builder.removeSubBuild();
  5931. return nodeType;
  5932. }
  5933. build( builder, ...params ) {
  5934. builder.addSubBuild( this.name );
  5935. const data = this.node.build( builder, ...params );
  5936. builder.removeSubBuild();
  5937. return data;
  5938. }
  5939. }
  5940. /**
  5941. * Creates a new sub-build node.
  5942. *
  5943. * @tsl
  5944. * @function
  5945. * @param {Node} node - The node to be built in the sub-build.
  5946. * @param {string} name - The name of the sub-build.
  5947. * @param {?string} [type=null] - The type of the node, if known.
  5948. * @returns {Node} A node object wrapping the SubBuildNode instance.
  5949. */
  5950. const subBuild = ( node, name, type = null ) => nodeObject( new SubBuildNode( nodeObject( node ), name, type ) );
  5951. /**
  5952. * Class for representing shader varyings as nodes. Varyings are create from
  5953. * existing nodes like the following:
  5954. *
  5955. * ```js
  5956. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  5957. * ```
  5958. *
  5959. * @augments Node
  5960. */
  5961. class VaryingNode extends Node {
  5962. static get type() {
  5963. return 'VaryingNode';
  5964. }
  5965. /**
  5966. * Constructs a new varying node.
  5967. *
  5968. * @param {Node} node - The node for which a varying should be created.
  5969. * @param {?string} name - The name of the varying in the shader.
  5970. */
  5971. constructor( node, name = null ) {
  5972. super();
  5973. /**
  5974. * The node for which a varying should be created.
  5975. *
  5976. * @type {Node}
  5977. */
  5978. this.node = node;
  5979. /**
  5980. * The name of the varying in the shader. If no name is defined,
  5981. * the node system auto-generates one.
  5982. *
  5983. * @type {?string}
  5984. * @default null
  5985. */
  5986. this.name = name;
  5987. /**
  5988. * This flag can be used for type testing.
  5989. *
  5990. * @type {boolean}
  5991. * @readonly
  5992. * @default true
  5993. */
  5994. this.isVaryingNode = true;
  5995. /**
  5996. * The interpolation type of the varying data.
  5997. *
  5998. * @type {?string}
  5999. * @default null
  6000. */
  6001. this.interpolationType = null;
  6002. /**
  6003. * The interpolation sampling type of varying data.
  6004. *
  6005. * @type {?string}
  6006. * @default null
  6007. */
  6008. this.interpolationSampling = null;
  6009. /**
  6010. * This flag is used for global cache.
  6011. *
  6012. * @type {boolean}
  6013. * @default true
  6014. */
  6015. this.global = true;
  6016. }
  6017. /**
  6018. * Defines the interpolation type of the varying.
  6019. *
  6020. * @param {string} type - The interpolation type.
  6021. * @param {?string} sampling - The interpolation sampling type
  6022. * @return {VaryingNode} A reference to this node.
  6023. */
  6024. setInterpolation( type, sampling = null ) {
  6025. this.interpolationType = type;
  6026. this.interpolationSampling = sampling;
  6027. return this;
  6028. }
  6029. getHash( builder ) {
  6030. return this.name || super.getHash( builder );
  6031. }
  6032. getNodeType( builder ) {
  6033. // VaryingNode is auto type
  6034. return this.node.getNodeType( builder );
  6035. }
  6036. /**
  6037. * This method performs the setup of a varying node with the current node builder.
  6038. *
  6039. * @param {NodeBuilder} builder - The current node builder.
  6040. * @return {NodeVarying} The node varying from the node builder.
  6041. */
  6042. setupVarying( builder ) {
  6043. const properties = builder.getNodeProperties( this );
  6044. let varying = properties.varying;
  6045. if ( varying === undefined ) {
  6046. const name = this.name;
  6047. const type = this.getNodeType( builder );
  6048. const interpolationType = this.interpolationType;
  6049. const interpolationSampling = this.interpolationSampling;
  6050. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  6051. properties.node = subBuild( this.node, 'VERTEX' );
  6052. }
  6053. // this property can be used to check if the varying can be optimized for a variable
  6054. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  6055. return varying;
  6056. }
  6057. setup( builder ) {
  6058. this.setupVarying( builder );
  6059. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  6060. }
  6061. analyze( builder ) {
  6062. this.setupVarying( builder );
  6063. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  6064. }
  6065. generate( builder ) {
  6066. const propertyKey = builder.getSubBuildProperty( 'property', builder.currentStack );
  6067. const properties = builder.getNodeProperties( this );
  6068. const varying = this.setupVarying( builder );
  6069. if ( properties[ propertyKey ] === undefined ) {
  6070. const type = this.getNodeType( builder );
  6071. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  6072. // force node run in vertex stage
  6073. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, properties.node, type, propertyName );
  6074. properties[ propertyKey ] = propertyName;
  6075. }
  6076. return builder.getPropertyName( varying );
  6077. }
  6078. }
  6079. /**
  6080. * TSL function for creating a varying node.
  6081. *
  6082. * @tsl
  6083. * @function
  6084. * @param {Node} node - The node for which a varying should be created.
  6085. * @param {?string} name - The name of the varying in the shader.
  6086. * @returns {VaryingNode}
  6087. */
  6088. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  6089. /**
  6090. * Computes a node in the vertex stage.
  6091. *
  6092. * @tsl
  6093. * @function
  6094. * @param {Node} node - The node which should be executed in the vertex stage.
  6095. * @returns {VaryingNode}
  6096. */
  6097. const vertexStage = ( node ) => varying( node );
  6098. addMethodChaining( 'toVarying', varying );
  6099. addMethodChaining( 'toVertexStage', vertexStage );
  6100. // Deprecated
  6101. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  6102. warn( 'TSL: .varying() has been renamed to .toVarying().' );
  6103. return varying( ...params );
  6104. } );
  6105. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  6106. warn( 'TSL: .vertexStage() has been renamed to .toVertexStage().' );
  6107. return varying( ...params );
  6108. } );
  6109. /**
  6110. * Converts the given color value from sRGB to linear-sRGB color space.
  6111. *
  6112. * @tsl
  6113. * @function
  6114. * @param {Node<vec3>} color - The sRGB color.
  6115. * @return {Node<vec3>} The linear-sRGB color.
  6116. */
  6117. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6118. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  6119. const b = color.mul( 0.0773993808 );
  6120. const factor = color.lessThanEqual( 0.04045 );
  6121. const rgbResult = mix( a, b, factor );
  6122. return rgbResult;
  6123. } ).setLayout( {
  6124. name: 'sRGBTransferEOTF',
  6125. type: 'vec3',
  6126. inputs: [
  6127. { name: 'color', type: 'vec3' }
  6128. ]
  6129. } );
  6130. /**
  6131. * Converts the given color value from linear-sRGB to sRGB color space.
  6132. *
  6133. * @tsl
  6134. * @function
  6135. * @param {Node<vec3>} color - The linear-sRGB color.
  6136. * @return {Node<vec3>} The sRGB color.
  6137. */
  6138. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6139. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  6140. const b = color.mul( 12.92 );
  6141. const factor = color.lessThanEqual( 0.0031308 );
  6142. const rgbResult = mix( a, b, factor );
  6143. return rgbResult;
  6144. } ).setLayout( {
  6145. name: 'sRGBTransferOETF',
  6146. type: 'vec3',
  6147. inputs: [
  6148. { name: 'color', type: 'vec3' }
  6149. ]
  6150. } );
  6151. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  6152. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  6153. /**
  6154. * This node represents a color space conversion. Meaning it converts
  6155. * a color value from a source to a target color space.
  6156. *
  6157. * @augments TempNode
  6158. */
  6159. class ColorSpaceNode extends TempNode {
  6160. static get type() {
  6161. return 'ColorSpaceNode';
  6162. }
  6163. /**
  6164. * Constructs a new color space node.
  6165. *
  6166. * @param {Node} colorNode - Represents the color to convert.
  6167. * @param {string} source - The source color space.
  6168. * @param {string} target - The target color space.
  6169. */
  6170. constructor( colorNode, source, target ) {
  6171. super( 'vec4' );
  6172. /**
  6173. * Represents the color to convert.
  6174. *
  6175. * @type {Node}
  6176. */
  6177. this.colorNode = colorNode;
  6178. /**
  6179. * The source color space.
  6180. *
  6181. * @type {string}
  6182. */
  6183. this.source = source;
  6184. /**
  6185. * The target color space.
  6186. *
  6187. * @type {string}
  6188. */
  6189. this.target = target;
  6190. }
  6191. /**
  6192. * This method resolves the constants `WORKING_COLOR_SPACE` and
  6193. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  6194. * color management and renderer.
  6195. *
  6196. * @param {NodeBuilder} builder - The current node builder.
  6197. * @param {string} colorSpace - The color space to resolve.
  6198. * @return {string} The resolved color space.
  6199. */
  6200. resolveColorSpace( builder, colorSpace ) {
  6201. if ( colorSpace === WORKING_COLOR_SPACE ) {
  6202. return ColorManagement.workingColorSpace;
  6203. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  6204. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  6205. }
  6206. return colorSpace;
  6207. }
  6208. setup( builder ) {
  6209. const { colorNode } = this;
  6210. const source = this.resolveColorSpace( builder, this.source );
  6211. const target = this.resolveColorSpace( builder, this.target );
  6212. let outputNode = colorNode;
  6213. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  6214. return outputNode;
  6215. }
  6216. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  6217. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  6218. }
  6219. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  6220. outputNode = vec4(
  6221. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  6222. outputNode.a
  6223. );
  6224. }
  6225. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  6226. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  6227. }
  6228. return outputNode;
  6229. }
  6230. }
  6231. /**
  6232. * TSL function for converting a given color node from the current working color space to the given color space.
  6233. *
  6234. * @tsl
  6235. * @function
  6236. * @param {Node} node - Represents the node to convert.
  6237. * @param {string} targetColorSpace - The target color space.
  6238. * @returns {ColorSpaceNode}
  6239. */
  6240. const workingToColorSpace = ( node, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace ) );
  6241. /**
  6242. * TSL function for converting a given color node from the given color space to the current working color space.
  6243. *
  6244. * @tsl
  6245. * @function
  6246. * @param {Node} node - Represents the node to convert.
  6247. * @param {string} sourceColorSpace - The source color space.
  6248. * @returns {ColorSpaceNode}
  6249. */
  6250. const colorSpaceToWorking = ( node, sourceColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE ) );
  6251. /**
  6252. * TSL function for converting a given color node from one color space to another one.
  6253. *
  6254. * @tsl
  6255. * @function
  6256. * @param {Node} node - Represents the node to convert.
  6257. * @param {string} sourceColorSpace - The source color space.
  6258. * @param {string} targetColorSpace - The target color space.
  6259. * @returns {ColorSpaceNode}
  6260. */
  6261. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  6262. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  6263. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  6264. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  6265. /**
  6266. * This class is only relevant if the referenced property is array-like.
  6267. * In this case, `ReferenceElementNode` allows to refer to a specific
  6268. * element inside the data structure via an index.
  6269. *
  6270. * @augments ArrayElementNode
  6271. */
  6272. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  6273. static get type() {
  6274. return 'ReferenceElementNode';
  6275. }
  6276. /**
  6277. * Constructs a new reference element node.
  6278. *
  6279. * @param {ReferenceBaseNode} referenceNode - The reference node.
  6280. * @param {Node} indexNode - The index node that defines the element access.
  6281. */
  6282. constructor( referenceNode, indexNode ) {
  6283. super( referenceNode, indexNode );
  6284. /**
  6285. * Similar to {@link ReferenceBaseNode#reference}, an additional
  6286. * property references to the current node.
  6287. *
  6288. * @type {?ReferenceBaseNode}
  6289. * @default null
  6290. */
  6291. this.referenceNode = referenceNode;
  6292. /**
  6293. * This flag can be used for type testing.
  6294. *
  6295. * @type {boolean}
  6296. * @readonly
  6297. * @default true
  6298. */
  6299. this.isReferenceElementNode = true;
  6300. }
  6301. /**
  6302. * This method is overwritten since the node type is inferred from
  6303. * the uniform type of the reference node.
  6304. *
  6305. * @return {string} The node type.
  6306. */
  6307. getNodeType() {
  6308. return this.referenceNode.uniformType;
  6309. }
  6310. generate( builder ) {
  6311. const snippet = super.generate( builder );
  6312. const arrayType = this.referenceNode.getNodeType();
  6313. const elementType = this.getNodeType();
  6314. return builder.format( snippet, arrayType, elementType );
  6315. }
  6316. };
  6317. /**
  6318. * Base class for nodes which establishes a reference to a property of another object.
  6319. * In this way, the value of the node is automatically linked to the value of
  6320. * referenced object. Reference nodes internally represent the linked value
  6321. * as a uniform.
  6322. *
  6323. * @augments Node
  6324. */
  6325. class ReferenceBaseNode extends Node {
  6326. static get type() {
  6327. return 'ReferenceBaseNode';
  6328. }
  6329. /**
  6330. * Constructs a new reference base node.
  6331. *
  6332. * @param {string} property - The name of the property the node refers to.
  6333. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  6334. * @param {?Object} [object=null] - The object the property belongs to.
  6335. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  6336. */
  6337. constructor( property, uniformType, object = null, count = null ) {
  6338. super();
  6339. /**
  6340. * The name of the property the node refers to.
  6341. *
  6342. * @type {string}
  6343. */
  6344. this.property = property;
  6345. /**
  6346. * The uniform type that should be used to represent the property value.
  6347. *
  6348. * @type {string}
  6349. */
  6350. this.uniformType = uniformType;
  6351. /**
  6352. * The object the property belongs to.
  6353. *
  6354. * @type {?Object}
  6355. * @default null
  6356. */
  6357. this.object = object;
  6358. /**
  6359. * When the linked property is an array, this parameter defines its length.
  6360. *
  6361. * @type {?number}
  6362. * @default null
  6363. */
  6364. this.count = count;
  6365. /**
  6366. * The property name might have dots so nested properties can be referred.
  6367. * The hierarchy of the names is stored inside this array.
  6368. *
  6369. * @type {Array<string>}
  6370. */
  6371. this.properties = property.split( '.' );
  6372. /**
  6373. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  6374. * since the final reference might be updated from calling code.
  6375. *
  6376. * @type {?Object}
  6377. * @default null
  6378. */
  6379. this.reference = object;
  6380. /**
  6381. * The uniform node that holds the value of the reference node.
  6382. *
  6383. * @type {UniformNode}
  6384. * @default null
  6385. */
  6386. this.node = null;
  6387. /**
  6388. * The uniform group of the internal uniform.
  6389. *
  6390. * @type {UniformGroupNode}
  6391. * @default null
  6392. */
  6393. this.group = null;
  6394. /**
  6395. * Overwritten since reference nodes are updated per object.
  6396. *
  6397. * @type {string}
  6398. * @default 'object'
  6399. */
  6400. this.updateType = NodeUpdateType.OBJECT;
  6401. }
  6402. /**
  6403. * Sets the uniform group for this reference node.
  6404. *
  6405. * @param {UniformGroupNode} group - The uniform group to set.
  6406. * @return {ReferenceBaseNode} A reference to this node.
  6407. */
  6408. setGroup( group ) {
  6409. this.group = group;
  6410. return this;
  6411. }
  6412. /**
  6413. * When the referred property is array-like, this method can be used
  6414. * to access elements via an index node.
  6415. *
  6416. * @param {IndexNode} indexNode - indexNode.
  6417. * @return {ReferenceElementNode} A reference to an element.
  6418. */
  6419. element( indexNode ) {
  6420. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  6421. }
  6422. /**
  6423. * Sets the node type which automatically defines the internal
  6424. * uniform type.
  6425. *
  6426. * @param {string} uniformType - The type to set.
  6427. */
  6428. setNodeType( uniformType ) {
  6429. const node = uniform( null, uniformType );
  6430. if ( this.group !== null ) {
  6431. node.setGroup( this.group );
  6432. }
  6433. this.node = node;
  6434. }
  6435. /**
  6436. * This method is overwritten since the node type is inferred from
  6437. * the type of the reference node.
  6438. *
  6439. * @param {NodeBuilder} builder - The current node builder.
  6440. * @return {string} The node type.
  6441. */
  6442. getNodeType( builder ) {
  6443. if ( this.node === null ) {
  6444. this.updateReference( builder );
  6445. this.updateValue();
  6446. }
  6447. return this.node.getNodeType( builder );
  6448. }
  6449. /**
  6450. * Returns the property value from the given referred object.
  6451. *
  6452. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  6453. * @return {any} The value.
  6454. */
  6455. getValueFromReference( object = this.reference ) {
  6456. const { properties } = this;
  6457. let value = object[ properties[ 0 ] ];
  6458. for ( let i = 1; i < properties.length; i ++ ) {
  6459. value = value[ properties[ i ] ];
  6460. }
  6461. return value;
  6462. }
  6463. /**
  6464. * Allows to update the reference based on the given state. The state is only
  6465. * evaluated {@link ReferenceBaseNode#object} is not set.
  6466. *
  6467. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6468. * @return {Object} The updated reference.
  6469. */
  6470. updateReference( state ) {
  6471. this.reference = this.object !== null ? this.object : state.object;
  6472. return this.reference;
  6473. }
  6474. /**
  6475. * The output of the reference node is the internal uniform node.
  6476. *
  6477. * @return {UniformNode} The output node.
  6478. */
  6479. setup() {
  6480. this.updateValue();
  6481. return this.node;
  6482. }
  6483. /**
  6484. * Overwritten to update the internal uniform value.
  6485. *
  6486. * @param {NodeFrame} frame - A reference to the current node frame.
  6487. */
  6488. update( /*frame*/ ) {
  6489. this.updateValue();
  6490. }
  6491. /**
  6492. * Retrieves the value from the referred object property and uses it
  6493. * to updated the internal uniform.
  6494. */
  6495. updateValue() {
  6496. if ( this.node === null ) this.setNodeType( this.uniformType );
  6497. const value = this.getValueFromReference();
  6498. if ( Array.isArray( value ) ) {
  6499. this.node.array = value;
  6500. } else {
  6501. this.node.value = value;
  6502. }
  6503. }
  6504. }
  6505. /**
  6506. * TSL function for creating a reference base node.
  6507. *
  6508. * @tsl
  6509. * @function
  6510. * @param {string} name - The name of the property the node refers to.
  6511. * @param {string} type - The uniform type that should be used to represent the property value.
  6512. * @param {Object} object - The object the property belongs to.
  6513. * @returns {ReferenceBaseNode}
  6514. */
  6515. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  6516. /**
  6517. * This node is a special type of reference node which is intended
  6518. * for linking renderer properties with node values.
  6519. * ```js
  6520. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  6521. * ```
  6522. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  6523. * automatically be updated.
  6524. *
  6525. * @augments ReferenceBaseNode
  6526. */
  6527. class RendererReferenceNode extends ReferenceBaseNode {
  6528. static get type() {
  6529. return 'RendererReferenceNode';
  6530. }
  6531. /**
  6532. * Constructs a new renderer reference node.
  6533. *
  6534. * @param {string} property - The name of the property the node refers to.
  6535. * @param {string} inputType - The uniform type that should be used to represent the property value.
  6536. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6537. * the node refers to the renderer of the current state.
  6538. */
  6539. constructor( property, inputType, renderer = null ) {
  6540. super( property, inputType, renderer );
  6541. /**
  6542. * The renderer the property belongs to. When no renderer is set,
  6543. * the node refers to the renderer of the current state.
  6544. *
  6545. * @type {?Renderer}
  6546. * @default null
  6547. */
  6548. this.renderer = renderer;
  6549. this.setGroup( renderGroup );
  6550. }
  6551. /**
  6552. * Updates the reference based on the given state. The state is only evaluated
  6553. * {@link RendererReferenceNode#renderer} is not set.
  6554. *
  6555. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6556. * @return {Object} The updated reference.
  6557. */
  6558. updateReference( state ) {
  6559. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  6560. return this.reference;
  6561. }
  6562. }
  6563. /**
  6564. * TSL function for creating a renderer reference node.
  6565. *
  6566. * @tsl
  6567. * @function
  6568. * @param {string} name - The name of the property the node refers to.
  6569. * @param {string} type - The uniform type that should be used to represent the property value.
  6570. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6571. * the node refers to the renderer of the current state.
  6572. * @returns {RendererReferenceNode}
  6573. */
  6574. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  6575. /**
  6576. * This node represents a tone mapping operation.
  6577. *
  6578. * @augments TempNode
  6579. */
  6580. class ToneMappingNode extends TempNode {
  6581. static get type() {
  6582. return 'ToneMappingNode';
  6583. }
  6584. /**
  6585. * Constructs a new tone mapping node.
  6586. *
  6587. * @param {number} toneMapping - The tone mapping type.
  6588. * @param {Node} exposureNode - The tone mapping exposure.
  6589. * @param {Node} [colorNode=null] - The color node to process.
  6590. */
  6591. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  6592. super( 'vec3' );
  6593. /**
  6594. * The tone mapping type.
  6595. *
  6596. * @private
  6597. * @type {number}
  6598. */
  6599. this._toneMapping = toneMapping;
  6600. /**
  6601. * The tone mapping exposure.
  6602. *
  6603. * @type {Node}
  6604. * @default null
  6605. */
  6606. this.exposureNode = exposureNode;
  6607. /**
  6608. * Represents the color to process.
  6609. *
  6610. * @type {?Node}
  6611. * @default null
  6612. */
  6613. this.colorNode = colorNode;
  6614. }
  6615. /**
  6616. * Overwrites the default `customCacheKey()` implementation by including the tone
  6617. * mapping type into the cache key.
  6618. *
  6619. * @return {number} The hash.
  6620. */
  6621. customCacheKey() {
  6622. return hash$1( this._toneMapping );
  6623. }
  6624. /**
  6625. * Sets the tone mapping type.
  6626. *
  6627. * @param {number} value - The tone mapping type.
  6628. * @return {ToneMappingNode} A reference to this node.
  6629. */
  6630. setToneMapping( value ) {
  6631. this._toneMapping = value;
  6632. return this;
  6633. }
  6634. /**
  6635. * Gets the tone mapping type.
  6636. *
  6637. * @returns {number} The tone mapping type.
  6638. */
  6639. getToneMapping() {
  6640. return this._toneMapping;
  6641. }
  6642. setup( builder ) {
  6643. const colorNode = this.colorNode || builder.context.color;
  6644. const toneMapping = this._toneMapping;
  6645. if ( toneMapping === NoToneMapping ) return colorNode;
  6646. let outputNode = null;
  6647. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  6648. if ( toneMappingFn !== null ) {
  6649. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  6650. } else {
  6651. error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  6652. outputNode = colorNode;
  6653. }
  6654. return outputNode;
  6655. }
  6656. }
  6657. /**
  6658. * TSL function for creating a tone mapping node.
  6659. *
  6660. * @tsl
  6661. * @function
  6662. * @param {number} mapping - The tone mapping type.
  6663. * @param {Node<float> | number} exposure - The tone mapping exposure.
  6664. * @param {Node<vec3> | Color} color - The color node to process.
  6665. * @returns {ToneMappingNode<vec3>}
  6666. */
  6667. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  6668. /**
  6669. * TSL object that represents the global tone mapping exposure of the renderer.
  6670. *
  6671. * @tsl
  6672. * @type {RendererReferenceNode<vec3>}
  6673. */
  6674. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  6675. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  6676. /**
  6677. * Internal buffer attribute library.
  6678. *
  6679. * @private
  6680. * @type {WeakMap<TypedArray, InterleavedBuffer>}
  6681. */
  6682. const _bufferLib = new WeakMap();
  6683. /**
  6684. * Internal method for retrieving or creating interleaved buffers.
  6685. *
  6686. * @private
  6687. * @param {TypedArray} value - The attribute data.
  6688. * @param {number} itemSize - The attribute item size.
  6689. * @returns {InterleavedBuffer} The interleaved buffer.
  6690. */
  6691. function _getBufferAttribute( value, itemSize ) {
  6692. let buffer = _bufferLib.get( value );
  6693. if ( buffer === undefined ) {
  6694. buffer = new InterleavedBuffer( value, itemSize );
  6695. _bufferLib.set( value, buffer );
  6696. }
  6697. return buffer;
  6698. }
  6699. /**
  6700. * In earlier `three.js` versions it was only possible to define attribute data
  6701. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  6702. * on the node level.
  6703. * ```js
  6704. * const geometry = new THREE.PlaneGeometry();
  6705. * const positionAttribute = geometry.getAttribute( 'position' );
  6706. *
  6707. * const colors = [];
  6708. * for ( let i = 0; i < position.count; i ++ ) {
  6709. * colors.push( 1, 0, 0 );
  6710. * }
  6711. *
  6712. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  6713. * ```
  6714. * This new approach is especially interesting when geometry data are generated via
  6715. * compute shaders. The below line converts a storage buffer into an attribute node.
  6716. * ```js
  6717. * material.positionNode = positionBuffer.toAttribute();
  6718. * ```
  6719. * @augments InputNode
  6720. */
  6721. class BufferAttributeNode extends InputNode {
  6722. static get type() {
  6723. return 'BufferAttributeNode';
  6724. }
  6725. /**
  6726. * Constructs a new buffer attribute node.
  6727. *
  6728. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  6729. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  6730. * @param {number} [bufferStride=0] - The buffer stride.
  6731. * @param {number} [bufferOffset=0] - The buffer offset.
  6732. */
  6733. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  6734. super( value, bufferType );
  6735. /**
  6736. * This flag can be used for type testing.
  6737. *
  6738. * @type {boolean}
  6739. * @readonly
  6740. * @default true
  6741. */
  6742. this.isBufferNode = true;
  6743. /**
  6744. * The buffer type (e.g. `'vec3'`).
  6745. *
  6746. * @type {?string}
  6747. * @default null
  6748. */
  6749. this.bufferType = bufferType;
  6750. /**
  6751. * The buffer stride.
  6752. *
  6753. * @type {number}
  6754. * @default 0
  6755. */
  6756. this.bufferStride = bufferStride;
  6757. /**
  6758. * The buffer offset.
  6759. *
  6760. * @type {number}
  6761. * @default 0
  6762. */
  6763. this.bufferOffset = bufferOffset;
  6764. /**
  6765. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  6766. * if you are planning to update the attribute data per frame.
  6767. *
  6768. * @type {number}
  6769. * @default StaticDrawUsage
  6770. */
  6771. this.usage = StaticDrawUsage;
  6772. /**
  6773. * Whether the attribute is instanced or not.
  6774. *
  6775. * @type {boolean}
  6776. * @default false
  6777. */
  6778. this.instanced = false;
  6779. /**
  6780. * A reference to the buffer attribute.
  6781. *
  6782. * @type {?BufferAttribute}
  6783. * @default null
  6784. */
  6785. this.attribute = null;
  6786. /**
  6787. * `BufferAttributeNode` sets this property to `true` by default.
  6788. *
  6789. * @type {boolean}
  6790. * @default true
  6791. */
  6792. this.global = true;
  6793. if ( value && value.isBufferAttribute === true && value.itemSize <= 4 ) {
  6794. this.attribute = value;
  6795. this.usage = value.usage;
  6796. this.instanced = value.isInstancedBufferAttribute;
  6797. }
  6798. }
  6799. /**
  6800. * This method is overwritten since the attribute data might be shared
  6801. * and thus the hash should be shared as well.
  6802. *
  6803. * @param {NodeBuilder} builder - The current node builder.
  6804. * @return {string} The hash.
  6805. */
  6806. getHash( builder ) {
  6807. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6808. let bufferData = builder.globalCache.getData( this.value );
  6809. if ( bufferData === undefined ) {
  6810. bufferData = {
  6811. node: this
  6812. };
  6813. builder.globalCache.setData( this.value, bufferData );
  6814. }
  6815. return bufferData.node.uuid;
  6816. }
  6817. return this.uuid;
  6818. }
  6819. /**
  6820. * This method is overwritten since the node type is inferred from
  6821. * the buffer attribute.
  6822. *
  6823. * @param {NodeBuilder} builder - The current node builder.
  6824. * @return {string} The node type.
  6825. */
  6826. getNodeType( builder ) {
  6827. if ( this.bufferType === null ) {
  6828. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6829. }
  6830. return this.bufferType;
  6831. }
  6832. /**
  6833. * Depending on which value was passed to the node, `setup()` behaves
  6834. * differently. If no instance of `BufferAttribute` was passed, the method
  6835. * creates an internal attribute and configures it respectively.
  6836. *
  6837. * @param {NodeBuilder} builder - The current node builder.
  6838. */
  6839. setup( builder ) {
  6840. if ( this.attribute !== null ) return;
  6841. //
  6842. const type = this.getNodeType( builder );
  6843. const itemSize = builder.getTypeLength( type );
  6844. const value = this.value;
  6845. const stride = this.bufferStride || itemSize;
  6846. const offset = this.bufferOffset;
  6847. let buffer;
  6848. if ( value.isInterleavedBuffer === true ) {
  6849. buffer = value;
  6850. } else if ( value.isBufferAttribute === true ) {
  6851. buffer = _getBufferAttribute( value.array, stride );
  6852. } else {
  6853. buffer = _getBufferAttribute( value, stride );
  6854. }
  6855. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6856. buffer.setUsage( this.usage );
  6857. this.attribute = bufferAttribute;
  6858. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6859. }
  6860. /**
  6861. * Generates the code snippet of the buffer attribute node.
  6862. *
  6863. * @param {NodeBuilder} builder - The current node builder.
  6864. * @return {string} The generated code snippet.
  6865. */
  6866. generate( builder ) {
  6867. const nodeType = this.getNodeType( builder );
  6868. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6869. const propertyName = builder.getPropertyName( nodeAttribute );
  6870. let output = null;
  6871. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6872. this.name = propertyName;
  6873. output = propertyName;
  6874. } else {
  6875. const nodeVarying = varying( this );
  6876. output = nodeVarying.build( builder, nodeType );
  6877. }
  6878. return output;
  6879. }
  6880. /**
  6881. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  6882. *
  6883. * @param {NodeBuilder} builder - The current node builder.
  6884. * @return {string} The input type.
  6885. */
  6886. getInputType( /*builder*/ ) {
  6887. return 'bufferAttribute';
  6888. }
  6889. /**
  6890. * Sets the `usage` property to the given value.
  6891. *
  6892. * @param {number} value - The usage to set.
  6893. * @return {BufferAttributeNode} A reference to this node.
  6894. */
  6895. setUsage( value ) {
  6896. this.usage = value;
  6897. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  6898. this.attribute.usage = value;
  6899. }
  6900. return this;
  6901. }
  6902. /**
  6903. * Sets the `instanced` property to the given value.
  6904. *
  6905. * @param {boolean} value - The value to set.
  6906. * @return {BufferAttributeNode} A reference to this node.
  6907. */
  6908. setInstanced( value ) {
  6909. this.instanced = value;
  6910. return this;
  6911. }
  6912. }
  6913. /**
  6914. * Internal method for creating buffer attribute nodes.
  6915. *
  6916. * @private
  6917. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6918. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6919. * @param {number} [stride=0] - The buffer stride.
  6920. * @param {number} [offset=0] - The buffer offset.
  6921. * @param {number} [usage=StaticDrawUsage] - The buffer usage.
  6922. * @param {boolean} [instanced=false] - Whether the buffer is instanced.
  6923. * @returns {BufferAttributeNode|Node} The buffer attribute node.
  6924. */
  6925. function createBufferAttribute( array, type = null, stride = 0, offset = 0, usage = StaticDrawUsage, instanced = false ) {
  6926. if ( type === 'mat3' || ( type === null && array.itemSize === 9 ) ) {
  6927. return mat3(
  6928. new BufferAttributeNode( array, 'vec3', 9, 0 ).setUsage( usage ).setInstanced( instanced ),
  6929. new BufferAttributeNode( array, 'vec3', 9, 3 ).setUsage( usage ).setInstanced( instanced ),
  6930. new BufferAttributeNode( array, 'vec3', 9, 6 ).setUsage( usage ).setInstanced( instanced )
  6931. );
  6932. } else if ( type === 'mat4' || ( type === null && array.itemSize === 16 ) ) {
  6933. return mat4(
  6934. new BufferAttributeNode( array, 'vec4', 16, 0 ).setUsage( usage ).setInstanced( instanced ),
  6935. new BufferAttributeNode( array, 'vec4', 16, 4 ).setUsage( usage ).setInstanced( instanced ),
  6936. new BufferAttributeNode( array, 'vec4', 16, 8 ).setUsage( usage ).setInstanced( instanced ),
  6937. new BufferAttributeNode( array, 'vec4', 16, 12 ).setUsage( usage ).setInstanced( instanced )
  6938. );
  6939. }
  6940. return new BufferAttributeNode( array, type, stride, offset );
  6941. }
  6942. /**
  6943. * TSL function for creating a buffer attribute node.
  6944. *
  6945. * @tsl
  6946. * @function
  6947. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6948. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6949. * @param {number} [stride=0] - The buffer stride.
  6950. * @param {number} [offset=0] - The buffer offset.
  6951. * @returns {BufferAttributeNode|Node}
  6952. */
  6953. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset );
  6954. /**
  6955. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  6956. * Use this function if attribute data are updated per frame.
  6957. *
  6958. * @tsl
  6959. * @function
  6960. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6961. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6962. * @param {number} [stride=0] - The buffer stride.
  6963. * @param {number} [offset=0] - The buffer offset.
  6964. * @returns {BufferAttributeNode|Node}
  6965. */
  6966. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, DynamicDrawUsage );
  6967. /**
  6968. * TSL function for creating a buffer attribute node but with enabled instancing
  6969. *
  6970. * @tsl
  6971. * @function
  6972. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6973. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6974. * @param {number} [stride=0] - The buffer stride.
  6975. * @param {number} [offset=0] - The buffer offset.
  6976. * @returns {BufferAttributeNode|Node}
  6977. */
  6978. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, StaticDrawUsage, true );
  6979. /**
  6980. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  6981. *
  6982. * @tsl
  6983. * @function
  6984. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6985. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6986. * @param {number} [stride=0] - The buffer stride.
  6987. * @param {number} [offset=0] - The buffer offset.
  6988. * @returns {BufferAttributeNode|Node}
  6989. */
  6990. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, DynamicDrawUsage, true );
  6991. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  6992. /**
  6993. * TODO
  6994. *
  6995. * @augments Node
  6996. */
  6997. class ComputeNode extends Node {
  6998. static get type() {
  6999. return 'ComputeNode';
  7000. }
  7001. /**
  7002. * Constructs a new compute node.
  7003. *
  7004. * @param {Node} computeNode - TODO
  7005. * @param {Array<number>} workgroupSize - TODO.
  7006. */
  7007. constructor( computeNode, workgroupSize ) {
  7008. super( 'void' );
  7009. /**
  7010. * This flag can be used for type testing.
  7011. *
  7012. * @type {boolean}
  7013. * @readonly
  7014. * @default true
  7015. */
  7016. this.isComputeNode = true;
  7017. /**
  7018. * TODO
  7019. *
  7020. * @type {Node}
  7021. */
  7022. this.computeNode = computeNode;
  7023. /**
  7024. * TODO
  7025. *
  7026. * @type {Array<number>}
  7027. * @default [ 64 ]
  7028. */
  7029. this.workgroupSize = workgroupSize;
  7030. /**
  7031. * TODO
  7032. *
  7033. * @type {number|Array<number>}
  7034. */
  7035. this.count = null;
  7036. /**
  7037. * TODO
  7038. *
  7039. * @type {number}
  7040. */
  7041. this.version = 1;
  7042. /**
  7043. * The name or label of the uniform.
  7044. *
  7045. * @type {string}
  7046. * @default ''
  7047. */
  7048. this.name = '';
  7049. /**
  7050. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  7051. * is executed once per object by default.
  7052. *
  7053. * @type {string}
  7054. * @default 'object'
  7055. */
  7056. this.updateBeforeType = NodeUpdateType.OBJECT;
  7057. /**
  7058. * TODO
  7059. *
  7060. * @type {?Function}
  7061. */
  7062. this.onInitFunction = null;
  7063. }
  7064. /**
  7065. * TODO
  7066. *
  7067. * @param {number|Array<number>} count - Array with [ x, y, z ] values for dispatch or a single number for the count
  7068. * @return {ComputeNode}
  7069. */
  7070. setCount( count ) {
  7071. this.count = count;
  7072. return this;
  7073. }
  7074. /**
  7075. * TODO
  7076. *
  7077. * @return {number|Array<number>}
  7078. */
  7079. getCount() {
  7080. return this.count;
  7081. }
  7082. /**
  7083. * Executes the `dispose` event for this node.
  7084. */
  7085. dispose() {
  7086. this.dispatchEvent( { type: 'dispose' } );
  7087. }
  7088. /**
  7089. * Sets the {@link ComputeNode#name} property.
  7090. *
  7091. * @param {string} name - The name of the uniform.
  7092. * @return {ComputeNode} A reference to this node.
  7093. */
  7094. setName( name ) {
  7095. this.name = name;
  7096. return this;
  7097. }
  7098. /**
  7099. * Sets the {@link ComputeNode#name} property.
  7100. *
  7101. * @deprecated
  7102. * @param {string} name - The name of the uniform.
  7103. * @return {ComputeNode} A reference to this node.
  7104. */
  7105. label( name ) {
  7106. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  7107. return this.setName( name );
  7108. }
  7109. /**
  7110. * TODO
  7111. *
  7112. * @param {Function} callback - TODO.
  7113. * @return {ComputeNode} A reference to this node.
  7114. */
  7115. onInit( callback ) {
  7116. this.onInitFunction = callback;
  7117. return this;
  7118. }
  7119. /**
  7120. * The method execute the compute for this node.
  7121. *
  7122. * @param {NodeFrame} frame - A reference to the current node frame.
  7123. */
  7124. updateBefore( { renderer } ) {
  7125. renderer.compute( this );
  7126. }
  7127. setup( builder ) {
  7128. const result = this.computeNode.build( builder );
  7129. if ( result ) {
  7130. const properties = builder.getNodeProperties( this );
  7131. properties.outputComputeNode = result.outputNode;
  7132. result.outputNode = null;
  7133. }
  7134. return result;
  7135. }
  7136. generate( builder, output ) {
  7137. const { shaderStage } = builder;
  7138. if ( shaderStage === 'compute' ) {
  7139. const snippet = this.computeNode.build( builder, 'void' );
  7140. if ( snippet !== '' ) {
  7141. builder.addLineFlowCode( snippet, this );
  7142. }
  7143. } else {
  7144. const properties = builder.getNodeProperties( this );
  7145. const outputComputeNode = properties.outputComputeNode;
  7146. if ( outputComputeNode ) {
  7147. return outputComputeNode.build( builder, output );
  7148. }
  7149. }
  7150. }
  7151. }
  7152. /**
  7153. * TSL function for creating a compute kernel node.
  7154. *
  7155. * @tsl
  7156. * @function
  7157. * @param {Node} node - TODO
  7158. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  7159. * @returns {AtomicFunctionNode}
  7160. */
  7161. const computeKernel = ( node, workgroupSize = [ 64 ] ) => {
  7162. if ( workgroupSize.length === 0 || workgroupSize.length > 3 ) {
  7163. error( 'TSL: compute() workgroupSize must have 1, 2, or 3 elements' );
  7164. }
  7165. for ( let i = 0; i < workgroupSize.length; i ++ ) {
  7166. const val = workgroupSize[ i ];
  7167. if ( typeof val !== 'number' || val <= 0 || ! Number.isInteger( val ) ) {
  7168. error( `TSL: compute() workgroupSize element at index [ ${ i } ] must be a positive integer` );
  7169. }
  7170. }
  7171. // Implicit fill-up to [ x, y, z ] with 1s, just like WGSL treats @workgroup_size when fewer dimensions are specified
  7172. while ( workgroupSize.length < 3 ) workgroupSize.push( 1 );
  7173. //
  7174. return nodeObject( new ComputeNode( nodeObject( node ), workgroupSize ) );
  7175. };
  7176. /**
  7177. * TSL function for creating a compute node.
  7178. *
  7179. * @tsl
  7180. * @function
  7181. * @param {Node} node - TODO
  7182. * @param {number|Array<number>} count - TODO.
  7183. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  7184. * @returns {AtomicFunctionNode}
  7185. */
  7186. const compute = ( node, count, workgroupSize ) => computeKernel( node, workgroupSize ).setCount( count );
  7187. addMethodChaining( 'compute', compute );
  7188. addMethodChaining( 'computeKernel', computeKernel );
  7189. /**
  7190. * This node can be used as a cache management component for another node.
  7191. * Caching is in general used by default in {@link NodeBuilder} but this node
  7192. * allows the usage of a shared parent cache during the build process.
  7193. *
  7194. * @augments Node
  7195. */
  7196. class IsolateNode extends Node {
  7197. static get type() {
  7198. return 'IsolateNode';
  7199. }
  7200. /**
  7201. * Constructs a new cache node.
  7202. *
  7203. * @param {Node} node - The node that should be cached.
  7204. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7205. */
  7206. constructor( node, parent = true ) {
  7207. super();
  7208. /**
  7209. * The node that should be cached.
  7210. *
  7211. * @type {Node}
  7212. */
  7213. this.node = node;
  7214. /**
  7215. * Whether this node refers to a shared parent cache or not.
  7216. *
  7217. * @type {boolean}
  7218. * @default true
  7219. */
  7220. this.parent = parent;
  7221. /**
  7222. * This flag can be used for type testing.
  7223. *
  7224. * @type {boolean}
  7225. * @readonly
  7226. * @default true
  7227. */
  7228. this.isIsolateNode = true;
  7229. }
  7230. getNodeType( builder ) {
  7231. const previousCache = builder.getCache();
  7232. const cache = builder.getCacheFromNode( this, this.parent );
  7233. builder.setCache( cache );
  7234. const nodeType = this.node.getNodeType( builder );
  7235. builder.setCache( previousCache );
  7236. return nodeType;
  7237. }
  7238. build( builder, ...params ) {
  7239. const previousCache = builder.getCache();
  7240. const cache = builder.getCacheFromNode( this, this.parent );
  7241. builder.setCache( cache );
  7242. const data = this.node.build( builder, ...params );
  7243. builder.setCache( previousCache );
  7244. return data;
  7245. }
  7246. setParent( parent ) {
  7247. this.parent = parent;
  7248. return this;
  7249. }
  7250. getParent() {
  7251. return this.parent;
  7252. }
  7253. }
  7254. /**
  7255. * TSL function for creating a cache node.
  7256. *
  7257. * @tsl
  7258. * @function
  7259. * @param {Node} node - The node that should be cached.
  7260. * @returns {IsolateNode}
  7261. */
  7262. const isolate = ( node ) => new IsolateNode( nodeObject( node ) );
  7263. /**
  7264. * TSL function for creating a cache node.
  7265. *
  7266. * @tsl
  7267. * @function
  7268. * @deprecated
  7269. * @param {Node} node - The node that should be cached.
  7270. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7271. * @returns {IsolateNode}
  7272. */
  7273. function cache( node, parent = true ) {
  7274. warn( 'TSL: "cache()" has been deprecated. Use "isolate()" instead.' ); // @deprecated r181
  7275. return isolate( node ).setParent( parent );
  7276. }
  7277. addMethodChaining( 'cache', cache );
  7278. addMethodChaining( 'isolate', isolate );
  7279. /**
  7280. * The class generates the code of a given node but returns another node in the output.
  7281. * This can be used to call a method or node that does not return a value, i.e.
  7282. * type `void` on an input where returning a value is required. Example:
  7283. *
  7284. * ```js
  7285. * material.colorNode = myColor.bypass( runVoidFn() )
  7286. *```
  7287. *
  7288. * @augments Node
  7289. */
  7290. class BypassNode extends Node {
  7291. static get type() {
  7292. return 'BypassNode';
  7293. }
  7294. /**
  7295. * Constructs a new bypass node.
  7296. *
  7297. * @param {Node} outputNode - The output node.
  7298. * @param {Node} callNode - The call node.
  7299. */
  7300. constructor( outputNode, callNode ) {
  7301. super();
  7302. /**
  7303. * This flag can be used for type testing.
  7304. *
  7305. * @type {boolean}
  7306. * @readonly
  7307. * @default true
  7308. */
  7309. this.isBypassNode = true;
  7310. /**
  7311. * The output node.
  7312. *
  7313. * @type {Node}
  7314. */
  7315. this.outputNode = outputNode;
  7316. /**
  7317. * The call node.
  7318. *
  7319. * @type {Node}
  7320. */
  7321. this.callNode = callNode;
  7322. }
  7323. getNodeType( builder ) {
  7324. return this.outputNode.getNodeType( builder );
  7325. }
  7326. generate( builder ) {
  7327. const snippet = this.callNode.build( builder, 'void' );
  7328. if ( snippet !== '' ) {
  7329. builder.addLineFlowCode( snippet, this );
  7330. }
  7331. return this.outputNode.build( builder );
  7332. }
  7333. }
  7334. /**
  7335. * TSL function for creating a bypass node.
  7336. *
  7337. * @tsl
  7338. * @function
  7339. * @param {Node} outputNode - The output node.
  7340. * @param {Node} callNode - The call node.
  7341. * @returns {BypassNode}
  7342. */
  7343. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  7344. addMethodChaining( 'bypass', bypass );
  7345. /**
  7346. * This node allows to remap a node value from one range into another. E.g a value of
  7347. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  7348. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  7349. *
  7350. * @augments Node
  7351. */
  7352. class RemapNode extends Node {
  7353. static get type() {
  7354. return 'RemapNode';
  7355. }
  7356. /**
  7357. * Constructs a new remap node.
  7358. *
  7359. * @param {Node} node - The node that should be remapped.
  7360. * @param {Node} inLowNode - The source or current lower bound of the range.
  7361. * @param {Node} inHighNode - The source or current upper bound of the range.
  7362. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  7363. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  7364. */
  7365. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  7366. super();
  7367. /**
  7368. * The node that should be remapped.
  7369. *
  7370. * @type {Node}
  7371. */
  7372. this.node = node;
  7373. /**
  7374. * The source or current lower bound of the range.
  7375. *
  7376. * @type {Node}
  7377. */
  7378. this.inLowNode = inLowNode;
  7379. /**
  7380. * The source or current upper bound of the range.
  7381. *
  7382. * @type {Node}
  7383. */
  7384. this.inHighNode = inHighNode;
  7385. /**
  7386. * The target lower bound of the range.
  7387. *
  7388. * @type {Node}
  7389. * @default float(0)
  7390. */
  7391. this.outLowNode = outLowNode;
  7392. /**
  7393. * The target upper bound of the range.
  7394. *
  7395. * @type {Node}
  7396. * @default float(1)
  7397. */
  7398. this.outHighNode = outHighNode;
  7399. /**
  7400. * Whether the node value should be clamped before
  7401. * remapping it to the target range.
  7402. *
  7403. * @type {boolean}
  7404. * @default true
  7405. */
  7406. this.doClamp = true;
  7407. }
  7408. setup() {
  7409. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  7410. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  7411. if ( doClamp === true ) t = t.clamp();
  7412. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  7413. }
  7414. }
  7415. /**
  7416. * TSL function for creating a remap node.
  7417. *
  7418. * @tsl
  7419. * @function
  7420. * @param {Node} node - The node that should be remapped.
  7421. * @param {Node} inLowNode - The source or current lower bound of the range.
  7422. * @param {Node} inHighNode - The source or current upper bound of the range.
  7423. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7424. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7425. * @returns {RemapNode}
  7426. */
  7427. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  7428. /**
  7429. * TSL function for creating a remap node, but with enabled clamping.
  7430. *
  7431. * @tsl
  7432. * @function
  7433. * @param {Node} node - The node that should be remapped.
  7434. * @param {Node} inLowNode - The source or current lower bound of the range.
  7435. * @param {Node} inHighNode - The source or current upper bound of the range.
  7436. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7437. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7438. * @returns {RemapNode}
  7439. */
  7440. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  7441. addMethodChaining( 'remap', remap );
  7442. addMethodChaining( 'remapClamp', remapClamp );
  7443. /**
  7444. * This class can be used to implement basic expressions in shader code.
  7445. * Basic examples for that are `return`, `continue` or `discard` statements.
  7446. *
  7447. * @augments Node
  7448. */
  7449. class ExpressionNode extends Node {
  7450. static get type() {
  7451. return 'ExpressionNode';
  7452. }
  7453. /**
  7454. * Constructs a new expression node.
  7455. *
  7456. * @param {string} [snippet=''] - The native code snippet.
  7457. * @param {string} [nodeType='void'] - The node type.
  7458. */
  7459. constructor( snippet = '', nodeType = 'void' ) {
  7460. super( nodeType );
  7461. /**
  7462. * The native code snippet.
  7463. *
  7464. * @type {string}
  7465. * @default ''
  7466. */
  7467. this.snippet = snippet;
  7468. }
  7469. generate( builder, output ) {
  7470. const type = this.getNodeType( builder );
  7471. const snippet = this.snippet;
  7472. if ( type === 'void' ) {
  7473. builder.addLineFlowCode( snippet, this );
  7474. } else {
  7475. return builder.format( snippet, type, output );
  7476. }
  7477. }
  7478. }
  7479. /**
  7480. * TSL function for creating an expression node.
  7481. *
  7482. * @tsl
  7483. * @function
  7484. * @param {string} [snippet] - The native code snippet.
  7485. * @param {?string} [nodeType='void'] - The node type.
  7486. * @returns {ExpressionNode}
  7487. */
  7488. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  7489. /**
  7490. * Represents a `discard` shader operation in TSL.
  7491. *
  7492. * @tsl
  7493. * @function
  7494. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  7495. * @return {Node} The `discard` expression.
  7496. */
  7497. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  7498. /**
  7499. * Represents a `return` shader operation in TSL.
  7500. *
  7501. * @tsl
  7502. * @function
  7503. * @return {ExpressionNode} The `return` expression.
  7504. */
  7505. const Return = () => expression( 'return' ).toStack();
  7506. addMethodChaining( 'discard', Discard );
  7507. /**
  7508. * Normally, tone mapping and color conversion happens automatically
  7509. * before outputting pixel too the default (screen) framebuffer. In certain
  7510. * post processing setups this happens to late because certain effects
  7511. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  7512. * to apply tone mapping and color space conversion at an arbitrary point
  7513. * in the effect chain.
  7514. *
  7515. * When applying tone mapping and color space conversion manually with this node,
  7516. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  7517. *
  7518. * ```js
  7519. * const postProcessing = new PostProcessing( renderer );
  7520. * postProcessing.outputColorTransform = false;
  7521. *
  7522. * const scenePass = pass( scene, camera );
  7523. * const outputPass = renderOutput( scenePass );
  7524. *
  7525. * postProcessing.outputNode = outputPass;
  7526. * ```
  7527. *
  7528. * @augments TempNode
  7529. */
  7530. class RenderOutputNode extends TempNode {
  7531. static get type() {
  7532. return 'RenderOutputNode';
  7533. }
  7534. /**
  7535. * Constructs a new render output node.
  7536. *
  7537. * @param {Node} colorNode - The color node to process.
  7538. * @param {?number} toneMapping - The tone mapping type.
  7539. * @param {?string} outputColorSpace - The output color space.
  7540. */
  7541. constructor( colorNode, toneMapping, outputColorSpace ) {
  7542. super( 'vec4' );
  7543. /**
  7544. * The color node to process.
  7545. *
  7546. * @type {Node}
  7547. */
  7548. this.colorNode = colorNode;
  7549. /**
  7550. * The tone mapping type.
  7551. *
  7552. * @private
  7553. * @type {?number}
  7554. */
  7555. this._toneMapping = toneMapping;
  7556. /**
  7557. * The output color space.
  7558. *
  7559. * @type {?string}
  7560. */
  7561. this.outputColorSpace = outputColorSpace;
  7562. /**
  7563. * This flag can be used for type testing.
  7564. *
  7565. * @type {boolean}
  7566. * @readonly
  7567. * @default true
  7568. */
  7569. this.isRenderOutputNode = true;
  7570. }
  7571. /**
  7572. * Sets the tone mapping type.
  7573. *
  7574. * @param {number} value - The tone mapping type.
  7575. * @return {ToneMappingNode} A reference to this node.
  7576. */
  7577. setToneMapping( value ) {
  7578. this._toneMapping = value;
  7579. return this;
  7580. }
  7581. /**
  7582. * Gets the tone mapping type.
  7583. *
  7584. * @returns {number} The tone mapping type.
  7585. */
  7586. getToneMapping() {
  7587. return this._toneMapping;
  7588. }
  7589. setup( { context } ) {
  7590. let outputNode = this.colorNode || context.color;
  7591. // tone mapping
  7592. const toneMapping = ( this._toneMapping !== null ? this._toneMapping : context.toneMapping ) || NoToneMapping;
  7593. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  7594. if ( toneMapping !== NoToneMapping ) {
  7595. outputNode = outputNode.toneMapping( toneMapping );
  7596. }
  7597. // working to output color space
  7598. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  7599. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  7600. }
  7601. return outputNode;
  7602. }
  7603. }
  7604. /**
  7605. * TSL function for creating a posterize node.
  7606. *
  7607. * @tsl
  7608. * @function
  7609. * @param {Node} color - The color node to process.
  7610. * @param {?number} [toneMapping=null] - The tone mapping type.
  7611. * @param {?string} [outputColorSpace=null] - The output color space.
  7612. * @returns {RenderOutputNode}
  7613. */
  7614. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  7615. addMethodChaining( 'renderOutput', renderOutput );
  7616. class DebugNode extends TempNode {
  7617. static get type() {
  7618. return 'DebugNode';
  7619. }
  7620. constructor( node, callback = null ) {
  7621. super();
  7622. this.node = node;
  7623. this.callback = callback;
  7624. }
  7625. getNodeType( builder ) {
  7626. return this.node.getNodeType( builder );
  7627. }
  7628. setup( builder ) {
  7629. return this.node.build( builder );
  7630. }
  7631. analyze( builder ) {
  7632. return this.node.build( builder );
  7633. }
  7634. generate( builder ) {
  7635. const callback = this.callback;
  7636. const snippet = this.node.build( builder );
  7637. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  7638. const border = '-'.repeat( title.length );
  7639. let code = '';
  7640. code += '// #' + title + '#\n';
  7641. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  7642. code += '/* ... */ ' + snippet + ' /* ... */\n';
  7643. code += '// #' + border + '#\n';
  7644. if ( callback !== null ) {
  7645. callback( builder, code );
  7646. } else {
  7647. log$1( code );
  7648. }
  7649. return snippet;
  7650. }
  7651. }
  7652. /**
  7653. * TSL function for creating a debug node.
  7654. *
  7655. * @tsl
  7656. * @function
  7657. * @param {Node} node - The node to debug.
  7658. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  7659. * @returns {DebugNode}
  7660. */
  7661. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) ).toStack();
  7662. addMethodChaining( 'debug', debug );
  7663. /**
  7664. * InspectorBase is the base class for all inspectors.
  7665. *
  7666. * @class InspectorBase
  7667. */
  7668. class InspectorBase {
  7669. /**
  7670. * Creates a new InspectorBase.
  7671. */
  7672. constructor() {
  7673. /**
  7674. * The renderer associated with this inspector.
  7675. *
  7676. * @type {WebGLRenderer}
  7677. * @private
  7678. */
  7679. this._renderer = null;
  7680. /**
  7681. * The current frame being processed.
  7682. *
  7683. * @type {Object}
  7684. */
  7685. this.currentFrame = null;
  7686. }
  7687. /**
  7688. * Returns the node frame for the current renderer.
  7689. *
  7690. * @return {Object} The node frame.
  7691. */
  7692. get nodeFrame() {
  7693. return this._renderer._nodes.nodeFrame;
  7694. }
  7695. /**
  7696. * Sets the renderer for this inspector.
  7697. *
  7698. * @param {WebGLRenderer} renderer - The renderer to associate with this inspector.
  7699. * @return {InspectorBase} This inspector instance.
  7700. */
  7701. setRenderer( renderer ) {
  7702. this._renderer = renderer;
  7703. return this;
  7704. }
  7705. /**
  7706. * Returns the renderer associated with this inspector.
  7707. *
  7708. * @return {WebGLRenderer} The associated renderer.
  7709. */
  7710. getRenderer() {
  7711. return this._renderer;
  7712. }
  7713. /**
  7714. * Initializes the inspector.
  7715. */
  7716. init() { }
  7717. /**
  7718. * Called when a frame begins.
  7719. */
  7720. begin() { }
  7721. /**
  7722. * Called when a frame ends.
  7723. */
  7724. finish() { }
  7725. /**
  7726. * Inspects a node.
  7727. *
  7728. * @param {Node} node - The node to inspect.
  7729. */
  7730. inspect( /*node*/ ) { }
  7731. /**
  7732. * When a compute operation is performed.
  7733. *
  7734. * @param {ComputeNode} computeNode - The compute node being executed.
  7735. * @param {number|Array<number>} dispatchSizeOrCount - The dispatch size or count.
  7736. */
  7737. computeAsync( /*computeNode, dispatchSizeOrCount*/ ) { }
  7738. /**
  7739. * Called when a compute operation begins.
  7740. *
  7741. * @param {string} uid - A unique identifier for the render context.
  7742. * @param {ComputeNode} computeNode - The compute node being executed.
  7743. */
  7744. beginCompute( /*uid, computeNode*/ ) { }
  7745. /**
  7746. * Called when a compute operation ends.
  7747. *
  7748. * @param {string} uid - A unique identifier for the render context.
  7749. * @param {ComputeNode} computeNode - The compute node being executed.
  7750. */
  7751. finishCompute( /*uid*/ ) { }
  7752. /**
  7753. * Called when a render operation begins.
  7754. *
  7755. * @param {string} uid - A unique identifier for the render context.
  7756. * @param {Scene} scene - The scene being rendered.
  7757. * @param {Camera} camera - The camera being used for rendering.
  7758. * @param {?WebGLRenderTarget} renderTarget - The render target, if any.
  7759. */
  7760. beginRender( /*uid, scene, camera, renderTarget*/ ) { }
  7761. /**
  7762. * Called when an animation loop ends.
  7763. *
  7764. * @param {string} uid - A unique identifier for the render context.
  7765. */
  7766. finishRender( /*uid*/ ) { }
  7767. /**
  7768. * Called when a texture copy operation is performed.
  7769. *
  7770. * @param {Texture} srcTexture - The source texture.
  7771. * @param {Texture} dstTexture - The destination texture.
  7772. */
  7773. copyTextureToTexture( /*srcTexture, dstTexture*/ ) { }
  7774. /**
  7775. * Called when a framebuffer copy operation is performed.
  7776. *
  7777. * @param {Texture} framebufferTexture - The texture associated with the framebuffer.
  7778. */
  7779. copyFramebufferToTexture( /*framebufferTexture*/ ) { }
  7780. }
  7781. /**
  7782. * InspectorNode is a wrapper node that allows inspection of node values during rendering.
  7783. * It can be used to debug or analyze node outputs in the rendering pipeline.
  7784. *
  7785. * @augments Node
  7786. */
  7787. class InspectorNode extends Node {
  7788. /**
  7789. * Returns the type of the node.
  7790. *
  7791. * @returns {string}
  7792. */
  7793. static get type() {
  7794. return 'InspectorNode';
  7795. }
  7796. /**
  7797. * Creates an InspectorNode.
  7798. *
  7799. * @param {Node} node - The node to inspect.
  7800. * @param {string} [name=''] - Optional name for the inspector node.
  7801. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7802. */
  7803. constructor( node, name = '', callback = null ) {
  7804. super();
  7805. this.node = node;
  7806. this.name = name;
  7807. this.callback = callback;
  7808. this.updateType = NodeUpdateType.FRAME;
  7809. this.isInspectorNode = true;
  7810. }
  7811. /**
  7812. * Returns the name of the inspector node.
  7813. *
  7814. * @returns {string}
  7815. */
  7816. getName() {
  7817. return this.name || this.node.name;
  7818. }
  7819. /**
  7820. * Updates the inspector node, allowing inspection of the wrapped node.
  7821. *
  7822. * @param {NodeFrame} frame - A reference to the current node frame.
  7823. */
  7824. update( frame ) {
  7825. frame.renderer.inspector.inspect( this );
  7826. }
  7827. /**
  7828. * Returns the type of the wrapped node.
  7829. *
  7830. * @param {NodeBuilder} builder - The node builder.
  7831. * @returns {string}
  7832. */
  7833. getNodeType( builder ) {
  7834. return this.node.getNodeType( builder );
  7835. }
  7836. /**
  7837. * Sets up the inspector node.
  7838. *
  7839. * @param {NodeBuilder} builder - The node builder.
  7840. * @returns {Node} The setup node.
  7841. */
  7842. setup( builder ) {
  7843. let node = this.node;
  7844. if ( builder.context.inspector === true && this.callback !== null ) {
  7845. node = this.callback( node );
  7846. }
  7847. if ( builder.renderer.backend.isWebGPUBackend !== true && builder.renderer.inspector.constructor !== InspectorBase ) {
  7848. warnOnce( 'TSL: ".toInspector()" is only available with WebGPU.' );
  7849. }
  7850. return node;
  7851. }
  7852. }
  7853. /**
  7854. * Creates an inspector node to wrap around a given node for inspection purposes.
  7855. *
  7856. * @tsl
  7857. * @param {Node} node - The node to inspect.
  7858. * @param {string} [name=''] - Optional name for the inspector node.
  7859. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7860. * @returns {Node} The inspector node.
  7861. */
  7862. function inspector( node, name = '', callback = null ) {
  7863. node = nodeObject( node );
  7864. return node.before( new InspectorNode( node, name, callback ) );
  7865. }
  7866. addMethodChaining( 'toInspector', inspector );
  7867. function addNodeElement( name/*, nodeElement*/ ) {
  7868. warn( 'TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  7869. }
  7870. /**
  7871. * Base class for representing shader attributes as nodes.
  7872. *
  7873. * @augments Node
  7874. */
  7875. class AttributeNode extends Node {
  7876. static get type() {
  7877. return 'AttributeNode';
  7878. }
  7879. /**
  7880. * Constructs a new attribute node.
  7881. *
  7882. * @param {string} attributeName - The name of the attribute.
  7883. * @param {?string} nodeType - The node type.
  7884. */
  7885. constructor( attributeName, nodeType = null ) {
  7886. super( nodeType );
  7887. /**
  7888. * `AttributeNode` sets this property to `true` by default.
  7889. *
  7890. * @type {boolean}
  7891. * @default true
  7892. */
  7893. this.global = true;
  7894. this._attributeName = attributeName;
  7895. }
  7896. getHash( builder ) {
  7897. return this.getAttributeName( builder );
  7898. }
  7899. getNodeType( builder ) {
  7900. let nodeType = this.nodeType;
  7901. if ( nodeType === null ) {
  7902. const attributeName = this.getAttributeName( builder );
  7903. if ( builder.hasGeometryAttribute( attributeName ) ) {
  7904. const attribute = builder.geometry.getAttribute( attributeName );
  7905. nodeType = builder.getTypeFromAttribute( attribute );
  7906. } else {
  7907. nodeType = 'float';
  7908. }
  7909. }
  7910. return nodeType;
  7911. }
  7912. /**
  7913. * Sets the attribute name to the given value. The method can be
  7914. * overwritten in derived classes if the final name must be computed
  7915. * analytically.
  7916. *
  7917. * @param {string} attributeName - The name of the attribute.
  7918. * @return {AttributeNode} A reference to this node.
  7919. */
  7920. setAttributeName( attributeName ) {
  7921. this._attributeName = attributeName;
  7922. return this;
  7923. }
  7924. /**
  7925. * Returns the attribute name of this node. The method can be
  7926. * overwritten in derived classes if the final name must be computed
  7927. * analytically.
  7928. *
  7929. * @param {NodeBuilder} builder - The current node builder.
  7930. * @return {string} The attribute name.
  7931. */
  7932. getAttributeName( /*builder*/ ) {
  7933. return this._attributeName;
  7934. }
  7935. generate( builder ) {
  7936. const attributeName = this.getAttributeName( builder );
  7937. const nodeType = this.getNodeType( builder );
  7938. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  7939. if ( geometryAttribute === true ) {
  7940. const attribute = builder.geometry.getAttribute( attributeName );
  7941. const attributeType = builder.getTypeFromAttribute( attribute );
  7942. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  7943. if ( builder.shaderStage === 'vertex' ) {
  7944. return builder.format( nodeAttribute.name, attributeType, nodeType );
  7945. } else {
  7946. const nodeVarying = varying( this );
  7947. return nodeVarying.build( builder, nodeType );
  7948. }
  7949. } else {
  7950. warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  7951. return builder.generateConst( nodeType );
  7952. }
  7953. }
  7954. serialize( data ) {
  7955. super.serialize( data );
  7956. data.global = this.global;
  7957. data._attributeName = this._attributeName;
  7958. }
  7959. deserialize( data ) {
  7960. super.deserialize( data );
  7961. this.global = data.global;
  7962. this._attributeName = data._attributeName;
  7963. }
  7964. }
  7965. /**
  7966. * TSL function for creating an attribute node.
  7967. *
  7968. * @tsl
  7969. * @function
  7970. * @param {string} name - The name of the attribute.
  7971. * @param {?string} [nodeType=null] - The node type.
  7972. * @returns {AttributeNode}
  7973. */
  7974. const attribute = ( name, nodeType = null ) => nodeObject( new AttributeNode( name, nodeType ) );
  7975. /**
  7976. * TSL function for creating an uv attribute node with the given index.
  7977. *
  7978. * @tsl
  7979. * @function
  7980. * @param {number} [index=0] - The uv index.
  7981. * @return {AttributeNode<vec2>} The uv attribute node.
  7982. */
  7983. const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  7984. /**
  7985. * A node that represents the dimensions of a texture. The texture size is
  7986. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  7987. * or `textureSize()`.
  7988. *
  7989. * @augments Node
  7990. */
  7991. class TextureSizeNode extends Node {
  7992. static get type() {
  7993. return 'TextureSizeNode';
  7994. }
  7995. /**
  7996. * Constructs a new texture size node.
  7997. *
  7998. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7999. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  8000. */
  8001. constructor( textureNode, levelNode = null ) {
  8002. super( 'uvec2' );
  8003. /**
  8004. * This flag can be used for type testing.
  8005. *
  8006. * @type {boolean}
  8007. * @readonly
  8008. * @default true
  8009. */
  8010. this.isTextureSizeNode = true;
  8011. /**
  8012. * A texture node which size should be retrieved.
  8013. *
  8014. * @type {TextureNode}
  8015. */
  8016. this.textureNode = textureNode;
  8017. /**
  8018. * A level node which defines the requested mip.
  8019. *
  8020. * @type {Node<int>}
  8021. * @default null
  8022. */
  8023. this.levelNode = levelNode;
  8024. }
  8025. generate( builder, output ) {
  8026. const textureProperty = this.textureNode.build( builder, 'property' );
  8027. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  8028. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  8029. }
  8030. }
  8031. /**
  8032. * TSL function for creating a texture size node.
  8033. *
  8034. * @tsl
  8035. * @function
  8036. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  8037. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  8038. * @returns {TextureSizeNode}
  8039. */
  8040. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  8041. /**
  8042. * A special type of uniform node that computes the
  8043. * maximum mipmap level for a given texture node.
  8044. *
  8045. * ```js
  8046. * const level = maxMipLevel( textureNode );
  8047. * ```
  8048. *
  8049. * @augments UniformNode
  8050. */
  8051. class MaxMipLevelNode extends UniformNode {
  8052. static get type() {
  8053. return 'MaxMipLevelNode';
  8054. }
  8055. /**
  8056. * Constructs a new max mip level node.
  8057. *
  8058. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  8059. */
  8060. constructor( textureNode ) {
  8061. super( 0 );
  8062. /**
  8063. * The texture node to compute the max mip level for.
  8064. *
  8065. * @private
  8066. * @type {TextureNode}
  8067. */
  8068. this._textureNode = textureNode;
  8069. /**
  8070. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  8071. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  8072. *
  8073. * @type {string}
  8074. * @default 'frame'
  8075. */
  8076. this.updateType = NodeUpdateType.FRAME;
  8077. }
  8078. /**
  8079. * The texture node to compute the max mip level for.
  8080. *
  8081. * @readonly
  8082. * @type {TextureNode}
  8083. */
  8084. get textureNode() {
  8085. return this._textureNode;
  8086. }
  8087. /**
  8088. * The texture.
  8089. *
  8090. * @readonly
  8091. * @type {Texture}
  8092. */
  8093. get texture() {
  8094. return this._textureNode.value;
  8095. }
  8096. update() {
  8097. const texture = this.texture;
  8098. const images = texture.images;
  8099. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  8100. if ( image && image.width !== undefined ) {
  8101. const { width, height } = image;
  8102. this.value = Math.log2( Math.max( width, height ) );
  8103. }
  8104. }
  8105. }
  8106. /**
  8107. * TSL function for creating a max mip level node.
  8108. *
  8109. * @tsl
  8110. * @function
  8111. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  8112. * @returns {MaxMipLevelNode}
  8113. */
  8114. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  8115. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  8116. /**
  8117. * This type of uniform node represents a 2D texture.
  8118. *
  8119. * @augments UniformNode
  8120. */
  8121. class TextureNode extends UniformNode {
  8122. static get type() {
  8123. return 'TextureNode';
  8124. }
  8125. /**
  8126. * Constructs a new texture node.
  8127. *
  8128. * @param {Texture} [value=EmptyTexture] - The texture.
  8129. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8130. * @param {?Node<int>} [levelNode=null] - The level node.
  8131. * @param {?Node<float>} [biasNode=null] - The bias node.
  8132. */
  8133. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  8134. super( value );
  8135. /**
  8136. * This flag can be used for type testing.
  8137. *
  8138. * @type {boolean}
  8139. * @readonly
  8140. * @default true
  8141. */
  8142. this.isTextureNode = true;
  8143. /**
  8144. * Represents the texture coordinates.
  8145. *
  8146. * @type {?Node<vec2|vec3>}
  8147. * @default null
  8148. */
  8149. this.uvNode = uvNode;
  8150. /**
  8151. * Represents the mip level that should be selected.
  8152. *
  8153. * @type {?Node<int>}
  8154. * @default null
  8155. */
  8156. this.levelNode = levelNode;
  8157. /**
  8158. * Represents the bias to be applied during level-of-detail computation.
  8159. *
  8160. * @type {?Node<float>}
  8161. * @default null
  8162. */
  8163. this.biasNode = biasNode;
  8164. /**
  8165. * Represents a reference value a texture sample is compared to.
  8166. *
  8167. * @type {?Node<float>}
  8168. * @default null
  8169. */
  8170. this.compareNode = null;
  8171. /**
  8172. * When using texture arrays, the depth node defines the layer to select.
  8173. *
  8174. * @type {?Node<int>}
  8175. * @default null
  8176. */
  8177. this.depthNode = null;
  8178. /**
  8179. * When defined, a texture is sampled using explicit gradients.
  8180. *
  8181. * @type {?Array<Node<vec2>>}
  8182. * @default null
  8183. */
  8184. this.gradNode = null;
  8185. /**
  8186. * Represents the optional texel offset applied to the unnormalized texture
  8187. * coordinate before sampling the texture.
  8188. *
  8189. * @type {?Node<ivec2|ivec3>}
  8190. * @default null
  8191. */
  8192. this.offsetNode = null;
  8193. /**
  8194. * Whether texture values should be sampled or fetched.
  8195. *
  8196. * @type {boolean}
  8197. * @default true
  8198. */
  8199. this.sampler = true;
  8200. /**
  8201. * Whether the uv transformation matrix should be
  8202. * automatically updated or not. Use `setUpdateMatrix()`
  8203. * if you want to change the value of the property.
  8204. *
  8205. * @type {boolean}
  8206. * @default false
  8207. */
  8208. this.updateMatrix = false;
  8209. /**
  8210. * By default the `update()` method is not executed. Depending on
  8211. * whether a uv transformation matrix and/or flipY is applied, `update()`
  8212. * is executed per object.
  8213. *
  8214. * @type {string}
  8215. * @default 'none'
  8216. */
  8217. this.updateType = NodeUpdateType.NONE;
  8218. /**
  8219. * The reference node.
  8220. *
  8221. * @type {?Node}
  8222. * @default null
  8223. */
  8224. this.referenceNode = null;
  8225. /**
  8226. * The texture value is stored in a private property.
  8227. *
  8228. * @private
  8229. * @type {Texture}
  8230. */
  8231. this._value = value;
  8232. /**
  8233. * The uniform node that represents the uv transformation matrix.
  8234. *
  8235. * @private
  8236. * @type {?UniformNode<mat3>}
  8237. * @default null
  8238. */
  8239. this._matrixUniform = null;
  8240. /**
  8241. * The uniform node that represents the y-flip. Only required for WebGL.
  8242. *
  8243. * @private
  8244. * @type {?UniformNode<bool>}
  8245. * @default null
  8246. */
  8247. this._flipYUniform = null;
  8248. this.setUpdateMatrix( uvNode === null );
  8249. }
  8250. set value( value ) {
  8251. if ( this.referenceNode ) {
  8252. this.referenceNode.value = value;
  8253. } else {
  8254. this._value = value;
  8255. }
  8256. }
  8257. /**
  8258. * The texture value.
  8259. *
  8260. * @type {Texture}
  8261. */
  8262. get value() {
  8263. return this.referenceNode ? this.referenceNode.value : this._value;
  8264. }
  8265. /**
  8266. * Overwritten since the uniform hash is defined by the texture's UUID.
  8267. *
  8268. * @param {NodeBuilder} builder - The current node builder.
  8269. * @return {string} The uniform hash.
  8270. */
  8271. getUniformHash( /*builder*/ ) {
  8272. return this.value.uuid;
  8273. }
  8274. /**
  8275. * Overwritten since the node type is inferred from the texture type.
  8276. *
  8277. * @param {NodeBuilder} builder - The current node builder.
  8278. * @return {string} The node type.
  8279. */
  8280. getNodeType( /*builder*/ ) {
  8281. if ( this.value.isDepthTexture === true ) return 'float';
  8282. if ( this.value.type === UnsignedIntType ) {
  8283. return 'uvec4';
  8284. } else if ( this.value.type === IntType ) {
  8285. return 'ivec4';
  8286. }
  8287. return 'vec4';
  8288. }
  8289. /**
  8290. * Overwrites the default implementation to return a fixed value `'texture'`.
  8291. *
  8292. * @param {NodeBuilder} builder - The current node builder.
  8293. * @return {string} The input type.
  8294. */
  8295. getInputType( /*builder*/ ) {
  8296. return 'texture';
  8297. }
  8298. /**
  8299. * Returns a default uvs based on the current texture's channel.
  8300. *
  8301. * @return {AttributeNode<vec2>} The default uvs.
  8302. */
  8303. getDefaultUV() {
  8304. return uv$1( this.value.channel );
  8305. }
  8306. /**
  8307. * Overwritten to always return the texture reference of the node.
  8308. *
  8309. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  8310. * @return {Texture} The texture reference.
  8311. */
  8312. updateReference( /*state*/ ) {
  8313. return this.value;
  8314. }
  8315. /**
  8316. * Transforms the given uv node with the texture transformation matrix.
  8317. *
  8318. * @param {Node} uvNode - The uv node to transform.
  8319. * @return {Node} The transformed uv node.
  8320. */
  8321. getTransformedUV( uvNode ) {
  8322. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  8323. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  8324. }
  8325. /**
  8326. * Defines whether the uv transformation matrix should automatically be updated or not.
  8327. *
  8328. * @param {boolean} value - The update toggle.
  8329. * @return {TextureNode} A reference to this node.
  8330. */
  8331. setUpdateMatrix( value ) {
  8332. this.updateMatrix = value;
  8333. return this;
  8334. }
  8335. /**
  8336. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  8337. * to modify the uv node for correct sampling.
  8338. *
  8339. * @param {NodeBuilder} builder - The current node builder.
  8340. * @param {Node} uvNode - The uv node to setup.
  8341. * @return {Node} The updated uv node.
  8342. */
  8343. setupUV( builder, uvNode ) {
  8344. if ( builder.isFlipY() ) {
  8345. if ( this._flipYUniform === null ) this._flipYUniform = uniform( false );
  8346. uvNode = uvNode.toVar();
  8347. if ( this.sampler ) {
  8348. uvNode = this._flipYUniform.select( uvNode.flipY(), uvNode );
  8349. } else {
  8350. uvNode = this._flipYUniform.select( uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) ), uvNode );
  8351. }
  8352. }
  8353. return uvNode;
  8354. }
  8355. /**
  8356. * Setups texture node by preparing the internal nodes for code generation.
  8357. *
  8358. * @param {NodeBuilder} builder - The current node builder.
  8359. */
  8360. setup( builder ) {
  8361. const properties = builder.getNodeProperties( this );
  8362. properties.referenceNode = this.referenceNode;
  8363. //
  8364. const texture = this.value;
  8365. if ( ! texture || texture.isTexture !== true ) {
  8366. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  8367. }
  8368. //
  8369. const uvNode = Fn( () => {
  8370. let uvNode = this.uvNode;
  8371. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  8372. uvNode = builder.context.getUV( this, builder );
  8373. }
  8374. if ( ! uvNode ) uvNode = this.getDefaultUV();
  8375. if ( this.updateMatrix === true ) {
  8376. uvNode = this.getTransformedUV( uvNode );
  8377. }
  8378. uvNode = this.setupUV( builder, uvNode );
  8379. //
  8380. this.updateType = ( this._matrixUniform !== null || this._flipYUniform !== null ) ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  8381. //
  8382. return uvNode;
  8383. } )();
  8384. //
  8385. let levelNode = this.levelNode;
  8386. if ( levelNode === null && builder.context.getTextureLevel ) {
  8387. levelNode = builder.context.getTextureLevel( this );
  8388. }
  8389. //
  8390. properties.uvNode = uvNode;
  8391. properties.levelNode = levelNode;
  8392. properties.biasNode = this.biasNode;
  8393. properties.compareNode = this.compareNode;
  8394. properties.gradNode = this.gradNode;
  8395. properties.depthNode = this.depthNode;
  8396. properties.offsetNode = this.offsetNode;
  8397. }
  8398. /**
  8399. * Generates the uv code snippet.
  8400. *
  8401. * @param {NodeBuilder} builder - The current node builder.
  8402. * @param {Node} uvNode - The uv node to generate code for.
  8403. * @return {string} The generated code snippet.
  8404. */
  8405. generateUV( builder, uvNode ) {
  8406. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  8407. }
  8408. /**
  8409. * Generates the offset code snippet.
  8410. *
  8411. * @param {NodeBuilder} builder - The current node builder.
  8412. * @param {Node} offsetNode - The offset node to generate code for.
  8413. * @return {string} The generated code snippet.
  8414. */
  8415. generateOffset( builder, offsetNode ) {
  8416. return offsetNode.build( builder, 'ivec2' );
  8417. }
  8418. /**
  8419. * Generates the snippet for the texture sampling.
  8420. *
  8421. * @param {NodeBuilder} builder - The current node builder.
  8422. * @param {string} textureProperty - The texture property.
  8423. * @param {string} uvSnippet - The uv snippet.
  8424. * @param {?string} levelSnippet - The level snippet.
  8425. * @param {?string} biasSnippet - The bias snippet.
  8426. * @param {?string} depthSnippet - The depth snippet.
  8427. * @param {?string} compareSnippet - The compare snippet.
  8428. * @param {?Array<string>} gradSnippet - The grad snippet.
  8429. * @param {?string} offsetSnippet - The offset snippet.
  8430. * @return {string} The generated code snippet.
  8431. */
  8432. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet ) {
  8433. const texture = this.value;
  8434. let snippet;
  8435. if ( biasSnippet ) {
  8436. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet );
  8437. } else if ( gradSnippet ) {
  8438. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet );
  8439. } else if ( compareSnippet ) {
  8440. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet );
  8441. } else if ( this.sampler === false ) {
  8442. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8443. } else if ( levelSnippet ) {
  8444. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8445. } else {
  8446. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet );
  8447. }
  8448. return snippet;
  8449. }
  8450. /**
  8451. * Generates the code snippet of the texture node.
  8452. *
  8453. * @param {NodeBuilder} builder - The current node builder.
  8454. * @param {string} output - The current output.
  8455. * @return {string} The generated code snippet.
  8456. */
  8457. generate( builder, output ) {
  8458. const texture = this.value;
  8459. const properties = builder.getNodeProperties( this );
  8460. const textureProperty = super.generate( builder, 'property' );
  8461. if ( /^sampler/.test( output ) ) {
  8462. return textureProperty + '_sampler';
  8463. } else if ( builder.isReference( output ) ) {
  8464. return textureProperty;
  8465. } else {
  8466. const nodeData = builder.getDataFromNode( this );
  8467. let propertyName = nodeData.propertyName;
  8468. if ( propertyName === undefined ) {
  8469. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode, offsetNode } = properties;
  8470. const uvSnippet = this.generateUV( builder, uvNode );
  8471. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  8472. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  8473. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  8474. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  8475. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  8476. const offsetSnippet = offsetNode ? this.generateOffset( builder, offsetNode ) : null;
  8477. const nodeVar = builder.getVarFromNode( this );
  8478. propertyName = builder.getPropertyName( nodeVar );
  8479. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet );
  8480. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  8481. nodeData.snippet = snippet;
  8482. nodeData.propertyName = propertyName;
  8483. }
  8484. let snippet = propertyName;
  8485. const nodeType = this.getNodeType( builder );
  8486. if ( builder.needsToWorkingColorSpace( texture ) ) {
  8487. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  8488. }
  8489. return builder.format( snippet, nodeType, output );
  8490. }
  8491. }
  8492. /**
  8493. * Sets the sampler value.
  8494. *
  8495. * @param {boolean} value - The sampler value to set.
  8496. * @return {TextureNode} A reference to this texture node.
  8497. */
  8498. setSampler( value ) {
  8499. this.sampler = value;
  8500. return this;
  8501. }
  8502. /**
  8503. * Returns the sampler value.
  8504. *
  8505. * @return {boolean} The sampler value.
  8506. */
  8507. getSampler() {
  8508. return this.sampler;
  8509. }
  8510. // @TODO: Move to TSL
  8511. /**
  8512. * @function
  8513. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  8514. *
  8515. * @param {Node} uvNode - The uv node.
  8516. * @return {TextureNode} A texture node representing the texture sample.
  8517. */
  8518. uv( uvNode ) { // @deprecated, r172
  8519. warn( 'TextureNode: .uv() has been renamed. Use .sample() instead.' );
  8520. return this.sample( uvNode );
  8521. }
  8522. /**
  8523. * Samples the texture with the given uv node.
  8524. *
  8525. * @param {Node} uvNode - The uv node.
  8526. * @return {TextureNode} A texture node representing the texture sample.
  8527. */
  8528. sample( uvNode ) {
  8529. const textureNode = this.clone();
  8530. textureNode.uvNode = nodeObject( uvNode );
  8531. textureNode.referenceNode = this.getBase();
  8532. return nodeObject( textureNode );
  8533. }
  8534. /**
  8535. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8536. *
  8537. * @param {Node<uvec2>} uvNode - The uv node.
  8538. * @returns {TextureNode} A texture node representing the texture load.
  8539. */
  8540. load( uvNode ) {
  8541. return this.sample( uvNode ).setSampler( false );
  8542. }
  8543. /**
  8544. * Samples a blurred version of the texture by defining an internal bias.
  8545. *
  8546. * @param {Node<float>} amountNode - How blurred the texture should be.
  8547. * @return {TextureNode} A texture node representing the texture sample.
  8548. */
  8549. blur( amountNode ) {
  8550. const textureNode = this.clone();
  8551. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  8552. textureNode.referenceNode = this.getBase();
  8553. const map = textureNode.value;
  8554. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  8555. warn( 'TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  8556. textureNode.biasNode = null;
  8557. }
  8558. return nodeObject( textureNode );
  8559. }
  8560. /**
  8561. * Samples a specific mip of the texture.
  8562. *
  8563. * @param {Node<int>} levelNode - The mip level to sample.
  8564. * @return {TextureNode} A texture node representing the texture sample.
  8565. */
  8566. level( levelNode ) {
  8567. const textureNode = this.clone();
  8568. textureNode.levelNode = nodeObject( levelNode );
  8569. textureNode.referenceNode = this.getBase();
  8570. return nodeObject( textureNode );
  8571. }
  8572. /**
  8573. * Returns the texture size of the requested level.
  8574. *
  8575. * @param {Node<int>} levelNode - The level to compute the size for.
  8576. * @return {TextureSizeNode} The texture size.
  8577. */
  8578. size( levelNode ) {
  8579. return textureSize( this, levelNode );
  8580. }
  8581. /**
  8582. * Samples the texture with the given bias.
  8583. *
  8584. * @param {Node<float>} biasNode - The bias node.
  8585. * @return {TextureNode} A texture node representing the texture sample.
  8586. */
  8587. bias( biasNode ) {
  8588. const textureNode = this.clone();
  8589. textureNode.biasNode = nodeObject( biasNode );
  8590. textureNode.referenceNode = this.getBase();
  8591. return nodeObject( textureNode );
  8592. }
  8593. /**
  8594. * Returns the base texture of this node.
  8595. * @return {TextureNode} The base texture node.
  8596. */
  8597. getBase() {
  8598. return this.referenceNode ? this.referenceNode.getBase() : this;
  8599. }
  8600. /**
  8601. * Samples the texture by executing a compare operation.
  8602. *
  8603. * @param {Node<float>} compareNode - The node that defines the compare value.
  8604. * @return {TextureNode} A texture node representing the texture sample.
  8605. */
  8606. compare( compareNode ) {
  8607. const textureNode = this.clone();
  8608. textureNode.compareNode = nodeObject( compareNode );
  8609. textureNode.referenceNode = this.getBase();
  8610. return nodeObject( textureNode );
  8611. }
  8612. /**
  8613. * Samples the texture using an explicit gradient.
  8614. *
  8615. * @param {Node<vec2>} gradNodeX - The gradX node.
  8616. * @param {Node<vec2>} gradNodeY - The gradY node.
  8617. * @return {TextureNode} A texture node representing the texture sample.
  8618. */
  8619. grad( gradNodeX, gradNodeY ) {
  8620. const textureNode = this.clone();
  8621. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  8622. textureNode.referenceNode = this.getBase();
  8623. return nodeObject( textureNode );
  8624. }
  8625. /**
  8626. * Samples the texture by defining a depth node.
  8627. *
  8628. * @param {Node<int>} depthNode - The depth node.
  8629. * @return {TextureNode} A texture node representing the texture sample.
  8630. */
  8631. depth( depthNode ) {
  8632. const textureNode = this.clone();
  8633. textureNode.depthNode = nodeObject( depthNode );
  8634. textureNode.referenceNode = this.getBase();
  8635. return nodeObject( textureNode );
  8636. }
  8637. /**
  8638. * Samples the texture by defining an offset node.
  8639. *
  8640. * @param {Node<ivec2>} offsetNode - The offset node.
  8641. * @return {TextureNode} A texture node representing the texture sample.
  8642. */
  8643. offset( offsetNode ) {
  8644. const textureNode = this.clone();
  8645. textureNode.offsetNode = nodeObject( offsetNode );
  8646. textureNode.referenceNode = this.getBase();
  8647. return nodeObject( textureNode );
  8648. }
  8649. // --
  8650. serialize( data ) {
  8651. super.serialize( data );
  8652. data.value = this.value.toJSON( data.meta ).uuid;
  8653. data.sampler = this.sampler;
  8654. data.updateMatrix = this.updateMatrix;
  8655. data.updateType = this.updateType;
  8656. }
  8657. deserialize( data ) {
  8658. super.deserialize( data );
  8659. this.value = data.meta.textures[ data.value ];
  8660. this.sampler = data.sampler;
  8661. this.updateMatrix = data.updateMatrix;
  8662. this.updateType = data.updateType;
  8663. }
  8664. /**
  8665. * The update is used to implement the update of the uv transformation matrix.
  8666. */
  8667. update() {
  8668. const texture = this.value;
  8669. const matrixUniform = this._matrixUniform;
  8670. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  8671. if ( texture.matrixAutoUpdate === true ) {
  8672. texture.updateMatrix();
  8673. }
  8674. //
  8675. const flipYUniform = this._flipYUniform;
  8676. if ( flipYUniform !== null ) {
  8677. flipYUniform.value = ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true );
  8678. }
  8679. }
  8680. /**
  8681. * Clones the texture node.
  8682. *
  8683. * @return {TextureNode} The cloned texture node.
  8684. */
  8685. clone() {
  8686. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  8687. newNode.sampler = this.sampler;
  8688. newNode.depthNode = this.depthNode;
  8689. newNode.compareNode = this.compareNode;
  8690. newNode.gradNode = this.gradNode;
  8691. newNode.offsetNode = this.offsetNode;
  8692. return newNode;
  8693. }
  8694. }
  8695. /**
  8696. * TSL function for creating a texture node.
  8697. *
  8698. * @tsl
  8699. * @function
  8700. * @param {?Texture} value - The texture.
  8701. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8702. * @param {?Node<int>} [levelNode=null] - The level node.
  8703. * @param {?Node<float>} [biasNode=null] - The bias node.
  8704. * @returns {TextureNode}
  8705. */
  8706. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  8707. /**
  8708. * TSL function for creating a texture node or sample a texture node already existing.
  8709. *
  8710. * @tsl
  8711. * @function
  8712. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8713. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8714. * @param {?Node<int>} [levelNode=null] - The level node.
  8715. * @param {?Node<float>} [biasNode=null] - The bias node.
  8716. * @returns {TextureNode}
  8717. */
  8718. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  8719. let textureNode;
  8720. if ( value && value.isTextureNode === true ) {
  8721. textureNode = nodeObject( value.clone() );
  8722. textureNode.referenceNode = value.getBase(); // Ensure the reference is set to the original node
  8723. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  8724. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  8725. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  8726. } else {
  8727. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  8728. }
  8729. return textureNode;
  8730. };
  8731. /**
  8732. * TSL function for creating a uniform texture node.
  8733. *
  8734. * @tsl
  8735. * @function
  8736. * @param {?Texture} value - The texture.
  8737. * @returns {TextureNode}
  8738. */
  8739. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  8740. /**
  8741. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8742. *
  8743. * @tsl
  8744. * @function
  8745. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8746. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8747. * @param {?Node<int>} [levelNode=null] - The level node.
  8748. * @param {?Node<float>} [biasNode=null] - The bias node.
  8749. * @returns {TextureNode}
  8750. */
  8751. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  8752. const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  8753. /**
  8754. * Converts a texture or texture node to a sampler.
  8755. *
  8756. * @tsl
  8757. * @function
  8758. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8759. * @returns {Node}
  8760. */
  8761. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  8762. /**
  8763. * Converts a texture or texture node to a sampler comparison.
  8764. *
  8765. * @tsl
  8766. * @function
  8767. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8768. * @returns {Node}
  8769. */
  8770. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  8771. /**
  8772. * A special type of uniform node which represents array-like data
  8773. * as uniform buffers. The access usually happens via `element()`
  8774. * which returns an instance of {@link ArrayElementNode}. For example:
  8775. *
  8776. * ```js
  8777. * const bufferNode = buffer( array, 'mat4', count );
  8778. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  8779. * ```
  8780. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  8781. * since it handles more input types and automatically cares about buffer paddings.
  8782. *
  8783. * @augments UniformNode
  8784. */
  8785. class BufferNode extends UniformNode {
  8786. static get type() {
  8787. return 'BufferNode';
  8788. }
  8789. /**
  8790. * Constructs a new buffer node.
  8791. *
  8792. * @param {Array<number>} value - Array-like buffer data.
  8793. * @param {string} bufferType - The data type of the buffer.
  8794. * @param {number} [bufferCount=0] - The count of buffer elements.
  8795. */
  8796. constructor( value, bufferType, bufferCount = 0 ) {
  8797. super( value, bufferType );
  8798. /**
  8799. * This flag can be used for type testing.
  8800. *
  8801. * @type {boolean}
  8802. * @readonly
  8803. * @default true
  8804. */
  8805. this.isBufferNode = true;
  8806. /**
  8807. * The data type of the buffer.
  8808. *
  8809. * @type {string}
  8810. */
  8811. this.bufferType = bufferType;
  8812. /**
  8813. * The uniform node that holds the value of the reference node.
  8814. *
  8815. * @type {number}
  8816. * @default 0
  8817. */
  8818. this.bufferCount = bufferCount;
  8819. /**
  8820. * An array of update ranges.
  8821. *
  8822. * @type {Array<{start: number, count: number}>}
  8823. */
  8824. this.updateRanges = [];
  8825. }
  8826. /**
  8827. * Adds a range of data in the data array to be updated on the GPU.
  8828. *
  8829. * @param {number} start - Position at which to start update.
  8830. * @param {number} count - The number of components to update.
  8831. */
  8832. addUpdateRange( start, count ) {
  8833. this.updateRanges.push( { start, count } );
  8834. }
  8835. /**
  8836. * Clears the update ranges.
  8837. */
  8838. clearUpdateRanges() {
  8839. this.updateRanges.length = 0;
  8840. }
  8841. /**
  8842. * The data type of the buffer elements.
  8843. *
  8844. * @param {NodeBuilder} builder - The current node builder.
  8845. * @return {string} The element type.
  8846. */
  8847. getElementType( builder ) {
  8848. return this.getNodeType( builder );
  8849. }
  8850. /**
  8851. * Overwrites the default implementation to return a fixed value `'buffer'`.
  8852. *
  8853. * @param {NodeBuilder} builder - The current node builder.
  8854. * @return {string} The input type.
  8855. */
  8856. getInputType( /*builder*/ ) {
  8857. return 'buffer';
  8858. }
  8859. }
  8860. /**
  8861. * TSL function for creating a buffer node.
  8862. *
  8863. * @tsl
  8864. * @function
  8865. * @param {Array<number>} value - Array-like buffer data.
  8866. * @param {string} type - The data type of a buffer element.
  8867. * @param {number} count - The count of buffer elements.
  8868. * @returns {BufferNode}
  8869. */
  8870. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  8871. /**
  8872. * Represents the element access on uniform array nodes.
  8873. *
  8874. * @augments ArrayElementNode
  8875. */
  8876. class UniformArrayElementNode extends ArrayElementNode {
  8877. static get type() {
  8878. return 'UniformArrayElementNode';
  8879. }
  8880. /**
  8881. * Constructs a new buffer node.
  8882. *
  8883. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  8884. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  8885. */
  8886. constructor( uniformArrayNode, indexNode ) {
  8887. super( uniformArrayNode, indexNode );
  8888. /**
  8889. * This flag can be used for type testing.
  8890. *
  8891. * @type {boolean}
  8892. * @readonly
  8893. * @default true
  8894. */
  8895. this.isArrayBufferElementNode = true;
  8896. }
  8897. generate( builder ) {
  8898. const snippet = super.generate( builder );
  8899. const type = this.getNodeType();
  8900. const paddedType = this.node.getPaddedType();
  8901. return builder.format( snippet, paddedType, type );
  8902. }
  8903. }
  8904. /**
  8905. * Similar to {@link BufferNode} this module represents array-like data as
  8906. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  8907. * data types in the array (e.g `three.js` primitives) and automatically
  8908. * manage buffer padding. It should be the first choice when working with
  8909. * uniforms buffers.
  8910. * ```js
  8911. * const tintColors = uniformArray( [
  8912. * new Color( 1, 0, 0 ),
  8913. * new Color( 0, 1, 0 ),
  8914. * new Color( 0, 0, 1 )
  8915. * ], 'color' );
  8916. *
  8917. * const redColor = tintColors.element( 0 );
  8918. *
  8919. * @augments BufferNode
  8920. */
  8921. class UniformArrayNode extends BufferNode {
  8922. static get type() {
  8923. return 'UniformArrayNode';
  8924. }
  8925. /**
  8926. * Constructs a new uniform array node.
  8927. *
  8928. * @param {Array<any>} value - Array holding the buffer data.
  8929. * @param {?string} [elementType=null] - The data type of a buffer element.
  8930. */
  8931. constructor( value, elementType = null ) {
  8932. super( null );
  8933. /**
  8934. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  8935. * hold number primitives as well as three.js objects like vectors, matrices
  8936. * or colors.
  8937. *
  8938. * @type {Array<any>}
  8939. */
  8940. this.array = value;
  8941. /**
  8942. * The data type of an array element.
  8943. *
  8944. * @type {string}
  8945. */
  8946. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  8947. /**
  8948. * The padded type. Uniform buffers must conform to a certain buffer layout
  8949. * so a separate type is computed to ensure correct buffer size.
  8950. *
  8951. * @type {string}
  8952. */
  8953. this.paddedType = this.getPaddedType();
  8954. /**
  8955. * Overwritten since uniform array nodes are updated per render.
  8956. *
  8957. * @type {string}
  8958. * @default 'render'
  8959. */
  8960. this.updateType = NodeUpdateType.RENDER;
  8961. /**
  8962. * This flag can be used for type testing.
  8963. *
  8964. * @type {boolean}
  8965. * @readonly
  8966. * @default true
  8967. */
  8968. this.isArrayBufferNode = true;
  8969. }
  8970. /**
  8971. * This method is overwritten since the node type is inferred from the
  8972. * {@link UniformArrayNode#paddedType}.
  8973. *
  8974. * @param {NodeBuilder} builder - The current node builder.
  8975. * @return {string} The node type.
  8976. */
  8977. getNodeType( /*builder*/ ) {
  8978. return this.paddedType;
  8979. }
  8980. /**
  8981. * The data type of the array elements.
  8982. *
  8983. * @param {NodeBuilder} builder - The current node builder.
  8984. * @return {string} The element type.
  8985. */
  8986. getElementType() {
  8987. return this.elementType;
  8988. }
  8989. /**
  8990. * Returns the padded type based on the element type.
  8991. *
  8992. * @return {string} The padded type.
  8993. */
  8994. getPaddedType() {
  8995. const elementType = this.elementType;
  8996. let paddedType = 'vec4';
  8997. if ( elementType === 'mat2' ) {
  8998. paddedType = 'mat2';
  8999. } else if ( /mat/.test( elementType ) === true ) {
  9000. paddedType = 'mat4';
  9001. } else if ( elementType.charAt( 0 ) === 'i' ) {
  9002. paddedType = 'ivec4';
  9003. } else if ( elementType.charAt( 0 ) === 'u' ) {
  9004. paddedType = 'uvec4';
  9005. }
  9006. return paddedType;
  9007. }
  9008. /**
  9009. * The update makes sure to correctly transfer the data from the (complex) objects
  9010. * in the array to the internal, correctly padded value buffer.
  9011. *
  9012. * @param {NodeFrame} frame - A reference to the current node frame.
  9013. */
  9014. update( /*frame*/ ) {
  9015. const { array, value } = this;
  9016. const elementType = this.elementType;
  9017. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  9018. for ( let i = 0; i < array.length; i ++ ) {
  9019. const index = i * 4;
  9020. value[ index ] = array[ i ];
  9021. }
  9022. } else if ( elementType === 'color' ) {
  9023. for ( let i = 0; i < array.length; i ++ ) {
  9024. const index = i * 4;
  9025. const vector = array[ i ];
  9026. value[ index ] = vector.r;
  9027. value[ index + 1 ] = vector.g;
  9028. value[ index + 2 ] = vector.b || 0;
  9029. //value[ index + 3 ] = vector.a || 0;
  9030. }
  9031. } else if ( elementType === 'mat2' ) {
  9032. for ( let i = 0; i < array.length; i ++ ) {
  9033. const index = i * 4;
  9034. const matrix = array[ i ];
  9035. value[ index ] = matrix.elements[ 0 ];
  9036. value[ index + 1 ] = matrix.elements[ 1 ];
  9037. value[ index + 2 ] = matrix.elements[ 2 ];
  9038. value[ index + 3 ] = matrix.elements[ 3 ];
  9039. }
  9040. } else if ( elementType === 'mat3' ) {
  9041. for ( let i = 0; i < array.length; i ++ ) {
  9042. const index = i * 16;
  9043. const matrix = array[ i ];
  9044. value[ index ] = matrix.elements[ 0 ];
  9045. value[ index + 1 ] = matrix.elements[ 1 ];
  9046. value[ index + 2 ] = matrix.elements[ 2 ];
  9047. value[ index + 4 ] = matrix.elements[ 3 ];
  9048. value[ index + 5 ] = matrix.elements[ 4 ];
  9049. value[ index + 6 ] = matrix.elements[ 5 ];
  9050. value[ index + 8 ] = matrix.elements[ 6 ];
  9051. value[ index + 9 ] = matrix.elements[ 7 ];
  9052. value[ index + 10 ] = matrix.elements[ 8 ];
  9053. value[ index + 15 ] = 1;
  9054. }
  9055. } else if ( elementType === 'mat4' ) {
  9056. for ( let i = 0; i < array.length; i ++ ) {
  9057. const index = i * 16;
  9058. const matrix = array[ i ];
  9059. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  9060. value[ index + i ] = matrix.elements[ i ];
  9061. }
  9062. }
  9063. } else {
  9064. for ( let i = 0; i < array.length; i ++ ) {
  9065. const index = i * 4;
  9066. const vector = array[ i ];
  9067. value[ index ] = vector.x;
  9068. value[ index + 1 ] = vector.y;
  9069. value[ index + 2 ] = vector.z || 0;
  9070. value[ index + 3 ] = vector.w || 0;
  9071. }
  9072. }
  9073. }
  9074. /**
  9075. * Implement the value buffer creation based on the array data.
  9076. *
  9077. * @param {NodeBuilder} builder - A reference to the current node builder.
  9078. * @return {null}
  9079. */
  9080. setup( builder ) {
  9081. const length = this.array.length;
  9082. const elementType = this.elementType;
  9083. let arrayType = Float32Array;
  9084. const paddedType = this.paddedType;
  9085. const paddedElementLength = builder.getTypeLength( paddedType );
  9086. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  9087. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  9088. this.value = new arrayType( length * paddedElementLength );
  9089. this.bufferCount = length;
  9090. this.bufferType = paddedType;
  9091. return super.setup( builder );
  9092. }
  9093. /**
  9094. * Overwrites the default `element()` method to provide element access
  9095. * based on {@link UniformArrayNode}.
  9096. *
  9097. * @param {IndexNode} indexNode - The index node.
  9098. * @return {UniformArrayElementNode}
  9099. */
  9100. element( indexNode ) {
  9101. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  9102. }
  9103. }
  9104. /**
  9105. * TSL function for creating an uniform array node.
  9106. *
  9107. * @tsl
  9108. * @function
  9109. * @param {Array<any>} values - Array-like data.
  9110. * @param {?string} [nodeType] - The data type of the array elements.
  9111. * @returns {UniformArrayNode}
  9112. */
  9113. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  9114. /**
  9115. * The node allows to set values for built-in shader variables. That is
  9116. * required for features like hardware-accelerated vertex clipping.
  9117. *
  9118. * @augments Node
  9119. */
  9120. class BuiltinNode extends Node {
  9121. /**
  9122. * Constructs a new builtin node.
  9123. *
  9124. * @param {string} name - The name of the built-in shader variable.
  9125. */
  9126. constructor( name ) {
  9127. super( 'float' );
  9128. /**
  9129. * The name of the built-in shader variable.
  9130. *
  9131. * @type {string}
  9132. */
  9133. this.name = name;
  9134. /**
  9135. * This flag can be used for type testing.
  9136. *
  9137. * @type {boolean}
  9138. * @readonly
  9139. * @default true
  9140. */
  9141. this.isBuiltinNode = true;
  9142. }
  9143. /**
  9144. * Generates the code snippet of the builtin node.
  9145. *
  9146. * @param {NodeBuilder} builder - The current node builder.
  9147. * @return {string} The generated code snippet.
  9148. */
  9149. generate( /* builder */ ) {
  9150. return this.name;
  9151. }
  9152. }
  9153. /**
  9154. * TSL function for creating a builtin node.
  9155. *
  9156. * @tsl
  9157. * @function
  9158. * @param {string} name - The name of the built-in shader variable.
  9159. * @returns {BuiltinNode}
  9160. */
  9161. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  9162. let _screenSizeVec, _viewportVec;
  9163. /**
  9164. * This node provides a collection of screen related metrics.
  9165. * Depending on {@link ScreenNode#scope}, the nodes can represent
  9166. * resolution or viewport data as well as fragment or uv coordinates.
  9167. *
  9168. * @augments Node
  9169. */
  9170. class ScreenNode extends Node {
  9171. static get type() {
  9172. return 'ScreenNode';
  9173. }
  9174. /**
  9175. * Constructs a new screen node.
  9176. *
  9177. * @param {('coordinate'|'viewport'|'size'|'uv'|'dpr')} scope - The node's scope.
  9178. */
  9179. constructor( scope ) {
  9180. super();
  9181. /**
  9182. * The node represents different metric depending on which scope is selected.
  9183. *
  9184. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  9185. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  9186. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  9187. * - `ScreenNode.UV`: Normalized coordinates.
  9188. * - `ScreenNode.DPR`: Device pixel ratio.
  9189. *
  9190. * @type {('coordinate'|'viewport'|'size'|'uv'|'dpr')}
  9191. */
  9192. this.scope = scope;
  9193. /**
  9194. * This output node.
  9195. *
  9196. * @private
  9197. * @type {?Node}
  9198. * @default null
  9199. */
  9200. this._output = null;
  9201. /**
  9202. * This flag can be used for type testing.
  9203. *
  9204. * @type {boolean}
  9205. * @readonly
  9206. * @default true
  9207. */
  9208. this.isViewportNode = true;
  9209. }
  9210. /**
  9211. * This method is overwritten since the node type depends on the selected scope.
  9212. *
  9213. * @return {('float'|'vec2'|'vec4')} The node type.
  9214. */
  9215. getNodeType() {
  9216. if ( this.scope === ScreenNode.DPR ) return 'float';
  9217. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  9218. else return 'vec2';
  9219. }
  9220. /**
  9221. * This method is overwritten since the node's update type depends on the selected scope.
  9222. *
  9223. * @return {NodeUpdateType} The update type.
  9224. */
  9225. getUpdateType() {
  9226. let updateType = NodeUpdateType.NONE;
  9227. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT || this.scope === ScreenNode.DPR ) {
  9228. updateType = NodeUpdateType.RENDER;
  9229. }
  9230. this.updateType = updateType;
  9231. return updateType;
  9232. }
  9233. /**
  9234. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  9235. * from the current renderer.
  9236. *
  9237. * @param {NodeFrame} frame - A reference to the current node frame.
  9238. */
  9239. update( { renderer } ) {
  9240. const renderTarget = renderer.getRenderTarget();
  9241. if ( this.scope === ScreenNode.VIEWPORT ) {
  9242. if ( renderTarget !== null ) {
  9243. _viewportVec.copy( renderTarget.viewport );
  9244. } else {
  9245. renderer.getViewport( _viewportVec );
  9246. _viewportVec.multiplyScalar( renderer.getPixelRatio() );
  9247. }
  9248. } else if ( this.scope === ScreenNode.DPR ) {
  9249. this._output.value = renderer.getPixelRatio();
  9250. } else {
  9251. if ( renderTarget !== null ) {
  9252. _screenSizeVec.width = renderTarget.width;
  9253. _screenSizeVec.height = renderTarget.height;
  9254. } else {
  9255. renderer.getDrawingBufferSize( _screenSizeVec );
  9256. }
  9257. }
  9258. }
  9259. setup( /*builder*/ ) {
  9260. const scope = this.scope;
  9261. let output = null;
  9262. if ( scope === ScreenNode.SIZE ) {
  9263. output = uniform( _screenSizeVec || ( _screenSizeVec = new Vector2() ) );
  9264. } else if ( scope === ScreenNode.VIEWPORT ) {
  9265. output = uniform( _viewportVec || ( _viewportVec = new Vector4() ) );
  9266. } else if ( scope === ScreenNode.DPR ) {
  9267. output = uniform( 1 );
  9268. } else {
  9269. output = vec2( screenCoordinate.div( screenSize ) );
  9270. }
  9271. this._output = output;
  9272. return output;
  9273. }
  9274. generate( builder ) {
  9275. if ( this.scope === ScreenNode.COORDINATE ) {
  9276. let coord = builder.getFragCoord();
  9277. if ( builder.isFlipY() ) {
  9278. // follow webgpu standards
  9279. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  9280. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  9281. }
  9282. return coord;
  9283. }
  9284. return super.generate( builder );
  9285. }
  9286. }
  9287. ScreenNode.COORDINATE = 'coordinate';
  9288. ScreenNode.VIEWPORT = 'viewport';
  9289. ScreenNode.SIZE = 'size';
  9290. ScreenNode.UV = 'uv';
  9291. ScreenNode.DPR = 'dpr';
  9292. // Screen
  9293. /**
  9294. * TSL object that represents the current DPR.
  9295. *
  9296. * @tsl
  9297. * @type {ScreenNode<float>}
  9298. */
  9299. const screenDPR = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.DPR );
  9300. /**
  9301. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  9302. *
  9303. * @tsl
  9304. * @type {ScreenNode<vec2>}
  9305. */
  9306. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  9307. /**
  9308. * TSL object that represents the screen resolution in physical pixel units.
  9309. *
  9310. * @tsl
  9311. * @type {ScreenNode<vec2>}
  9312. */
  9313. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  9314. /**
  9315. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  9316. *
  9317. * @tsl
  9318. * @type {ScreenNode<vec2>}
  9319. */
  9320. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  9321. // Viewport
  9322. /**
  9323. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  9324. *
  9325. * @tsl
  9326. * @type {ScreenNode<vec4>}
  9327. */
  9328. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  9329. /**
  9330. * TSL object that represents the viewport resolution in physical pixel units.
  9331. *
  9332. * @tsl
  9333. * @type {ScreenNode<vec2>}
  9334. */
  9335. const viewportSize = viewport.zw;
  9336. /**
  9337. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  9338. *
  9339. * @tsl
  9340. * @type {ScreenNode<vec2>}
  9341. */
  9342. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  9343. /**
  9344. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  9345. *
  9346. * @tsl
  9347. * @type {ScreenNode<vec2>}
  9348. */
  9349. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  9350. // Deprecated
  9351. /**
  9352. * @deprecated since r169. Use {@link screenSize} instead.
  9353. */
  9354. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  9355. warn( 'TSL: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  9356. return screenSize;
  9357. }, 'vec2' ).once() )();
  9358. /**
  9359. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  9360. *
  9361. * @tsl
  9362. * @type {UniformNode<uint>}
  9363. */
  9364. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setName( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  9365. /**
  9366. * TSL object that represents the `near` value of the camera used for the current render.
  9367. *
  9368. * @tsl
  9369. * @type {UniformNode<float>}
  9370. */
  9371. const cameraNear = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  9372. /**
  9373. * TSL object that represents the `far` value of the camera used for the current render.
  9374. *
  9375. * @tsl
  9376. * @type {UniformNode<float>}
  9377. */
  9378. const cameraFar = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  9379. /**
  9380. * TSL object that represents the projection matrix of the camera used for the current render.
  9381. *
  9382. * @tsl
  9383. * @type {UniformNode<mat4>}
  9384. */
  9385. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9386. let cameraProjectionMatrix;
  9387. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9388. const matrices = [];
  9389. for ( const subCamera of camera.cameras ) {
  9390. matrices.push( subCamera.projectionMatrix );
  9391. }
  9392. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatrices' );
  9393. cameraProjectionMatrix = cameraProjectionMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrix' );
  9394. } else {
  9395. cameraProjectionMatrix = uniform( 'mat4' ).setName( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  9396. }
  9397. return cameraProjectionMatrix;
  9398. } ).once() )();
  9399. /**
  9400. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  9401. *
  9402. * @tsl
  9403. * @type {UniformNode<mat4>}
  9404. */
  9405. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9406. let cameraProjectionMatrixInverse;
  9407. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9408. const matrices = [];
  9409. for ( const subCamera of camera.cameras ) {
  9410. matrices.push( subCamera.projectionMatrixInverse );
  9411. }
  9412. const cameraProjectionMatricesInverse = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatricesInverse' );
  9413. cameraProjectionMatrixInverse = cameraProjectionMatricesInverse.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrixInverse' );
  9414. } else {
  9415. cameraProjectionMatrixInverse = uniform( 'mat4' ).setName( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  9416. }
  9417. return cameraProjectionMatrixInverse;
  9418. } ).once() )();
  9419. /**
  9420. * TSL object that represents the view matrix of the camera used for the current render.
  9421. *
  9422. * @tsl
  9423. * @type {UniformNode<mat4>}
  9424. */
  9425. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9426. let cameraViewMatrix;
  9427. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9428. const matrices = [];
  9429. for ( const subCamera of camera.cameras ) {
  9430. matrices.push( subCamera.matrixWorldInverse );
  9431. }
  9432. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraViewMatrices' );
  9433. cameraViewMatrix = cameraViewMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraViewMatrix' );
  9434. } else {
  9435. cameraViewMatrix = uniform( 'mat4' ).setName( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  9436. }
  9437. return cameraViewMatrix;
  9438. } ).once() )();
  9439. /**
  9440. * TSL object that represents the world matrix of the camera used for the current render.
  9441. *
  9442. * @tsl
  9443. * @type {UniformNode<mat4>}
  9444. */
  9445. const cameraWorldMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9446. let cameraWorldMatrix;
  9447. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9448. const matrices = [];
  9449. for ( const subCamera of camera.cameras ) {
  9450. matrices.push( subCamera.matrixWorld );
  9451. }
  9452. const cameraWorldMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraWorldMatrices' );
  9453. cameraWorldMatrix = cameraWorldMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraWorldMatrix' );
  9454. } else {
  9455. cameraWorldMatrix = uniform( 'mat4' ).setName( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  9456. }
  9457. return cameraWorldMatrix;
  9458. } ).once() )();
  9459. /**
  9460. * TSL object that represents the normal matrix of the camera used for the current render.
  9461. *
  9462. * @tsl
  9463. * @type {UniformNode<mat3>}
  9464. */
  9465. const cameraNormalMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9466. let cameraNormalMatrix;
  9467. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9468. const matrices = [];
  9469. for ( const subCamera of camera.cameras ) {
  9470. matrices.push( subCamera.normalMatrix );
  9471. }
  9472. const cameraNormalMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraNormalMatrices' );
  9473. cameraNormalMatrix = cameraNormalMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraNormalMatrix' );
  9474. } else {
  9475. cameraNormalMatrix = uniform( 'mat3' ).setName( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  9476. }
  9477. return cameraNormalMatrix;
  9478. } ).once() )();
  9479. /**
  9480. * TSL object that represents the position in world space of the camera used for the current render.
  9481. *
  9482. * @tsl
  9483. * @type {UniformNode<vec3>}
  9484. */
  9485. const cameraPosition = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9486. let cameraPosition;
  9487. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9488. const positions = [];
  9489. for ( let i = 0, l = camera.cameras.length; i < l; i ++ ) {
  9490. positions.push( new Vector3() );
  9491. }
  9492. const cameraPositions = uniformArray( positions ).setGroup( renderGroup ).setName( 'cameraPositions' ).onRenderUpdate( ( { camera }, self ) => {
  9493. const subCameras = camera.cameras;
  9494. const array = self.array;
  9495. for ( let i = 0, l = subCameras.length; i < l; i ++ ) {
  9496. array[ i ].setFromMatrixPosition( subCameras[ i ].matrixWorld );
  9497. }
  9498. } );
  9499. cameraPosition = cameraPositions.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraPosition' );
  9500. } else {
  9501. cameraPosition = uniform( new Vector3() ).setName( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  9502. }
  9503. return cameraPosition;
  9504. } ).once() )();
  9505. /**
  9506. * TSL object that represents the viewport of the camera used for the current render.
  9507. *
  9508. * @tsl
  9509. * @type {UniformNode<vec4>}
  9510. */
  9511. const cameraViewport = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9512. let cameraViewport;
  9513. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9514. const viewports = [];
  9515. for ( const subCamera of camera.cameras ) {
  9516. viewports.push( subCamera.viewport );
  9517. }
  9518. const cameraViewports = uniformArray( viewports, 'vec4' ).setGroup( renderGroup ).setName( 'cameraViewports' );
  9519. cameraViewport = cameraViewports.element( cameraIndex ).toConst( 'cameraViewport' );
  9520. } else {
  9521. // Fallback for single camera
  9522. cameraViewport = vec4( 0, 0, screenSize.x, screenSize.y ).toConst( 'cameraViewport' );
  9523. }
  9524. return cameraViewport;
  9525. } ).once() )();
  9526. const _sphere = /*@__PURE__*/ new Sphere();
  9527. /**
  9528. * This node can be used to access transformation related metrics of 3D objects.
  9529. * Depending on the selected scope, a different metric is represented as a uniform
  9530. * in the shader. The following scopes are supported:
  9531. *
  9532. * - `POSITION`: The object's position in world space.
  9533. * - `VIEW_POSITION`: The object's position in view/camera space.
  9534. * - `DIRECTION`: The object's direction in world space.
  9535. * - `SCALE`: The object's scale in world space.
  9536. * - `WORLD_MATRIX`: The object's matrix in world space.
  9537. *
  9538. * @augments Node
  9539. */
  9540. class Object3DNode extends Node {
  9541. static get type() {
  9542. return 'Object3DNode';
  9543. }
  9544. /**
  9545. * Constructs a new object 3D node.
  9546. *
  9547. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9548. * @param {?Object3D} [object3d=null] - The 3D object.
  9549. */
  9550. constructor( scope, object3d = null ) {
  9551. super();
  9552. /**
  9553. * The node reports a different type of transformation depending on the scope.
  9554. *
  9555. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  9556. */
  9557. this.scope = scope;
  9558. /**
  9559. * The 3D object.
  9560. *
  9561. * @type {?Object3D}
  9562. * @default null
  9563. */
  9564. this.object3d = object3d;
  9565. /**
  9566. * Overwritten since this type of node is updated per object.
  9567. *
  9568. * @type {string}
  9569. * @default 'object'
  9570. */
  9571. this.updateType = NodeUpdateType.OBJECT;
  9572. /**
  9573. * Holds the value of the node as a uniform.
  9574. *
  9575. * @type {UniformNode}
  9576. */
  9577. this.uniformNode = new UniformNode( null );
  9578. }
  9579. /**
  9580. * Overwritten since the node type is inferred from the scope.
  9581. *
  9582. * @return {('mat4'|'vec3'|'float')} The node type.
  9583. */
  9584. getNodeType() {
  9585. const scope = this.scope;
  9586. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9587. return 'mat4';
  9588. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9589. return 'vec3';
  9590. } else if ( scope === Object3DNode.RADIUS ) {
  9591. return 'float';
  9592. }
  9593. }
  9594. /**
  9595. * Updates the uniform value depending on the scope.
  9596. *
  9597. * @param {NodeFrame} frame - The current node frame.
  9598. */
  9599. update( frame ) {
  9600. const object = this.object3d;
  9601. const uniformNode = this.uniformNode;
  9602. const scope = this.scope;
  9603. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9604. uniformNode.value = object.matrixWorld;
  9605. } else if ( scope === Object3DNode.POSITION ) {
  9606. uniformNode.value = uniformNode.value || new Vector3();
  9607. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9608. } else if ( scope === Object3DNode.SCALE ) {
  9609. uniformNode.value = uniformNode.value || new Vector3();
  9610. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  9611. } else if ( scope === Object3DNode.DIRECTION ) {
  9612. uniformNode.value = uniformNode.value || new Vector3();
  9613. object.getWorldDirection( uniformNode.value );
  9614. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  9615. const camera = frame.camera;
  9616. uniformNode.value = uniformNode.value || new Vector3();
  9617. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9618. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  9619. } else if ( scope === Object3DNode.RADIUS ) {
  9620. const geometry = frame.object.geometry;
  9621. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9622. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  9623. uniformNode.value = _sphere.radius;
  9624. }
  9625. }
  9626. /**
  9627. * Generates the code snippet of the uniform node. The node type of the uniform
  9628. * node also depends on the selected scope.
  9629. *
  9630. * @param {NodeBuilder} builder - The current node builder.
  9631. * @return {string} The generated code snippet.
  9632. */
  9633. generate( builder ) {
  9634. const scope = this.scope;
  9635. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9636. this.uniformNode.nodeType = 'mat4';
  9637. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9638. this.uniformNode.nodeType = 'vec3';
  9639. } else if ( scope === Object3DNode.RADIUS ) {
  9640. this.uniformNode.nodeType = 'float';
  9641. }
  9642. return this.uniformNode.build( builder );
  9643. }
  9644. serialize( data ) {
  9645. super.serialize( data );
  9646. data.scope = this.scope;
  9647. }
  9648. deserialize( data ) {
  9649. super.deserialize( data );
  9650. this.scope = data.scope;
  9651. }
  9652. }
  9653. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  9654. Object3DNode.POSITION = 'position';
  9655. Object3DNode.SCALE = 'scale';
  9656. Object3DNode.VIEW_POSITION = 'viewPosition';
  9657. Object3DNode.DIRECTION = 'direction';
  9658. Object3DNode.RADIUS = 'radius';
  9659. /**
  9660. * TSL function for creating an object 3D node that represents the object's direction in world space.
  9661. *
  9662. * @tsl
  9663. * @function
  9664. * @param {?Object3D} [object3d] - The 3D object.
  9665. * @returns {Object3DNode<vec3>}
  9666. */
  9667. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  9668. /**
  9669. * TSL function for creating an object 3D node that represents the object's world matrix.
  9670. *
  9671. * @tsl
  9672. * @function
  9673. * @param {?Object3D} [object3d] - The 3D object.
  9674. * @returns {Object3DNode<mat4>}
  9675. */
  9676. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  9677. /**
  9678. * TSL function for creating an object 3D node that represents the object's position in world space.
  9679. *
  9680. * @tsl
  9681. * @function
  9682. * @param {?Object3D} [object3d] - The 3D object.
  9683. * @returns {Object3DNode<vec3>}
  9684. */
  9685. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  9686. /**
  9687. * TSL function for creating an object 3D node that represents the object's scale in world space.
  9688. *
  9689. * @tsl
  9690. * @function
  9691. * @param {?Object3D} [object3d] - The 3D object.
  9692. * @returns {Object3DNode<vec3>}
  9693. */
  9694. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  9695. /**
  9696. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  9697. *
  9698. * @tsl
  9699. * @function
  9700. * @param {?Object3D} [object3d] - The 3D object.
  9701. * @returns {Object3DNode<vec3>}
  9702. */
  9703. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  9704. /**
  9705. * TSL function for creating an object 3D node that represents the object's radius.
  9706. *
  9707. * @tsl
  9708. * @function
  9709. * @param {?Object3D} [object3d] - The 3D object.
  9710. * @returns {Object3DNode<float>}
  9711. */
  9712. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  9713. /**
  9714. * This type of node is a specialized version of `Object3DNode`
  9715. * with larger set of model related metrics. Unlike `Object3DNode`,
  9716. * `ModelNode` extracts the reference to the 3D object from the
  9717. * current node frame state.
  9718. *
  9719. * @augments Object3DNode
  9720. */
  9721. class ModelNode extends Object3DNode {
  9722. static get type() {
  9723. return 'ModelNode';
  9724. }
  9725. /**
  9726. * Constructs a new object model node.
  9727. *
  9728. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9729. */
  9730. constructor( scope ) {
  9731. super( scope );
  9732. }
  9733. /**
  9734. * Extracts the model reference from the frame state and then
  9735. * updates the uniform value depending on the scope.
  9736. *
  9737. * @param {NodeFrame} frame - The current node frame.
  9738. */
  9739. update( frame ) {
  9740. this.object3d = frame.object;
  9741. super.update( frame );
  9742. }
  9743. }
  9744. /**
  9745. * TSL object that represents the object's direction in world space.
  9746. *
  9747. * @tsl
  9748. * @type {ModelNode<vec3>}
  9749. */
  9750. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  9751. /**
  9752. * TSL object that represents the object's world matrix.
  9753. *
  9754. * @tsl
  9755. * @type {ModelNode<mat4>}
  9756. */
  9757. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  9758. /**
  9759. * TSL object that represents the object's position in world space.
  9760. *
  9761. * @tsl
  9762. * @type {ModelNode<vec3>}
  9763. */
  9764. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  9765. /**
  9766. * TSL object that represents the object's scale in world space.
  9767. *
  9768. * @tsl
  9769. * @type {ModelNode<vec3>}
  9770. */
  9771. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  9772. /**
  9773. * TSL object that represents the object's position in view/camera space.
  9774. *
  9775. * @tsl
  9776. * @type {ModelNode<vec3>}
  9777. */
  9778. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  9779. /**
  9780. * TSL object that represents the object's radius.
  9781. *
  9782. * @tsl
  9783. * @type {ModelNode<float>}
  9784. */
  9785. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  9786. /**
  9787. * TSL object that represents the object's normal matrix.
  9788. *
  9789. * @tsl
  9790. * @type {UniformNode<mat3>}
  9791. */
  9792. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  9793. /**
  9794. * TSL object that represents the object's inverse world matrix.
  9795. *
  9796. * @tsl
  9797. * @type {UniformNode<mat4>}
  9798. */
  9799. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  9800. /**
  9801. * TSL object that represents the object's model view matrix.
  9802. *
  9803. * @tsl
  9804. * @type {Node<mat4>}
  9805. */
  9806. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9807. return builder.context.modelViewMatrix || mediumpModelViewMatrix;
  9808. } ).once() )().toVar( 'modelViewMatrix' );
  9809. // GPU Precision
  9810. /**
  9811. * TSL object that represents the object's model view in `mediump` precision.
  9812. *
  9813. * @tsl
  9814. * @type {Node<mat4>}
  9815. */
  9816. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  9817. // CPU Precision
  9818. /**
  9819. * TSL object that represents the object's model view in `highp` precision
  9820. * which is achieved by computing the matrix in JS and not in the shader.
  9821. *
  9822. * @tsl
  9823. * @type {Node<mat4>}
  9824. */
  9825. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9826. builder.context.isHighPrecisionModelViewMatrix = true;
  9827. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  9828. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9829. } );
  9830. } ).once() )().toVar( 'highpModelViewMatrix' );
  9831. /**
  9832. * TSL object that represents the object's model normal view in `highp` precision
  9833. * which is achieved by computing the matrix in JS and not in the shader.
  9834. *
  9835. * @tsl
  9836. * @type {Node<mat3>}
  9837. */
  9838. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9839. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  9840. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  9841. if ( isHighPrecisionModelViewMatrix !== true ) {
  9842. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9843. }
  9844. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  9845. } );
  9846. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  9847. /**
  9848. * TSL object that represents the position attribute of the current rendered object.
  9849. *
  9850. * @tsl
  9851. * @type {AttributeNode<vec3>}
  9852. */
  9853. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  9854. /**
  9855. * TSL object that represents the vertex position in local space of the current rendered object.
  9856. *
  9857. * @tsl
  9858. * @type {AttributeNode<vec3>}
  9859. */
  9860. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  9861. /**
  9862. * TSL object that represents the previous vertex position in local space of the current rendered object.
  9863. * Used in context of {@link VelocityNode} for rendering motion vectors.
  9864. *
  9865. * @tsl
  9866. * @type {AttributeNode<vec3>}
  9867. */
  9868. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  9869. /**
  9870. * TSL object that represents the vertex position in world space of the current rendered object.
  9871. *
  9872. * @tsl
  9873. * @type {VaryingNode<vec3>}
  9874. */
  9875. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  9876. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getSubBuildProperty( 'v_positionWorld' ) );
  9877. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9878. /**
  9879. * TSL object that represents the position world direction of the current rendered object.
  9880. *
  9881. * @tsl
  9882. * @type {Node<vec3>}
  9883. */
  9884. const positionWorldDirection = /*@__PURE__*/ ( Fn( () => {
  9885. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' );
  9886. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  9887. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9888. /**
  9889. * TSL object that represents the vertex position in view space of the current rendered object.
  9890. *
  9891. * @tsl
  9892. * @type {VaryingNode<vec3>}
  9893. */
  9894. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  9895. return builder.context.setupPositionView().toVarying( 'v_positionView' );
  9896. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9897. /**
  9898. * TSL object that represents the position view direction of the current rendered object.
  9899. *
  9900. * @tsl
  9901. * @type {VaryingNode<vec3>}
  9902. */
  9903. const positionViewDirection = /*@__PURE__*/ ( Fn( ( builder ) => {
  9904. let output;
  9905. if ( builder.camera.isOrthographicCamera ) {
  9906. output = vec3( 0, 0, 1 );
  9907. } else {
  9908. output = positionView.negate().toVarying( 'v_positionViewDirection' ).normalize();
  9909. }
  9910. return output.toVar( 'positionViewDirection' );
  9911. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9912. /**
  9913. * This node can be used to evaluate whether a primitive is front or back facing.
  9914. *
  9915. * @augments Node
  9916. */
  9917. class FrontFacingNode extends Node {
  9918. static get type() {
  9919. return 'FrontFacingNode';
  9920. }
  9921. /**
  9922. * Constructs a new front facing node.
  9923. */
  9924. constructor() {
  9925. super( 'bool' );
  9926. /**
  9927. * This flag can be used for type testing.
  9928. *
  9929. * @type {boolean}
  9930. * @readonly
  9931. * @default true
  9932. */
  9933. this.isFrontFacingNode = true;
  9934. }
  9935. generate( builder ) {
  9936. if ( builder.shaderStage !== 'fragment' ) return 'true';
  9937. //
  9938. const { material } = builder;
  9939. if ( material.side === BackSide ) {
  9940. return 'false';
  9941. }
  9942. return builder.getFrontFacing();
  9943. }
  9944. }
  9945. /**
  9946. * TSL object that represents whether a primitive is front or back facing
  9947. *
  9948. * @tsl
  9949. * @type {FrontFacingNode<bool>}
  9950. */
  9951. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  9952. /**
  9953. * TSL object that represents the front facing status as a number instead of a bool.
  9954. * `1` means front facing, `-1` means back facing.
  9955. *
  9956. * @tsl
  9957. * @type {Node<float>}
  9958. */
  9959. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  9960. /**
  9961. * Converts a direction vector to a face direction vector based on the material's side.
  9962. *
  9963. * If the material is set to `BackSide`, the direction is inverted.
  9964. * If the material is set to `DoubleSide`, the direction is multiplied by `faceDirection`.
  9965. *
  9966. * @tsl
  9967. * @param {Node<vec3>} direction - The direction vector to convert.
  9968. * @returns {Node<vec3>} The converted direction vector.
  9969. */
  9970. const directionToFaceDirection = /*@__PURE__*/ Fn( ( [ direction ], { material } ) => {
  9971. const side = material.side;
  9972. if ( side === BackSide ) {
  9973. direction = direction.mul( -1 );
  9974. } else if ( side === DoubleSide ) {
  9975. direction = direction.mul( faceDirection );
  9976. }
  9977. return direction;
  9978. } );
  9979. /**
  9980. * TSL object that represents the normal attribute of the current rendered object in local space.
  9981. *
  9982. * @tsl
  9983. * @type {Node<vec3>}
  9984. */
  9985. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  9986. /**
  9987. * TSL object that represents the vertex normal of the current rendered object in local space.
  9988. *
  9989. * @tsl
  9990. * @type {Node<vec3>}
  9991. */
  9992. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  9993. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  9994. warn( 'TSL: Vertex attribute "normal" not found on geometry.' );
  9995. return vec3( 0, 1, 0 );
  9996. }
  9997. return normalGeometry;
  9998. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  9999. /**
  10000. * TSL object that represents the flat vertex normal of the current rendered object in view space.
  10001. *
  10002. * @tsl
  10003. * @type {Node<vec3>}
  10004. */
  10005. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  10006. /**
  10007. * TSL object that represents the vertex normal of the current rendered object in view space.
  10008. *
  10009. * @tsl
  10010. * @type {Node<vec3>}
  10011. */
  10012. const normalViewGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  10013. let node;
  10014. if ( builder.material.flatShading === true ) {
  10015. node = normalFlat;
  10016. } else {
  10017. node = transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry' ).normalize();
  10018. }
  10019. return node;
  10020. }, 'vec3' ).once() )().toVar( 'normalViewGeometry' );
  10021. /**
  10022. * TSL object that represents the vertex normal of the current rendered object in world space.
  10023. *
  10024. * @tsl
  10025. * @type {Node<vec3>}
  10026. */
  10027. const normalWorldGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  10028. let normal = normalViewGeometry.transformDirection( cameraViewMatrix );
  10029. if ( builder.material.flatShading !== true ) {
  10030. normal = normal.toVarying( 'v_normalWorldGeometry' );
  10031. }
  10032. return normal.normalize().toVar( 'normalWorldGeometry' );
  10033. }, 'vec3' ).once() )();
  10034. /**
  10035. * TSL object that represents the vertex normal of the current rendered object in view space.
  10036. *
  10037. * @tsl
  10038. * @type {Node<vec3>}
  10039. */
  10040. const normalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, material, context } ) => {
  10041. let node;
  10042. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  10043. node = normalViewGeometry;
  10044. if ( material.flatShading !== true ) {
  10045. node = directionToFaceDirection( node );
  10046. }
  10047. } else {
  10048. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  10049. node = context.setupNormal().context( { getUV: null } );
  10050. }
  10051. return node;
  10052. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'normalView' );
  10053. /**
  10054. * TSL object that represents the vertex normal of the current rendered object in world space.
  10055. *
  10056. * @tsl
  10057. * @type {Node<vec3>}
  10058. */
  10059. const normalWorld = /*@__PURE__*/ normalView.transformDirection( cameraViewMatrix ).toVar( 'normalWorld' );
  10060. /**
  10061. * TSL object that represents the clearcoat vertex normal of the current rendered object in view space.
  10062. *
  10063. * @tsl
  10064. * @type {Node<vec3>}
  10065. */
  10066. const clearcoatNormalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, context } ) => {
  10067. let node;
  10068. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  10069. node = normalView;
  10070. } else {
  10071. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  10072. node = context.setupClearcoatNormal().context( { getUV: null } );
  10073. }
  10074. return node;
  10075. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'clearcoatNormalView' );
  10076. /**
  10077. * Transforms the normal with the given matrix.
  10078. *
  10079. * @tsl
  10080. * @function
  10081. * @param {Node<vec3>} normal - The normal.
  10082. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  10083. * @return {Node<vec3>} The transformed normal.
  10084. */
  10085. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  10086. const m = mat3( matrix );
  10087. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  10088. return m.mul( transformedNormal ).xyz;
  10089. } );
  10090. /**
  10091. * Transforms the given normal from local to view space.
  10092. *
  10093. * @tsl
  10094. * @function
  10095. * @param {Node<vec3>} normal - The normal.
  10096. * @param {NodeBuilder} builder - The current node builder.
  10097. * @return {Node<vec3>} The transformed normal.
  10098. */
  10099. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  10100. const modelNormalViewMatrix = builder.context.modelNormalViewMatrix;
  10101. if ( modelNormalViewMatrix ) {
  10102. return modelNormalViewMatrix.transformDirection( normal );
  10103. }
  10104. //
  10105. const transformedNormal = modelNormalMatrix.mul( normal );
  10106. return cameraViewMatrix.transformDirection( transformedNormal );
  10107. } );
  10108. // Deprecated
  10109. /**
  10110. * TSL object that represents the transformed vertex normal of the current rendered object in view space.
  10111. *
  10112. * @tsl
  10113. * @type {Node<vec3>}
  10114. * @deprecated since r178. Use `normalView` instead.
  10115. */
  10116. const transformedNormalView = ( Fn( () => { // @deprecated, r177
  10117. warn( 'TSL: "transformedNormalView" is deprecated. Use "normalView" instead.' );
  10118. return normalView;
  10119. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10120. /**
  10121. * TSL object that represents the transformed vertex normal of the current rendered object in world space.
  10122. *
  10123. * @tsl
  10124. * @type {Node<vec3>}
  10125. * @deprecated since r178. Use `normalWorld` instead.
  10126. */
  10127. const transformedNormalWorld = ( Fn( () => { // @deprecated, r177
  10128. warn( 'TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.' );
  10129. return normalWorld;
  10130. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10131. /**
  10132. * TSL object that represents the transformed clearcoat vertex normal of the current rendered object in view space.
  10133. *
  10134. * @tsl
  10135. * @type {Node<vec3>}
  10136. * @deprecated since r178. Use `clearcoatNormalView` instead.
  10137. */
  10138. const transformedClearcoatNormalView = ( Fn( () => { // @deprecated, r177
  10139. warn( 'TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.' );
  10140. return clearcoatNormalView;
  10141. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10142. const _e1$1 = /*@__PURE__*/ new Euler();
  10143. const _m1$1 = /*@__PURE__*/ new Matrix4();
  10144. /**
  10145. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  10146. *
  10147. * @tsl
  10148. * @type {UniformNode<float>}
  10149. */
  10150. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  10151. /**
  10152. * TSL object that represents the intensity of environment maps of PBR materials.
  10153. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  10154. *
  10155. * @tsl
  10156. * @type {Node<float>}
  10157. */
  10158. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  10159. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  10160. } );
  10161. /**
  10162. * TSL object that represents the rotation of environment maps.
  10163. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  10164. * rotation of `scene.environment` instead.
  10165. *
  10166. * @tsl
  10167. * @type {Node<mat4>}
  10168. */
  10169. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  10170. return frame.material;
  10171. } ).onObjectUpdate( function ( { material, scene } ) {
  10172. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  10173. if ( rotation ) {
  10174. _e1$1.copy( rotation );
  10175. _m1$1.makeRotationFromEuler( _e1$1 );
  10176. } else {
  10177. _m1$1.identity();
  10178. }
  10179. return _m1$1;
  10180. } );
  10181. /**
  10182. * The reflect vector in view space.
  10183. *
  10184. * @tsl
  10185. * @type {Node<vec3>}
  10186. */
  10187. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( normalView );
  10188. /**
  10189. * The refract vector in view space.
  10190. *
  10191. * @tsl
  10192. * @type {Node<vec3>}
  10193. */
  10194. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( normalView, materialRefractionRatio );
  10195. /**
  10196. * Used for sampling cube maps when using cube reflection mapping.
  10197. *
  10198. * @tsl
  10199. * @type {Node<vec3>}
  10200. */
  10201. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  10202. /**
  10203. * Used for sampling cube maps when using cube refraction mapping.
  10204. *
  10205. * @tsl
  10206. * @type {Node<vec3>}
  10207. */
  10208. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  10209. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  10210. /**
  10211. * This type of uniform node represents a cube texture.
  10212. *
  10213. * @augments TextureNode
  10214. */
  10215. class CubeTextureNode extends TextureNode {
  10216. static get type() {
  10217. return 'CubeTextureNode';
  10218. }
  10219. /**
  10220. * Constructs a new cube texture node.
  10221. *
  10222. * @param {CubeTexture} value - The cube texture.
  10223. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10224. * @param {?Node<int>} [levelNode=null] - The level node.
  10225. * @param {?Node<float>} [biasNode=null] - The bias node.
  10226. */
  10227. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  10228. super( value, uvNode, levelNode, biasNode );
  10229. /**
  10230. * This flag can be used for type testing.
  10231. *
  10232. * @type {boolean}
  10233. * @readonly
  10234. * @default true
  10235. */
  10236. this.isCubeTextureNode = true;
  10237. }
  10238. /**
  10239. * Overwrites the default implementation to return the appropriate cube texture type.
  10240. *
  10241. * @param {NodeBuilder} builder - The current node builder.
  10242. * @return {string} The input type.
  10243. */
  10244. getInputType( /*builder*/ ) {
  10245. if ( this.value.isDepthTexture === true ) {
  10246. return 'cubeDepthTexture';
  10247. }
  10248. return 'cubeTexture';
  10249. }
  10250. /**
  10251. * Returns a default uvs based on the mapping type of the cube texture.
  10252. *
  10253. * @return {Node<vec3>} The default uv attribute.
  10254. */
  10255. getDefaultUV() {
  10256. const texture = this.value;
  10257. if ( texture.mapping === CubeReflectionMapping ) {
  10258. return reflectVector;
  10259. } else if ( texture.mapping === CubeRefractionMapping ) {
  10260. return refractVector;
  10261. } else {
  10262. error( 'CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  10263. return vec3( 0, 0, 0 );
  10264. }
  10265. }
  10266. /**
  10267. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  10268. * for cube textures. The uv transformation matrix is not applied to cube textures.
  10269. *
  10270. * @param {boolean} value - The update toggle.
  10271. */
  10272. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  10273. /**
  10274. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  10275. * to modify the uv node for correct sampling.
  10276. *
  10277. * @param {NodeBuilder} builder - The current node builder.
  10278. * @param {Node} uvNode - The uv node to setup.
  10279. * @return {Node} The updated uv node.
  10280. */
  10281. setupUV( builder, uvNode ) {
  10282. const texture = this.value;
  10283. // Depth textures (shadow maps) - no environment rotation, Y flip for WebGPU
  10284. if ( texture.isDepthTexture === true ) {
  10285. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  10286. return vec3( uvNode.x, uvNode.y.negate(), uvNode.z );
  10287. }
  10288. return uvNode;
  10289. }
  10290. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  10291. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  10292. }
  10293. return materialEnvRotation.mul( uvNode );
  10294. }
  10295. /**
  10296. * Generates the uv code snippet.
  10297. *
  10298. * @param {NodeBuilder} builder - The current node builder.
  10299. * @param {Node} cubeUV - The uv node to generate code for.
  10300. * @return {string} The generated code snippet.
  10301. */
  10302. generateUV( builder, cubeUV ) {
  10303. return cubeUV.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  10304. }
  10305. }
  10306. /**
  10307. * TSL function for creating a cube texture node.
  10308. *
  10309. * @tsl
  10310. * @function
  10311. * @param {CubeTexture} value - The cube texture.
  10312. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10313. * @param {?Node<int>} [levelNode=null] - The level node.
  10314. * @param {?Node<float>} [biasNode=null] - The bias node.
  10315. * @returns {CubeTextureNode}
  10316. */
  10317. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  10318. /**
  10319. * TSL function for creating a cube texture uniform node.
  10320. *
  10321. * @tsl
  10322. * @function
  10323. * @param {?(CubeTexture|CubeTextureNode)} [value=EmptyTexture] - The cube texture.
  10324. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10325. * @param {?Node<int>} [levelNode=null] - The level node.
  10326. * @param {?Node<float>} [biasNode=null] - The bias node.
  10327. * @returns {CubeTextureNode}
  10328. */
  10329. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  10330. let textureNode;
  10331. if ( value && value.isCubeTextureNode === true ) {
  10332. textureNode = nodeObject( value.clone() );
  10333. textureNode.referenceNode = value; // Ensure the reference is set to the original node
  10334. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  10335. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  10336. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  10337. } else {
  10338. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  10339. }
  10340. return textureNode;
  10341. };
  10342. /**
  10343. * TSL function for creating a uniform cube texture node.
  10344. *
  10345. * @tsl
  10346. * @function
  10347. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  10348. * @returns {CubeTextureNode}
  10349. */
  10350. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  10351. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  10352. /**
  10353. * This class is only relevant if the referenced property is array-like.
  10354. * In this case, `ReferenceElementNode` allows to refer to a specific
  10355. * element inside the data structure via an index.
  10356. *
  10357. * @augments ArrayElementNode
  10358. */
  10359. class ReferenceElementNode extends ArrayElementNode {
  10360. static get type() {
  10361. return 'ReferenceElementNode';
  10362. }
  10363. /**
  10364. * Constructs a new reference element node.
  10365. *
  10366. * @param {?ReferenceNode} referenceNode - The reference node.
  10367. * @param {Node} indexNode - The index node that defines the element access.
  10368. */
  10369. constructor( referenceNode, indexNode ) {
  10370. super( referenceNode, indexNode );
  10371. /**
  10372. * Similar to {@link ReferenceNode#reference}, an additional
  10373. * property references to the current node.
  10374. *
  10375. * @type {?ReferenceNode}
  10376. * @default null
  10377. */
  10378. this.referenceNode = referenceNode;
  10379. /**
  10380. * This flag can be used for type testing.
  10381. *
  10382. * @type {boolean}
  10383. * @readonly
  10384. * @default true
  10385. */
  10386. this.isReferenceElementNode = true;
  10387. }
  10388. /**
  10389. * This method is overwritten since the node type is inferred from
  10390. * the uniform type of the reference node.
  10391. *
  10392. * @return {string} The node type.
  10393. */
  10394. getNodeType() {
  10395. return this.referenceNode.uniformType;
  10396. }
  10397. generate( builder ) {
  10398. const snippet = super.generate( builder );
  10399. const arrayType = this.referenceNode.getNodeType();
  10400. const elementType = this.getNodeType();
  10401. return builder.format( snippet, arrayType, elementType );
  10402. }
  10403. }
  10404. /**
  10405. * This type of node establishes a reference to a property of another object.
  10406. * In this way, the value of the node is automatically linked to the value of
  10407. * referenced object. Reference nodes internally represent the linked value
  10408. * as a uniform.
  10409. *
  10410. * @augments Node
  10411. */
  10412. class ReferenceNode extends Node {
  10413. static get type() {
  10414. return 'ReferenceNode';
  10415. }
  10416. /**
  10417. * Constructs a new reference node.
  10418. *
  10419. * @param {string} property - The name of the property the node refers to.
  10420. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  10421. * @param {?Object} [object=null] - The object the property belongs to.
  10422. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  10423. */
  10424. constructor( property, uniformType, object = null, count = null ) {
  10425. super();
  10426. /**
  10427. * The name of the property the node refers to.
  10428. *
  10429. * @type {string}
  10430. */
  10431. this.property = property;
  10432. /**
  10433. * The uniform type that should be used to represent the property value.
  10434. *
  10435. * @type {string}
  10436. */
  10437. this.uniformType = uniformType;
  10438. /**
  10439. * The object the property belongs to.
  10440. *
  10441. * @type {?Object}
  10442. * @default null
  10443. */
  10444. this.object = object;
  10445. /**
  10446. * When the linked property is an array, this parameter defines its length.
  10447. *
  10448. * @type {?number}
  10449. * @default null
  10450. */
  10451. this.count = count;
  10452. /**
  10453. * The property name might have dots so nested properties can be referred.
  10454. * The hierarchy of the names is stored inside this array.
  10455. *
  10456. * @type {Array<string>}
  10457. */
  10458. this.properties = property.split( '.' );
  10459. /**
  10460. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  10461. * since the final reference might be updated from calling code.
  10462. *
  10463. * @type {?Object}
  10464. * @default null
  10465. */
  10466. this.reference = object;
  10467. /**
  10468. * The uniform node that holds the value of the reference node.
  10469. *
  10470. * @type {UniformNode}
  10471. * @default null
  10472. */
  10473. this.node = null;
  10474. /**
  10475. * The uniform group of the internal uniform.
  10476. *
  10477. * @type {UniformGroupNode}
  10478. * @default null
  10479. */
  10480. this.group = null;
  10481. /**
  10482. * An optional label of the internal uniform node.
  10483. *
  10484. * @type {?string}
  10485. * @default null
  10486. */
  10487. this.name = null;
  10488. /**
  10489. * Overwritten since reference nodes are updated per object.
  10490. *
  10491. * @type {string}
  10492. * @default 'object'
  10493. */
  10494. this.updateType = NodeUpdateType.OBJECT;
  10495. }
  10496. /**
  10497. * When the referred property is array-like, this method can be used
  10498. * to access elements via an index node.
  10499. *
  10500. * @param {IndexNode} indexNode - indexNode.
  10501. * @return {ReferenceElementNode} A reference to an element.
  10502. */
  10503. element( indexNode ) {
  10504. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  10505. }
  10506. /**
  10507. * Sets the uniform group for this reference node.
  10508. *
  10509. * @param {UniformGroupNode} group - The uniform group to set.
  10510. * @return {ReferenceNode} A reference to this node.
  10511. */
  10512. setGroup( group ) {
  10513. this.group = group;
  10514. return this;
  10515. }
  10516. /**
  10517. * Sets the name for the internal uniform.
  10518. *
  10519. * @param {string} name - The label to set.
  10520. * @return {ReferenceNode} A reference to this node.
  10521. */
  10522. setName( name ) {
  10523. this.name = name;
  10524. return this;
  10525. }
  10526. /**
  10527. * Sets the label for the internal uniform.
  10528. *
  10529. * @deprecated
  10530. * @param {string} name - The label to set.
  10531. * @return {ReferenceNode} A reference to this node.
  10532. */
  10533. label( name ) {
  10534. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  10535. return this.setName( name );
  10536. }
  10537. /**
  10538. * Sets the node type which automatically defines the internal
  10539. * uniform type.
  10540. *
  10541. * @param {string} uniformType - The type to set.
  10542. */
  10543. setNodeType( uniformType ) {
  10544. let node = null;
  10545. if ( this.count !== null ) {
  10546. node = buffer( null, uniformType, this.count );
  10547. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  10548. node = uniformArray( null, uniformType );
  10549. } else if ( uniformType === 'texture' ) {
  10550. node = texture( null );
  10551. } else if ( uniformType === 'cubeTexture' ) {
  10552. node = cubeTexture( null );
  10553. } else {
  10554. node = uniform( null, uniformType );
  10555. }
  10556. if ( this.group !== null ) {
  10557. node.setGroup( this.group );
  10558. }
  10559. if ( this.name !== null ) node.setName( this.name );
  10560. this.node = node;
  10561. }
  10562. /**
  10563. * This method is overwritten since the node type is inferred from
  10564. * the type of the reference node.
  10565. *
  10566. * @param {NodeBuilder} builder - The current node builder.
  10567. * @return {string} The node type.
  10568. */
  10569. getNodeType( builder ) {
  10570. if ( this.node === null ) {
  10571. this.updateReference( builder );
  10572. this.updateValue();
  10573. }
  10574. return this.node.getNodeType( builder );
  10575. }
  10576. /**
  10577. * Returns the property value from the given referred object.
  10578. *
  10579. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  10580. * @return {any} The value.
  10581. */
  10582. getValueFromReference( object = this.reference ) {
  10583. const { properties } = this;
  10584. let value = object[ properties[ 0 ] ];
  10585. for ( let i = 1; i < properties.length; i ++ ) {
  10586. value = value[ properties[ i ] ];
  10587. }
  10588. return value;
  10589. }
  10590. /**
  10591. * Allows to update the reference based on the given state. The state is only
  10592. * evaluated {@link ReferenceNode#object} is not set.
  10593. *
  10594. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10595. * @return {Object} The updated reference.
  10596. */
  10597. updateReference( state ) {
  10598. this.reference = this.object !== null ? this.object : state.object;
  10599. return this.reference;
  10600. }
  10601. /**
  10602. * The output of the reference node is the internal uniform node.
  10603. *
  10604. * @param {NodeBuilder} builder - The current node builder.
  10605. * @return {UniformNode} The output node.
  10606. */
  10607. setup( /* builder */ ) {
  10608. this.updateValue();
  10609. return this.node;
  10610. }
  10611. /**
  10612. * Overwritten to update the internal uniform value.
  10613. *
  10614. * @param {NodeFrame} frame - A reference to the current node frame.
  10615. */
  10616. update( /*frame*/ ) {
  10617. this.updateValue();
  10618. }
  10619. /**
  10620. * Retrieves the value from the referred object property and uses it
  10621. * to updated the internal uniform.
  10622. */
  10623. updateValue() {
  10624. if ( this.node === null ) this.setNodeType( this.uniformType );
  10625. const value = this.getValueFromReference();
  10626. if ( Array.isArray( value ) ) {
  10627. this.node.array = value;
  10628. } else {
  10629. this.node.value = value;
  10630. }
  10631. }
  10632. }
  10633. /**
  10634. * TSL function for creating a reference node.
  10635. *
  10636. * @tsl
  10637. * @function
  10638. * @param {string} name - The name of the property the node refers to.
  10639. * @param {string} type - The uniform type that should be used to represent the property value.
  10640. * @param {?Object} [object] - The object the property belongs to.
  10641. * @returns {ReferenceNode}
  10642. */
  10643. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  10644. /**
  10645. * TSL function for creating a reference node. Use this function if you want need a reference
  10646. * to an array-like property that should be represented as a uniform buffer.
  10647. *
  10648. * @tsl
  10649. * @function
  10650. * @param {string} name - The name of the property the node refers to.
  10651. * @param {string} type - The uniform type that should be used to represent the property value.
  10652. * @param {number} count - The number of value inside the array-like object.
  10653. * @param {Object} object - An array-like object the property belongs to.
  10654. * @returns {ReferenceNode}
  10655. */
  10656. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  10657. /**
  10658. * This node is a special type of reference node which is intended
  10659. * for linking material properties with node values.
  10660. * ```js
  10661. * const opacityNode = materialReference( 'opacity', 'float', material );
  10662. * ```
  10663. * When changing `material.opacity`, the node value of `opacityNode` will
  10664. * automatically be updated.
  10665. *
  10666. * @augments ReferenceNode
  10667. */
  10668. class MaterialReferenceNode extends ReferenceNode {
  10669. static get type() {
  10670. return 'MaterialReferenceNode';
  10671. }
  10672. /**
  10673. * Constructs a new material reference node.
  10674. *
  10675. * @param {string} property - The name of the property the node refers to.
  10676. * @param {string} inputType - The uniform type that should be used to represent the property value.
  10677. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  10678. * the node refers to the material of the current rendered object.
  10679. */
  10680. constructor( property, inputType, material = null ) {
  10681. super( property, inputType, material );
  10682. /**
  10683. * The material the property belongs to. When no material is set,
  10684. * the node refers to the material of the current rendered object.
  10685. *
  10686. * @type {?Material}
  10687. * @default null
  10688. */
  10689. this.material = material;
  10690. /**
  10691. * This flag can be used for type testing.
  10692. *
  10693. * @type {boolean}
  10694. * @readonly
  10695. * @default true
  10696. */
  10697. this.isMaterialReferenceNode = true;
  10698. }
  10699. /**
  10700. * Updates the reference based on the given state. The state is only evaluated
  10701. * {@link MaterialReferenceNode#material} is not set.
  10702. *
  10703. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10704. * @return {Object} The updated reference.
  10705. */
  10706. updateReference( state ) {
  10707. this.reference = this.material !== null ? this.material : state.material;
  10708. return this.reference;
  10709. }
  10710. }
  10711. /**
  10712. * TSL function for creating a material reference node.
  10713. *
  10714. * @tsl
  10715. * @function
  10716. * @param {string} name - The name of the property the node refers to.
  10717. * @param {string} type - The uniform type that should be used to represent the property value.
  10718. * @param {?Material} [material=null] - The material the property belongs to.
  10719. * When no material is set, the node refers to the material of the current rendered object.
  10720. * @returns {MaterialReferenceNode}
  10721. */
  10722. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  10723. // Normal Mapping Without Precomputed Tangents
  10724. // http://www.thetenthplanet.de/archives/1180
  10725. const uv = uv$1();
  10726. const q0 = positionView.dFdx();
  10727. const q1 = positionView.dFdy();
  10728. const st0 = uv.dFdx();
  10729. const st1 = uv.dFdy();
  10730. const N = normalView;
  10731. const q1perp = q1.cross( N );
  10732. const q0perp = N.cross( q0 );
  10733. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  10734. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  10735. const det = T.dot( T ).max( B.dot( B ) );
  10736. const scale$1 = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() );
  10737. /**
  10738. * Tangent vector in view space, computed dynamically from geometry and UV derivatives.
  10739. * Useful for normal mapping without precomputed tangents.
  10740. *
  10741. * Reference: http://www.thetenthplanet.de/archives/1180
  10742. *
  10743. * @tsl
  10744. * @type {Node<vec3>}
  10745. */
  10746. const tangentViewFrame = /*@__PURE__*/ T.mul( scale$1 ).toVar( 'tangentViewFrame' );
  10747. /**
  10748. * Bitangent vector in view space, computed dynamically from geometry and UV derivatives.
  10749. * Complements the tangentViewFrame for constructing the tangent space basis.
  10750. *
  10751. * Reference: http://www.thetenthplanet.de/archives/1180
  10752. *
  10753. * @tsl
  10754. * @type {Node<vec3>}
  10755. */
  10756. const bitangentViewFrame = /*@__PURE__*/ B.mul( scale$1 ).toVar( 'bitangentViewFrame' );
  10757. /**
  10758. * TSL object that represents the tangent attribute of the current rendered object.
  10759. *
  10760. * @tsl
  10761. * @type {Node<vec4>}
  10762. */
  10763. const tangentGeometry = /*@__PURE__*/ attribute( 'tangent', 'vec4' );
  10764. /**
  10765. * TSL object that represents the vertex tangent in local space of the current rendered object.
  10766. *
  10767. * @tsl
  10768. * @type {Node<vec3>}
  10769. */
  10770. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  10771. /**
  10772. * TSL object that represents the vertex tangent in view space of the current rendered object.
  10773. *
  10774. * @tsl
  10775. * @type {Node<vec3>}
  10776. */
  10777. const tangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10778. let node;
  10779. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10780. node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize();
  10781. } else {
  10782. node = tangentViewFrame;
  10783. }
  10784. if ( material.flatShading !== true ) {
  10785. node = directionToFaceDirection( node );
  10786. }
  10787. return node;
  10788. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' );
  10789. /**
  10790. * TSL object that represents the vertex tangent in world space of the current rendered object.
  10791. *
  10792. * @tsl
  10793. * @type {Node<vec3>}
  10794. */
  10795. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  10796. /**
  10797. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  10798. *
  10799. * @tsl
  10800. * @private
  10801. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  10802. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  10803. * @returns {Node<vec3>} The bitangent node.
  10804. */
  10805. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], { subBuildFn, material } ) => {
  10806. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  10807. if ( subBuildFn === 'NORMAL' && material.flatShading !== true ) {
  10808. bitangent = bitangent.toVarying( varyingName );
  10809. }
  10810. return bitangent;
  10811. } ).once( [ 'NORMAL' ] );
  10812. /**
  10813. * TSL object that represents the bitangent attribute of the current rendered object.
  10814. *
  10815. * @tsl
  10816. * @type {Node<vec3>}
  10817. */
  10818. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  10819. /**
  10820. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  10821. *
  10822. * @tsl
  10823. * @type {Node<vec3>}
  10824. */
  10825. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  10826. /**
  10827. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  10828. *
  10829. * @tsl
  10830. * @type {Node<vec3>}
  10831. */
  10832. const bitangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10833. let node;
  10834. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10835. node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize();
  10836. } else {
  10837. node = bitangentViewFrame;
  10838. }
  10839. if ( material.flatShading !== true ) {
  10840. node = directionToFaceDirection( node );
  10841. }
  10842. return node;
  10843. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' );
  10844. /**
  10845. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  10846. *
  10847. * @tsl
  10848. * @type {Node<vec3>}
  10849. */
  10850. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  10851. /**
  10852. * TSL object that represents the TBN matrix in view space.
  10853. *
  10854. * @tsl
  10855. * @type {Node<mat3>}
  10856. */
  10857. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView ).toVar( 'TBNViewMatrix' );
  10858. /**
  10859. * TSL object that represents the parallax direction.
  10860. *
  10861. * @tsl
  10862. * @type {Node<mat3>}
  10863. */
  10864. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  10865. /**
  10866. * TSL function for computing parallax uv coordinates.
  10867. *
  10868. * @tsl
  10869. * @function
  10870. * @param {Node<vec2>} uv - A uv node.
  10871. * @param {Node<vec2>} scale - A scale node.
  10872. * @returns {Node<vec2>} Parallax uv coordinates.
  10873. */
  10874. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  10875. /**
  10876. * TSL function for computing bent normals.
  10877. *
  10878. * @tsl
  10879. * @function
  10880. * @returns {Node<vec3>} Bent normals.
  10881. */
  10882. const bentNormalView = /*@__PURE__*/ ( Fn( () => {
  10883. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  10884. let bentNormal = anisotropyB.cross( positionViewDirection );
  10885. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  10886. bentNormal = mix( bentNormal, normalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  10887. return bentNormal;
  10888. } ).once() )();
  10889. /**
  10890. * Packs a direction vector into a color value.
  10891. *
  10892. * @tsl
  10893. * @function
  10894. * @param {Node<vec3>} node - The direction to pack.
  10895. * @return {Node<vec3>} The color.
  10896. */
  10897. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  10898. /**
  10899. * Unpacks a color value into a direction vector.
  10900. *
  10901. * @tsl
  10902. * @function
  10903. * @param {Node<vec3>} node - The color to unpack.
  10904. * @return {Node<vec3>} The direction.
  10905. */
  10906. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  10907. /**
  10908. * Unpacks a tangent space normal, reconstructing the Z component by projecting the X,Y coordinates onto the hemisphere.
  10909. * The X,Y coordinates are expected to be in the [-1, 1] range.
  10910. *
  10911. * @tsl
  10912. * @function
  10913. * @param {Node<vec2>} xy - The X,Y coordinates of the normal.
  10914. * @return {Node<vec3>} The resulting normal.
  10915. */
  10916. const unpackNormal = ( xy ) => vec3( xy, sqrt( saturate( float( 1.0 ).sub( dot( xy, xy ) ) ) ) );
  10917. /**
  10918. * This class can be used for applying normals maps to materials.
  10919. *
  10920. * ```js
  10921. * material.normalNode = normalMap( texture( normalTex ) );
  10922. * ```
  10923. *
  10924. * @augments TempNode
  10925. */
  10926. class NormalMapNode extends TempNode {
  10927. static get type() {
  10928. return 'NormalMapNode';
  10929. }
  10930. /**
  10931. * Constructs a new normal map node.
  10932. *
  10933. * @param {Node<vec3>} node - Represents the normal map data.
  10934. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10935. */
  10936. constructor( node, scaleNode = null ) {
  10937. super( 'vec3' );
  10938. /**
  10939. * Represents the normal map data.
  10940. *
  10941. * @type {Node<vec3>}
  10942. */
  10943. this.node = node;
  10944. /**
  10945. * Controls the intensity of the effect.
  10946. *
  10947. * @type {?Node<vec2>}
  10948. * @default null
  10949. */
  10950. this.scaleNode = scaleNode;
  10951. /**
  10952. * The normal map type.
  10953. *
  10954. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  10955. * @default TangentSpaceNormalMap
  10956. */
  10957. this.normalMapType = TangentSpaceNormalMap;
  10958. /**
  10959. * Controls how to unpack the sampled normal map values.
  10960. *
  10961. * @type {string}
  10962. * @default NoNormalPacking
  10963. */
  10964. this.unpackNormalMode = NoNormalPacking;
  10965. }
  10966. setup( { material } ) {
  10967. const { normalMapType, scaleNode, unpackNormalMode } = this;
  10968. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  10969. if ( normalMapType === TangentSpaceNormalMap ) {
  10970. if ( unpackNormalMode === NormalRGPacking ) {
  10971. normalMap = unpackNormal( normalMap.xy );
  10972. } else if ( unpackNormalMode === NormalGAPacking ) {
  10973. normalMap = unpackNormal( normalMap.yw );
  10974. } else if ( unpackNormalMode !== NoNormalPacking ) {
  10975. console.error( `THREE.NodeMaterial: Unexpected unpack normal mode: ${ unpackNormalMode }` );
  10976. }
  10977. } else {
  10978. if ( unpackNormalMode !== NoNormalPacking ) {
  10979. console.error( `THREE.NodeMaterial: Normal map type '${ normalMapType }' is not compatible with unpack normal mode '${ unpackNormalMode }'` );
  10980. }
  10981. }
  10982. if ( scaleNode !== null ) {
  10983. let scale = scaleNode;
  10984. if ( material.flatShading === true ) {
  10985. scale = directionToFaceDirection( scale );
  10986. }
  10987. normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z );
  10988. }
  10989. let output = null;
  10990. if ( normalMapType === ObjectSpaceNormalMap ) {
  10991. output = transformNormalToView( normalMap );
  10992. } else if ( normalMapType === TangentSpaceNormalMap ) {
  10993. output = TBNViewMatrix.mul( normalMap ).normalize();
  10994. } else {
  10995. error( `NodeMaterial: Unsupported normal map type: ${ normalMapType }` );
  10996. output = normalView; // Fallback to default normal view
  10997. }
  10998. return output;
  10999. }
  11000. }
  11001. /**
  11002. * TSL function for creating a normal map node.
  11003. *
  11004. * @tsl
  11005. * @function
  11006. * @param {Node<vec3>} node - Represents the normal map data.
  11007. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  11008. * @returns {NormalMapNode}
  11009. */
  11010. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  11011. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  11012. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  11013. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  11014. // It's used to preserve the same TextureNode instance
  11015. const sampleTexture = ( callback ) => textureNode.isolate().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } );
  11016. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  11017. return vec2(
  11018. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  11019. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  11020. ).mul( bumpScale );
  11021. } );
  11022. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  11023. const perturbNormalArb = Fn( ( inputs ) => {
  11024. const { surf_pos, surf_norm, dHdxy } = inputs;
  11025. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  11026. const vSigmaX = surf_pos.dFdx().normalize();
  11027. const vSigmaY = surf_pos.dFdy().normalize();
  11028. const vN = surf_norm; // normalized
  11029. const R1 = vSigmaY.cross( vN );
  11030. const R2 = vN.cross( vSigmaX );
  11031. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  11032. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  11033. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  11034. } );
  11035. /**
  11036. * This class can be used for applying bump maps to materials.
  11037. *
  11038. * ```js
  11039. * material.normalNode = bumpMap( texture( bumpTex ) );
  11040. * ```
  11041. *
  11042. * @augments TempNode
  11043. */
  11044. class BumpMapNode extends TempNode {
  11045. static get type() {
  11046. return 'BumpMapNode';
  11047. }
  11048. /**
  11049. * Constructs a new bump map node.
  11050. *
  11051. * @param {Node<float>} textureNode - Represents the bump map data.
  11052. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  11053. */
  11054. constructor( textureNode, scaleNode = null ) {
  11055. super( 'vec3' );
  11056. /**
  11057. * Represents the bump map data.
  11058. *
  11059. * @type {Node<float>}
  11060. */
  11061. this.textureNode = textureNode;
  11062. /**
  11063. * Controls the intensity of the bump effect.
  11064. *
  11065. * @type {?Node<float>}
  11066. * @default null
  11067. */
  11068. this.scaleNode = scaleNode;
  11069. }
  11070. setup() {
  11071. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  11072. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  11073. return perturbNormalArb( {
  11074. surf_pos: positionView,
  11075. surf_norm: normalView,
  11076. dHdxy
  11077. } );
  11078. }
  11079. }
  11080. /**
  11081. * TSL function for creating a bump map node.
  11082. *
  11083. * @tsl
  11084. * @function
  11085. * @param {Node<float>} textureNode - Represents the bump map data.
  11086. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  11087. * @returns {BumpMapNode}
  11088. */
  11089. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  11090. const _propertyCache = new Map();
  11091. /**
  11092. * This class should simplify the node access to material properties.
  11093. * It internal uses reference nodes to make sure changes to material
  11094. * properties are automatically reflected to predefined TSL objects
  11095. * like e.g. `materialColor`.
  11096. *
  11097. * @augments Node
  11098. */
  11099. class MaterialNode extends Node {
  11100. static get type() {
  11101. return 'MaterialNode';
  11102. }
  11103. /**
  11104. * Constructs a new material node.
  11105. *
  11106. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  11107. */
  11108. constructor( scope ) {
  11109. super();
  11110. /**
  11111. * The scope defines what material property is referred by the node.
  11112. *
  11113. * @type {string}
  11114. */
  11115. this.scope = scope;
  11116. }
  11117. /**
  11118. * Returns a cached reference node for the given property and type.
  11119. *
  11120. * @param {string} property - The name of the material property.
  11121. * @param {string} type - The uniform type of the property.
  11122. * @return {MaterialReferenceNode} A material reference node representing the property access.
  11123. */
  11124. getCache( property, type ) {
  11125. let node = _propertyCache.get( property );
  11126. if ( node === undefined ) {
  11127. node = materialReference( property, type );
  11128. _propertyCache.set( property, node );
  11129. }
  11130. return node;
  11131. }
  11132. /**
  11133. * Returns a float-typed material reference node for the given property name.
  11134. *
  11135. * @param {string} property - The name of the material property.
  11136. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  11137. */
  11138. getFloat( property ) {
  11139. return this.getCache( property, 'float' );
  11140. }
  11141. /**
  11142. * Returns a color-typed material reference node for the given property name.
  11143. *
  11144. * @param {string} property - The name of the material property.
  11145. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  11146. */
  11147. getColor( property ) {
  11148. return this.getCache( property, 'color' );
  11149. }
  11150. /**
  11151. * Returns a texture-typed material reference node for the given property name.
  11152. *
  11153. * @param {string} property - The name of the material property.
  11154. * @return {MaterialReferenceNode} A material reference node representing the property access.
  11155. */
  11156. getTexture( property ) {
  11157. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  11158. }
  11159. /**
  11160. * The node setup is done depending on the selected scope. Multiple material properties
  11161. * might be grouped into a single node composition if they logically belong together.
  11162. *
  11163. * @param {NodeBuilder} builder - The current node builder.
  11164. * @return {Node} The node representing the selected scope.
  11165. */
  11166. setup( builder ) {
  11167. const material = builder.context.material;
  11168. const scope = this.scope;
  11169. let node = null;
  11170. if ( scope === MaterialNode.COLOR ) {
  11171. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  11172. if ( material.map && material.map.isTexture === true ) {
  11173. node = colorNode.mul( this.getTexture( 'map' ) );
  11174. } else {
  11175. node = colorNode;
  11176. }
  11177. } else if ( scope === MaterialNode.OPACITY ) {
  11178. const opacityNode = this.getFloat( scope );
  11179. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  11180. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  11181. } else {
  11182. node = opacityNode;
  11183. }
  11184. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  11185. if ( material.specularMap && material.specularMap.isTexture === true ) {
  11186. node = this.getTexture( 'specular' ).r;
  11187. } else {
  11188. node = float( 1 );
  11189. }
  11190. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  11191. const specularIntensityNode = this.getFloat( scope );
  11192. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  11193. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  11194. } else {
  11195. node = specularIntensityNode;
  11196. }
  11197. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  11198. const specularColorNode = this.getColor( scope );
  11199. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  11200. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  11201. } else {
  11202. node = specularColorNode;
  11203. }
  11204. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  11205. const roughnessNode = this.getFloat( scope );
  11206. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  11207. node = roughnessNode.mul( this.getTexture( scope ).g );
  11208. } else {
  11209. node = roughnessNode;
  11210. }
  11211. } else if ( scope === MaterialNode.METALNESS ) {
  11212. const metalnessNode = this.getFloat( scope );
  11213. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  11214. node = metalnessNode.mul( this.getTexture( scope ).b );
  11215. } else {
  11216. node = metalnessNode;
  11217. }
  11218. } else if ( scope === MaterialNode.EMISSIVE ) {
  11219. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  11220. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  11221. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  11222. node = emissiveNode.mul( this.getTexture( scope ) );
  11223. } else {
  11224. node = emissiveNode;
  11225. }
  11226. } else if ( scope === MaterialNode.NORMAL ) {
  11227. if ( material.normalMap ) {
  11228. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  11229. node.normalMapType = material.normalMapType;
  11230. if ( material.normalMap.format == RGFormat || material.normalMap.format == RED_GREEN_RGTC2_Format || material.normalMap.format == RG11_EAC_Format ) {
  11231. node.unpackNormalMode = NormalRGPacking;
  11232. }
  11233. } else if ( material.bumpMap ) {
  11234. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  11235. } else {
  11236. node = normalView;
  11237. }
  11238. } else if ( scope === MaterialNode.CLEARCOAT ) {
  11239. const clearcoatNode = this.getFloat( scope );
  11240. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  11241. node = clearcoatNode.mul( this.getTexture( scope ).r );
  11242. } else {
  11243. node = clearcoatNode;
  11244. }
  11245. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  11246. const clearcoatRoughnessNode = this.getFloat( scope );
  11247. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  11248. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  11249. } else {
  11250. node = clearcoatRoughnessNode;
  11251. }
  11252. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  11253. if ( material.clearcoatNormalMap ) {
  11254. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  11255. } else {
  11256. node = normalView;
  11257. }
  11258. } else if ( scope === MaterialNode.SHEEN ) {
  11259. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  11260. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  11261. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  11262. } else {
  11263. node = sheenNode;
  11264. }
  11265. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  11266. const sheenRoughnessNode = this.getFloat( scope );
  11267. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  11268. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  11269. } else {
  11270. node = sheenRoughnessNode;
  11271. }
  11272. node = node.clamp( 0.0001, 1.0 );
  11273. } else if ( scope === MaterialNode.ANISOTROPY ) {
  11274. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  11275. const anisotropyPolar = this.getTexture( scope );
  11276. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  11277. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  11278. } else {
  11279. node = materialAnisotropyVector;
  11280. }
  11281. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  11282. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  11283. if ( material.iridescenceThicknessMap ) {
  11284. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  11285. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  11286. } else {
  11287. node = iridescenceThicknessMaximum;
  11288. }
  11289. } else if ( scope === MaterialNode.TRANSMISSION ) {
  11290. const transmissionNode = this.getFloat( scope );
  11291. if ( material.transmissionMap ) {
  11292. node = transmissionNode.mul( this.getTexture( scope ).r );
  11293. } else {
  11294. node = transmissionNode;
  11295. }
  11296. } else if ( scope === MaterialNode.THICKNESS ) {
  11297. const thicknessNode = this.getFloat( scope );
  11298. if ( material.thicknessMap ) {
  11299. node = thicknessNode.mul( this.getTexture( scope ).g );
  11300. } else {
  11301. node = thicknessNode;
  11302. }
  11303. } else if ( scope === MaterialNode.IOR ) {
  11304. node = this.getFloat( scope );
  11305. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  11306. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  11307. } else if ( scope === MaterialNode.AO ) {
  11308. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  11309. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  11310. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  11311. } else {
  11312. const outputType = this.getNodeType( builder );
  11313. node = this.getCache( scope, outputType );
  11314. }
  11315. return node;
  11316. }
  11317. }
  11318. MaterialNode.ALPHA_TEST = 'alphaTest';
  11319. MaterialNode.COLOR = 'color';
  11320. MaterialNode.OPACITY = 'opacity';
  11321. MaterialNode.SHININESS = 'shininess';
  11322. MaterialNode.SPECULAR = 'specular';
  11323. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  11324. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  11325. MaterialNode.SPECULAR_COLOR = 'specularColor';
  11326. MaterialNode.REFLECTIVITY = 'reflectivity';
  11327. MaterialNode.ROUGHNESS = 'roughness';
  11328. MaterialNode.METALNESS = 'metalness';
  11329. MaterialNode.NORMAL = 'normal';
  11330. MaterialNode.CLEARCOAT = 'clearcoat';
  11331. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  11332. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  11333. MaterialNode.EMISSIVE = 'emissive';
  11334. MaterialNode.ROTATION = 'rotation';
  11335. MaterialNode.SHEEN = 'sheen';
  11336. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  11337. MaterialNode.ANISOTROPY = 'anisotropy';
  11338. MaterialNode.IRIDESCENCE = 'iridescence';
  11339. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  11340. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  11341. MaterialNode.IOR = 'ior';
  11342. MaterialNode.TRANSMISSION = 'transmission';
  11343. MaterialNode.THICKNESS = 'thickness';
  11344. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  11345. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  11346. MaterialNode.LINE_SCALE = 'scale';
  11347. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  11348. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  11349. MaterialNode.LINE_WIDTH = 'linewidth';
  11350. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  11351. MaterialNode.POINT_SIZE = 'size';
  11352. MaterialNode.DISPERSION = 'dispersion';
  11353. MaterialNode.LIGHT_MAP = 'light';
  11354. MaterialNode.AO = 'ao';
  11355. /**
  11356. * TSL object that represents alpha test of the current material.
  11357. *
  11358. * @tsl
  11359. * @type {Node<float>}
  11360. */
  11361. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  11362. /**
  11363. * TSL object that represents the diffuse color of the current material.
  11364. * The value is composed via `color` * `map`.
  11365. *
  11366. * @tsl
  11367. * @type {Node<vec3>}
  11368. */
  11369. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  11370. /**
  11371. * TSL object that represents the shininess of the current material.
  11372. *
  11373. * @tsl
  11374. * @type {Node<float>}
  11375. */
  11376. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  11377. /**
  11378. * TSL object that represents the emissive color of the current material.
  11379. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  11380. *
  11381. * @tsl
  11382. * @type {Node<vec3>}
  11383. */
  11384. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  11385. /**
  11386. * TSL object that represents the opacity of the current material.
  11387. * The value is composed via `opacity` * `alphaMap`.
  11388. *
  11389. * @tsl
  11390. * @type {Node<float>}
  11391. */
  11392. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  11393. /**
  11394. * TSL object that represents the specular of the current material.
  11395. *
  11396. * @tsl
  11397. * @type {Node<vec3>}
  11398. */
  11399. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  11400. /**
  11401. * TSL object that represents the specular intensity of the current material.
  11402. * The value is composed via `specularIntensity` * `specularMap.a`.
  11403. *
  11404. * @tsl
  11405. * @type {Node<float>}
  11406. */
  11407. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  11408. /**
  11409. * TSL object that represents the specular color of the current material.
  11410. * The value is composed via `specularColor` * `specularMap.rgb`.
  11411. *
  11412. * @tsl
  11413. * @type {Node<vec3>}
  11414. */
  11415. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  11416. /**
  11417. * TSL object that represents the specular strength of the current material.
  11418. * The value is composed via `specularMap.r`.
  11419. *
  11420. * @tsl
  11421. * @type {Node<float>}
  11422. */
  11423. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  11424. /**
  11425. * TSL object that represents the reflectivity of the current material.
  11426. *
  11427. * @tsl
  11428. * @type {Node<float>}
  11429. */
  11430. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  11431. /**
  11432. * TSL object that represents the roughness of the current material.
  11433. * The value is composed via `roughness` * `roughnessMap.g`.
  11434. *
  11435. * @tsl
  11436. * @type {Node<float>}
  11437. */
  11438. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  11439. /**
  11440. * TSL object that represents the metalness of the current material.
  11441. * The value is composed via `metalness` * `metalnessMap.b`.
  11442. *
  11443. * @tsl
  11444. * @type {Node<float>}
  11445. */
  11446. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  11447. /**
  11448. * TSL object that represents the normal of the current material.
  11449. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  11450. *
  11451. * @tsl
  11452. * @type {Node<vec3>}
  11453. */
  11454. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  11455. /**
  11456. * TSL object that represents the clearcoat of the current material.
  11457. * The value is composed via `clearcoat` * `clearcoatMap.r`
  11458. *
  11459. * @tsl
  11460. * @type {Node<float>}
  11461. */
  11462. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  11463. /**
  11464. * TSL object that represents the clearcoat roughness of the current material.
  11465. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  11466. *
  11467. * @tsl
  11468. * @type {Node<float>}
  11469. */
  11470. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  11471. /**
  11472. * TSL object that represents the clearcoat normal of the current material.
  11473. * The value will be either `clearcoatNormalMap` or `normalView`.
  11474. *
  11475. * @tsl
  11476. * @type {Node<vec3>}
  11477. */
  11478. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  11479. /**
  11480. * TSL object that represents the rotation of the current sprite material.
  11481. *
  11482. * @tsl
  11483. * @type {Node<float>}
  11484. */
  11485. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  11486. /**
  11487. * TSL object that represents the sheen color of the current material.
  11488. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  11489. *
  11490. * @tsl
  11491. * @type {Node<vec3>}
  11492. */
  11493. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  11494. /**
  11495. * TSL object that represents the sheen roughness of the current material.
  11496. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  11497. *
  11498. * @tsl
  11499. * @type {Node<float>}
  11500. */
  11501. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  11502. /**
  11503. * TSL object that represents the anisotropy of the current material.
  11504. *
  11505. * @tsl
  11506. * @type {Node<vec2>}
  11507. */
  11508. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  11509. /**
  11510. * TSL object that represents the iridescence of the current material.
  11511. *
  11512. * @tsl
  11513. * @type {Node<float>}
  11514. */
  11515. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  11516. /**
  11517. * TSL object that represents the iridescence IOR of the current material.
  11518. *
  11519. * @tsl
  11520. * @type {Node<float>}
  11521. */
  11522. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  11523. /**
  11524. * TSL object that represents the iridescence thickness of the current material.
  11525. *
  11526. * @tsl
  11527. * @type {Node<float>}
  11528. */
  11529. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  11530. /**
  11531. * TSL object that represents the transmission of the current material.
  11532. * The value is composed via `transmission` * `transmissionMap.r`.
  11533. *
  11534. * @tsl
  11535. * @type {Node<float>}
  11536. */
  11537. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  11538. /**
  11539. * TSL object that represents the thickness of the current material.
  11540. * The value is composed via `thickness` * `thicknessMap.g`.
  11541. *
  11542. * @tsl
  11543. * @type {Node<float>}
  11544. */
  11545. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  11546. /**
  11547. * TSL object that represents the IOR of the current material.
  11548. *
  11549. * @tsl
  11550. * @type {Node<float>}
  11551. */
  11552. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  11553. /**
  11554. * TSL object that represents the attenuation distance of the current material.
  11555. *
  11556. * @tsl
  11557. * @type {Node<float>}
  11558. */
  11559. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  11560. /**
  11561. * TSL object that represents the attenuation color of the current material.
  11562. *
  11563. * @tsl
  11564. * @type {Node<vec3>}
  11565. */
  11566. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  11567. /**
  11568. * TSL object that represents the scale of the current dashed line material.
  11569. *
  11570. * @tsl
  11571. * @type {Node<float>}
  11572. */
  11573. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  11574. /**
  11575. * TSL object that represents the dash size of the current dashed line material.
  11576. *
  11577. * @tsl
  11578. * @type {Node<float>}
  11579. */
  11580. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  11581. /**
  11582. * TSL object that represents the gap size of the current dashed line material.
  11583. *
  11584. * @tsl
  11585. * @type {Node<float>}
  11586. */
  11587. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  11588. /**
  11589. * TSL object that represents the line width of the current line material.
  11590. *
  11591. * @tsl
  11592. * @type {Node<float>}
  11593. */
  11594. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  11595. /**
  11596. * TSL object that represents the dash offset of the current line material.
  11597. *
  11598. * @tsl
  11599. * @type {Node<float>}
  11600. */
  11601. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  11602. /**
  11603. * TSL object that represents the point size of the current points material.
  11604. *
  11605. * @tsl
  11606. * @type {Node<float>}
  11607. */
  11608. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  11609. /**
  11610. * TSL object that represents the dispersion of the current material.
  11611. *
  11612. * @tsl
  11613. * @type {Node<float>}
  11614. */
  11615. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  11616. /**
  11617. * TSL object that represents the light map of the current material.
  11618. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  11619. *
  11620. * @tsl
  11621. * @type {Node<vec3>}
  11622. */
  11623. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  11624. /**
  11625. * TSL object that represents the ambient occlusion map of the current material.
  11626. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  11627. *
  11628. * @tsl
  11629. * @type {Node<float>}
  11630. */
  11631. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  11632. /**
  11633. * TSL object that represents the anisotropy vector of the current material.
  11634. *
  11635. * @tsl
  11636. * @type {Node<vec2>}
  11637. */
  11638. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  11639. return frame.material;
  11640. } ).onRenderUpdate( function ( { material } ) {
  11641. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  11642. } );
  11643. /**
  11644. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  11645. *
  11646. * @tsl
  11647. * @type {VaryingNode<vec4>}
  11648. */
  11649. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  11650. return builder.context.setupModelViewProjection();
  11651. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  11652. /**
  11653. * This class enables element access on instances of {@link StorageBufferNode}.
  11654. * In most cases, it is indirectly used when accessing elements with the
  11655. * {@link StorageBufferNode#element} method.
  11656. *
  11657. * ```js
  11658. * const position = positionStorage.element( instanceIndex );
  11659. * ```
  11660. *
  11661. * @augments ArrayElementNode
  11662. */
  11663. class StorageArrayElementNode extends ArrayElementNode {
  11664. static get type() {
  11665. return 'StorageArrayElementNode';
  11666. }
  11667. /**
  11668. * Constructs storage buffer element node.
  11669. *
  11670. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11671. * @param {Node} indexNode - The index node that defines the element access.
  11672. */
  11673. constructor( storageBufferNode, indexNode ) {
  11674. super( storageBufferNode, indexNode );
  11675. /**
  11676. * This flag can be used for type testing.
  11677. *
  11678. * @type {boolean}
  11679. * @readonly
  11680. * @default true
  11681. */
  11682. this.isStorageArrayElementNode = true;
  11683. }
  11684. /**
  11685. * The storage buffer node.
  11686. *
  11687. * @param {Node} value
  11688. * @type {StorageBufferNode}
  11689. */
  11690. set storageBufferNode( value ) {
  11691. this.node = value;
  11692. }
  11693. get storageBufferNode() {
  11694. return this.node;
  11695. }
  11696. getMemberType( builder, name ) {
  11697. const structTypeNode = this.storageBufferNode.structTypeNode;
  11698. if ( structTypeNode ) {
  11699. return structTypeNode.getMemberType( builder, name );
  11700. }
  11701. return 'void';
  11702. }
  11703. setup( builder ) {
  11704. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11705. if ( this.node.isPBO === true ) {
  11706. builder.setupPBO( this.node );
  11707. }
  11708. }
  11709. return super.setup( builder );
  11710. }
  11711. generate( builder, output ) {
  11712. let snippet;
  11713. const isAssignContext = builder.context.assign;
  11714. //
  11715. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11716. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  11717. snippet = builder.generatePBO( this );
  11718. } else {
  11719. snippet = this.node.build( builder );
  11720. }
  11721. } else {
  11722. snippet = super.generate( builder );
  11723. }
  11724. if ( isAssignContext !== true ) {
  11725. const type = this.getNodeType( builder );
  11726. snippet = builder.format( snippet, type, output );
  11727. }
  11728. return snippet;
  11729. }
  11730. }
  11731. /**
  11732. * TSL function for creating a storage element node.
  11733. *
  11734. * @tsl
  11735. * @function
  11736. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11737. * @param {Node} indexNode - The index node that defines the element access.
  11738. * @returns {StorageArrayElementNode}
  11739. */
  11740. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  11741. /**
  11742. * This node is used in context of compute shaders and allows to define a
  11743. * storage buffer for data. A typical workflow is to create instances of
  11744. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  11745. * setup up a compute shader that writes into the buffers and then convert
  11746. * the storage buffers to attribute nodes for rendering.
  11747. *
  11748. * ```js
  11749. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  11750. *
  11751. * const computeInit = Fn( () => { // the compute shader
  11752. *
  11753. * const position = positionBuffer.element( instanceIndex );
  11754. *
  11755. * // compute position data
  11756. *
  11757. * position.x = 1;
  11758. * position.y = 1;
  11759. * position.z = 1;
  11760. *
  11761. * } )().compute( particleCount );
  11762. *
  11763. * const particleMaterial = new THREE.SpriteNodeMaterial();
  11764. * particleMaterial.positionNode = positionBuffer.toAttribute();
  11765. *
  11766. * renderer.computeAsync( computeInit );
  11767. *
  11768. * ```
  11769. *
  11770. * @augments BufferNode
  11771. */
  11772. class StorageBufferNode extends BufferNode {
  11773. static get type() {
  11774. return 'StorageBufferNode';
  11775. }
  11776. /**
  11777. * Constructs a new storage buffer node.
  11778. *
  11779. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11780. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  11781. * @param {number} [bufferCount=0] - The buffer count.
  11782. */
  11783. constructor( value, bufferType = null, bufferCount = 0 ) {
  11784. let nodeType, structTypeNode = null;
  11785. if ( bufferType && bufferType.isStruct ) {
  11786. nodeType = 'struct';
  11787. structTypeNode = bufferType.layout;
  11788. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  11789. bufferCount = value.count;
  11790. }
  11791. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  11792. nodeType = getTypeFromLength( value.itemSize );
  11793. bufferCount = value.count;
  11794. } else {
  11795. nodeType = bufferType;
  11796. }
  11797. super( value, nodeType, bufferCount );
  11798. /**
  11799. * This flag can be used for type testing.
  11800. *
  11801. * @type {boolean}
  11802. * @readonly
  11803. * @default true
  11804. */
  11805. this.isStorageBufferNode = true;
  11806. /**
  11807. * The buffer struct type.
  11808. *
  11809. * @type {?StructTypeNode}
  11810. * @default null
  11811. */
  11812. this.structTypeNode = structTypeNode;
  11813. /**
  11814. * The access type of the texture node.
  11815. *
  11816. * @type {string}
  11817. * @default 'readWrite'
  11818. */
  11819. this.access = NodeAccess.READ_WRITE;
  11820. /**
  11821. * Whether the node is atomic or not.
  11822. *
  11823. * @type {boolean}
  11824. * @default false
  11825. */
  11826. this.isAtomic = false;
  11827. /**
  11828. * Whether the node represents a PBO or not.
  11829. * Only relevant for WebGL.
  11830. *
  11831. * @type {boolean}
  11832. * @default false
  11833. */
  11834. this.isPBO = false;
  11835. /**
  11836. * A reference to the internal buffer attribute node.
  11837. *
  11838. * @private
  11839. * @type {?BufferAttributeNode}
  11840. * @default null
  11841. */
  11842. this._attribute = null;
  11843. /**
  11844. * A reference to the internal varying node.
  11845. *
  11846. * @private
  11847. * @type {?VaryingNode}
  11848. * @default null
  11849. */
  11850. this._varying = null;
  11851. /**
  11852. * `StorageBufferNode` sets this property to `true` by default.
  11853. *
  11854. * @type {boolean}
  11855. * @default true
  11856. */
  11857. this.global = true;
  11858. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  11859. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  11860. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  11861. else value.isStorageBufferAttribute = true;
  11862. }
  11863. }
  11864. /**
  11865. * This method is overwritten since the buffer data might be shared
  11866. * and thus the hash should be shared as well.
  11867. *
  11868. * @param {NodeBuilder} builder - The current node builder.
  11869. * @return {string} The hash.
  11870. */
  11871. getHash( builder ) {
  11872. if ( this.bufferCount === 0 ) {
  11873. let bufferData = builder.globalCache.getData( this.value );
  11874. if ( bufferData === undefined ) {
  11875. bufferData = {
  11876. node: this
  11877. };
  11878. builder.globalCache.setData( this.value, bufferData );
  11879. }
  11880. return bufferData.node.uuid;
  11881. }
  11882. return this.uuid;
  11883. }
  11884. /**
  11885. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  11886. *
  11887. * @param {NodeBuilder} builder - The current node builder.
  11888. * @return {string} The input type.
  11889. */
  11890. getInputType( /*builder*/ ) {
  11891. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  11892. }
  11893. /**
  11894. * Enables element access with the given index node.
  11895. *
  11896. * @param {IndexNode} indexNode - The index node.
  11897. * @return {StorageArrayElementNode} A node representing the element access.
  11898. */
  11899. element( indexNode ) {
  11900. return storageElement( this, indexNode );
  11901. }
  11902. /**
  11903. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  11904. *
  11905. * @param {boolean} value - The value so set.
  11906. * @return {StorageBufferNode} A reference to this node.
  11907. */
  11908. setPBO( value ) {
  11909. this.isPBO = value;
  11910. return this;
  11911. }
  11912. /**
  11913. * Returns the `isPBO` value.
  11914. *
  11915. * @return {boolean} Whether the node represents a PBO or not.
  11916. */
  11917. getPBO() {
  11918. return this.isPBO;
  11919. }
  11920. /**
  11921. * Defines the node access.
  11922. *
  11923. * @param {string} value - The node access.
  11924. * @return {StorageBufferNode} A reference to this node.
  11925. */
  11926. setAccess( value ) {
  11927. this.access = value;
  11928. return this;
  11929. }
  11930. /**
  11931. * Convenience method for configuring a read-only node access.
  11932. *
  11933. * @return {StorageBufferNode} A reference to this node.
  11934. */
  11935. toReadOnly() {
  11936. return this.setAccess( NodeAccess.READ_ONLY );
  11937. }
  11938. /**
  11939. * Defines whether the node is atomic or not.
  11940. *
  11941. * @param {boolean} value - The atomic flag.
  11942. * @return {StorageBufferNode} A reference to this node.
  11943. */
  11944. setAtomic( value ) {
  11945. this.isAtomic = value;
  11946. return this;
  11947. }
  11948. /**
  11949. * Convenience method for making this node atomic.
  11950. *
  11951. * @return {StorageBufferNode} A reference to this node.
  11952. */
  11953. toAtomic() {
  11954. return this.setAtomic( true );
  11955. }
  11956. /**
  11957. * Returns attribute data for this storage buffer node.
  11958. *
  11959. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  11960. */
  11961. getAttributeData() {
  11962. if ( this._attribute === null ) {
  11963. this._attribute = bufferAttribute( this.value );
  11964. this._varying = varying( this._attribute );
  11965. }
  11966. return {
  11967. attribute: this._attribute,
  11968. varying: this._varying
  11969. };
  11970. }
  11971. /**
  11972. * This method is overwritten since the node type from the availability of storage buffers
  11973. * and the attribute data.
  11974. *
  11975. * @param {NodeBuilder} builder - The current node builder.
  11976. * @return {string} The node type.
  11977. */
  11978. getNodeType( builder ) {
  11979. if ( this.structTypeNode !== null ) {
  11980. return this.structTypeNode.getNodeType( builder );
  11981. }
  11982. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11983. return super.getNodeType( builder );
  11984. }
  11985. const { attribute } = this.getAttributeData();
  11986. return attribute.getNodeType( builder );
  11987. }
  11988. /**
  11989. * Returns the type of a member of the struct.
  11990. *
  11991. * @param {NodeBuilder} builder - The current node builder.
  11992. * @param {string} name - The name of the member.
  11993. * @return {string} The type of the member.
  11994. */
  11995. getMemberType( builder, name ) {
  11996. if ( this.structTypeNode !== null ) {
  11997. return this.structTypeNode.getMemberType( builder, name );
  11998. }
  11999. return 'void';
  12000. }
  12001. /**
  12002. * Generates the code snippet of the storage buffer node.
  12003. *
  12004. * @param {NodeBuilder} builder - The current node builder.
  12005. * @return {string} The generated code snippet.
  12006. */
  12007. generate( builder ) {
  12008. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  12009. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12010. return super.generate( builder );
  12011. }
  12012. const { attribute, varying } = this.getAttributeData();
  12013. const output = varying.build( builder );
  12014. builder.registerTransform( output, attribute );
  12015. return output;
  12016. }
  12017. }
  12018. /**
  12019. * TSL function for creating a storage buffer node.
  12020. *
  12021. * @tsl
  12022. * @function
  12023. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12024. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  12025. * @param {number} [count=0] - The buffer count.
  12026. * @returns {StorageBufferNode}
  12027. */
  12028. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  12029. /**
  12030. * @tsl
  12031. * @function
  12032. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  12033. *
  12034. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12035. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  12036. * @param {number} count - The buffer count.
  12037. * @returns {StorageBufferNode}
  12038. */
  12039. const storageObject = ( value, type, count ) => { // @deprecated, r171
  12040. warn( 'TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  12041. return storage( value, type, count ).setPBO( true );
  12042. };
  12043. /**
  12044. * This class represents shader indices of different types. The following predefined node
  12045. * objects cover frequent use cases:
  12046. *
  12047. * - `vertexIndex`: The index of a vertex within a mesh.
  12048. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  12049. * - `drawIndex`: The index of a draw call.
  12050. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  12051. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  12052. * - `subgroupIndex`: The index of a compute invocation's subgroup within its workgroup.
  12053. *
  12054. * @augments Node
  12055. */
  12056. class IndexNode extends Node {
  12057. static get type() {
  12058. return 'IndexNode';
  12059. }
  12060. /**
  12061. * Constructs a new index node.
  12062. *
  12063. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationGlobal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  12064. */
  12065. constructor( scope ) {
  12066. super( 'uint' );
  12067. /**
  12068. * The scope of the index node.
  12069. *
  12070. * @type {string}
  12071. */
  12072. this.scope = scope;
  12073. /**
  12074. * This flag can be used for type testing.
  12075. *
  12076. * @type {boolean}
  12077. * @readonly
  12078. * @default true
  12079. */
  12080. this.isIndexNode = true;
  12081. }
  12082. generate( builder ) {
  12083. const nodeType = this.getNodeType( builder );
  12084. const scope = this.scope;
  12085. let propertyName;
  12086. if ( scope === IndexNode.VERTEX ) {
  12087. propertyName = builder.getVertexIndex();
  12088. } else if ( scope === IndexNode.INSTANCE ) {
  12089. propertyName = builder.getInstanceIndex();
  12090. } else if ( scope === IndexNode.DRAW ) {
  12091. propertyName = builder.getDrawIndex();
  12092. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  12093. propertyName = builder.getInvocationLocalIndex();
  12094. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  12095. propertyName = builder.getInvocationSubgroupIndex();
  12096. } else if ( scope === IndexNode.SUBGROUP ) {
  12097. propertyName = builder.getSubgroupIndex();
  12098. } else {
  12099. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  12100. }
  12101. let output;
  12102. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  12103. output = propertyName;
  12104. } else {
  12105. const nodeVarying = varying( this );
  12106. output = nodeVarying.build( builder, nodeType );
  12107. }
  12108. return output;
  12109. }
  12110. }
  12111. IndexNode.VERTEX = 'vertex';
  12112. IndexNode.INSTANCE = 'instance';
  12113. IndexNode.SUBGROUP = 'subgroup';
  12114. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  12115. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  12116. IndexNode.DRAW = 'draw';
  12117. /**
  12118. * TSL object that represents the index of a vertex within a mesh.
  12119. *
  12120. * @tsl
  12121. * @type {IndexNode}
  12122. */
  12123. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  12124. /**
  12125. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  12126. *
  12127. * @tsl
  12128. * @type {IndexNode}
  12129. */
  12130. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  12131. /**
  12132. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  12133. *
  12134. * @tsl
  12135. * @type {IndexNode}
  12136. */
  12137. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  12138. /**
  12139. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  12140. *
  12141. * @tsl
  12142. * @type {IndexNode}
  12143. */
  12144. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  12145. /**
  12146. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  12147. *
  12148. * @tsl
  12149. * @type {IndexNode}
  12150. */
  12151. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  12152. /**
  12153. * TSL object that represents the index of a draw call.
  12154. *
  12155. * @tsl
  12156. * @type {IndexNode}
  12157. */
  12158. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  12159. /**
  12160. * This node implements the vertex shader logic which is required
  12161. * when rendering 3D objects via instancing. The code makes sure
  12162. * vertex positions, normals and colors can be modified via instanced
  12163. * data.
  12164. *
  12165. * @augments Node
  12166. */
  12167. class InstanceNode extends Node {
  12168. static get type() {
  12169. return 'InstanceNode';
  12170. }
  12171. /**
  12172. * Constructs a new instance node.
  12173. *
  12174. * @param {number} count - The number of instances.
  12175. * @param {InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  12176. * @param {?InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  12177. */
  12178. constructor( count, instanceMatrix, instanceColor = null ) {
  12179. super( 'void' );
  12180. /**
  12181. * The number of instances.
  12182. *
  12183. * @type {number}
  12184. */
  12185. this.count = count;
  12186. /**
  12187. * Instanced buffer attribute representing the transformation of instances.
  12188. *
  12189. * @type {InstancedBufferAttribute}
  12190. */
  12191. this.instanceMatrix = instanceMatrix;
  12192. /**
  12193. * Instanced buffer attribute representing the color of instances.
  12194. *
  12195. * @type {InstancedBufferAttribute}
  12196. */
  12197. this.instanceColor = instanceColor;
  12198. /**
  12199. * The node that represents the instance matrix data.
  12200. *
  12201. * @type {?Node}
  12202. */
  12203. this.instanceMatrixNode = null;
  12204. /**
  12205. * The node that represents the instance color data.
  12206. *
  12207. * @type {?Node}
  12208. * @default null
  12209. */
  12210. this.instanceColorNode = null;
  12211. /**
  12212. * The update type is set to `frame` since an update
  12213. * of instanced buffer data must be checked per frame.
  12214. *
  12215. * @type {string}
  12216. * @default 'frame'
  12217. */
  12218. this.updateType = NodeUpdateType.FRAME;
  12219. /**
  12220. * A reference to a buffer that is used by `instanceMatrixNode`.
  12221. *
  12222. * @type {?InstancedInterleavedBuffer}
  12223. */
  12224. this.buffer = null;
  12225. /**
  12226. * A reference to a buffer that is used by `instanceColorNode`.
  12227. *
  12228. * @type {?InstancedBufferAttribute}
  12229. */
  12230. this.bufferColor = null;
  12231. }
  12232. /**
  12233. * Tracks whether the matrix data is provided via a storage buffer.
  12234. *
  12235. * @type {boolean}
  12236. */
  12237. get isStorageMatrix() {
  12238. const { instanceMatrix } = this;
  12239. return instanceMatrix && instanceMatrix.isStorageInstancedBufferAttribute === true;
  12240. }
  12241. /**
  12242. * Tracks whether the color data is provided via a storage buffer.
  12243. *
  12244. * @type {boolean}
  12245. */
  12246. get isStorageColor() {
  12247. const { instanceColor } = this;
  12248. return instanceColor && instanceColor.isStorageInstancedBufferAttribute === true;
  12249. }
  12250. /**
  12251. * Setups the internal buffers and nodes and assigns the transformed vertex data
  12252. * to predefined node variables for accumulation. That follows the same patterns
  12253. * like with morph and skinning nodes.
  12254. *
  12255. * @param {NodeBuilder} builder - The current node builder.
  12256. */
  12257. setup( builder ) {
  12258. const { instanceMatrix, instanceColor, isStorageMatrix, isStorageColor } = this;
  12259. const { count } = instanceMatrix;
  12260. let { instanceMatrixNode, instanceColorNode } = this;
  12261. if ( instanceMatrixNode === null ) {
  12262. if ( isStorageMatrix ) {
  12263. instanceMatrixNode = storage( instanceMatrix, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  12264. } else {
  12265. // Both backends have ~64kb UBO limit; fallback to attributes above 1000 matrices.
  12266. if ( count <= 1000 ) {
  12267. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  12268. } else {
  12269. const interleaved = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  12270. this.buffer = interleaved;
  12271. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  12272. const instanceBuffers = [
  12273. bufferFn( interleaved, 'vec4', 16, 0 ),
  12274. bufferFn( interleaved, 'vec4', 16, 4 ),
  12275. bufferFn( interleaved, 'vec4', 16, 8 ),
  12276. bufferFn( interleaved, 'vec4', 16, 12 )
  12277. ];
  12278. instanceMatrixNode = mat4( ...instanceBuffers );
  12279. }
  12280. }
  12281. this.instanceMatrixNode = instanceMatrixNode;
  12282. }
  12283. if ( instanceColor && instanceColorNode === null ) {
  12284. if ( isStorageColor ) {
  12285. instanceColorNode = storage( instanceColor, 'vec3', Math.max( instanceColor.count, 1 ) ).element( instanceIndex );
  12286. } else {
  12287. const bufferAttribute = new InstancedBufferAttribute( instanceColor.array, 3 );
  12288. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  12289. this.bufferColor = bufferAttribute;
  12290. instanceColorNode = vec3( bufferFn( bufferAttribute, 'vec3', 3, 0 ) );
  12291. }
  12292. this.instanceColorNode = instanceColorNode;
  12293. }
  12294. // POSITION
  12295. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  12296. positionLocal.assign( instancePosition );
  12297. // NORMAL
  12298. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  12299. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  12300. // ASSIGNS
  12301. normalLocal.assign( instanceNormal );
  12302. }
  12303. // COLOR
  12304. if ( this.instanceColorNode !== null ) {
  12305. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  12306. }
  12307. }
  12308. /**
  12309. * Checks if the internal buffers require an update.
  12310. *
  12311. * @param {NodeFrame} frame - The current node frame.
  12312. */
  12313. update( /*frame*/ ) {
  12314. if ( this.buffer !== null && this.isStorageMatrix !== true ) {
  12315. this.buffer.clearUpdateRanges();
  12316. this.buffer.updateRanges.push( ... this.instanceMatrix.updateRanges );
  12317. // update version if necessary
  12318. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.instanceMatrix.version !== this.buffer.version ) {
  12319. this.buffer.version = this.instanceMatrix.version;
  12320. }
  12321. }
  12322. if ( this.instanceColor && this.bufferColor !== null && this.isStorageColor !== true ) {
  12323. this.bufferColor.clearUpdateRanges();
  12324. this.bufferColor.updateRanges.push( ... this.instanceColor.updateRanges );
  12325. if ( this.instanceColor.usage !== DynamicDrawUsage && this.instanceColor.version !== this.bufferColor.version ) {
  12326. this.bufferColor.version = this.instanceColor.version;
  12327. }
  12328. }
  12329. }
  12330. }
  12331. /**
  12332. * TSL function for creating an instance node.
  12333. *
  12334. * @tsl
  12335. * @function
  12336. * @param {number} count - The number of instances.
  12337. * @param {InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  12338. * @param {?InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  12339. * @returns {InstanceNode}
  12340. */
  12341. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  12342. /**
  12343. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  12344. * It allows an easier setup of the instance node.
  12345. *
  12346. * @augments InstanceNode
  12347. */
  12348. class InstancedMeshNode extends InstanceNode {
  12349. static get type() {
  12350. return 'InstancedMeshNode';
  12351. }
  12352. /**
  12353. * Constructs a new instanced mesh node.
  12354. *
  12355. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  12356. */
  12357. constructor( instancedMesh ) {
  12358. const { count, instanceMatrix, instanceColor } = instancedMesh;
  12359. super( count, instanceMatrix, instanceColor );
  12360. /**
  12361. * A reference to the instanced mesh.
  12362. *
  12363. * @type {InstancedMesh}
  12364. */
  12365. this.instancedMesh = instancedMesh;
  12366. }
  12367. }
  12368. /**
  12369. * TSL function for creating an instanced mesh node.
  12370. *
  12371. * @tsl
  12372. * @function
  12373. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  12374. * @returns {InstancedMeshNode}
  12375. */
  12376. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  12377. /**
  12378. * This node implements the vertex shader logic which is required
  12379. * when rendering 3D objects via batching. `BatchNode` must be used
  12380. * with instances of {@link BatchedMesh}.
  12381. *
  12382. * @augments Node
  12383. */
  12384. class BatchNode extends Node {
  12385. static get type() {
  12386. return 'BatchNode';
  12387. }
  12388. /**
  12389. * Constructs a new batch node.
  12390. *
  12391. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  12392. */
  12393. constructor( batchMesh ) {
  12394. super( 'void' );
  12395. /**
  12396. * A reference to batched mesh.
  12397. *
  12398. * @type {BatchedMesh}
  12399. */
  12400. this.batchMesh = batchMesh;
  12401. /**
  12402. * The batching index node.
  12403. *
  12404. * @type {?IndexNode}
  12405. * @default null
  12406. */
  12407. this.batchingIdNode = null;
  12408. }
  12409. /**
  12410. * Setups the internal buffers and nodes and assigns the transformed vertex data
  12411. * to predefined node variables for accumulation. That follows the same patterns
  12412. * like with morph and skinning nodes.
  12413. *
  12414. * @param {NodeBuilder} builder - The current node builder.
  12415. */
  12416. setup( builder ) {
  12417. if ( this.batchingIdNode === null ) {
  12418. if ( builder.getDrawIndex() === null ) {
  12419. this.batchingIdNode = instanceIndex;
  12420. } else {
  12421. this.batchingIdNode = drawIndex;
  12422. }
  12423. }
  12424. const getIndirectIndex = Fn( ( [ id ] ) => {
  12425. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x ).toConst();
  12426. const x = int( id ).mod( size ).toConst();
  12427. const y = int( id ).div( size ).toConst();
  12428. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  12429. } ).setLayout( {
  12430. name: 'getIndirectIndex',
  12431. type: 'uint',
  12432. inputs: [
  12433. { name: 'id', type: 'int' }
  12434. ]
  12435. } );
  12436. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  12437. const matricesTexture = this.batchMesh._matricesTexture;
  12438. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x ).toConst();
  12439. const j = float( indirectId ).mul( 4 ).toInt().toConst();
  12440. const x = j.mod( size ).toConst();
  12441. const y = j.div( size ).toConst();
  12442. const batchingMatrix = mat4(
  12443. textureLoad( matricesTexture, ivec2( x, y ) ),
  12444. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  12445. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  12446. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  12447. );
  12448. const colorsTexture = this.batchMesh._colorsTexture;
  12449. if ( colorsTexture !== null ) {
  12450. const getBatchingColor = Fn( ( [ id ] ) => {
  12451. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x ).toConst();
  12452. const j = id;
  12453. const x = j.mod( size ).toConst();
  12454. const y = j.div( size ).toConst();
  12455. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  12456. } ).setLayout( {
  12457. name: 'getBatchingColor',
  12458. type: 'vec3',
  12459. inputs: [
  12460. { name: 'id', type: 'int' }
  12461. ]
  12462. } );
  12463. const color = getBatchingColor( indirectId );
  12464. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  12465. }
  12466. const bm = mat3( batchingMatrix );
  12467. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  12468. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  12469. const batchingNormal = bm.mul( transformedNormal ).xyz;
  12470. normalLocal.assign( batchingNormal );
  12471. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  12472. tangentLocal.mulAssign( bm );
  12473. }
  12474. }
  12475. }
  12476. /**
  12477. * TSL function for creating a batch node.
  12478. *
  12479. * @tsl
  12480. * @function
  12481. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  12482. * @returns {BatchNode}
  12483. */
  12484. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  12485. const _frameId = new WeakMap();
  12486. /**
  12487. * This node implements the vertex transformation shader logic which is required
  12488. * for skinning/skeletal animation.
  12489. *
  12490. * @augments Node
  12491. */
  12492. class SkinningNode extends Node {
  12493. static get type() {
  12494. return 'SkinningNode';
  12495. }
  12496. /**
  12497. * Constructs a new skinning node.
  12498. *
  12499. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12500. */
  12501. constructor( skinnedMesh ) {
  12502. super( 'void' );
  12503. /**
  12504. * The skinned mesh.
  12505. *
  12506. * @type {SkinnedMesh}
  12507. */
  12508. this.skinnedMesh = skinnedMesh;
  12509. /**
  12510. * The update type overwritten since skinning nodes are updated per object.
  12511. *
  12512. * @type {string}
  12513. */
  12514. this.updateType = NodeUpdateType.OBJECT;
  12515. //
  12516. /**
  12517. * The skin index attribute.
  12518. *
  12519. * @type {AttributeNode}
  12520. */
  12521. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  12522. /**
  12523. * The skin weight attribute.
  12524. *
  12525. * @type {AttributeNode}
  12526. */
  12527. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  12528. /**
  12529. * The bind matrix node.
  12530. *
  12531. * @type {Node<mat4>}
  12532. */
  12533. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  12534. /**
  12535. * The bind matrix inverse node.
  12536. *
  12537. * @type {Node<mat4>}
  12538. */
  12539. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  12540. /**
  12541. * The bind matrices as a uniform buffer node.
  12542. *
  12543. * @type {Node}
  12544. */
  12545. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12546. /**
  12547. * The current vertex position in local space.
  12548. *
  12549. * @type {Node<vec3>}
  12550. */
  12551. this.positionNode = positionLocal;
  12552. /**
  12553. * The result of vertex position in local space.
  12554. *
  12555. * @type {Node<vec3>}
  12556. */
  12557. this.toPositionNode = positionLocal;
  12558. /**
  12559. * The previous bind matrices as a uniform buffer node.
  12560. * Required for computing motion vectors.
  12561. *
  12562. * @type {?Node}
  12563. * @default null
  12564. */
  12565. this.previousBoneMatricesNode = null;
  12566. }
  12567. /**
  12568. * Transforms the given vertex position via skinning.
  12569. *
  12570. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12571. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  12572. * @return {Node<vec3>} The transformed vertex position.
  12573. */
  12574. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  12575. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12576. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12577. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12578. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12579. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12580. // POSITION
  12581. const skinVertex = bindMatrixNode.mul( position );
  12582. const skinned = add(
  12583. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  12584. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  12585. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  12586. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  12587. );
  12588. return bindMatrixInverseNode.mul( skinned ).xyz;
  12589. }
  12590. /**
  12591. * Transforms the given vertex normal via skinning.
  12592. *
  12593. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12594. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  12595. * @return {Node<vec3>} The transformed vertex normal.
  12596. */
  12597. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  12598. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12599. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12600. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12601. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12602. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12603. // NORMAL
  12604. let skinMatrix = add(
  12605. skinWeightNode.x.mul( boneMatX ),
  12606. skinWeightNode.y.mul( boneMatY ),
  12607. skinWeightNode.z.mul( boneMatZ ),
  12608. skinWeightNode.w.mul( boneMatW )
  12609. );
  12610. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  12611. return skinMatrix.transformDirection( normal ).xyz;
  12612. }
  12613. /**
  12614. * Computes the transformed/skinned vertex position of the previous frame.
  12615. *
  12616. * @param {NodeBuilder} builder - The current node builder.
  12617. * @return {Node<vec3>} The skinned position from the previous frame.
  12618. */
  12619. getPreviousSkinnedPosition( builder ) {
  12620. const skinnedMesh = builder.object;
  12621. if ( this.previousBoneMatricesNode === null ) {
  12622. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  12623. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12624. }
  12625. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  12626. }
  12627. /**
  12628. * Returns `true` if bone matrices from the previous frame are required. Relevant
  12629. * when computing motion vectors with {@link VelocityNode}.
  12630. *
  12631. * @param {NodeBuilder} builder - The current node builder.
  12632. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  12633. */
  12634. needsPreviousBoneMatrices( builder ) {
  12635. const mrt = builder.renderer.getMRT();
  12636. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  12637. }
  12638. /**
  12639. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  12640. *
  12641. * @param {NodeBuilder} builder - The current node builder.
  12642. * @return {Node<vec3>} The transformed vertex position.
  12643. */
  12644. setup( builder ) {
  12645. if ( this.needsPreviousBoneMatrices( builder ) ) {
  12646. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  12647. }
  12648. const skinPosition = this.getSkinnedPosition();
  12649. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  12650. //
  12651. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  12652. const skinNormal = this.getSkinnedNormal();
  12653. normalLocal.assign( skinNormal );
  12654. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  12655. tangentLocal.assign( skinNormal );
  12656. }
  12657. }
  12658. return skinPosition;
  12659. }
  12660. /**
  12661. * Generates the code snippet of the skinning node.
  12662. *
  12663. * @param {NodeBuilder} builder - The current node builder.
  12664. * @param {string} output - The current output.
  12665. * @return {string} The generated code snippet.
  12666. */
  12667. generate( builder, output ) {
  12668. if ( output !== 'void' ) {
  12669. return super.generate( builder, output );
  12670. }
  12671. }
  12672. /**
  12673. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  12674. *
  12675. * @param {NodeFrame} frame - The current node frame.
  12676. */
  12677. update( frame ) {
  12678. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  12679. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  12680. _frameId.set( skeleton, frame.frameId );
  12681. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  12682. skeleton.update();
  12683. }
  12684. }
  12685. /**
  12686. * TSL function for creating a skinning node.
  12687. *
  12688. * @tsl
  12689. * @function
  12690. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12691. * @returns {SkinningNode}
  12692. */
  12693. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  12694. /**
  12695. * TSL function for computing skinning.
  12696. *
  12697. * @tsl
  12698. * @function
  12699. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12700. * @param {Node<vec3>} [toPosition=null] - The target position.
  12701. * @returns {SkinningNode}
  12702. */
  12703. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  12704. const node = new SkinningNode( skinnedMesh );
  12705. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12706. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12707. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12708. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  12709. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  12710. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  12711. node.toPositionNode = toPosition;
  12712. return nodeObject( node );
  12713. };
  12714. /**
  12715. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  12716. * ```js
  12717. * Loop( count, ( { i } ) => {
  12718. *
  12719. * } );
  12720. * ```
  12721. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  12722. * ```js
  12723. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  12724. *
  12725. * } );
  12726. *```
  12727. * Nested loops can be defined in a compacted form:
  12728. * ```js
  12729. * Loop( 10, 5, ( { i, j } ) => {
  12730. *
  12731. * } );
  12732. * ```
  12733. * Loops that should run backwards can be defined like so:
  12734. * ```js
  12735. * Loop( { start: 10 }, () => {} );
  12736. * ```
  12737. * It is possible to execute with boolean values, similar to the `while` syntax.
  12738. * ```js
  12739. * const value = float( 0 ).toVar();
  12740. *
  12741. * Loop( value.lessThan( 10 ), () => {
  12742. *
  12743. * value.addAssign( 1 );
  12744. *
  12745. * } );
  12746. * ```
  12747. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  12748. * @augments Node
  12749. */
  12750. class LoopNode extends Node {
  12751. static get type() {
  12752. return 'LoopNode';
  12753. }
  12754. /**
  12755. * Constructs a new loop node.
  12756. *
  12757. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  12758. */
  12759. constructor( params = [] ) {
  12760. super( 'void' );
  12761. this.params = params;
  12762. }
  12763. /**
  12764. * Returns a loop variable name based on an index. The pattern is
  12765. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  12766. *
  12767. * @param {number} index - The index.
  12768. * @return {string} The loop variable name.
  12769. */
  12770. getVarName( index ) {
  12771. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  12772. }
  12773. /**
  12774. * Returns properties about this node.
  12775. *
  12776. * @param {NodeBuilder} builder - The current node builder.
  12777. * @return {Object} The node properties.
  12778. */
  12779. getProperties( builder ) {
  12780. const properties = builder.getNodeProperties( this );
  12781. if ( properties.stackNode !== undefined ) return properties;
  12782. //
  12783. const inputs = {};
  12784. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12785. const param = this.params[ i ];
  12786. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  12787. const type = ( param.isNode !== true && param.type ) || 'int';
  12788. inputs[ name ] = expression( name, type );
  12789. }
  12790. const stack = builder.addStack();
  12791. const fnCall = this.params[ this.params.length - 1 ]( inputs );
  12792. properties.returnsNode = fnCall.context( { nodeLoop: fnCall } );
  12793. properties.stackNode = stack;
  12794. const baseParam = this.params[ 0 ];
  12795. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  12796. const fnUpdateCall = Fn( this.params[ 0 ].update )( inputs );
  12797. properties.updateNode = fnUpdateCall.context( { nodeLoop: fnUpdateCall } );
  12798. }
  12799. builder.removeStack();
  12800. return properties;
  12801. }
  12802. setup( builder ) {
  12803. // setup properties
  12804. this.getProperties( builder );
  12805. if ( builder.fnCall ) {
  12806. const shaderNodeData = builder.getDataFromNode( builder.fnCall.shaderNode );
  12807. shaderNodeData.hasLoop = true;
  12808. }
  12809. }
  12810. generate( builder ) {
  12811. const properties = this.getProperties( builder );
  12812. const params = this.params;
  12813. const stackNode = properties.stackNode;
  12814. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  12815. const param = params[ i ];
  12816. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  12817. if ( param.isNode ) {
  12818. if ( param.getNodeType( builder ) === 'bool' ) {
  12819. isWhile = true;
  12820. type = 'bool';
  12821. end = param.build( builder, type );
  12822. } else {
  12823. type = 'int';
  12824. name = this.getVarName( i );
  12825. start = '0';
  12826. end = param.build( builder, type );
  12827. condition = '<';
  12828. }
  12829. } else {
  12830. type = param.type || 'int';
  12831. name = param.name || this.getVarName( i );
  12832. start = param.start;
  12833. end = param.end;
  12834. condition = param.condition;
  12835. update = param.update;
  12836. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  12837. else if ( start && start.isNode ) start = start.build( builder, type );
  12838. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  12839. else if ( end && end.isNode ) end = end.build( builder, type );
  12840. if ( start !== undefined && end === undefined ) {
  12841. start = start + ' - 1';
  12842. end = '0';
  12843. condition = '>=';
  12844. } else if ( end !== undefined && start === undefined ) {
  12845. start = '0';
  12846. condition = '<';
  12847. }
  12848. if ( condition === undefined ) {
  12849. if ( Number( start ) > Number( end ) ) {
  12850. condition = '>=';
  12851. } else {
  12852. condition = '<';
  12853. }
  12854. }
  12855. }
  12856. let loopSnippet;
  12857. if ( isWhile ) {
  12858. loopSnippet = `while ( ${ end } )`;
  12859. } else {
  12860. const internalParam = { start, end};
  12861. //
  12862. const startSnippet = internalParam.start;
  12863. const endSnippet = internalParam.end;
  12864. let updateSnippet;
  12865. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  12866. if ( update !== undefined && update !== null ) {
  12867. switch ( typeof update ) {
  12868. case 'function':
  12869. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  12870. const snippet = flow.code.replace( /\t|;/g, '' );
  12871. updateSnippet = snippet;
  12872. break;
  12873. case 'number':
  12874. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  12875. break;
  12876. case 'string':
  12877. updateSnippet = name + ' ' + update;
  12878. break;
  12879. default:
  12880. if ( update.isNode ) {
  12881. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  12882. } else {
  12883. error( 'TSL: \'Loop( { update: ... } )\' is not a function, string or number.' );
  12884. updateSnippet = 'break /* invalid update */';
  12885. }
  12886. }
  12887. } else {
  12888. if ( type === 'int' || type === 'uint' ) {
  12889. update = condition.includes( '<' ) ? '++' : '--';
  12890. } else {
  12891. update = deltaOperator() + ' 1.';
  12892. }
  12893. updateSnippet = name + ' ' + update;
  12894. }
  12895. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  12896. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  12897. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  12898. }
  12899. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  12900. }
  12901. const stackSnippet = stackNode.build( builder, 'void' );
  12902. properties.returnsNode.build( builder, 'void' );
  12903. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  12904. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12905. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  12906. }
  12907. builder.addFlowTab();
  12908. }
  12909. }
  12910. /**
  12911. * TSL function for creating a loop node.
  12912. *
  12913. * @tsl
  12914. * @function
  12915. * @param {...any} params - A list of parameters.
  12916. * @returns {LoopNode}
  12917. */
  12918. const Loop = ( ...params ) => new LoopNode( nodeArray( params, 'int' ) ).toStack();
  12919. /**
  12920. * TSL function for creating a `Continue()` expression.
  12921. *
  12922. * @tsl
  12923. * @function
  12924. * @returns {ExpressionNode}
  12925. */
  12926. const Continue = () => expression( 'continue' ).toStack();
  12927. /**
  12928. * TSL function for creating a `Break()` expression.
  12929. *
  12930. * @tsl
  12931. * @function
  12932. * @returns {ExpressionNode}
  12933. */
  12934. const Break = () => expression( 'break' ).toStack();
  12935. const _morphTextures = /*@__PURE__*/ new WeakMap();
  12936. const _morphVec4 = /*@__PURE__*/ new Vector4();
  12937. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  12938. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  12939. const y = texelIndex.div( width );
  12940. const x = texelIndex.sub( y.mul( width ) );
  12941. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  12942. return bufferAttrib.mul( influence );
  12943. } );
  12944. function getEntry( geometry ) {
  12945. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12946. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  12947. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  12948. // instead of using attributes, the WebGL 2 code path encodes morph targets
  12949. // into an array of data textures. Each layer represents a single morph target.
  12950. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12951. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12952. let entry = _morphTextures.get( geometry );
  12953. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  12954. if ( entry !== undefined ) entry.texture.dispose();
  12955. const morphTargets = geometry.morphAttributes.position || [];
  12956. const morphNormals = geometry.morphAttributes.normal || [];
  12957. const morphColors = geometry.morphAttributes.color || [];
  12958. let vertexDataCount = 0;
  12959. if ( hasMorphPosition === true ) vertexDataCount = 1;
  12960. if ( hasMorphNormals === true ) vertexDataCount = 2;
  12961. if ( hasMorphColors === true ) vertexDataCount = 3;
  12962. let width = geometry.attributes.position.count * vertexDataCount;
  12963. let height = 1;
  12964. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  12965. if ( width > maxTextureSize ) {
  12966. height = Math.ceil( width / maxTextureSize );
  12967. width = maxTextureSize;
  12968. }
  12969. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  12970. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  12971. bufferTexture.type = FloatType;
  12972. bufferTexture.needsUpdate = true;
  12973. // fill buffer
  12974. const vertexDataStride = vertexDataCount * 4;
  12975. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  12976. const morphTarget = morphTargets[ i ];
  12977. const morphNormal = morphNormals[ i ];
  12978. const morphColor = morphColors[ i ];
  12979. const offset = width * height * 4 * i;
  12980. for ( let j = 0; j < morphTarget.count; j ++ ) {
  12981. const stride = j * vertexDataStride;
  12982. if ( hasMorphPosition === true ) {
  12983. _morphVec4.fromBufferAttribute( morphTarget, j );
  12984. buffer[ offset + stride + 0 ] = _morphVec4.x;
  12985. buffer[ offset + stride + 1 ] = _morphVec4.y;
  12986. buffer[ offset + stride + 2 ] = _morphVec4.z;
  12987. buffer[ offset + stride + 3 ] = 0;
  12988. }
  12989. if ( hasMorphNormals === true ) {
  12990. _morphVec4.fromBufferAttribute( morphNormal, j );
  12991. buffer[ offset + stride + 4 ] = _morphVec4.x;
  12992. buffer[ offset + stride + 5 ] = _morphVec4.y;
  12993. buffer[ offset + stride + 6 ] = _morphVec4.z;
  12994. buffer[ offset + stride + 7 ] = 0;
  12995. }
  12996. if ( hasMorphColors === true ) {
  12997. _morphVec4.fromBufferAttribute( morphColor, j );
  12998. buffer[ offset + stride + 8 ] = _morphVec4.x;
  12999. buffer[ offset + stride + 9 ] = _morphVec4.y;
  13000. buffer[ offset + stride + 10 ] = _morphVec4.z;
  13001. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  13002. }
  13003. }
  13004. }
  13005. entry = {
  13006. count: morphTargetsCount,
  13007. texture: bufferTexture,
  13008. stride: vertexDataCount,
  13009. size: new Vector2( width, height )
  13010. };
  13011. _morphTextures.set( geometry, entry );
  13012. function disposeTexture() {
  13013. bufferTexture.dispose();
  13014. _morphTextures.delete( geometry );
  13015. geometry.removeEventListener( 'dispose', disposeTexture );
  13016. }
  13017. geometry.addEventListener( 'dispose', disposeTexture );
  13018. }
  13019. return entry;
  13020. }
  13021. /**
  13022. * This node implements the vertex transformation shader logic which is required
  13023. * for morph target animation.
  13024. *
  13025. * @augments Node
  13026. */
  13027. class MorphNode extends Node {
  13028. static get type() {
  13029. return 'MorphNode';
  13030. }
  13031. /**
  13032. * Constructs a new morph node.
  13033. *
  13034. * @param {Mesh} mesh - The mesh holding the morph targets.
  13035. */
  13036. constructor( mesh ) {
  13037. super( 'void' );
  13038. /**
  13039. * The mesh holding the morph targets.
  13040. *
  13041. * @type {Mesh}
  13042. */
  13043. this.mesh = mesh;
  13044. /**
  13045. * A uniform node which represents the morph base influence value.
  13046. *
  13047. * @type {UniformNode<float>}
  13048. */
  13049. this.morphBaseInfluence = uniform( 1 );
  13050. /**
  13051. * The update type overwritten since morph nodes are updated per object.
  13052. *
  13053. * @type {string}
  13054. */
  13055. this.updateType = NodeUpdateType.OBJECT;
  13056. }
  13057. /**
  13058. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  13059. *
  13060. * @param {NodeBuilder} builder - The current node builder.
  13061. */
  13062. setup( builder ) {
  13063. const { geometry } = builder;
  13064. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  13065. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  13066. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  13067. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  13068. // nodes
  13069. const { texture: bufferMap, stride, size } = getEntry( geometry );
  13070. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  13071. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  13072. const width = int( size.width );
  13073. Loop( morphTargetsCount, ( { i } ) => {
  13074. const influence = float( 0 ).toVar();
  13075. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  13076. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  13077. } else {
  13078. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  13079. }
  13080. If( influence.notEqual( 0 ), () => {
  13081. if ( hasMorphPosition === true ) {
  13082. positionLocal.addAssign( getMorph( {
  13083. bufferMap,
  13084. influence,
  13085. stride,
  13086. width,
  13087. depth: i,
  13088. offset: int( 0 )
  13089. } ) );
  13090. }
  13091. if ( hasMorphNormals === true ) {
  13092. normalLocal.addAssign( getMorph( {
  13093. bufferMap,
  13094. influence,
  13095. stride,
  13096. width,
  13097. depth: i,
  13098. offset: int( 1 )
  13099. } ) );
  13100. }
  13101. } );
  13102. } );
  13103. }
  13104. /**
  13105. * Updates the state of the morphed mesh by updating the base influence.
  13106. *
  13107. * @param {NodeFrame} frame - The current node frame.
  13108. */
  13109. update( /*frame*/ ) {
  13110. const morphBaseInfluence = this.morphBaseInfluence;
  13111. if ( this.mesh.geometry.morphTargetsRelative ) {
  13112. morphBaseInfluence.value = 1;
  13113. } else {
  13114. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  13115. }
  13116. }
  13117. }
  13118. /**
  13119. * TSL function for creating a morph node.
  13120. *
  13121. * @tsl
  13122. * @function
  13123. * @param {Mesh} mesh - The mesh holding the morph targets.
  13124. * @returns {MorphNode}
  13125. */
  13126. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  13127. /**
  13128. * Base class for lighting nodes.
  13129. *
  13130. * @augments Node
  13131. */
  13132. class LightingNode extends Node {
  13133. static get type() {
  13134. return 'LightingNode';
  13135. }
  13136. /**
  13137. * Constructs a new lighting node.
  13138. */
  13139. constructor() {
  13140. super( 'vec3' );
  13141. /**
  13142. * This flag can be used for type testing.
  13143. *
  13144. * @type {boolean}
  13145. * @readonly
  13146. * @default true
  13147. */
  13148. this.isLightingNode = true;
  13149. }
  13150. }
  13151. /**
  13152. * A generic class that can be used by nodes which contribute
  13153. * ambient occlusion to the scene. E.g. an ambient occlusion map
  13154. * node can be used as input for this module. Used in {@link NodeMaterial}.
  13155. *
  13156. * @augments LightingNode
  13157. */
  13158. class AONode extends LightingNode {
  13159. static get type() {
  13160. return 'AONode';
  13161. }
  13162. /**
  13163. * Constructs a new AO node.
  13164. *
  13165. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  13166. */
  13167. constructor( aoNode = null ) {
  13168. super();
  13169. /**
  13170. * The ambient occlusion node.
  13171. *
  13172. * @type {?Node<float>}
  13173. * @default null
  13174. */
  13175. this.aoNode = aoNode;
  13176. }
  13177. setup( builder ) {
  13178. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  13179. }
  13180. }
  13181. /**
  13182. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  13183. * by adding lighting specific context data. It represents the runtime context of
  13184. * {@link LightsNode}.
  13185. *
  13186. * @augments ContextNode
  13187. */
  13188. class LightingContextNode extends ContextNode {
  13189. static get type() {
  13190. return 'LightingContextNode';
  13191. }
  13192. /**
  13193. * Constructs a new lighting context node.
  13194. *
  13195. * @param {LightsNode} lightsNode - The lights node.
  13196. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  13197. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  13198. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  13199. */
  13200. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  13201. super( lightsNode );
  13202. /**
  13203. * The current lighting model.
  13204. *
  13205. * @type {?LightingModel}
  13206. * @default null
  13207. */
  13208. this.lightingModel = lightingModel;
  13209. /**
  13210. * A backdrop node.
  13211. *
  13212. * @type {?Node<vec3>}
  13213. * @default null
  13214. */
  13215. this.backdropNode = backdropNode;
  13216. /**
  13217. * A backdrop alpha node.
  13218. *
  13219. * @type {?Node<float>}
  13220. * @default null
  13221. */
  13222. this.backdropAlphaNode = backdropAlphaNode;
  13223. this._value = null;
  13224. }
  13225. /**
  13226. * Returns a lighting context object.
  13227. *
  13228. * @return {{
  13229. * radiance: Node<vec3>,
  13230. * irradiance: Node<vec3>,
  13231. * iblIrradiance: Node<vec3>,
  13232. * ambientOcclusion: Node<float>,
  13233. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  13234. * backdrop: Node<vec3>,
  13235. * backdropAlpha: Node<float>
  13236. * }} The lighting context object.
  13237. */
  13238. getContext() {
  13239. const { backdropNode, backdropAlphaNode } = this;
  13240. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  13241. directSpecular = vec3().toVar( 'directSpecular' ),
  13242. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  13243. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  13244. const reflectedLight = {
  13245. directDiffuse,
  13246. directSpecular,
  13247. indirectDiffuse,
  13248. indirectSpecular
  13249. };
  13250. const context = {
  13251. radiance: vec3().toVar( 'radiance' ),
  13252. irradiance: vec3().toVar( 'irradiance' ),
  13253. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  13254. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  13255. reflectedLight,
  13256. backdrop: backdropNode,
  13257. backdropAlpha: backdropAlphaNode
  13258. };
  13259. return context;
  13260. }
  13261. setup( builder ) {
  13262. this.value = this._value || ( this._value = this.getContext() );
  13263. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  13264. return super.setup( builder );
  13265. }
  13266. }
  13267. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  13268. /**
  13269. * A generic class that can be used by nodes which contribute
  13270. * irradiance to the scene. E.g. a light map node can be used
  13271. * as input for this module. Used in {@link NodeMaterial}.
  13272. *
  13273. * @augments LightingNode
  13274. */
  13275. class IrradianceNode extends LightingNode {
  13276. static get type() {
  13277. return 'IrradianceNode';
  13278. }
  13279. /**
  13280. * Constructs a new irradiance node.
  13281. *
  13282. * @param {Node<vec3>} node - A node contributing irradiance.
  13283. */
  13284. constructor( node ) {
  13285. super();
  13286. /**
  13287. * A node contributing irradiance.
  13288. *
  13289. * @type {Node<vec3>}
  13290. */
  13291. this.node = node;
  13292. }
  13293. setup( builder ) {
  13294. builder.context.irradiance.addAssign( this.node );
  13295. }
  13296. }
  13297. const _size$5 = /*@__PURE__*/ new Vector2();
  13298. /**
  13299. * A special type of texture node which represents the data of the current viewport
  13300. * as a texture. The module extracts data from the current bound framebuffer with
  13301. * a copy operation so no extra render pass is required to produce the texture data
  13302. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  13303. * variety of effects like refractive or transmissive materials.
  13304. *
  13305. * @augments TextureNode
  13306. */
  13307. class ViewportTextureNode extends TextureNode {
  13308. static get type() {
  13309. return 'ViewportTextureNode';
  13310. }
  13311. /**
  13312. * Constructs a new viewport texture node.
  13313. *
  13314. * @param {Node} [uvNode=screenUV] - The uv node.
  13315. * @param {?Node} [levelNode=null] - The level node.
  13316. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13317. */
  13318. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  13319. let defaultFramebuffer = null;
  13320. if ( framebufferTexture === null ) {
  13321. defaultFramebuffer = new FramebufferTexture();
  13322. defaultFramebuffer.minFilter = LinearMipmapLinearFilter;
  13323. framebufferTexture = defaultFramebuffer;
  13324. } else {
  13325. defaultFramebuffer = framebufferTexture;
  13326. }
  13327. super( framebufferTexture, uvNode, levelNode );
  13328. /**
  13329. * Whether to generate mipmaps or not.
  13330. *
  13331. * @type {boolean}
  13332. * @default false
  13333. */
  13334. this.generateMipmaps = false;
  13335. /**
  13336. * The reference framebuffer texture. This is used to store the framebuffer texture
  13337. * for the current render target. If the render target changes, a new framebuffer texture
  13338. * is created automatically.
  13339. *
  13340. * @type {FramebufferTexture}
  13341. * @default null
  13342. */
  13343. this.defaultFramebuffer = defaultFramebuffer;
  13344. /**
  13345. * This flag can be used for type testing.
  13346. *
  13347. * @type {boolean}
  13348. * @readonly
  13349. * @default true
  13350. */
  13351. this.isOutputTextureNode = true;
  13352. /**
  13353. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  13354. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  13355. *
  13356. * @type {string}
  13357. * @default 'frame'
  13358. */
  13359. this.updateBeforeType = NodeUpdateType.FRAME;
  13360. /**
  13361. * The framebuffer texture for the current renderer context.
  13362. *
  13363. * @type {WeakMap<RenderTarget, FramebufferTexture>}
  13364. * @private
  13365. */
  13366. this._cacheTextures = new WeakMap();
  13367. }
  13368. /**
  13369. * This methods returns a texture for the given render target reference.
  13370. *
  13371. * To avoid rendering errors, `ViewportTextureNode` must use unique framebuffer textures
  13372. * for different render contexts.
  13373. *
  13374. * @param {?RenderTarget} [reference=null] - The render target reference.
  13375. * @return {Texture} The framebuffer texture.
  13376. */
  13377. getTextureForReference( reference = null ) {
  13378. let defaultFramebuffer;
  13379. let cacheTextures;
  13380. if ( this.referenceNode ) {
  13381. defaultFramebuffer = this.referenceNode.defaultFramebuffer;
  13382. cacheTextures = this.referenceNode._cacheTextures;
  13383. } else {
  13384. defaultFramebuffer = this.defaultFramebuffer;
  13385. cacheTextures = this._cacheTextures;
  13386. }
  13387. if ( reference === null ) {
  13388. return defaultFramebuffer;
  13389. }
  13390. if ( cacheTextures.has( reference ) === false ) {
  13391. const framebufferTexture = defaultFramebuffer.clone();
  13392. cacheTextures.set( reference, framebufferTexture );
  13393. }
  13394. return cacheTextures.get( reference );
  13395. }
  13396. updateReference( frame ) {
  13397. const renderTarget = frame.renderer.getRenderTarget();
  13398. this.value = this.getTextureForReference( renderTarget );
  13399. return this.value;
  13400. }
  13401. updateBefore( frame ) {
  13402. const renderer = frame.renderer;
  13403. const renderTarget = renderer.getRenderTarget();
  13404. if ( renderTarget === null ) {
  13405. renderer.getDrawingBufferSize( _size$5 );
  13406. } else {
  13407. _size$5.set( renderTarget.width, renderTarget.height );
  13408. }
  13409. //
  13410. const framebufferTexture = this.getTextureForReference( renderTarget );
  13411. if ( framebufferTexture.image.width !== _size$5.width || framebufferTexture.image.height !== _size$5.height ) {
  13412. framebufferTexture.image.width = _size$5.width;
  13413. framebufferTexture.image.height = _size$5.height;
  13414. framebufferTexture.needsUpdate = true;
  13415. }
  13416. //
  13417. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  13418. framebufferTexture.generateMipmaps = this.generateMipmaps;
  13419. renderer.copyFramebufferToTexture( framebufferTexture );
  13420. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  13421. }
  13422. clone() {
  13423. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  13424. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  13425. return viewportTextureNode;
  13426. }
  13427. }
  13428. /**
  13429. * TSL function for creating a viewport texture node.
  13430. *
  13431. * @tsl
  13432. * @function
  13433. * @param {?Node} [uvNode=screenUV] - The uv node.
  13434. * @param {?Node} [levelNode=null] - The level node.
  13435. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13436. * @returns {ViewportTextureNode}
  13437. */
  13438. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  13439. /**
  13440. * TSL function for creating a viewport texture node with enabled mipmap generation.
  13441. *
  13442. * @tsl
  13443. * @function
  13444. * @param {?Node} [uvNode=screenUV] - The uv node.
  13445. * @param {?Node} [levelNode=null] - The level node.
  13446. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13447. * @returns {ViewportTextureNode}
  13448. */
  13449. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  13450. let _sharedDepthbuffer = null;
  13451. /**
  13452. * Represents the depth of the current viewport as a texture. This module
  13453. * can be used in combination with viewport texture to achieve effects
  13454. * that require depth evaluation.
  13455. *
  13456. * @augments ViewportTextureNode
  13457. */
  13458. class ViewportDepthTextureNode extends ViewportTextureNode {
  13459. static get type() {
  13460. return 'ViewportDepthTextureNode';
  13461. }
  13462. /**
  13463. * Constructs a new viewport depth texture node.
  13464. *
  13465. * @param {Node} [uvNode=screenUV] - The uv node.
  13466. * @param {?Node} [levelNode=null] - The level node.
  13467. */
  13468. constructor( uvNode = screenUV, levelNode = null ) {
  13469. if ( _sharedDepthbuffer === null ) {
  13470. _sharedDepthbuffer = new DepthTexture();
  13471. }
  13472. super( uvNode, levelNode, _sharedDepthbuffer );
  13473. }
  13474. /**
  13475. * Overwritten so the method always returns the unique shared
  13476. * depth texture.
  13477. *
  13478. * @return {DepthTexture} The shared depth texture.
  13479. */
  13480. getTextureForReference() {
  13481. return _sharedDepthbuffer;
  13482. }
  13483. }
  13484. /**
  13485. * TSL function for a viewport depth texture node.
  13486. *
  13487. * @tsl
  13488. * @function
  13489. * @param {?Node} [uvNode=screenUV] - The uv node.
  13490. * @param {?Node} [levelNode=null] - The level node.
  13491. * @returns {ViewportDepthTextureNode}
  13492. */
  13493. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  13494. /**
  13495. * This node offers a collection of features in context of the depth logic in the fragment shader.
  13496. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  13497. * fragment or for depth evaluation purposes.
  13498. *
  13499. * @augments Node
  13500. */
  13501. class ViewportDepthNode extends Node {
  13502. static get type() {
  13503. return 'ViewportDepthNode';
  13504. }
  13505. /**
  13506. * Constructs a new viewport depth node.
  13507. *
  13508. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  13509. * @param {?Node} [valueNode=null] - The value node.
  13510. */
  13511. constructor( scope, valueNode = null ) {
  13512. super( 'float' );
  13513. /**
  13514. * The node behaves differently depending on which scope is selected.
  13515. *
  13516. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  13517. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  13518. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  13519. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  13520. *
  13521. * @type {('depth'|'depthBase'|'linearDepth')}
  13522. */
  13523. this.scope = scope;
  13524. /**
  13525. * Can be used to define a custom depth value.
  13526. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  13527. *
  13528. * @type {?Node}
  13529. * @default null
  13530. */
  13531. this.valueNode = valueNode;
  13532. /**
  13533. * This flag can be used for type testing.
  13534. *
  13535. * @type {boolean}
  13536. * @readonly
  13537. * @default true
  13538. */
  13539. this.isViewportDepthNode = true;
  13540. }
  13541. generate( builder ) {
  13542. const { scope } = this;
  13543. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13544. return builder.getFragDepth();
  13545. }
  13546. return super.generate( builder );
  13547. }
  13548. setup( { camera } ) {
  13549. const { scope } = this;
  13550. const value = this.valueNode;
  13551. let node = null;
  13552. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13553. if ( value !== null ) {
  13554. node = depthBase().assign( value );
  13555. }
  13556. } else if ( scope === ViewportDepthNode.DEPTH ) {
  13557. if ( camera.isPerspectiveCamera ) {
  13558. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  13559. } else {
  13560. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13561. }
  13562. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  13563. if ( value !== null ) {
  13564. if ( camera.isPerspectiveCamera ) {
  13565. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  13566. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  13567. } else {
  13568. node = value;
  13569. }
  13570. } else {
  13571. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13572. }
  13573. }
  13574. return node;
  13575. }
  13576. }
  13577. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  13578. ViewportDepthNode.DEPTH = 'depth';
  13579. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  13580. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  13581. /**
  13582. * TSL function for converting a viewZ value to an orthographic depth value.
  13583. *
  13584. * @tsl
  13585. * @function
  13586. * @param {Node<float>} viewZ - The viewZ node.
  13587. * @param {Node<float>} near - The camera's near value.
  13588. * @param {Node<float>} far - The camera's far value.
  13589. * @returns {Node<float>}
  13590. */
  13591. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  13592. /**
  13593. * TSL function for converting an orthographic depth value to a viewZ value.
  13594. *
  13595. * @tsl
  13596. * @function
  13597. * @param {Node<float>} depth - The orthographic depth.
  13598. * @param {Node<float>} near - The camera's near value.
  13599. * @param {Node<float>} far - The camera's far value.
  13600. * @returns {Node<float>}
  13601. */
  13602. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  13603. /**
  13604. * TSL function for converting a viewZ value to a perspective depth value.
  13605. *
  13606. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  13607. *
  13608. * @tsl
  13609. * @function
  13610. * @param {Node<float>} viewZ - The viewZ node.
  13611. * @param {Node<float>} near - The camera's near value.
  13612. * @param {Node<float>} far - The camera's far value.
  13613. * @returns {Node<float>}
  13614. */
  13615. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  13616. /**
  13617. * TSL function for converting a perspective depth value to a viewZ value.
  13618. *
  13619. * @tsl
  13620. * @function
  13621. * @param {Node<float>} depth - The perspective depth.
  13622. * @param {Node<float>} near - The camera's near value.
  13623. * @param {Node<float>} far - The camera's far value.
  13624. * @returns {Node<float>}
  13625. */
  13626. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  13627. /**
  13628. * TSL function for converting a viewZ value to a logarithmic depth value.
  13629. *
  13630. * @tsl
  13631. * @function
  13632. * @param {Node<float>} viewZ - The viewZ node.
  13633. * @param {Node<float>} near - The camera's near value.
  13634. * @param {Node<float>} far - The camera's far value.
  13635. * @returns {Node<float>}
  13636. */
  13637. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  13638. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  13639. // The final logarithmic depth formula used here is adapted from one described in an
  13640. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  13641. // which was an improvement upon an earlier formula one described in an
  13642. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  13643. // Ulrich's formula is the following:
  13644. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  13645. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  13646. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  13647. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  13648. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  13649. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  13650. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  13651. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  13652. // be used, and ultimately Ulrich's "near plane" version was chosen.
  13653. // Outerra eventually made another improvement to their original "C-constant" variant,
  13654. // but it still does not incorporate the camera near plane (for this version,
  13655. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  13656. // Here we make 4 changes to Ulrich's formula:
  13657. // 1. Clamp the camera near plane so we don't divide by 0.
  13658. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  13659. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  13660. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  13661. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  13662. // so we do the same here, hence the 'viewZ.negate()' call.
  13663. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  13664. near = near.max( 1e-6 ).toVar();
  13665. const numerator = log2( viewZ.negate().div( near ) );
  13666. const denominator = log2( far.div( near ) );
  13667. return numerator.div( denominator );
  13668. };
  13669. /**
  13670. * TSL function for converting a logarithmic depth value to a viewZ value.
  13671. *
  13672. * @tsl
  13673. * @function
  13674. * @param {Node<float>} depth - The logarithmic depth.
  13675. * @param {Node<float>} near - The camera's near value.
  13676. * @param {Node<float>} far - The camera's far value.
  13677. * @returns {Node<float>}
  13678. */
  13679. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  13680. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  13681. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  13682. // a negative viewZ).
  13683. const exponent = depth.mul( log( far.div( near ) ) );
  13684. return float( Math.E ).pow( exponent ).mul( near ).negate();
  13685. };
  13686. /**
  13687. * TSL function for defining a value for the current fragment's depth.
  13688. *
  13689. * @tsl
  13690. * @function
  13691. * @param {Node<float>} value - The depth value to set.
  13692. * @returns {ViewportDepthNode<float>}
  13693. */
  13694. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  13695. /**
  13696. * TSL object that represents the depth value for the current fragment.
  13697. *
  13698. * @tsl
  13699. * @type {ViewportDepthNode}
  13700. */
  13701. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  13702. /**
  13703. * TSL function for converting a perspective depth value to linear depth.
  13704. *
  13705. * @tsl
  13706. * @function
  13707. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  13708. * @returns {ViewportDepthNode<float>}
  13709. */
  13710. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  13711. /**
  13712. * TSL object that represents the linear (orthographic) depth value of the current fragment
  13713. *
  13714. * @tsl
  13715. * @type {ViewportDepthNode}
  13716. */
  13717. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  13718. depth.assign = ( value ) => depthBase( value );
  13719. /**
  13720. * This node is used in {@link NodeMaterial} to setup the clipping
  13721. * which can happen hardware-accelerated (if supported) and optionally
  13722. * use alpha-to-coverage for anti-aliasing clipped edges.
  13723. *
  13724. * @augments Node
  13725. */
  13726. class ClippingNode extends Node {
  13727. static get type() {
  13728. return 'ClippingNode';
  13729. }
  13730. /**
  13731. * Constructs a new clipping node.
  13732. *
  13733. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  13734. * the selected scope influences the behavior of the node and what type of code is generated.
  13735. */
  13736. constructor( scope = ClippingNode.DEFAULT ) {
  13737. super();
  13738. /**
  13739. * The node's scope. Similar to other nodes, the selected scope influences
  13740. * the behavior of the node and what type of code is generated.
  13741. *
  13742. * @type {('default'|'hardware'|'alphaToCoverage')}
  13743. */
  13744. this.scope = scope;
  13745. }
  13746. /**
  13747. * Setups the node depending on the selected scope.
  13748. *
  13749. * @param {NodeBuilder} builder - The current node builder.
  13750. * @return {Node} The result node.
  13751. */
  13752. setup( builder ) {
  13753. super.setup( builder );
  13754. const clippingContext = builder.clippingContext;
  13755. const { intersectionPlanes, unionPlanes } = clippingContext;
  13756. this.hardwareClipping = builder.material.hardwareClipping;
  13757. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  13758. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  13759. } else if ( this.scope === ClippingNode.HARDWARE ) {
  13760. return this.setupHardwareClipping( unionPlanes, builder );
  13761. } else {
  13762. return this.setupDefault( intersectionPlanes, unionPlanes );
  13763. }
  13764. }
  13765. /**
  13766. * Setups alpha to coverage.
  13767. *
  13768. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13769. * @param {Array<Vector4>} unionPlanes - The union planes.
  13770. * @return {Node} The result node.
  13771. */
  13772. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  13773. return Fn( () => {
  13774. const distanceToPlane = float().toVar( 'distanceToPlane' );
  13775. const distanceGradient = float().toVar( 'distanceToGradient' );
  13776. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  13777. const numUnionPlanes = unionPlanes.length;
  13778. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13779. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13780. Loop( numUnionPlanes, ( { i } ) => {
  13781. const plane = clippingPlanes.element( i );
  13782. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13783. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13784. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  13785. } );
  13786. }
  13787. const numIntersectionPlanes = intersectionPlanes.length;
  13788. if ( numIntersectionPlanes > 0 ) {
  13789. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13790. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  13791. Loop( numIntersectionPlanes, ( { i } ) => {
  13792. const plane = clippingPlanes.element( i );
  13793. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13794. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13795. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  13796. } );
  13797. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  13798. }
  13799. diffuseColor.a.mulAssign( clipOpacity );
  13800. diffuseColor.a.equal( 0.0 ).discard();
  13801. } )();
  13802. }
  13803. /**
  13804. * Setups the default clipping.
  13805. *
  13806. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13807. * @param {Array<Vector4>} unionPlanes - The union planes.
  13808. * @return {Node} The result node.
  13809. */
  13810. setupDefault( intersectionPlanes, unionPlanes ) {
  13811. return Fn( () => {
  13812. const numUnionPlanes = unionPlanes.length;
  13813. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13814. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13815. Loop( numUnionPlanes, ( { i } ) => {
  13816. const plane = clippingPlanes.element( i );
  13817. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  13818. } );
  13819. }
  13820. const numIntersectionPlanes = intersectionPlanes.length;
  13821. if ( numIntersectionPlanes > 0 ) {
  13822. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13823. const clipped = bool( true ).toVar( 'clipped' );
  13824. Loop( numIntersectionPlanes, ( { i } ) => {
  13825. const plane = clippingPlanes.element( i );
  13826. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  13827. } );
  13828. clipped.discard();
  13829. }
  13830. } )();
  13831. }
  13832. /**
  13833. * Setups hardware clipping.
  13834. *
  13835. * @param {Array<Vector4>} unionPlanes - The union planes.
  13836. * @param {NodeBuilder} builder - The current node builder.
  13837. * @return {Node} The result node.
  13838. */
  13839. setupHardwareClipping( unionPlanes, builder ) {
  13840. const numUnionPlanes = unionPlanes.length;
  13841. builder.enableHardwareClipping( numUnionPlanes );
  13842. return Fn( () => {
  13843. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13844. const hw_clip_distances = builtin( builder.getClipDistance() );
  13845. Loop( numUnionPlanes, ( { i } ) => {
  13846. const plane = clippingPlanes.element( i );
  13847. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  13848. hw_clip_distances.element( i ).assign( distance );
  13849. } );
  13850. } )();
  13851. }
  13852. }
  13853. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  13854. ClippingNode.DEFAULT = 'default';
  13855. ClippingNode.HARDWARE = 'hardware';
  13856. /**
  13857. * TSL function for setting up the default clipping logic.
  13858. *
  13859. * @tsl
  13860. * @function
  13861. * @returns {ClippingNode}
  13862. */
  13863. const clipping = () => nodeObject( new ClippingNode() );
  13864. /**
  13865. * TSL function for setting up alpha to coverage.
  13866. *
  13867. * @tsl
  13868. * @function
  13869. * @returns {ClippingNode}
  13870. */
  13871. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  13872. /**
  13873. * TSL function for setting up hardware-based clipping.
  13874. *
  13875. * @tsl
  13876. * @function
  13877. * @returns {ClippingNode}
  13878. */
  13879. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  13880. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  13881. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  13882. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13883. 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 ) ) ) ) ) );
  13884. } );
  13885. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13886. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  13887. } );
  13888. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  13889. // Find the discretized derivatives of our coordinates
  13890. const maxDeriv = max$1(
  13891. length( dFdx( position.xyz ) ),
  13892. length( dFdy( position.xyz ) )
  13893. );
  13894. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  13895. // Find two nearest log-discretized noise scales
  13896. const pixScales = vec2(
  13897. exp2( floor( log2( pixScale ) ) ),
  13898. exp2( ceil( log2( pixScale ) ) )
  13899. );
  13900. // Compute alpha thresholds at our two noise scales
  13901. const alpha = vec2(
  13902. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  13903. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  13904. );
  13905. // Factor to interpolate lerp with
  13906. const lerpFactor = fract( log2( pixScale ) );
  13907. // Interpolate alpha threshold from noise at two scales
  13908. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  13909. // Pass into CDF to compute uniformly distrib threshold
  13910. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  13911. const cases = vec3(
  13912. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  13913. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  13914. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  13915. // Find our final, uniformly distributed alpha threshold (ατ)
  13916. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  13917. // Avoids ατ == 0. Could also do ατ =1-ατ
  13918. return clamp( threshold, 1.0e-6, 1.0 );
  13919. } ).setLayout( {
  13920. name: 'getAlphaHashThreshold',
  13921. type: 'float',
  13922. inputs: [
  13923. { name: 'position', type: 'vec3' }
  13924. ]
  13925. } );
  13926. /**
  13927. * An attribute node for representing vertex colors.
  13928. *
  13929. * @augments AttributeNode
  13930. */
  13931. class VertexColorNode extends AttributeNode {
  13932. static get type() {
  13933. return 'VertexColorNode';
  13934. }
  13935. /**
  13936. * Constructs a new vertex color node.
  13937. *
  13938. * @param {number} index - The attribute index.
  13939. */
  13940. constructor( index ) {
  13941. super( null, 'vec4' );
  13942. /**
  13943. * This flag can be used for type testing.
  13944. *
  13945. * @type {boolean}
  13946. * @readonly
  13947. * @default true
  13948. */
  13949. this.isVertexColorNode = true;
  13950. /**
  13951. * The attribute index to enable more than one sets of vertex colors.
  13952. *
  13953. * @type {number}
  13954. * @default 0
  13955. */
  13956. this.index = index;
  13957. }
  13958. /**
  13959. * Overwrites the default implementation by honoring the attribute index.
  13960. *
  13961. * @param {NodeBuilder} builder - The current node builder.
  13962. * @return {string} The attribute name.
  13963. */
  13964. getAttributeName( /*builder*/ ) {
  13965. const index = this.index;
  13966. return 'color' + ( index > 0 ? index : '' );
  13967. }
  13968. generate( builder ) {
  13969. const attributeName = this.getAttributeName( builder );
  13970. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  13971. let result;
  13972. if ( geometryAttribute === true ) {
  13973. result = super.generate( builder );
  13974. } else {
  13975. // Vertex color fallback should be white
  13976. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  13977. }
  13978. return result;
  13979. }
  13980. serialize( data ) {
  13981. super.serialize( data );
  13982. data.index = this.index;
  13983. }
  13984. deserialize( data ) {
  13985. super.deserialize( data );
  13986. this.index = data.index;
  13987. }
  13988. }
  13989. /**
  13990. * TSL function for creating a reference node.
  13991. *
  13992. * @tsl
  13993. * @function
  13994. * @param {number} [index=0] - The attribute index.
  13995. * @returns {VertexColorNode}
  13996. */
  13997. const vertexColor = ( index = 0 ) => nodeObject( new VertexColorNode( index ) );
  13998. /**
  13999. * Represents a "Color Burn" blend mode.
  14000. *
  14001. * It's designed to darken the base layer's colors based on the color of the blend layer.
  14002. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  14003. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  14004. *
  14005. * @tsl
  14006. * @function
  14007. * @param {Node<vec3>} base - The base color.
  14008. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  14009. * @return {Node<vec3>} The result.
  14010. */
  14011. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14012. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  14013. } ).setLayout( {
  14014. name: 'blendBurn',
  14015. type: 'vec3',
  14016. inputs: [
  14017. { name: 'base', type: 'vec3' },
  14018. { name: 'blend', type: 'vec3' }
  14019. ]
  14020. } );
  14021. /**
  14022. * Represents a "Color Dodge" blend mode.
  14023. *
  14024. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  14025. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  14026. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  14027. *
  14028. * @tsl
  14029. * @function
  14030. * @param {Node<vec3>} base - The base color.
  14031. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  14032. * @return {Node<vec3>} The result.
  14033. */
  14034. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14035. return min$1( base.div( blend.oneMinus() ), 1.0 );
  14036. } ).setLayout( {
  14037. name: 'blendDodge',
  14038. type: 'vec3',
  14039. inputs: [
  14040. { name: 'base', type: 'vec3' },
  14041. { name: 'blend', type: 'vec3' }
  14042. ]
  14043. } );
  14044. /**
  14045. * Represents a "Screen" blend mode.
  14046. *
  14047. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  14048. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  14049. * effects.
  14050. *
  14051. * @tsl
  14052. * @function
  14053. * @param {Node<vec3>} base - The base color.
  14054. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  14055. * @return {Node<vec3>} The result.
  14056. */
  14057. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14058. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  14059. } ).setLayout( {
  14060. name: 'blendScreen',
  14061. type: 'vec3',
  14062. inputs: [
  14063. { name: 'base', type: 'vec3' },
  14064. { name: 'blend', type: 'vec3' }
  14065. ]
  14066. } );
  14067. /**
  14068. * Represents a "Overlay" blend mode.
  14069. *
  14070. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  14071. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  14072. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  14073. *
  14074. * @tsl
  14075. * @function
  14076. * @param {Node<vec3>} base - The base color.
  14077. * @param {Node<vec3>} blend - The blend color
  14078. * @return {Node<vec3>} The result.
  14079. */
  14080. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14081. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  14082. } ).setLayout( {
  14083. name: 'blendOverlay',
  14084. type: 'vec3',
  14085. inputs: [
  14086. { name: 'base', type: 'vec3' },
  14087. { name: 'blend', type: 'vec3' }
  14088. ]
  14089. } );
  14090. /**
  14091. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  14092. * It assumes both input colors have non-premultiplied alpha.
  14093. *
  14094. * @tsl
  14095. * @function
  14096. * @param {Node<vec4>} base - The base color.
  14097. * @param {Node<vec4>} blend - The blend color
  14098. * @return {Node<vec4>} The result.
  14099. */
  14100. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14101. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  14102. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  14103. } ).setLayout( {
  14104. name: 'blendColor',
  14105. type: 'vec4',
  14106. inputs: [
  14107. { name: 'base', type: 'vec4' },
  14108. { name: 'blend', type: 'vec4' }
  14109. ]
  14110. } );
  14111. /**
  14112. * Premultiplies the RGB channels of a color by its alpha channel.
  14113. *
  14114. * This function is useful for converting a non-premultiplied alpha color
  14115. * into a premultiplied alpha format, where the RGB values are scaled
  14116. * by the alpha value. Premultiplied alpha is often used in graphics
  14117. * rendering for certain operations, such as compositing and image processing.
  14118. *
  14119. * @tsl
  14120. * @function
  14121. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  14122. * @return {Node<vec4>} The color with premultiplied alpha.
  14123. */
  14124. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  14125. return vec4( color.rgb.mul( color.a ), color.a );
  14126. }, { color: 'vec4', return: 'vec4' } );
  14127. /**
  14128. * Unpremultiplies the RGB channels of a color by its alpha channel.
  14129. *
  14130. * This function is useful for converting a premultiplied alpha color
  14131. * back into a non-premultiplied alpha format, where the RGB values are
  14132. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  14133. * rendering for certain operations, such as compositing and image processing.
  14134. *
  14135. * @tsl
  14136. * @function
  14137. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  14138. * @return {Node<vec4>} The color with non-premultiplied alpha.
  14139. */
  14140. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  14141. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  14142. return vec4( color.rgb.div( color.a ), color.a );
  14143. }, { color: 'vec4', return: 'vec4' } );
  14144. // Deprecated
  14145. /**
  14146. * @tsl
  14147. * @function
  14148. * @deprecated since r171. Use {@link blendBurn} instead.
  14149. *
  14150. * @param {...any} params
  14151. * @returns {Function}
  14152. */
  14153. const burn = ( ...params ) => { // @deprecated, r171
  14154. warn( 'TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  14155. return blendBurn( params );
  14156. };
  14157. /**
  14158. * @tsl
  14159. * @function
  14160. * @deprecated since r171. Use {@link blendDodge} instead.
  14161. *
  14162. * @param {...any} params
  14163. * @returns {Function}
  14164. */
  14165. const dodge = ( ...params ) => { // @deprecated, r171
  14166. warn( 'TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  14167. return blendDodge( params );
  14168. };
  14169. /**
  14170. * @tsl
  14171. * @function
  14172. * @deprecated since r171. Use {@link blendScreen} instead.
  14173. *
  14174. * @param {...any} params
  14175. * @returns {Function}
  14176. */
  14177. const screen = ( ...params ) => { // @deprecated, r171
  14178. warn( 'TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  14179. return blendScreen( params );
  14180. };
  14181. /**
  14182. * @tsl
  14183. * @function
  14184. * @deprecated since r171. Use {@link blendOverlay} instead.
  14185. *
  14186. * @param {...any} params
  14187. * @returns {Function}
  14188. */
  14189. const overlay = ( ...params ) => { // @deprecated, r171
  14190. warn( 'TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  14191. return blendOverlay( params );
  14192. };
  14193. /**
  14194. * Base class for all node materials.
  14195. *
  14196. * @augments Material
  14197. */
  14198. class NodeMaterial extends Material {
  14199. static get type() {
  14200. return 'NodeMaterial';
  14201. }
  14202. /**
  14203. * Represents the type of the node material.
  14204. *
  14205. * @type {string}
  14206. */
  14207. get type() {
  14208. return this.constructor.type;
  14209. }
  14210. set type( _value ) { /* */ }
  14211. /**
  14212. * Constructs a new node material.
  14213. */
  14214. constructor() {
  14215. super();
  14216. /**
  14217. * This flag can be used for type testing.
  14218. *
  14219. * @type {boolean}
  14220. * @readonly
  14221. * @default true
  14222. */
  14223. this.isNodeMaterial = true;
  14224. /**
  14225. * Whether this material is affected by fog or not.
  14226. *
  14227. * @type {boolean}
  14228. * @default true
  14229. */
  14230. this.fog = true;
  14231. /**
  14232. * Whether this material is affected by lights or not.
  14233. *
  14234. * @type {boolean}
  14235. * @default false
  14236. */
  14237. this.lights = false;
  14238. /**
  14239. * Whether this material uses hardware clipping or not.
  14240. * This property is managed by the engine and should not be
  14241. * modified by apps.
  14242. *
  14243. * @type {boolean}
  14244. * @default false
  14245. */
  14246. this.hardwareClipping = false;
  14247. /**
  14248. * Node materials which set their `lights` property to `true`
  14249. * are affected by all lights of the scene. Sometimes selective
  14250. * lighting is wanted which means only _some_ lights in the scene
  14251. * affect a material. This can be achieved by creating an instance
  14252. * of {@link LightsNode} with a list of selective
  14253. * lights and assign the node to this property.
  14254. *
  14255. * ```js
  14256. * const customLightsNode = lights( [ light1, light2 ] );
  14257. * material.lightsNode = customLightsNode;
  14258. * ```
  14259. *
  14260. * @type {?LightsNode}
  14261. * @default null
  14262. */
  14263. this.lightsNode = null;
  14264. /**
  14265. * The environment of node materials can be defined by an environment
  14266. * map assigned to the `envMap` property or by `Scene.environment`
  14267. * if the node material is a PBR material. This node property allows to overwrite
  14268. * the default behavior and define the environment with a custom node.
  14269. *
  14270. * ```js
  14271. * material.envNode = pmremTexture( renderTarget.texture );
  14272. * ```
  14273. *
  14274. * @type {?Node<vec3>}
  14275. * @default null
  14276. */
  14277. this.envNode = null;
  14278. /**
  14279. * The lighting of node materials might be influenced by ambient occlusion.
  14280. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  14281. * and the respective `aoMapIntensity`. This node property allows to overwrite
  14282. * the default and define the ambient occlusion with a custom node instead.
  14283. *
  14284. * If you don't want to overwrite the diffuse color but modify the existing
  14285. * values instead, use {@link materialAO}.
  14286. *
  14287. * @type {?Node<float>}
  14288. * @default null
  14289. */
  14290. this.aoNode = null;
  14291. /**
  14292. * The diffuse color of node materials is by default inferred from the
  14293. * `color` and `map` properties. This node property allows to overwrite the default
  14294. * and define the diffuse color with a node instead.
  14295. *
  14296. * ```js
  14297. * material.colorNode = color( 0xff0000 ); // define red color
  14298. * ```
  14299. *
  14300. * If you don't want to overwrite the diffuse color but modify the existing
  14301. * values instead, use {@link materialColor}.
  14302. *
  14303. * ```js
  14304. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  14305. * ```
  14306. *
  14307. * @type {?Node<vec3>}
  14308. * @default null
  14309. */
  14310. this.colorNode = null;
  14311. /**
  14312. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  14313. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  14314. * and define the normals with a node instead.
  14315. *
  14316. * If you don't want to overwrite the normals but modify the existing values instead,
  14317. * use {@link materialNormal}.
  14318. *
  14319. * @type {?Node<vec3>}
  14320. * @default null
  14321. */
  14322. this.normalNode = null;
  14323. /**
  14324. * The opacity of node materials is by default inferred from the `opacity`
  14325. * and `alphaMap` properties. This node property allows to overwrite the default
  14326. * and define the opacity with a node instead.
  14327. *
  14328. * If you don't want to overwrite the opacity but modify the existing
  14329. * value instead, use {@link materialOpacity}.
  14330. *
  14331. * @type {?Node<float>}
  14332. * @default null
  14333. */
  14334. this.opacityNode = null;
  14335. /**
  14336. * This node can be used to implement a variety of filter-like effects. The idea is
  14337. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  14338. * to create an arbitrary effect and then assign the node composition to this property.
  14339. * Everything behind the object using this material will now be affected by a filter.
  14340. *
  14341. * ```js
  14342. * const material = new NodeMaterial()
  14343. * material.transparent = true;
  14344. *
  14345. * // everything behind the object will be monochromatic
  14346. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  14347. * ```
  14348. *
  14349. * Backdrop computations are part of the lighting so only lit materials can use this property.
  14350. *
  14351. * @type {?Node<vec3>}
  14352. * @default null
  14353. */
  14354. this.backdropNode = null;
  14355. /**
  14356. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  14357. *
  14358. * @type {?Node<float>}
  14359. * @default null
  14360. */
  14361. this.backdropAlphaNode = null;
  14362. /**
  14363. * The alpha test of node materials is by default inferred from the `alphaTest`
  14364. * property. This node property allows to overwrite the default and define the
  14365. * alpha test with a node instead.
  14366. *
  14367. * If you don't want to overwrite the alpha test but modify the existing
  14368. * value instead, use {@link materialAlphaTest}.
  14369. *
  14370. * @type {?Node<float>}
  14371. * @default null
  14372. */
  14373. this.alphaTestNode = null;
  14374. /**
  14375. * Discards the fragment if the mask value is `false`.
  14376. *
  14377. * @type {?Node<bool>}
  14378. * @default null
  14379. */
  14380. this.maskNode = null;
  14381. /**
  14382. * The local vertex positions are computed based on multiple factors like the
  14383. * attribute data, morphing or skinning. This node property allows to overwrite
  14384. * the default and define local vertex positions with nodes instead.
  14385. *
  14386. * If you don't want to overwrite the vertex positions but modify the existing
  14387. * values instead, use {@link positionLocal}.
  14388. *
  14389. *```js
  14390. * material.positionNode = positionLocal.add( displace );
  14391. * ```
  14392. *
  14393. * @type {?Node<vec3>}
  14394. * @default null
  14395. */
  14396. this.positionNode = null;
  14397. /**
  14398. * This node property is intended for logic which modifies geometry data once or per animation step.
  14399. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  14400. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  14401. * can be implemented.
  14402. *
  14403. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  14404. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  14405. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  14406. * eventually assigned to `geometryNode`.
  14407. *
  14408. * @type {?Function}
  14409. * @default null
  14410. */
  14411. this.geometryNode = null;
  14412. /**
  14413. * Allows to overwrite depth values in the fragment shader.
  14414. *
  14415. * @type {?Node<float>}
  14416. * @default null
  14417. */
  14418. this.depthNode = null;
  14419. /**
  14420. * Allows to overwrite the position used for shadow map rendering which
  14421. * is by default {@link positionWorld}, the vertex position
  14422. * in world space.
  14423. *
  14424. * @type {?Node<float>}
  14425. * @default null
  14426. */
  14427. this.receivedShadowPositionNode = null;
  14428. /**
  14429. * Allows to overwrite the geometry position used for shadow map projection which
  14430. * is by default {@link positionLocal}, the vertex position in local space.
  14431. *
  14432. * @type {?Node<float>}
  14433. * @default null
  14434. */
  14435. this.castShadowPositionNode = null;
  14436. /**
  14437. * This node can be used to influence how an object using this node material
  14438. * receive shadows.
  14439. *
  14440. * ```js
  14441. * const totalShadows = float( 1 ).toVar();
  14442. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  14443. * totalShadows.mulAssign( shadow );
  14444. * //return float( 1 ); // bypass received shadows
  14445. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  14446. * } );
  14447. *
  14448. * @type {?(Function|FunctionNode<vec4>)}
  14449. * @default null
  14450. */
  14451. this.receivedShadowNode = null;
  14452. /**
  14453. * This node can be used to influence how an object using this node material
  14454. * casts shadows. To apply a color to shadows, you can simply do:
  14455. *
  14456. * ```js
  14457. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  14458. * ```
  14459. *
  14460. * Which can be nice to fake colored shadows of semi-transparent objects. It
  14461. * is also common to use the property with `Fn` function so checks are performed
  14462. * per fragment.
  14463. *
  14464. * ```js
  14465. * materialCustomShadow.castShadowNode = Fn( () => {
  14466. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  14467. * return materialColor;
  14468. * } )();
  14469. * ```
  14470. *
  14471. * @type {?Node<vec4>}
  14472. * @default null
  14473. */
  14474. this.castShadowNode = null;
  14475. /**
  14476. * This node can be used to define the final output of the material.
  14477. *
  14478. * TODO: Explain the differences to `fragmentNode`.
  14479. *
  14480. * @type {?Node<vec4>}
  14481. * @default null
  14482. */
  14483. this.outputNode = null;
  14484. /**
  14485. * MRT configuration is done on renderer or pass level. This node allows to
  14486. * overwrite what values are written into MRT targets on material level. This
  14487. * can be useful for implementing selective FX features that should only affect
  14488. * specific objects.
  14489. *
  14490. * @type {?MRTNode}
  14491. * @default null
  14492. */
  14493. this.mrtNode = null;
  14494. /**
  14495. * This node property can be used if you need complete freedom in implementing
  14496. * the fragment shader. Assigning a node will replace the built-in material
  14497. * logic used in the fragment stage.
  14498. *
  14499. * @type {?Node<vec4>}
  14500. * @default null
  14501. */
  14502. this.fragmentNode = null;
  14503. /**
  14504. * This node property can be used if you need complete freedom in implementing
  14505. * the vertex shader. Assigning a node will replace the built-in material logic
  14506. * used in the vertex stage.
  14507. *
  14508. * @type {?Node<vec4>}
  14509. * @default null
  14510. */
  14511. this.vertexNode = null;
  14512. /**
  14513. * This node can be used as a global context management component for this material.
  14514. *
  14515. * @type {?ContextNode}
  14516. * @default null
  14517. */
  14518. this.contextNode = null;
  14519. // Deprecated properties
  14520. Object.defineProperty( this, 'shadowPositionNode', { // @deprecated, r176
  14521. get: () => {
  14522. return this.receivedShadowPositionNode;
  14523. },
  14524. set: ( value ) => {
  14525. warn( 'NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".' );
  14526. this.receivedShadowPositionNode = value;
  14527. }
  14528. } );
  14529. }
  14530. /**
  14531. * Returns an array of child nodes for this material.
  14532. *
  14533. * @private
  14534. * @returns {Array<{property: string, childNode: Node}>}
  14535. */
  14536. _getNodeChildren() {
  14537. const children = [];
  14538. for ( const property of Object.getOwnPropertyNames( this ) ) {
  14539. if ( property.startsWith( '_' ) === true ) continue;
  14540. const object = this[ property ];
  14541. if ( object && object.isNode === true ) {
  14542. children.push( { property, childNode: object } );
  14543. }
  14544. }
  14545. return children;
  14546. }
  14547. /**
  14548. * Allows to define a custom cache key that influence the material key computation
  14549. * for render objects.
  14550. *
  14551. * @return {string} The custom cache key.
  14552. */
  14553. customProgramCacheKey() {
  14554. const values = [];
  14555. for ( const { property, childNode } of this._getNodeChildren() ) {
  14556. values.push( hashString( property.slice( 0, -4 ) ), childNode.getCacheKey() );
  14557. }
  14558. return this.type + hashArray( values );
  14559. }
  14560. /**
  14561. * Builds this material with the given node builder.
  14562. *
  14563. * @param {NodeBuilder} builder - The current node builder.
  14564. */
  14565. build( builder ) {
  14566. this.setup( builder );
  14567. }
  14568. /**
  14569. * Setups a node material observer with the given builder.
  14570. *
  14571. * @param {NodeBuilder} builder - The current node builder.
  14572. * @return {NodeMaterialObserver} The node material observer.
  14573. */
  14574. setupObserver( builder ) {
  14575. return new NodeMaterialObserver( builder );
  14576. }
  14577. /**
  14578. * Setups the vertex and fragment stage of this node material.
  14579. *
  14580. * @param {NodeBuilder} builder - The current node builder.
  14581. */
  14582. setup( builder ) {
  14583. builder.context.setupNormal = () => subBuild( this.setupNormal( builder ), 'NORMAL', 'vec3' );
  14584. builder.context.setupPositionView = () => this.setupPositionView( builder );
  14585. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  14586. const renderer = builder.renderer;
  14587. const renderTarget = renderer.getRenderTarget();
  14588. // < CONTEXT >
  14589. if ( renderer.contextNode.isContextNode === true ) {
  14590. builder.context = { ...builder.context, ...renderer.contextNode.getFlowContextData() };
  14591. } else {
  14592. error( 'NodeMaterial: "renderer.contextNode" must be an instance of `context()`.' );
  14593. }
  14594. if ( this.contextNode !== null ) {
  14595. if ( this.contextNode.isContextNode === true ) {
  14596. builder.context = { ...builder.context, ...this.contextNode.getFlowContextData() };
  14597. } else {
  14598. error( 'NodeMaterial: "material.contextNode" must be an instance of `context()`.' );
  14599. }
  14600. }
  14601. // < VERTEX STAGE >
  14602. builder.addStack();
  14603. const mvp = subBuild( this.setupVertex( builder ), 'VERTEX' );
  14604. const vertexNode = this.vertexNode || mvp;
  14605. builder.stack.outputNode = vertexNode;
  14606. this.setupHardwareClipping( builder );
  14607. if ( this.geometryNode !== null ) {
  14608. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  14609. }
  14610. builder.addFlow( 'vertex', builder.removeStack() );
  14611. // < FRAGMENT STAGE >
  14612. builder.addStack();
  14613. let resultNode;
  14614. const clippingNode = this.setupClipping( builder );
  14615. if ( this.depthWrite === true || this.depthTest === true ) {
  14616. // only write depth if depth buffer is configured
  14617. if ( renderTarget !== null ) {
  14618. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  14619. } else {
  14620. if ( renderer.depth === true ) this.setupDepth( builder );
  14621. }
  14622. }
  14623. if ( this.fragmentNode === null ) {
  14624. this.setupDiffuseColor( builder );
  14625. this.setupVariants( builder );
  14626. const outgoingLightNode = this.setupLighting( builder );
  14627. if ( clippingNode !== null ) builder.stack.addToStack( clippingNode );
  14628. // force unsigned floats - useful for RenderTargets
  14629. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  14630. resultNode = this.setupOutput( builder, basicOutput );
  14631. // OUTPUT NODE
  14632. output.assign( resultNode );
  14633. //
  14634. const isCustomOutput = this.outputNode !== null;
  14635. if ( isCustomOutput ) resultNode = this.outputNode;
  14636. //
  14637. if ( builder.context.getOutput ) {
  14638. resultNode = builder.context.getOutput( resultNode, builder );
  14639. }
  14640. // MRT
  14641. if ( renderTarget !== null ) {
  14642. const mrt = renderer.getMRT();
  14643. const materialMRT = this.mrtNode;
  14644. if ( mrt !== null ) {
  14645. if ( isCustomOutput ) output.assign( resultNode );
  14646. resultNode = mrt;
  14647. if ( materialMRT !== null ) {
  14648. resultNode = mrt.merge( materialMRT );
  14649. }
  14650. } else if ( materialMRT !== null ) {
  14651. resultNode = materialMRT;
  14652. }
  14653. }
  14654. } else {
  14655. let fragmentNode = this.fragmentNode;
  14656. if ( fragmentNode.isOutputStructNode !== true ) {
  14657. fragmentNode = vec4( fragmentNode );
  14658. }
  14659. resultNode = this.setupOutput( builder, fragmentNode );
  14660. }
  14661. builder.stack.outputNode = resultNode;
  14662. builder.addFlow( 'fragment', builder.removeStack() );
  14663. // < OBSERVER >
  14664. builder.observer = this.setupObserver( builder );
  14665. }
  14666. /**
  14667. * Setups the clipping node.
  14668. *
  14669. * @param {NodeBuilder} builder - The current node builder.
  14670. * @return {ClippingNode} The clipping node.
  14671. */
  14672. setupClipping( builder ) {
  14673. if ( builder.clippingContext === null ) return null;
  14674. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  14675. let result = null;
  14676. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  14677. const samples = builder.renderer.currentSamples;
  14678. if ( this.alphaToCoverage && samples > 1 ) {
  14679. // to be added to flow when the color/alpha value has been determined
  14680. result = clippingAlpha();
  14681. } else {
  14682. builder.stack.addToStack( clipping() );
  14683. }
  14684. }
  14685. return result;
  14686. }
  14687. /**
  14688. * Setups the hardware clipping if available on the current device.
  14689. *
  14690. * @param {NodeBuilder} builder - The current node builder.
  14691. */
  14692. setupHardwareClipping( builder ) {
  14693. this.hardwareClipping = false;
  14694. if ( builder.clippingContext === null ) return;
  14695. const candidateCount = builder.clippingContext.unionPlanes.length;
  14696. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  14697. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  14698. builder.stack.addToStack( hardwareClipping() );
  14699. this.hardwareClipping = true;
  14700. }
  14701. return;
  14702. }
  14703. /**
  14704. * Setups the depth of this material.
  14705. *
  14706. * @param {NodeBuilder} builder - The current node builder.
  14707. */
  14708. setupDepth( builder ) {
  14709. const { renderer, camera } = builder;
  14710. // Depth
  14711. let depthNode = this.depthNode;
  14712. if ( depthNode === null ) {
  14713. const mrt = renderer.getMRT();
  14714. if ( mrt && mrt.has( 'depth' ) ) {
  14715. depthNode = mrt.get( 'depth' );
  14716. } else if ( renderer.logarithmicDepthBuffer === true ) {
  14717. if ( camera.isPerspectiveCamera ) {
  14718. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  14719. } else {
  14720. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  14721. }
  14722. }
  14723. }
  14724. if ( depthNode !== null ) {
  14725. depth.assign( depthNode ).toStack();
  14726. }
  14727. }
  14728. /**
  14729. * Setups the position node in view space. This method exists
  14730. * so derived node materials can modify the implementation e.g. sprite materials.
  14731. *
  14732. * @param {NodeBuilder} builder - The current node builder.
  14733. * @return {Node<vec3>} The position in view space.
  14734. */
  14735. setupPositionView( /*builder*/ ) {
  14736. return modelViewMatrix.mul( positionLocal ).xyz;
  14737. }
  14738. /**
  14739. * Setups the position in clip space.
  14740. *
  14741. * @param {NodeBuilder} builder - The current node builder.
  14742. * @return {Node<vec4>} The position in view space.
  14743. */
  14744. setupModelViewProjection( /*builder*/ ) {
  14745. return cameraProjectionMatrix.mul( positionView );
  14746. }
  14747. /**
  14748. * Setups the logic for the vertex stage.
  14749. *
  14750. * @param {NodeBuilder} builder - The current node builder.
  14751. * @return {Node<vec4>} The position in clip space.
  14752. */
  14753. setupVertex( builder ) {
  14754. builder.addStack();
  14755. this.setupPosition( builder );
  14756. builder.context.vertex = builder.removeStack();
  14757. return modelViewProjection;
  14758. }
  14759. /**
  14760. * Setups the computation of the position in local space.
  14761. *
  14762. * @param {NodeBuilder} builder - The current node builder.
  14763. * @return {Node<vec3>} The position in local space.
  14764. */
  14765. setupPosition( builder ) {
  14766. const { object, geometry } = builder;
  14767. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  14768. morphReference( object ).toStack();
  14769. }
  14770. if ( object.isSkinnedMesh === true ) {
  14771. skinning( object ).toStack();
  14772. }
  14773. if ( this.displacementMap ) {
  14774. const displacementMap = materialReference( 'displacementMap', 'texture' );
  14775. const displacementScale = materialReference( 'displacementScale', 'float' );
  14776. const displacementBias = materialReference( 'displacementBias', 'float' );
  14777. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  14778. }
  14779. if ( object.isBatchedMesh ) {
  14780. batch( object ).toStack();
  14781. }
  14782. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  14783. instancedMesh( object ).toStack();
  14784. }
  14785. if ( this.positionNode !== null ) {
  14786. positionLocal.assign( subBuild( this.positionNode, 'POSITION', 'vec3' ) );
  14787. }
  14788. return positionLocal;
  14789. }
  14790. /**
  14791. * Setups the computation of the material's diffuse color.
  14792. *
  14793. * @param {NodeBuilder} builder - The current node builder.
  14794. * @param {BufferGeometry} geometry - The geometry.
  14795. */
  14796. setupDiffuseColor( builder ) {
  14797. const { object, geometry } = builder;
  14798. // MASK
  14799. if ( this.maskNode !== null ) {
  14800. // Discard if the mask is `false`
  14801. bool( this.maskNode ).not().discard();
  14802. }
  14803. // COLOR
  14804. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  14805. // VERTEX COLORS
  14806. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  14807. colorNode = colorNode.mul( vertexColor() );
  14808. }
  14809. // INSTANCED COLORS
  14810. if ( object.instanceColor ) {
  14811. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  14812. colorNode = instanceColor.mul( colorNode );
  14813. }
  14814. if ( object.isBatchedMesh && object._colorsTexture ) {
  14815. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  14816. colorNode = batchColor.mul( colorNode );
  14817. }
  14818. // DIFFUSE COLOR
  14819. diffuseColor.assign( colorNode );
  14820. // OPACITY
  14821. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14822. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  14823. // ALPHA TEST
  14824. let alphaTestNode = null;
  14825. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  14826. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  14827. if ( this.alphaToCoverage === true ) {
  14828. diffuseColor.a = smoothstep( alphaTestNode, alphaTestNode.add( fwidth( diffuseColor.a ) ), diffuseColor.a );
  14829. diffuseColor.a.lessThanEqual( 0 ).discard();
  14830. } else {
  14831. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  14832. }
  14833. }
  14834. // ALPHA HASH
  14835. if ( this.alphaHash === true ) {
  14836. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  14837. }
  14838. // OPAQUE
  14839. if ( builder.isOpaque() ) {
  14840. diffuseColor.a.assign( 1.0 );
  14841. }
  14842. }
  14843. /**
  14844. * Abstract interface method that can be implemented by derived materials
  14845. * to setup material-specific node variables.
  14846. *
  14847. * @abstract
  14848. * @param {NodeBuilder} builder - The current node builder.
  14849. */
  14850. setupVariants( /*builder*/ ) {
  14851. // Interface function.
  14852. }
  14853. /**
  14854. * Setups the outgoing light node variable
  14855. *
  14856. * @return {Node<vec3>} The outgoing light node.
  14857. */
  14858. setupOutgoingLight() {
  14859. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  14860. }
  14861. /**
  14862. * Setups the normal node from the material.
  14863. *
  14864. * @return {Node<vec3>} The normal node.
  14865. */
  14866. setupNormal() {
  14867. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  14868. }
  14869. /**
  14870. * Setups the environment node from the material.
  14871. *
  14872. * @param {NodeBuilder} builder - The current node builder.
  14873. * @return {Node<vec4>} The environment node.
  14874. */
  14875. setupEnvironment( /*builder*/ ) {
  14876. let node = null;
  14877. if ( this.envNode ) {
  14878. node = this.envNode;
  14879. } else if ( this.envMap ) {
  14880. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  14881. }
  14882. return node;
  14883. }
  14884. /**
  14885. * Setups the light map node from the material.
  14886. *
  14887. * @param {NodeBuilder} builder - The current node builder.
  14888. * @return {Node<vec3>} The light map node.
  14889. */
  14890. setupLightMap( builder ) {
  14891. let node = null;
  14892. if ( builder.material.lightMap ) {
  14893. node = new IrradianceNode( materialLightMap );
  14894. }
  14895. return node;
  14896. }
  14897. /**
  14898. * Setups the lights node based on the scene, environment and material.
  14899. *
  14900. * @param {NodeBuilder} builder - The current node builder.
  14901. * @return {LightsNode} The lights node.
  14902. */
  14903. setupLights( builder ) {
  14904. const materialLightsNode = [];
  14905. //
  14906. const envNode = this.setupEnvironment( builder );
  14907. if ( envNode && envNode.isLightingNode ) {
  14908. materialLightsNode.push( envNode );
  14909. }
  14910. const lightMapNode = this.setupLightMap( builder );
  14911. if ( lightMapNode && lightMapNode.isLightingNode ) {
  14912. materialLightsNode.push( lightMapNode );
  14913. }
  14914. let aoNode = this.aoNode;
  14915. if ( aoNode === null && builder.material.aoMap ) {
  14916. aoNode = materialAO;
  14917. }
  14918. if ( builder.context.getAO ) {
  14919. aoNode = builder.context.getAO( aoNode, builder );
  14920. }
  14921. if ( aoNode ) {
  14922. materialLightsNode.push( new AONode( aoNode ) );
  14923. }
  14924. let lightsN = this.lightsNode || builder.lightsNode;
  14925. if ( materialLightsNode.length > 0 ) {
  14926. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  14927. }
  14928. return lightsN;
  14929. }
  14930. /**
  14931. * This method should be implemented by most derived materials
  14932. * since it defines the material's lighting model.
  14933. *
  14934. * @abstract
  14935. * @param {NodeBuilder} builder - The current node builder.
  14936. * @return {LightingModel} The lighting model.
  14937. */
  14938. setupLightingModel( /*builder*/ ) {
  14939. // Interface function.
  14940. }
  14941. /**
  14942. * Setups the outgoing light node.
  14943. *
  14944. * @param {NodeBuilder} builder - The current node builder.
  14945. * @return {Node<vec3>} The outgoing light node.
  14946. */
  14947. setupLighting( builder ) {
  14948. const { material } = builder;
  14949. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  14950. // OUTGOING LIGHT
  14951. const lights = this.lights === true || this.lightsNode !== null;
  14952. const lightsNode = lights ? this.setupLights( builder ) : null;
  14953. let outgoingLightNode = this.setupOutgoingLight( builder );
  14954. if ( lightsNode && lightsNode.getScope().hasLights ) {
  14955. const lightingModel = this.setupLightingModel( builder ) || null;
  14956. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  14957. } else if ( backdropNode !== null ) {
  14958. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  14959. }
  14960. // EMISSIVE
  14961. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  14962. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  14963. outgoingLightNode = outgoingLightNode.add( emissive );
  14964. }
  14965. return outgoingLightNode;
  14966. }
  14967. /**
  14968. * Setup the fog.
  14969. *
  14970. * @param {NodeBuilder} builder - The current node builder.
  14971. * @param {Node<vec4>} outputNode - The existing output node.
  14972. * @return {Node<vec4>} The output node.
  14973. */
  14974. setupFog( builder, outputNode ) {
  14975. const fogNode = builder.fogNode;
  14976. if ( fogNode ) {
  14977. output.assign( outputNode );
  14978. outputNode = vec4( fogNode.toVar() );
  14979. }
  14980. return outputNode;
  14981. }
  14982. /**
  14983. * Setups premultiplied alpha.
  14984. *
  14985. * @param {NodeBuilder} builder - The current node builder.
  14986. * @param {Node<vec4>} outputNode - The existing output node.
  14987. * @return {Node<vec4>} The output node.
  14988. */
  14989. setupPremultipliedAlpha( builder, outputNode ) {
  14990. return premultiplyAlpha( outputNode );
  14991. }
  14992. /**
  14993. * Setups the output node.
  14994. *
  14995. * @param {NodeBuilder} builder - The current node builder.
  14996. * @param {Node<vec4>} outputNode - The existing output node.
  14997. * @return {Node<vec4>} The output node.
  14998. */
  14999. setupOutput( builder, outputNode ) {
  15000. // FOG
  15001. if ( this.fog === true ) {
  15002. outputNode = this.setupFog( builder, outputNode );
  15003. }
  15004. // PREMULTIPLIED ALPHA
  15005. if ( this.premultipliedAlpha === true ) {
  15006. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  15007. }
  15008. return outputNode;
  15009. }
  15010. /**
  15011. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  15012. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  15013. * defining all material properties of the classic type in the node type.
  15014. *
  15015. * @param {Material} material - The material to copy properties with their values to this node material.
  15016. */
  15017. setDefaultValues( material ) {
  15018. // This approach is to reuse the native refreshUniforms*
  15019. // and turn available the use of features like transmission and environment in core
  15020. for ( const property in material ) {
  15021. const value = material[ property ];
  15022. if ( this[ property ] === undefined ) {
  15023. this[ property ] = value;
  15024. if ( value && value.clone ) this[ property ] = value.clone();
  15025. }
  15026. }
  15027. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  15028. for ( const key in descriptors ) {
  15029. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  15030. descriptors[ key ].get !== undefined ) {
  15031. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  15032. }
  15033. }
  15034. }
  15035. /**
  15036. * Serializes this material to JSON.
  15037. *
  15038. * @param {?(Object|string)} meta - The meta information for serialization.
  15039. * @return {Object} The serialized node.
  15040. */
  15041. toJSON( meta ) {
  15042. const isRoot = ( meta === undefined || typeof meta === 'string' );
  15043. if ( isRoot ) {
  15044. meta = {
  15045. textures: {},
  15046. images: {},
  15047. nodes: {}
  15048. };
  15049. }
  15050. const data = Material.prototype.toJSON.call( this, meta );
  15051. data.inputNodes = {};
  15052. for ( const { property, childNode } of this._getNodeChildren() ) {
  15053. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  15054. }
  15055. // TODO: Copied from Object3D.toJSON
  15056. function extractFromCache( cache ) {
  15057. const values = [];
  15058. for ( const key in cache ) {
  15059. const data = cache[ key ];
  15060. delete data.metadata;
  15061. values.push( data );
  15062. }
  15063. return values;
  15064. }
  15065. if ( isRoot ) {
  15066. const textures = extractFromCache( meta.textures );
  15067. const images = extractFromCache( meta.images );
  15068. const nodes = extractFromCache( meta.nodes );
  15069. if ( textures.length > 0 ) data.textures = textures;
  15070. if ( images.length > 0 ) data.images = images;
  15071. if ( nodes.length > 0 ) data.nodes = nodes;
  15072. }
  15073. return data;
  15074. }
  15075. /**
  15076. * Copies the properties of the given node material to this instance.
  15077. *
  15078. * @param {NodeMaterial} source - The material to copy.
  15079. * @return {NodeMaterial} A reference to this node material.
  15080. */
  15081. copy( source ) {
  15082. this.lightsNode = source.lightsNode;
  15083. this.envNode = source.envNode;
  15084. this.aoNode = source.aoNode;
  15085. this.colorNode = source.colorNode;
  15086. this.normalNode = source.normalNode;
  15087. this.opacityNode = source.opacityNode;
  15088. this.backdropNode = source.backdropNode;
  15089. this.backdropAlphaNode = source.backdropAlphaNode;
  15090. this.alphaTestNode = source.alphaTestNode;
  15091. this.maskNode = source.maskNode;
  15092. this.positionNode = source.positionNode;
  15093. this.geometryNode = source.geometryNode;
  15094. this.depthNode = source.depthNode;
  15095. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  15096. this.castShadowPositionNode = source.castShadowPositionNode;
  15097. this.receivedShadowNode = source.receivedShadowNode;
  15098. this.castShadowNode = source.castShadowNode;
  15099. this.outputNode = source.outputNode;
  15100. this.mrtNode = source.mrtNode;
  15101. this.fragmentNode = source.fragmentNode;
  15102. this.vertexNode = source.vertexNode;
  15103. this.contextNode = source.contextNode;
  15104. return super.copy( source );
  15105. }
  15106. }
  15107. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  15108. /**
  15109. * Node material version of {@link LineBasicMaterial}.
  15110. *
  15111. * @augments NodeMaterial
  15112. */
  15113. class LineBasicNodeMaterial extends NodeMaterial {
  15114. static get type() {
  15115. return 'LineBasicNodeMaterial';
  15116. }
  15117. /**
  15118. * Constructs a new line basic node material.
  15119. *
  15120. * @param {Object} [parameters] - The configuration parameter.
  15121. */
  15122. constructor( parameters ) {
  15123. super();
  15124. /**
  15125. * This flag can be used for type testing.
  15126. *
  15127. * @type {boolean}
  15128. * @readonly
  15129. * @default true
  15130. */
  15131. this.isLineBasicNodeMaterial = true;
  15132. this.setDefaultValues( _defaultValues$d );
  15133. this.setValues( parameters );
  15134. }
  15135. }
  15136. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  15137. /**
  15138. * Node material version of {@link LineDashedMaterial}.
  15139. *
  15140. * @augments NodeMaterial
  15141. */
  15142. class LineDashedNodeMaterial extends NodeMaterial {
  15143. static get type() {
  15144. return 'LineDashedNodeMaterial';
  15145. }
  15146. /**
  15147. * Constructs a new line dashed node material.
  15148. *
  15149. * @param {Object} [parameters] - The configuration parameter.
  15150. */
  15151. constructor( parameters ) {
  15152. super();
  15153. /**
  15154. * This flag can be used for type testing.
  15155. *
  15156. * @type {boolean}
  15157. * @readonly
  15158. * @default true
  15159. */
  15160. this.isLineDashedNodeMaterial = true;
  15161. this.setDefaultValues( _defaultValues$c );
  15162. /**
  15163. * The dash offset.
  15164. *
  15165. * @type {number}
  15166. * @default 0
  15167. */
  15168. this.dashOffset = 0;
  15169. /**
  15170. * The offset of dash materials is by default inferred from the `dashOffset`
  15171. * property. This node property allows to overwrite the default
  15172. * and define the offset with a node instead.
  15173. *
  15174. * If you don't want to overwrite the offset but modify the existing
  15175. * value instead, use {@link materialLineDashOffset}.
  15176. *
  15177. * @type {?Node<float>}
  15178. * @default null
  15179. */
  15180. this.offsetNode = null;
  15181. /**
  15182. * The scale of dash materials is by default inferred from the `scale`
  15183. * property. This node property allows to overwrite the default
  15184. * and define the scale with a node instead.
  15185. *
  15186. * If you don't want to overwrite the scale but modify the existing
  15187. * value instead, use {@link materialLineScale}.
  15188. *
  15189. * @type {?Node<float>}
  15190. * @default null
  15191. */
  15192. this.dashScaleNode = null;
  15193. /**
  15194. * The dash size of dash materials is by default inferred from the `dashSize`
  15195. * property. This node property allows to overwrite the default
  15196. * and define the dash size with a node instead.
  15197. *
  15198. * If you don't want to overwrite the dash size but modify the existing
  15199. * value instead, use {@link materialLineDashSize}.
  15200. *
  15201. * @type {?Node<float>}
  15202. * @default null
  15203. */
  15204. this.dashSizeNode = null;
  15205. /**
  15206. * The gap size of dash materials is by default inferred from the `gapSize`
  15207. * property. This node property allows to overwrite the default
  15208. * and define the gap size with a node instead.
  15209. *
  15210. * If you don't want to overwrite the gap size but modify the existing
  15211. * value instead, use {@link materialLineGapSize}.
  15212. *
  15213. * @type {?Node<float>}
  15214. * @default null
  15215. */
  15216. this.gapSizeNode = null;
  15217. this.setValues( parameters );
  15218. }
  15219. /**
  15220. * Setups the dash specific node variables.
  15221. *
  15222. * @param {NodeBuilder} builder - The current node builder.
  15223. */
  15224. setupVariants( /* builder */ ) {
  15225. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15226. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15227. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15228. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15229. dashSize.assign( dashSizeNode );
  15230. gapSize.assign( gapSizeNode );
  15231. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  15232. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  15233. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  15234. }
  15235. }
  15236. let _sharedFramebuffer = null;
  15237. /**
  15238. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  15239. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  15240. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  15241. *
  15242. * @augments ViewportTextureNode
  15243. */
  15244. class ViewportSharedTextureNode extends ViewportTextureNode {
  15245. static get type() {
  15246. return 'ViewportSharedTextureNode';
  15247. }
  15248. /**
  15249. * Constructs a new viewport shared texture node.
  15250. *
  15251. * @param {Node} [uvNode=screenUV] - The uv node.
  15252. * @param {?Node} [levelNode=null] - The level node.
  15253. */
  15254. constructor( uvNode = screenUV, levelNode = null ) {
  15255. if ( _sharedFramebuffer === null ) {
  15256. _sharedFramebuffer = new FramebufferTexture();
  15257. }
  15258. super( uvNode, levelNode, _sharedFramebuffer );
  15259. }
  15260. /**
  15261. * Overwritten so the method always returns the unique shared
  15262. * framebuffer texture.
  15263. *
  15264. * @return {FramebufferTexture} The shared framebuffer texture.
  15265. */
  15266. getTextureForReference() {
  15267. return _sharedFramebuffer;
  15268. }
  15269. updateReference() {
  15270. return this;
  15271. }
  15272. }
  15273. /**
  15274. * TSL function for creating a shared viewport texture node.
  15275. *
  15276. * @tsl
  15277. * @function
  15278. * @param {?Node} [uvNode=screenUV] - The uv node.
  15279. * @param {?Node} [levelNode=null] - The level node.
  15280. * @returns {ViewportSharedTextureNode}
  15281. */
  15282. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  15283. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  15284. /**
  15285. * This node material can be used to render lines with a size larger than one
  15286. * by representing them as instanced meshes.
  15287. *
  15288. * @augments NodeMaterial
  15289. */
  15290. class Line2NodeMaterial extends NodeMaterial {
  15291. static get type() {
  15292. return 'Line2NodeMaterial';
  15293. }
  15294. /**
  15295. * Constructs a new node material for wide line rendering.
  15296. *
  15297. * @param {Object} [parameters={}] - The configuration parameter.
  15298. */
  15299. constructor( parameters = {} ) {
  15300. super();
  15301. /**
  15302. * This flag can be used for type testing.
  15303. *
  15304. * @type {boolean}
  15305. * @readonly
  15306. * @default true
  15307. */
  15308. this.isLine2NodeMaterial = true;
  15309. this.setDefaultValues( _defaultValues$b );
  15310. /**
  15311. * Whether vertex colors should be used or not.
  15312. *
  15313. * @type {boolean}
  15314. * @default false
  15315. */
  15316. this.useColor = parameters.vertexColors;
  15317. /**
  15318. * The dash offset.
  15319. *
  15320. * @type {number}
  15321. * @default 0
  15322. */
  15323. this.dashOffset = 0;
  15324. /**
  15325. * Defines the lines color.
  15326. *
  15327. * @type {?Node<vec3>}
  15328. * @default null
  15329. */
  15330. this.lineColorNode = null;
  15331. /**
  15332. * Defines the offset.
  15333. *
  15334. * @type {?Node<float>}
  15335. * @default null
  15336. */
  15337. this.offsetNode = null;
  15338. /**
  15339. * Defines the dash scale.
  15340. *
  15341. * @type {?Node<float>}
  15342. * @default null
  15343. */
  15344. this.dashScaleNode = null;
  15345. /**
  15346. * Defines the dash size.
  15347. *
  15348. * @type {?Node<float>}
  15349. * @default null
  15350. */
  15351. this.dashSizeNode = null;
  15352. /**
  15353. * Defines the gap size.
  15354. *
  15355. * @type {?Node<float>}
  15356. * @default null
  15357. */
  15358. this.gapSizeNode = null;
  15359. /**
  15360. * Blending is set to `NoBlending` since transparency
  15361. * is not supported, yet.
  15362. *
  15363. * @type {number}
  15364. * @default 0
  15365. */
  15366. this.blending = NoBlending;
  15367. this._useDash = parameters.dashed;
  15368. this._useAlphaToCoverage = true;
  15369. this._useWorldUnits = false;
  15370. this.setValues( parameters );
  15371. }
  15372. /**
  15373. * Setups the vertex and fragment stage of this node material.
  15374. *
  15375. * @param {NodeBuilder} builder - The current node builder.
  15376. */
  15377. setup( builder ) {
  15378. const { renderer } = builder;
  15379. const useAlphaToCoverage = this._useAlphaToCoverage;
  15380. const useColor = this.useColor;
  15381. const useDash = this._useDash;
  15382. const useWorldUnits = this._useWorldUnits;
  15383. const trimSegment = Fn( ( { start, end } ) => {
  15384. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  15385. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  15386. const nearEstimate = b.mul( -0.5 ).div( a );
  15387. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  15388. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  15389. } ).setLayout( {
  15390. name: 'trimSegment',
  15391. type: 'vec4',
  15392. inputs: [
  15393. { name: 'start', type: 'vec4' },
  15394. { name: 'end', type: 'vec4' }
  15395. ]
  15396. } );
  15397. this.vertexNode = Fn( () => {
  15398. const instanceStart = attribute( 'instanceStart' );
  15399. const instanceEnd = attribute( 'instanceEnd' );
  15400. // camera space
  15401. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  15402. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  15403. if ( useDash ) {
  15404. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15405. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15406. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  15407. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  15408. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  15409. lineDistance = lineDistance.add( offsetNode );
  15410. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  15411. }
  15412. if ( useWorldUnits ) {
  15413. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  15414. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  15415. }
  15416. const aspect = viewport.z.div( viewport.w );
  15417. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  15418. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  15419. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  15420. // perhaps there is a more elegant solution -- WestLangley
  15421. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  15422. If( perspective, () => {
  15423. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  15424. end.assign( trimSegment( { start: start, end: end } ) );
  15425. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  15426. start.assign( trimSegment( { start: end, end: start } ) );
  15427. } );
  15428. } );
  15429. // clip space
  15430. const clipStart = cameraProjectionMatrix.mul( start );
  15431. const clipEnd = cameraProjectionMatrix.mul( end );
  15432. // ndc space
  15433. const ndcStart = clipStart.xyz.div( clipStart.w );
  15434. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  15435. // direction
  15436. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  15437. // account for clip-space aspect ratio
  15438. dir.x.assign( dir.x.mul( aspect ) );
  15439. dir.assign( dir.normalize() );
  15440. const clip = vec4().toVar();
  15441. if ( useWorldUnits ) {
  15442. // get the offset direction as perpendicular to the view vector
  15443. const worldDir = end.xyz.sub( start.xyz ).normalize();
  15444. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  15445. const worldUp = worldDir.cross( tmpFwd ).normalize();
  15446. const worldFwd = worldDir.cross( worldUp );
  15447. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  15448. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  15449. // height offset
  15450. const hw = materialLineWidth.mul( 0.5 );
  15451. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  15452. // don't extend the line if we're rendering dashes because we
  15453. // won't be rendering the endcaps
  15454. if ( ! useDash ) {
  15455. // cap extension
  15456. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  15457. // add width to the box
  15458. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  15459. // endcaps
  15460. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  15461. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  15462. } );
  15463. }
  15464. // project the worldpos
  15465. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  15466. // shift the depth of the projected points so the line
  15467. // segments overlap neatly
  15468. const clipPose = vec3().toVar();
  15469. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  15470. clip.z.assign( clipPose.z.mul( clip.w ) );
  15471. } else {
  15472. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  15473. // undo aspect ratio adjustment
  15474. dir.x.assign( dir.x.div( aspect ) );
  15475. offset.x.assign( offset.x.div( aspect ) );
  15476. // sign flip
  15477. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  15478. // endcaps
  15479. If( positionGeometry.y.lessThan( 0.0 ), () => {
  15480. offset.assign( offset.sub( dir ) );
  15481. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  15482. offset.assign( offset.add( dir ) );
  15483. } );
  15484. // adjust for linewidth
  15485. offset.assign( offset.mul( materialLineWidth ) );
  15486. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  15487. offset.assign( offset.div( viewport.w.div( screenDPR ) ) );
  15488. // select end
  15489. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  15490. // back to clip space
  15491. offset.assign( offset.mul( clip.w ) );
  15492. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  15493. }
  15494. return clip;
  15495. } )();
  15496. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  15497. const p13 = p1.sub( p3 );
  15498. const p43 = p4.sub( p3 );
  15499. const p21 = p2.sub( p1 );
  15500. const d1343 = p13.dot( p43 );
  15501. const d4321 = p43.dot( p21 );
  15502. const d1321 = p13.dot( p21 );
  15503. const d4343 = p43.dot( p43 );
  15504. const d2121 = p21.dot( p21 );
  15505. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  15506. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  15507. const mua = numer.div( denom ).clamp();
  15508. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  15509. return vec2( mua, mub );
  15510. } );
  15511. this.colorNode = Fn( () => {
  15512. const vUv = uv$1();
  15513. if ( useDash ) {
  15514. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15515. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15516. dashSize.assign( dashSizeNode );
  15517. gapSize.assign( gapSizeNode );
  15518. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  15519. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  15520. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  15521. }
  15522. const alpha = float( 1 ).toVar( 'alpha' );
  15523. if ( useWorldUnits ) {
  15524. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  15525. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  15526. // Find the closest points on the view ray and the line segment
  15527. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  15528. const lineDir = worldEnd.sub( worldStart );
  15529. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  15530. const p1 = worldStart.add( lineDir.mul( params.x ) );
  15531. const p2 = rayEnd.mul( params.y );
  15532. const delta = p1.sub( p2 );
  15533. const len = delta.length();
  15534. const norm = len.div( materialLineWidth );
  15535. if ( ! useDash ) {
  15536. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15537. const dnorm = norm.fwidth();
  15538. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  15539. } else {
  15540. norm.greaterThan( 0.5 ).discard();
  15541. }
  15542. }
  15543. } else {
  15544. // round endcaps
  15545. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15546. const a = vUv.x;
  15547. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15548. const len2 = a.mul( a ).add( b.mul( b ) );
  15549. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  15550. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15551. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  15552. } );
  15553. } else {
  15554. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15555. const a = vUv.x;
  15556. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15557. const len2 = a.mul( a ).add( b.mul( b ) );
  15558. len2.greaterThan( 1.0 ).discard();
  15559. } );
  15560. }
  15561. }
  15562. let lineColorNode;
  15563. if ( this.lineColorNode ) {
  15564. lineColorNode = this.lineColorNode;
  15565. } else {
  15566. if ( useColor ) {
  15567. const instanceColorStart = attribute( 'instanceColorStart' );
  15568. const instanceColorEnd = attribute( 'instanceColorEnd' );
  15569. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  15570. lineColorNode = instanceColor.mul( materialColor );
  15571. } else {
  15572. lineColorNode = materialColor;
  15573. }
  15574. }
  15575. return vec4( lineColorNode, alpha );
  15576. } )();
  15577. if ( this.transparent ) {
  15578. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15579. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  15580. }
  15581. super.setup( builder );
  15582. }
  15583. /**
  15584. * Whether the lines should sized in world units or not.
  15585. * When set to `false` the unit is pixel.
  15586. *
  15587. * @type {boolean}
  15588. * @default false
  15589. */
  15590. get worldUnits() {
  15591. return this._useWorldUnits;
  15592. }
  15593. set worldUnits( value ) {
  15594. if ( this._useWorldUnits !== value ) {
  15595. this._useWorldUnits = value;
  15596. this.needsUpdate = true;
  15597. }
  15598. }
  15599. /**
  15600. * Whether the lines should be dashed or not.
  15601. *
  15602. * @type {boolean}
  15603. * @default false
  15604. */
  15605. get dashed() {
  15606. return this._useDash;
  15607. }
  15608. set dashed( value ) {
  15609. if ( this._useDash !== value ) {
  15610. this._useDash = value;
  15611. this.needsUpdate = true;
  15612. }
  15613. }
  15614. /**
  15615. * Whether alpha to coverage should be used or not.
  15616. *
  15617. * @type {boolean}
  15618. * @default true
  15619. */
  15620. get alphaToCoverage() {
  15621. return this._useAlphaToCoverage;
  15622. }
  15623. set alphaToCoverage( value ) {
  15624. if ( this._useAlphaToCoverage !== value ) {
  15625. this._useAlphaToCoverage = value;
  15626. this.needsUpdate = true;
  15627. }
  15628. }
  15629. }
  15630. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  15631. /**
  15632. * Node material version of {@link MeshNormalMaterial}.
  15633. *
  15634. * @augments NodeMaterial
  15635. */
  15636. class MeshNormalNodeMaterial extends NodeMaterial {
  15637. static get type() {
  15638. return 'MeshNormalNodeMaterial';
  15639. }
  15640. /**
  15641. * Constructs a new mesh normal node material.
  15642. *
  15643. * @param {Object} [parameters] - The configuration parameter.
  15644. */
  15645. constructor( parameters ) {
  15646. super();
  15647. /**
  15648. * This flag can be used for type testing.
  15649. *
  15650. * @type {boolean}
  15651. * @readonly
  15652. * @default true
  15653. */
  15654. this.isMeshNormalNodeMaterial = true;
  15655. this.setDefaultValues( _defaultValues$a );
  15656. this.setValues( parameters );
  15657. }
  15658. /**
  15659. * Overwrites the default implementation by computing the diffuse color
  15660. * based on the normal data.
  15661. */
  15662. setupDiffuseColor() {
  15663. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15664. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  15665. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( normalView ), opacityNode ), SRGBColorSpace ) );
  15666. }
  15667. }
  15668. /**
  15669. * TSL function for creating an equirect uv node.
  15670. *
  15671. * Can be used to compute texture coordinates for projecting an
  15672. * equirectangular texture onto a mesh for using it as the scene's
  15673. * background.
  15674. *
  15675. * ```js
  15676. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  15677. * ```
  15678. *
  15679. * @tsl
  15680. * @function
  15681. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  15682. * @returns {Node<vec2>}
  15683. */
  15684. const equirectUV = /*@__PURE__*/ Fn( ( [ dir = positionWorldDirection ] ) => {
  15685. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  15686. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  15687. return vec2( u, v );
  15688. } );
  15689. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  15690. /**
  15691. * This class represents a cube render target. It is a special version
  15692. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  15693. *
  15694. * @augments WebGLCubeRenderTarget
  15695. */
  15696. class CubeRenderTarget extends WebGLCubeRenderTarget {
  15697. /**
  15698. * Constructs a new cube render target.
  15699. *
  15700. * @param {number} [size=1] - The size of the render target.
  15701. * @param {RenderTarget~Options} [options] - The configuration object.
  15702. */
  15703. constructor( size = 1, options = {} ) {
  15704. super( size, options );
  15705. /**
  15706. * This flag can be used for type testing.
  15707. *
  15708. * @type {boolean}
  15709. * @readonly
  15710. * @default true
  15711. */
  15712. this.isCubeRenderTarget = true;
  15713. }
  15714. /**
  15715. * Converts the given equirectangular texture to a cube map.
  15716. *
  15717. * @param {Renderer} renderer - The renderer.
  15718. * @param {Texture} texture - The equirectangular texture.
  15719. * @return {CubeRenderTarget} A reference to this cube render target.
  15720. */
  15721. fromEquirectangularTexture( renderer, texture$1 ) {
  15722. const currentMinFilter = texture$1.minFilter;
  15723. const currentGenerateMipmaps = texture$1.generateMipmaps;
  15724. texture$1.generateMipmaps = true;
  15725. this.texture.type = texture$1.type;
  15726. this.texture.colorSpace = texture$1.colorSpace;
  15727. this.texture.generateMipmaps = texture$1.generateMipmaps;
  15728. this.texture.minFilter = texture$1.minFilter;
  15729. this.texture.magFilter = texture$1.magFilter;
  15730. const geometry = new BoxGeometry( 5, 5, 5 );
  15731. const uvNode = equirectUV( positionWorldDirection );
  15732. const material = new NodeMaterial();
  15733. material.colorNode = texture( texture$1, uvNode, 0 );
  15734. material.side = BackSide;
  15735. material.blending = NoBlending;
  15736. const mesh = new Mesh( geometry, material );
  15737. const scene = new Scene();
  15738. scene.add( mesh );
  15739. // Avoid blurred poles
  15740. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  15741. const camera = new CubeCamera( 1, 10, this );
  15742. const currentMRT = renderer.getMRT();
  15743. renderer.setMRT( null );
  15744. camera.update( renderer, scene );
  15745. renderer.setMRT( currentMRT );
  15746. texture$1.minFilter = currentMinFilter;
  15747. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  15748. mesh.geometry.dispose();
  15749. mesh.material.dispose();
  15750. return this;
  15751. }
  15752. }
  15753. const _cache$1 = new WeakMap();
  15754. /**
  15755. * This node can be used to automatically convert environment maps in the
  15756. * equirectangular format into the cube map format.
  15757. *
  15758. * @augments TempNode
  15759. */
  15760. class CubeMapNode extends TempNode {
  15761. static get type() {
  15762. return 'CubeMapNode';
  15763. }
  15764. /**
  15765. * Constructs a new cube map node.
  15766. *
  15767. * @param {Node} envNode - The node representing the environment map.
  15768. */
  15769. constructor( envNode ) {
  15770. super( 'vec3' );
  15771. /**
  15772. * The node representing the environment map.
  15773. *
  15774. * @type {Node}
  15775. */
  15776. this.envNode = envNode;
  15777. /**
  15778. * A reference to the internal cube texture.
  15779. *
  15780. * @private
  15781. * @type {?CubeTexture}
  15782. * @default null
  15783. */
  15784. this._cubeTexture = null;
  15785. /**
  15786. * A reference to the internal cube texture node.
  15787. *
  15788. * @private
  15789. * @type {CubeTextureNode}
  15790. */
  15791. this._cubeTextureNode = cubeTexture( null );
  15792. const defaultTexture = new CubeTexture();
  15793. defaultTexture.isRenderTargetTexture = true;
  15794. /**
  15795. * A default cube texture that acts as a placeholder.
  15796. * It is used when the conversion from equirectangular to cube
  15797. * map has not finished yet for a given texture.
  15798. *
  15799. * @private
  15800. * @type {CubeTexture}
  15801. */
  15802. this._defaultTexture = defaultTexture;
  15803. /**
  15804. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  15805. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  15806. *
  15807. * @type {string}
  15808. * @default 'render'
  15809. */
  15810. this.updateBeforeType = NodeUpdateType.RENDER;
  15811. }
  15812. updateBefore( frame ) {
  15813. const { renderer, material } = frame;
  15814. const envNode = this.envNode;
  15815. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  15816. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  15817. if ( texture && texture.isTexture ) {
  15818. const mapping = texture.mapping;
  15819. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  15820. // check for converted cubemap map
  15821. if ( _cache$1.has( texture ) ) {
  15822. const cubeMap = _cache$1.get( texture );
  15823. mapTextureMapping( cubeMap, texture.mapping );
  15824. this._cubeTexture = cubeMap;
  15825. } else {
  15826. // create cube map from equirectangular map
  15827. const image = texture.image;
  15828. if ( isEquirectangularMapReady$1( image ) ) {
  15829. const renderTarget = new CubeRenderTarget( image.height );
  15830. renderTarget.fromEquirectangularTexture( renderer, texture );
  15831. mapTextureMapping( renderTarget.texture, texture.mapping );
  15832. this._cubeTexture = renderTarget.texture;
  15833. _cache$1.set( texture, renderTarget.texture );
  15834. texture.addEventListener( 'dispose', onTextureDispose );
  15835. } else {
  15836. // default cube texture as fallback when equirectangular texture is not yet loaded
  15837. this._cubeTexture = this._defaultTexture;
  15838. }
  15839. }
  15840. //
  15841. this._cubeTextureNode.value = this._cubeTexture;
  15842. } else {
  15843. // envNode already refers to a cube map
  15844. this._cubeTextureNode = this.envNode;
  15845. }
  15846. }
  15847. }
  15848. }
  15849. setup( builder ) {
  15850. this.updateBefore( builder );
  15851. return this._cubeTextureNode;
  15852. }
  15853. }
  15854. /**
  15855. * Returns true if the given equirectangular image has been fully loaded
  15856. * and is ready for further processing.
  15857. *
  15858. * @private
  15859. * @param {Image} image - The equirectangular image to check.
  15860. * @return {boolean} Whether the image is ready or not.
  15861. */
  15862. function isEquirectangularMapReady$1( image ) {
  15863. if ( image === null || image === undefined ) return false;
  15864. return image.height > 0;
  15865. }
  15866. /**
  15867. * This function is executed when `dispose()` is called on the equirectangular
  15868. * texture. In this case, the generated cube map with its render target
  15869. * is deleted as well.
  15870. *
  15871. * @private
  15872. * @param {Object} event - The event object.
  15873. */
  15874. function onTextureDispose( event ) {
  15875. const texture = event.target;
  15876. texture.removeEventListener( 'dispose', onTextureDispose );
  15877. const renderTarget = _cache$1.get( texture );
  15878. if ( renderTarget !== undefined ) {
  15879. _cache$1.delete( texture );
  15880. renderTarget.dispose();
  15881. }
  15882. }
  15883. /**
  15884. * This function makes sure the generated cube map uses the correct
  15885. * texture mapping that corresponds to the equirectangular original.
  15886. *
  15887. * @private
  15888. * @param {Texture} texture - The cube texture.
  15889. * @param {number} mapping - The original texture mapping.
  15890. */
  15891. function mapTextureMapping( texture, mapping ) {
  15892. if ( mapping === EquirectangularReflectionMapping ) {
  15893. texture.mapping = CubeReflectionMapping;
  15894. } else if ( mapping === EquirectangularRefractionMapping ) {
  15895. texture.mapping = CubeRefractionMapping;
  15896. }
  15897. }
  15898. /**
  15899. * TSL function for creating a cube map node.
  15900. *
  15901. * @tsl
  15902. * @function
  15903. * @param {Node} envNode - The node representing the environment map.
  15904. * @returns {CubeMapNode}
  15905. */
  15906. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  15907. /**
  15908. * Represents a basic model for Image-based lighting (IBL). The environment
  15909. * is defined via environment maps in the equirectangular or cube map format.
  15910. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  15911. * or {@link MeshPhongNodeMaterial}.
  15912. *
  15913. * @augments LightingNode
  15914. */
  15915. class BasicEnvironmentNode extends LightingNode {
  15916. static get type() {
  15917. return 'BasicEnvironmentNode';
  15918. }
  15919. /**
  15920. * Constructs a new basic environment node.
  15921. *
  15922. * @param {Node} [envNode=null] - A node representing the environment.
  15923. */
  15924. constructor( envNode = null ) {
  15925. super();
  15926. /**
  15927. * A node representing the environment.
  15928. *
  15929. * @type {Node}
  15930. * @default null
  15931. */
  15932. this.envNode = envNode;
  15933. }
  15934. setup( builder ) {
  15935. // environment property is used in the finish() method of BasicLightingModel
  15936. builder.context.environment = cubeMapNode( this.envNode );
  15937. }
  15938. }
  15939. /**
  15940. * A specific version of {@link IrradianceNode} that is only relevant
  15941. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  15942. * requires a special scaling factor for the light map.
  15943. *
  15944. * @augments LightingNode
  15945. */
  15946. class BasicLightMapNode extends LightingNode {
  15947. static get type() {
  15948. return 'BasicLightMapNode';
  15949. }
  15950. /**
  15951. * Constructs a new basic light map node.
  15952. *
  15953. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  15954. */
  15955. constructor( lightMapNode = null ) {
  15956. super();
  15957. /**
  15958. * The light map node.
  15959. *
  15960. * @type {?Node<vec3>}
  15961. */
  15962. this.lightMapNode = lightMapNode;
  15963. }
  15964. setup( builder ) {
  15965. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  15966. const RECIPROCAL_PI = float( 1 / Math.PI );
  15967. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  15968. }
  15969. }
  15970. /**
  15971. * Abstract class for implementing lighting models. The module defines
  15972. * multiple methods that concrete lighting models can implement. These
  15973. * methods are executed at different points during the light evaluation
  15974. * process.
  15975. */
  15976. class LightingModel {
  15977. /**
  15978. * This method is intended for setting up lighting model and context data
  15979. * which are later used in the evaluation process.
  15980. *
  15981. * @abstract
  15982. * @param {NodeBuilder} builder - The current node builder.
  15983. */
  15984. start( builder ) {
  15985. // lights ( direct )
  15986. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  15987. // indirect
  15988. this.indirect( builder );
  15989. }
  15990. /**
  15991. * This method is intended for executing final tasks like final updates
  15992. * to the outgoing light.
  15993. *
  15994. * @abstract
  15995. * @param {NodeBuilder} builder - The current node builder.
  15996. */
  15997. finish( /*builder*/ ) { }
  15998. /**
  15999. * This method is intended for implementing the direct light term and
  16000. * executed during the build process of directional, point and spot light nodes.
  16001. *
  16002. * @abstract
  16003. * @param {Object} lightData - The light data.
  16004. * @param {NodeBuilder} builder - The current node builder.
  16005. */
  16006. direct( /*lightData, builder*/ ) { }
  16007. /**
  16008. * This method is intended for implementing the direct light term for
  16009. * rect area light nodes.
  16010. *
  16011. * @abstract
  16012. * @param {Object} lightData - The light data.
  16013. * @param {NodeBuilder} builder - The current node builder.
  16014. */
  16015. directRectArea( /*lightData, builder*/ ) {}
  16016. /**
  16017. * This method is intended for implementing the indirect light term.
  16018. *
  16019. * @abstract
  16020. * @param {NodeBuilder} builder - The current node builder.
  16021. */
  16022. indirect( /*builder*/ ) { }
  16023. /**
  16024. * This method is intended for implementing the ambient occlusion term.
  16025. * Unlike other methods, this method must be called manually by the lighting
  16026. * model in its indirect term.
  16027. *
  16028. * @abstract
  16029. * @param {NodeBuilder} builder - The current node builder.
  16030. */
  16031. ambientOcclusion( /*input, stack, builder*/ ) { }
  16032. }
  16033. /**
  16034. * Represents the lighting model for unlit materials. The only light contribution
  16035. * is baked indirect lighting modulated with ambient occlusion and the material's
  16036. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  16037. *
  16038. * @augments LightingModel
  16039. */
  16040. class BasicLightingModel extends LightingModel {
  16041. /**
  16042. * Constructs a new basic lighting model.
  16043. */
  16044. constructor() {
  16045. super();
  16046. }
  16047. /**
  16048. * Implements the baked indirect lighting with its modulation.
  16049. *
  16050. * @param {NodeBuilder} builder - The current node builder.
  16051. */
  16052. indirect( { context } ) {
  16053. const ambientOcclusion = context.ambientOcclusion;
  16054. const reflectedLight = context.reflectedLight;
  16055. const irradianceLightMap = context.irradianceLightMap;
  16056. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  16057. // accumulation (baked indirect lighting only)
  16058. if ( irradianceLightMap ) {
  16059. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  16060. } else {
  16061. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  16062. }
  16063. // modulation
  16064. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16065. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  16066. }
  16067. /**
  16068. * Implements the environment mapping.
  16069. *
  16070. * @param {NodeBuilder} builder - The current node builder.
  16071. */
  16072. finish( builder ) {
  16073. const { material, context } = builder;
  16074. const outgoingLight = context.outgoingLight;
  16075. const envNode = builder.context.environment;
  16076. if ( envNode ) {
  16077. switch ( material.combine ) {
  16078. case MultiplyOperation:
  16079. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  16080. break;
  16081. case MixOperation:
  16082. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  16083. break;
  16084. case AddOperation:
  16085. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  16086. break;
  16087. default:
  16088. warn( 'BasicLightingModel: Unsupported .combine value:', material.combine );
  16089. break;
  16090. }
  16091. }
  16092. }
  16093. }
  16094. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  16095. /**
  16096. * Node material version of {@link MeshBasicMaterial}.
  16097. *
  16098. * @augments NodeMaterial
  16099. */
  16100. class MeshBasicNodeMaterial extends NodeMaterial {
  16101. static get type() {
  16102. return 'MeshBasicNodeMaterial';
  16103. }
  16104. /**
  16105. * Constructs a new mesh basic node material.
  16106. *
  16107. * @param {Object} [parameters] - The configuration parameter.
  16108. */
  16109. constructor( parameters ) {
  16110. super();
  16111. /**
  16112. * This flag can be used for type testing.
  16113. *
  16114. * @type {boolean}
  16115. * @readonly
  16116. * @default true
  16117. */
  16118. this.isMeshBasicNodeMaterial = true;
  16119. /**
  16120. * Although the basic material is by definition unlit, we set
  16121. * this property to `true` since we use a lighting model to compute
  16122. * the outgoing light of the fragment shader.
  16123. *
  16124. * @type {boolean}
  16125. * @default true
  16126. */
  16127. this.lights = true;
  16128. this.setDefaultValues( _defaultValues$9 );
  16129. this.setValues( parameters );
  16130. }
  16131. /**
  16132. * Basic materials are not affected by normal and bump maps so we
  16133. * return by default {@link normalViewGeometry}.
  16134. *
  16135. * @return {Node<vec3>} The normal node.
  16136. */
  16137. setupNormal() {
  16138. return directionToFaceDirection( normalViewGeometry ); // see #28839
  16139. }
  16140. /**
  16141. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16142. * to implement the default environment mapping.
  16143. *
  16144. * @param {NodeBuilder} builder - The current node builder.
  16145. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16146. */
  16147. setupEnvironment( builder ) {
  16148. const envNode = super.setupEnvironment( builder );
  16149. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16150. }
  16151. /**
  16152. * This method must be overwritten since light maps are evaluated
  16153. * with a special scaling factor for basic materials.
  16154. *
  16155. * @param {NodeBuilder} builder - The current node builder.
  16156. * @return {?BasicLightMapNode<vec3>} The light map node.
  16157. */
  16158. setupLightMap( builder ) {
  16159. let node = null;
  16160. if ( builder.material.lightMap ) {
  16161. node = new BasicLightMapNode( materialLightMap );
  16162. }
  16163. return node;
  16164. }
  16165. /**
  16166. * The material overwrites this method because `lights` is set to `true` but
  16167. * we still want to return the diffuse color as the outgoing light.
  16168. *
  16169. * @return {Node<vec3>} The outgoing light node.
  16170. */
  16171. setupOutgoingLight() {
  16172. return diffuseColor.rgb;
  16173. }
  16174. /**
  16175. * Setups the lighting model.
  16176. *
  16177. * @return {BasicLightingModel} The lighting model.
  16178. */
  16179. setupLightingModel() {
  16180. return new BasicLightingModel();
  16181. }
  16182. }
  16183. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  16184. // Original approximation by Christophe Schlick '94
  16185. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  16186. // Optimized variant (presented by Epic at SIGGRAPH '13)
  16187. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  16188. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  16189. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  16190. } ); // validated
  16191. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  16192. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  16193. } ); // validated
  16194. const G_BlinnPhong_Implicit = () => float( 0.25 );
  16195. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  16196. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  16197. } );
  16198. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16199. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16200. const dotNH = normalView.dot( halfDir ).clamp();
  16201. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16202. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  16203. const G = G_BlinnPhong_Implicit();
  16204. const D = D_BlinnPhong( { dotNH } );
  16205. return F.mul( G ).mul( D );
  16206. } );
  16207. /**
  16208. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  16209. *
  16210. * @augments BasicLightingModel
  16211. */
  16212. class PhongLightingModel extends BasicLightingModel {
  16213. /**
  16214. * Constructs a new phong lighting model.
  16215. *
  16216. * @param {boolean} [specular=true] - Whether specular is supported or not.
  16217. */
  16218. constructor( specular = true ) {
  16219. super();
  16220. /**
  16221. * Whether specular is supported or not. Set this to `false` if you are
  16222. * looking for a Lambert-like material meaning a material for non-shiny
  16223. * surfaces, without specular highlights.
  16224. *
  16225. * @type {boolean}
  16226. * @default true
  16227. */
  16228. this.specular = specular;
  16229. }
  16230. /**
  16231. * Implements the direct lighting. The specular portion is optional an can be controlled
  16232. * with the {@link PhongLightingModel#specular} flag.
  16233. *
  16234. * @param {Object} lightData - The light data.
  16235. */
  16236. direct( { lightDirection, lightColor, reflectedLight } ) {
  16237. const dotNL = normalView.dot( lightDirection ).clamp();
  16238. const irradiance = dotNL.mul( lightColor );
  16239. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  16240. if ( this.specular === true ) {
  16241. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  16242. }
  16243. }
  16244. /**
  16245. * Implements the indirect lighting.
  16246. *
  16247. * @param {NodeBuilder} builder - The current node builder.
  16248. */
  16249. indirect( builder ) {
  16250. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  16251. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16252. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16253. }
  16254. }
  16255. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  16256. /**
  16257. * Node material version of {@link MeshLambertMaterial}.
  16258. *
  16259. * @augments NodeMaterial
  16260. */
  16261. class MeshLambertNodeMaterial extends NodeMaterial {
  16262. static get type() {
  16263. return 'MeshLambertNodeMaterial';
  16264. }
  16265. /**
  16266. * Constructs a new mesh lambert node material.
  16267. *
  16268. * @param {Object} [parameters] - The configuration parameter.
  16269. */
  16270. constructor( parameters ) {
  16271. super();
  16272. /**
  16273. * This flag can be used for type testing.
  16274. *
  16275. * @type {boolean}
  16276. * @readonly
  16277. * @default true
  16278. */
  16279. this.isMeshLambertNodeMaterial = true;
  16280. /**
  16281. * Set to `true` because lambert materials react on lights.
  16282. *
  16283. * @type {boolean}
  16284. * @default true
  16285. */
  16286. this.lights = true;
  16287. this.setDefaultValues( _defaultValues$8 );
  16288. this.setValues( parameters );
  16289. }
  16290. /**
  16291. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16292. * to implement the default environment mapping.
  16293. *
  16294. * @param {NodeBuilder} builder - The current node builder.
  16295. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16296. */
  16297. setupEnvironment( builder ) {
  16298. const envNode = super.setupEnvironment( builder );
  16299. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16300. }
  16301. /**
  16302. * Setups the lighting model.
  16303. *
  16304. * @return {PhongLightingModel} The lighting model.
  16305. */
  16306. setupLightingModel( /*builder*/ ) {
  16307. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  16308. }
  16309. }
  16310. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  16311. /**
  16312. * Node material version of {@link MeshPhongMaterial}.
  16313. *
  16314. * @augments NodeMaterial
  16315. */
  16316. class MeshPhongNodeMaterial extends NodeMaterial {
  16317. static get type() {
  16318. return 'MeshPhongNodeMaterial';
  16319. }
  16320. /**
  16321. * Constructs a new mesh lambert node material.
  16322. *
  16323. * @param {Object} [parameters] - The configuration parameter.
  16324. */
  16325. constructor( parameters ) {
  16326. super();
  16327. /**
  16328. * This flag can be used for type testing.
  16329. *
  16330. * @type {boolean}
  16331. * @readonly
  16332. * @default true
  16333. */
  16334. this.isMeshPhongNodeMaterial = true;
  16335. /**
  16336. * Set to `true` because phong materials react on lights.
  16337. *
  16338. * @type {boolean}
  16339. * @default true
  16340. */
  16341. this.lights = true;
  16342. /**
  16343. * The shininess of phong materials is by default inferred from the `shininess`
  16344. * property. This node property allows to overwrite the default
  16345. * and define the shininess with a node instead.
  16346. *
  16347. * If you don't want to overwrite the shininess but modify the existing
  16348. * value instead, use {@link materialShininess}.
  16349. *
  16350. * @type {?Node<float>}
  16351. * @default null
  16352. */
  16353. this.shininessNode = null;
  16354. /**
  16355. * The specular color of phong materials is by default inferred from the
  16356. * `specular` property. This node property allows to overwrite the default
  16357. * and define the specular color with a node instead.
  16358. *
  16359. * If you don't want to overwrite the specular color but modify the existing
  16360. * value instead, use {@link materialSpecular}.
  16361. *
  16362. * @type {?Node<vec3>}
  16363. * @default null
  16364. */
  16365. this.specularNode = null;
  16366. this.setDefaultValues( _defaultValues$7 );
  16367. this.setValues( parameters );
  16368. }
  16369. /**
  16370. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16371. * to implement the default environment mapping.
  16372. *
  16373. * @param {NodeBuilder} builder - The current node builder.
  16374. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16375. */
  16376. setupEnvironment( builder ) {
  16377. const envNode = super.setupEnvironment( builder );
  16378. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16379. }
  16380. /**
  16381. * Setups the lighting model.
  16382. *
  16383. * @return {PhongLightingModel} The lighting model.
  16384. */
  16385. setupLightingModel( /*builder*/ ) {
  16386. return new PhongLightingModel();
  16387. }
  16388. /**
  16389. * Setups the phong specific node variables.
  16390. *
  16391. * @param {NodeBuilder} builder - The current node builder.
  16392. */
  16393. setupVariants( /*builder*/ ) {
  16394. // SHININESS
  16395. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16396. shininess.assign( shininessNode );
  16397. // SPECULAR COLOR
  16398. const specularNode = this.specularNode || materialSpecular;
  16399. specularColor.assign( specularNode );
  16400. }
  16401. copy( source ) {
  16402. this.shininessNode = source.shininessNode;
  16403. this.specularNode = source.specularNode;
  16404. return super.copy( source );
  16405. }
  16406. }
  16407. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  16408. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  16409. return float( 0 );
  16410. }
  16411. const dxy = normalViewGeometry.dFdx().abs().max( normalViewGeometry.dFdy().abs() );
  16412. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  16413. return geometryRoughness;
  16414. } );
  16415. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  16416. const { roughness } = inputs;
  16417. const geometryRoughness = getGeometryRoughness();
  16418. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  16419. roughnessFactor = roughnessFactor.add( geometryRoughness );
  16420. roughnessFactor = roughnessFactor.min( 1.0 );
  16421. return roughnessFactor;
  16422. } );
  16423. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  16424. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  16425. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  16426. const a2 = alpha.pow2();
  16427. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  16428. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  16429. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  16430. } ).setLayout( {
  16431. name: 'V_GGX_SmithCorrelated',
  16432. type: 'float',
  16433. inputs: [
  16434. { name: 'alpha', type: 'float' },
  16435. { name: 'dotNL', type: 'float' },
  16436. { name: 'dotNV', type: 'float' }
  16437. ]
  16438. } ); // validated
  16439. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16440. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  16441. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  16442. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  16443. const v = div( 0.5, gv.add( gl ) );
  16444. return v;
  16445. } ).setLayout( {
  16446. name: 'V_GGX_SmithCorrelated_Anisotropic',
  16447. type: 'float',
  16448. inputs: [
  16449. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16450. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16451. { name: 'dotTV', type: 'float', qualifier: 'in' },
  16452. { name: 'dotBV', type: 'float', qualifier: 'in' },
  16453. { name: 'dotTL', type: 'float', qualifier: 'in' },
  16454. { name: 'dotBL', type: 'float', qualifier: 'in' },
  16455. { name: 'dotNV', type: 'float', qualifier: 'in' },
  16456. { name: 'dotNL', type: 'float', qualifier: 'in' }
  16457. ]
  16458. } );
  16459. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  16460. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  16461. // alpha is "roughness squared" in Disney’s reparameterization
  16462. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  16463. const a2 = alpha.pow2();
  16464. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  16465. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  16466. } ).setLayout( {
  16467. name: 'D_GGX',
  16468. type: 'float',
  16469. inputs: [
  16470. { name: 'alpha', type: 'float' },
  16471. { name: 'dotNH', type: 'float' }
  16472. ]
  16473. } ); // validated
  16474. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  16475. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16476. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  16477. const a2 = alphaT.mul( alphaB );
  16478. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  16479. const v2 = v.dot( v );
  16480. const w2 = a2.div( v2 );
  16481. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  16482. } ).setLayout( {
  16483. name: 'D_GGX_Anisotropic',
  16484. type: 'float',
  16485. inputs: [
  16486. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16487. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16488. { name: 'dotNH', type: 'float', qualifier: 'in' },
  16489. { name: 'dotTH', type: 'float', qualifier: 'in' },
  16490. { name: 'dotBH', type: 'float', qualifier: 'in' }
  16491. ]
  16492. } );
  16493. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  16494. const BRDF_GGX = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness, f, normalView: normalView$1 = normalView, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16495. const alpha = roughness.pow2(); // UE4's roughness
  16496. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16497. const dotNL = normalView$1.dot( lightDirection ).clamp();
  16498. const dotNV = normalView$1.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16499. const dotNH = normalView$1.dot( halfDir ).clamp();
  16500. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16501. let F = F_Schlick( { f0, f90, dotVH } );
  16502. let V, D;
  16503. if ( defined( USE_IRIDESCENCE ) ) {
  16504. F = iridescence.mix( F, f );
  16505. }
  16506. if ( defined( USE_ANISOTROPY ) ) {
  16507. const dotTL = anisotropyT.dot( lightDirection );
  16508. const dotTV = anisotropyT.dot( positionViewDirection );
  16509. const dotTH = anisotropyT.dot( halfDir );
  16510. const dotBL = anisotropyB.dot( lightDirection );
  16511. const dotBV = anisotropyB.dot( positionViewDirection );
  16512. const dotBH = anisotropyB.dot( halfDir );
  16513. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  16514. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  16515. } else {
  16516. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  16517. D = D_GGX( { alpha, dotNH } );
  16518. }
  16519. return F.mul( V ).mul( D );
  16520. } ); // validated
  16521. /**
  16522. * Precomputed DFG LUT for Image-Based Lighting
  16523. * Resolution: 16x16
  16524. * Samples: 4096 per texel
  16525. * Format: RG16F (2 half floats per texel: scale, bias)
  16526. */
  16527. const DATA = new Uint16Array( [
  16528. 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,
  16529. 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,
  16530. 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,
  16531. 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,
  16532. 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,
  16533. 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,
  16534. 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,
  16535. 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,
  16536. 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,
  16537. 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,
  16538. 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,
  16539. 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,
  16540. 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,
  16541. 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,
  16542. 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,
  16543. 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
  16544. ] );
  16545. let lut = null;
  16546. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  16547. if ( lut === null ) {
  16548. lut = new DataTexture( DATA, 16, 16, RGFormat, HalfFloatType );
  16549. lut.name = 'DFG_LUT';
  16550. lut.minFilter = LinearFilter;
  16551. lut.magFilter = LinearFilter;
  16552. lut.wrapS = ClampToEdgeWrapping;
  16553. lut.wrapT = ClampToEdgeWrapping;
  16554. lut.generateMipmaps = false;
  16555. lut.needsUpdate = true;
  16556. }
  16557. const uv = vec2( roughness, dotNV );
  16558. return texture( lut, uv ).rg;
  16559. } );
  16560. // GGX BRDF with multi-scattering energy compensation for direct lighting
  16561. // This provides more accurate energy conservation, especially for rough materials
  16562. // Based on "Practical Multiple Scattering Compensation for Microfacet Models"
  16563. // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf
  16564. const BRDF_GGX_Multiscatter = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness: _roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16565. // Single-scattering BRDF (standard GGX)
  16566. const singleScatter = BRDF_GGX( { lightDirection, f0, f90, roughness: _roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } );
  16567. // Multi-scattering compensation
  16568. const dotNL = normalView.dot( lightDirection ).clamp();
  16569. const dotNV = normalView.dot( positionViewDirection ).clamp();
  16570. // Precomputed DFG values for view and light directions
  16571. const dfgV = DFGApprox( { roughness: _roughness, dotNV } );
  16572. const dfgL = DFGApprox( { roughness: _roughness, dotNV: dotNL } );
  16573. // Single-scattering energy for view and light
  16574. const FssEss_V = f0.mul( dfgV.x ).add( f90.mul( dfgV.y ) );
  16575. const FssEss_L = f0.mul( dfgL.x ).add( f90.mul( dfgL.y ) );
  16576. const Ess_V = dfgV.x.add( dfgV.y );
  16577. const Ess_L = dfgL.x.add( dfgL.y );
  16578. // Energy lost to multiple scattering
  16579. const Ems_V = float( 1.0 ).sub( Ess_V );
  16580. const Ems_L = float( 1.0 ).sub( Ess_L );
  16581. // Average Fresnel reflectance
  16582. const Favg = f0.add( f0.oneMinus().mul( 0.047619 ) ); // 1/21
  16583. // Multiple scattering contribution
  16584. // Uses geometric mean of view and light contributions for better energy distribution
  16585. 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 ) );
  16586. // Energy compensation factor
  16587. const compensationFactor = Ems_V.mul( Ems_L );
  16588. const multiScatter = Fms.mul( compensationFactor );
  16589. return singleScatter.add( multiScatter );
  16590. } );
  16591. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  16592. const { dotNV, specularColor, specularF90, roughness } = inputs;
  16593. const fab = DFGApprox( { dotNV, roughness } );
  16594. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16595. } );
  16596. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  16597. const x = dotVH.oneMinus().saturate();
  16598. const x2 = x.mul( x );
  16599. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  16600. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  16601. } ).setLayout( {
  16602. name: 'Schlick_to_F0',
  16603. type: 'vec3',
  16604. inputs: [
  16605. { name: 'f', type: 'vec3' },
  16606. { name: 'f90', type: 'float' },
  16607. { name: 'dotVH', type: 'float' }
  16608. ]
  16609. } );
  16610. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16611. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  16612. const alpha = roughness.pow2();
  16613. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  16614. const invAlpha = float( 1.0 ).div( alpha );
  16615. const cos2h = dotNH.pow2();
  16616. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  16617. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  16618. } ).setLayout( {
  16619. name: 'D_Charlie',
  16620. type: 'float',
  16621. inputs: [
  16622. { name: 'roughness', type: 'float' },
  16623. { name: 'dotNH', type: 'float' }
  16624. ]
  16625. } );
  16626. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16627. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  16628. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  16629. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  16630. } ).setLayout( {
  16631. name: 'V_Neubelt',
  16632. type: 'float',
  16633. inputs: [
  16634. { name: 'dotNV', type: 'float' },
  16635. { name: 'dotNL', type: 'float' }
  16636. ]
  16637. } );
  16638. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16639. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16640. const dotNL = normalView.dot( lightDirection ).clamp();
  16641. const dotNV = normalView.dot( positionViewDirection ).clamp();
  16642. const dotNH = normalView.dot( halfDir ).clamp();
  16643. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  16644. const V = V_Neubelt( { dotNV, dotNL } );
  16645. return sheen.mul( D ).mul( V );
  16646. } );
  16647. // Rect Area Light
  16648. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  16649. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  16650. // code: https://github.com/selfshadow/ltc_code/
  16651. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  16652. const LUT_SIZE = 64.0;
  16653. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  16654. const LUT_BIAS = 0.5 / LUT_SIZE;
  16655. const dotNV = N.dot( V ).saturate();
  16656. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  16657. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  16658. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  16659. return uv;
  16660. } ).setLayout( {
  16661. name: 'LTC_Uv',
  16662. type: 'vec2',
  16663. inputs: [
  16664. { name: 'N', type: 'vec3' },
  16665. { name: 'V', type: 'vec3' },
  16666. { name: 'roughness', type: 'float' }
  16667. ]
  16668. } );
  16669. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  16670. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  16671. // An approximation of the form factor of a horizon-clipped rectangle.
  16672. const l = f.length();
  16673. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  16674. } ).setLayout( {
  16675. name: 'LTC_ClippedSphereFormFactor',
  16676. type: 'float',
  16677. inputs: [
  16678. { name: 'f', type: 'vec3' }
  16679. ]
  16680. } );
  16681. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  16682. const x = v1.dot( v2 );
  16683. const y = x.abs().toVar();
  16684. // rational polynomial approximation to theta / sin( theta ) / 2PI
  16685. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  16686. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  16687. const v = a.div( b );
  16688. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  16689. return v1.cross( v2 ).mul( theta_sintheta );
  16690. } ).setLayout( {
  16691. name: 'LTC_EdgeVectorFormFactor',
  16692. type: 'vec3',
  16693. inputs: [
  16694. { name: 'v1', type: 'vec3' },
  16695. { name: 'v2', type: 'vec3' }
  16696. ]
  16697. } );
  16698. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  16699. // bail if point is on back side of plane of light
  16700. // assumes ccw winding order of light vertices
  16701. const v1 = p1.sub( p0 ).toVar();
  16702. const v2 = p3.sub( p0 ).toVar();
  16703. const lightNormal = v1.cross( v2 );
  16704. const result = vec3().toVar();
  16705. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16706. // construct orthonormal basis around N
  16707. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  16708. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  16709. // compute transform
  16710. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  16711. // transform rect
  16712. // & project rect onto sphere
  16713. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  16714. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  16715. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  16716. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  16717. // calculate vector form factor
  16718. const vectorFormFactor = vec3( 0 ).toVar();
  16719. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16720. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16721. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16722. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16723. // adjust for horizon clipping
  16724. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  16725. } );
  16726. return result;
  16727. } ).setLayout( {
  16728. name: 'LTC_Evaluate',
  16729. type: 'vec3',
  16730. inputs: [
  16731. { name: 'N', type: 'vec3' },
  16732. { name: 'V', type: 'vec3' },
  16733. { name: 'P', type: 'vec3' },
  16734. { name: 'mInv', type: 'mat3' },
  16735. { name: 'p0', type: 'vec3' },
  16736. { name: 'p1', type: 'vec3' },
  16737. { name: 'p2', type: 'vec3' },
  16738. { name: 'p3', type: 'vec3' }
  16739. ]
  16740. } );
  16741. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  16742. // bail if point is on back side of plane of light
  16743. // assumes ccw winding order of light vertices
  16744. const v1 = p1.sub( p0 ).toVar();
  16745. const v2 = p3.sub( p0 ).toVar();
  16746. const lightNormal = v1.cross( v2 );
  16747. const result = vec3().toVar();
  16748. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16749. // transform rect
  16750. // & project rect onto sphere
  16751. const coords0 = p0.sub( P ).normalize().toVar();
  16752. const coords1 = p1.sub( P ).normalize().toVar();
  16753. const coords2 = p2.sub( P ).normalize().toVar();
  16754. const coords3 = p3.sub( P ).normalize().toVar();
  16755. // calculate vector form factor
  16756. const vectorFormFactor = vec3( 0 ).toVar();
  16757. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16758. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16759. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16760. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16761. // adjust for horizon clipping
  16762. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  16763. } );
  16764. return result;
  16765. } ).setLayout( {
  16766. name: 'LTC_Evaluate',
  16767. type: 'vec3',
  16768. inputs: [
  16769. { name: 'P', type: 'vec3' },
  16770. { name: 'p0', type: 'vec3' },
  16771. { name: 'p1', type: 'vec3' },
  16772. { name: 'p2', type: 'vec3' },
  16773. { name: 'p3', type: 'vec3' }
  16774. ]
  16775. } );
  16776. // Mipped Bicubic Texture Filtering by N8
  16777. // https://www.shadertoy.com/view/Dl2SDW
  16778. const bC = 1.0 / 6.0;
  16779. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  16780. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  16781. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  16782. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  16783. const g0 = ( a ) => w0( a ).add( w1( a ) );
  16784. const g1 = ( a ) => w2( a ).add( w3( a ) );
  16785. // h0 and h1 are the two offset functions
  16786. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  16787. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  16788. const bicubic = ( textureNode, texelSize, lod ) => {
  16789. const uv = textureNode.uvNode;
  16790. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  16791. const iuv = floor( uvScaled );
  16792. const fuv = fract( uvScaled );
  16793. const g0x = g0( fuv.x );
  16794. const g1x = g1( fuv.x );
  16795. const h0x = h0( fuv.x );
  16796. const h1x = h1( fuv.x );
  16797. const h0y = h0( fuv.y );
  16798. const h1y = h1( fuv.y );
  16799. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16800. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16801. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16802. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16803. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  16804. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  16805. return a.add( b );
  16806. };
  16807. /**
  16808. * Applies mipped bicubic texture filtering to the given texture node.
  16809. *
  16810. * @tsl
  16811. * @function
  16812. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16813. * @param {Node<float>} lodNode - Defines the LOD to sample from.
  16814. * @return {Node} The filtered texture sample.
  16815. */
  16816. const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => {
  16817. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  16818. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  16819. const fLodSizeInv = div( 1.0, fLodSize );
  16820. const cLodSizeInv = div( 1.0, cLodSize );
  16821. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  16822. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  16823. return fract( lodNode ).mix( fSample, cSample );
  16824. } );
  16825. /**
  16826. * Applies mipped bicubic texture filtering to the given texture node.
  16827. *
  16828. * @tsl
  16829. * @function
  16830. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16831. * @param {Node<float>} [strength] - Defines the strength of the bicubic filtering.
  16832. * @return {Node} The filtered texture sample.
  16833. */
  16834. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => {
  16835. const lod = strength.mul( maxMipLevel( textureNode ) );
  16836. return textureBicubicLevel( textureNode, lod );
  16837. } );
  16838. //
  16839. // Transmission
  16840. //
  16841. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  16842. // Direction of refracted light.
  16843. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  16844. // Compute rotation-independent scaling of the model matrix.
  16845. const modelScale = vec3(
  16846. length( modelMatrix[ 0 ].xyz ),
  16847. length( modelMatrix[ 1 ].xyz ),
  16848. length( modelMatrix[ 2 ].xyz )
  16849. );
  16850. // The thickness is specified in local space.
  16851. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  16852. } ).setLayout( {
  16853. name: 'getVolumeTransmissionRay',
  16854. type: 'vec3',
  16855. inputs: [
  16856. { name: 'n', type: 'vec3' },
  16857. { name: 'v', type: 'vec3' },
  16858. { name: 'thickness', type: 'float' },
  16859. { name: 'ior', type: 'float' },
  16860. { name: 'modelMatrix', type: 'mat4' }
  16861. ]
  16862. } );
  16863. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  16864. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  16865. // an IOR of 1.5 results in the default amount of microfacet refraction.
  16866. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  16867. } ).setLayout( {
  16868. name: 'applyIorToRoughness',
  16869. type: 'float',
  16870. inputs: [
  16871. { name: 'roughness', type: 'float' },
  16872. { name: 'ior', type: 'float' }
  16873. ]
  16874. } );
  16875. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  16876. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  16877. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  16878. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  16879. const transmissionSample = vTexture.sample( fragCoord );
  16880. //const transmissionSample = viewportMipTexture( fragCoord );
  16881. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  16882. return textureBicubicLevel( transmissionSample, lod );
  16883. } );
  16884. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  16885. If( attenuationDistance.notEqual( 0 ), () => {
  16886. // Compute light attenuation using Beer's law.
  16887. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  16888. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  16889. return transmittance;
  16890. } );
  16891. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  16892. return vec3( 1.0 );
  16893. } ).setLayout( {
  16894. name: 'volumeAttenuation',
  16895. type: 'vec3',
  16896. inputs: [
  16897. { name: 'transmissionDistance', type: 'float' },
  16898. { name: 'attenuationColor', type: 'vec3' },
  16899. { name: 'attenuationDistance', type: 'float' }
  16900. ]
  16901. } );
  16902. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  16903. let transmittedLight, transmittance;
  16904. if ( dispersion ) {
  16905. transmittedLight = vec4().toVar();
  16906. transmittance = vec3().toVar();
  16907. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  16908. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  16909. Loop( { start: 0, end: 3 }, ( { i } ) => {
  16910. const ior = iors.element( i );
  16911. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16912. const refractedRayExit = position.add( transmissionRay );
  16913. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16914. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16915. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16916. refractionCoords.addAssign( 1.0 );
  16917. refractionCoords.divAssign( 2.0 );
  16918. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16919. // Sample framebuffer to get pixel the refracted ray hits.
  16920. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  16921. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  16922. transmittedLight.a.addAssign( transmissionSample.a );
  16923. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  16924. } );
  16925. transmittedLight.a.divAssign( 3.0 );
  16926. } else {
  16927. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16928. const refractedRayExit = position.add( transmissionRay );
  16929. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16930. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16931. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16932. refractionCoords.addAssign( 1.0 );
  16933. refractionCoords.divAssign( 2.0 );
  16934. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16935. // Sample framebuffer to get pixel the refracted ray hits.
  16936. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  16937. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  16938. }
  16939. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  16940. const dotNV = n.dot( v ).clamp();
  16941. // Get the specular component.
  16942. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  16943. dotNV,
  16944. specularColor,
  16945. specularF90,
  16946. roughness
  16947. } ) );
  16948. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  16949. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  16950. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  16951. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  16952. } );
  16953. //
  16954. // Iridescence
  16955. //
  16956. // XYZ to linear-sRGB color space
  16957. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  16958. 3.2404542, -0.969266, 0.0556434,
  16959. -1.5371385, 1.8760108, -0.2040259,
  16960. -0.4985314, 0.0415560, 1.0572252
  16961. );
  16962. // Assume air interface for top
  16963. // Note: We don't handle the case fresnel0 == 1
  16964. const Fresnel0ToIor = ( fresnel0 ) => {
  16965. const sqrtF0 = fresnel0.sqrt();
  16966. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  16967. };
  16968. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  16969. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  16970. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  16971. };
  16972. // Fresnel equations for dielectric/dielectric interfaces.
  16973. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  16974. // Evaluation XYZ sensitivity curves in Fourier space
  16975. const evalSensitivity = ( OPD, shift ) => {
  16976. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  16977. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  16978. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  16979. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  16980. 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() );
  16981. 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() );
  16982. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  16983. const rgb = XYZ_TO_REC709.mul( xyz );
  16984. return rgb;
  16985. };
  16986. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  16987. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  16988. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  16989. // Evaluate the cosTheta on the base layer (Snell law)
  16990. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  16991. // Handle TIR:
  16992. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  16993. If( cosTheta2Sq.lessThan( 0 ), () => {
  16994. return vec3( 1.0 );
  16995. } );
  16996. const cosTheta2 = cosTheta2Sq.sqrt();
  16997. // First interface
  16998. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  16999. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  17000. //const R21 = R12;
  17001. const T121 = R12.oneMinus();
  17002. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  17003. const phi21 = float( Math.PI ).sub( phi12 );
  17004. // Second interface
  17005. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  17006. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  17007. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  17008. const phi23 = vec3(
  17009. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  17010. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  17011. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  17012. );
  17013. // Phase shift
  17014. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  17015. const phi = vec3( phi21 ).add( phi23 );
  17016. // Compound terms
  17017. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  17018. const r123 = R123.sqrt();
  17019. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  17020. // Reflectance term for m = 0 (DC term amplitude)
  17021. const C0 = R12.add( Rs );
  17022. const I = C0.toVar();
  17023. // Reflectance term for m > 0 (pairs of diracs)
  17024. const Cm = Rs.sub( T121 ).toVar();
  17025. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  17026. Cm.mulAssign( r123 );
  17027. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  17028. I.addAssign( Cm.mul( Sm ) );
  17029. } );
  17030. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  17031. return I.max( vec3( 0.0 ) );
  17032. } ).setLayout( {
  17033. name: 'evalIridescence',
  17034. type: 'vec3',
  17035. inputs: [
  17036. { name: 'outsideIOR', type: 'float' },
  17037. { name: 'eta2', type: 'float' },
  17038. { name: 'cosTheta1', type: 'float' },
  17039. { name: 'thinFilmThickness', type: 'float' },
  17040. { name: 'baseF0', type: 'vec3' }
  17041. ]
  17042. } );
  17043. //
  17044. // Sheen
  17045. //
  17046. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  17047. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF".
  17048. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  17049. const dotNV = normal.dot( viewDir ).saturate();
  17050. const r2 = roughness.mul( roughness );
  17051. const rInv = roughness.add( 0.1 ).reciprocal();
  17052. const a = float( -1.9362 ).add( roughness.mul( 1.0678 ) ).add( r2.mul( 0.4573 ) ).sub( rInv.mul( 0.8469 ) );
  17053. const b = float( -0.6014 ).add( roughness.mul( 0.5538 ) ).sub( r2.mul( 0.4670 ) ).sub( rInv.mul( 0.1255 ) );
  17054. const DG = a.mul( dotNV ).add( b ).exp();
  17055. return DG.saturate();
  17056. } );
  17057. const clearcoatF0 = vec3( 0.04 );
  17058. const clearcoatF90 = float( 1 );
  17059. /**
  17060. * Represents the lighting model for a PBR material.
  17061. *
  17062. * @augments LightingModel
  17063. */
  17064. class PhysicalLightingModel extends LightingModel {
  17065. /**
  17066. * Constructs a new physical lighting model.
  17067. *
  17068. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  17069. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  17070. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  17071. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  17072. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  17073. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  17074. */
  17075. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  17076. super();
  17077. /**
  17078. * Whether clearcoat is supported or not.
  17079. *
  17080. * @type {boolean}
  17081. * @default false
  17082. */
  17083. this.clearcoat = clearcoat;
  17084. /**
  17085. * Whether sheen is supported or not.
  17086. *
  17087. * @type {boolean}
  17088. * @default false
  17089. */
  17090. this.sheen = sheen;
  17091. /**
  17092. * Whether iridescence is supported or not.
  17093. *
  17094. * @type {boolean}
  17095. * @default false
  17096. */
  17097. this.iridescence = iridescence;
  17098. /**
  17099. * Whether anisotropy is supported or not.
  17100. *
  17101. * @type {boolean}
  17102. * @default false
  17103. */
  17104. this.anisotropy = anisotropy;
  17105. /**
  17106. * Whether transmission is supported or not.
  17107. *
  17108. * @type {boolean}
  17109. * @default false
  17110. */
  17111. this.transmission = transmission;
  17112. /**
  17113. * Whether dispersion is supported or not.
  17114. *
  17115. * @type {boolean}
  17116. * @default false
  17117. */
  17118. this.dispersion = dispersion;
  17119. /**
  17120. * The clear coat radiance.
  17121. *
  17122. * @type {?Node}
  17123. * @default null
  17124. */
  17125. this.clearcoatRadiance = null;
  17126. /**
  17127. * The clear coat specular direct.
  17128. *
  17129. * @type {?Node}
  17130. * @default null
  17131. */
  17132. this.clearcoatSpecularDirect = null;
  17133. /**
  17134. * The clear coat specular indirect.
  17135. *
  17136. * @type {?Node}
  17137. * @default null
  17138. */
  17139. this.clearcoatSpecularIndirect = null;
  17140. /**
  17141. * The sheen specular direct.
  17142. *
  17143. * @type {?Node}
  17144. * @default null
  17145. */
  17146. this.sheenSpecularDirect = null;
  17147. /**
  17148. * The sheen specular indirect.
  17149. *
  17150. * @type {?Node}
  17151. * @default null
  17152. */
  17153. this.sheenSpecularIndirect = null;
  17154. /**
  17155. * The iridescence Fresnel.
  17156. *
  17157. * @type {?Node}
  17158. * @default null
  17159. */
  17160. this.iridescenceFresnel = null;
  17161. /**
  17162. * The iridescence F0.
  17163. *
  17164. * @type {?Node}
  17165. * @default null
  17166. */
  17167. this.iridescenceF0 = null;
  17168. /**
  17169. * The iridescence F0 dielectric.
  17170. *
  17171. * @type {?Node}
  17172. * @default null
  17173. */
  17174. this.iridescenceF0Dielectric = null;
  17175. /**
  17176. * The iridescence F0 metallic.
  17177. *
  17178. * @type {?Node}
  17179. * @default null
  17180. */
  17181. this.iridescenceF0Metallic = null;
  17182. }
  17183. /**
  17184. * Depending on what features are requested, the method prepares certain node variables
  17185. * which are later used for lighting computations.
  17186. *
  17187. * @param {NodeBuilder} builder - The current node builder.
  17188. */
  17189. start( builder ) {
  17190. if ( this.clearcoat === true ) {
  17191. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  17192. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  17193. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  17194. }
  17195. if ( this.sheen === true ) {
  17196. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  17197. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  17198. }
  17199. if ( this.iridescence === true ) {
  17200. const dotNVi = normalView.dot( positionViewDirection ).clamp();
  17201. const iridescenceFresnelDielectric = evalIridescence( {
  17202. outsideIOR: float( 1.0 ),
  17203. eta2: iridescenceIOR,
  17204. cosTheta1: dotNVi,
  17205. thinFilmThickness: iridescenceThickness,
  17206. baseF0: specularColor
  17207. } );
  17208. const iridescenceFresnelMetallic = evalIridescence( {
  17209. outsideIOR: float( 1.0 ),
  17210. eta2: iridescenceIOR,
  17211. cosTheta1: dotNVi,
  17212. thinFilmThickness: iridescenceThickness,
  17213. baseF0: diffuseColor.rgb
  17214. } );
  17215. this.iridescenceFresnel = mix( iridescenceFresnelDielectric, iridescenceFresnelMetallic, metalness );
  17216. this.iridescenceF0Dielectric = Schlick_to_F0( { f: iridescenceFresnelDielectric, f90: 1.0, dotVH: dotNVi } );
  17217. this.iridescenceF0Metallic = Schlick_to_F0( { f: iridescenceFresnelMetallic, f90: 1.0, dotVH: dotNVi } );
  17218. this.iridescenceF0 = mix( this.iridescenceF0Dielectric, this.iridescenceF0Metallic, metalness );
  17219. }
  17220. if ( this.transmission === true ) {
  17221. const position = positionWorld;
  17222. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  17223. const n = normalWorld;
  17224. const context = builder.context;
  17225. context.backdrop = getIBLVolumeRefraction(
  17226. n,
  17227. v,
  17228. roughness,
  17229. diffuseContribution,
  17230. specularColorBlended,
  17231. specularF90, // specularF90
  17232. position, // positionWorld
  17233. modelWorldMatrix, // modelMatrix
  17234. cameraViewMatrix, // viewMatrix
  17235. cameraProjectionMatrix, // projMatrix
  17236. ior,
  17237. thickness,
  17238. attenuationColor,
  17239. attenuationDistance,
  17240. this.dispersion ? dispersion : null
  17241. );
  17242. context.backdropAlpha = transmission;
  17243. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  17244. }
  17245. super.start( builder );
  17246. }
  17247. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  17248. // Approximates multi-scattering in order to preserve energy.
  17249. // http://www.jcgt.org/published/0008/01/03/
  17250. computeMultiscattering( singleScatter, multiScatter, specularF90, f0, iridescenceF0 = null ) {
  17251. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17252. const fab = DFGApprox( { roughness, dotNV } );
  17253. const Fr = iridescenceF0 ? iridescence.mix( f0, iridescenceF0 ) : f0;
  17254. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  17255. const Ess = fab.x.add( fab.y );
  17256. const Ems = Ess.oneMinus();
  17257. const Favg = Fr.add( Fr.oneMinus().mul( 0.047619 ) ); // 1/21
  17258. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  17259. singleScatter.addAssign( FssEss );
  17260. multiScatter.addAssign( Fms.mul( Ems ) );
  17261. }
  17262. /**
  17263. * Implements the direct light.
  17264. *
  17265. * @param {Object} lightData - The light data.
  17266. * @param {NodeBuilder} builder - The current node builder.
  17267. */
  17268. direct( { lightDirection, lightColor, reflectedLight }, /* builder */ ) {
  17269. const dotNL = normalView.dot( lightDirection ).clamp();
  17270. const irradiance = dotNL.mul( lightColor ).toVar();
  17271. if ( this.sheen === true ) {
  17272. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  17273. const sheenAlbedoV = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17274. const sheenAlbedoL = IBLSheenBRDF( { normal: normalView, viewDir: lightDirection, roughness: sheenRoughness } );
  17275. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedoV.max( sheenAlbedoL ) ).oneMinus();
  17276. irradiance.mulAssign( sheenEnergyComp );
  17277. }
  17278. if ( this.clearcoat === true ) {
  17279. const dotNLcc = clearcoatNormalView.dot( lightDirection ).clamp();
  17280. const ccIrradiance = dotNLcc.mul( lightColor );
  17281. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: clearcoatNormalView } ) ) );
  17282. }
  17283. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseContribution } ) ) );
  17284. 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 } ) ) );
  17285. }
  17286. /**
  17287. * This method is intended for implementing the direct light term for
  17288. * rect area light nodes.
  17289. *
  17290. * @param {Object} input - The input data.
  17291. * @param {NodeBuilder} builder - The current node builder.
  17292. */
  17293. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 }, /* builder */ ) {
  17294. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  17295. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  17296. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  17297. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  17298. const N = normalView;
  17299. const V = positionViewDirection;
  17300. const P = positionView.toVar();
  17301. const uv = LTC_Uv( { N, V, roughness } );
  17302. const t1 = ltc_1.sample( uv ).toVar();
  17303. const t2 = ltc_2.sample( uv ).toVar();
  17304. const mInv = mat3(
  17305. vec3( t1.x, 0, t1.y ),
  17306. vec3( 0, 1, 0 ),
  17307. vec3( t1.z, 0, t1.w )
  17308. ).toVar();
  17309. // LTC Fresnel Approximation by Stephen Hill
  17310. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  17311. const fresnel = specularColorBlended.mul( t2.x ).add( specularColorBlended.oneMinus().mul( t2.y ) ).toVar();
  17312. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  17313. 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 } ) ) );
  17314. }
  17315. /**
  17316. * Implements the indirect lighting.
  17317. *
  17318. * @param {NodeBuilder} builder - The current node builder.
  17319. */
  17320. indirect( builder ) {
  17321. this.indirectDiffuse( builder );
  17322. this.indirectSpecular( builder );
  17323. this.ambientOcclusion( builder );
  17324. }
  17325. /**
  17326. * Implements the indirect diffuse term.
  17327. *
  17328. * @param {NodeBuilder} builder - The current node builder.
  17329. */
  17330. indirectDiffuse( builder ) {
  17331. const { irradiance, reflectedLight } = builder.context;
  17332. const diffuse = irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseContribution } ) ).toVar();
  17333. if ( this.sheen === true ) {
  17334. const sheenAlbedo = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17335. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedo ).oneMinus();
  17336. diffuse.mulAssign( sheenEnergyComp );
  17337. }
  17338. reflectedLight.indirectDiffuse.addAssign( diffuse );
  17339. }
  17340. /**
  17341. * Implements the indirect specular term.
  17342. *
  17343. * @param {NodeBuilder} builder - The current node builder.
  17344. */
  17345. indirectSpecular( builder ) {
  17346. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  17347. if ( this.sheen === true ) {
  17348. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  17349. sheen,
  17350. IBLSheenBRDF( {
  17351. normal: normalView,
  17352. viewDir: positionViewDirection,
  17353. roughness: sheenRoughness
  17354. } )
  17355. ) );
  17356. }
  17357. if ( this.clearcoat === true ) {
  17358. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17359. const clearcoatEnv = EnvironmentBRDF( {
  17360. dotNV: dotNVcc,
  17361. specularColor: clearcoatF0,
  17362. specularF90: clearcoatF90,
  17363. roughness: clearcoatRoughness
  17364. } );
  17365. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  17366. }
  17367. // Both indirect specular and indirect diffuse light accumulate here
  17368. // Compute multiscattering separately for dielectric and metallic, then mix
  17369. const singleScatteringDielectric = vec3().toVar( 'singleScatteringDielectric' );
  17370. const multiScatteringDielectric = vec3().toVar( 'multiScatteringDielectric' );
  17371. const singleScatteringMetallic = vec3().toVar( 'singleScatteringMetallic' );
  17372. const multiScatteringMetallic = vec3().toVar( 'multiScatteringMetallic' );
  17373. this.computeMultiscattering( singleScatteringDielectric, multiScatteringDielectric, specularF90, specularColor, this.iridescenceF0Dielectric );
  17374. this.computeMultiscattering( singleScatteringMetallic, multiScatteringMetallic, specularF90, diffuseColor.rgb, this.iridescenceF0Metallic );
  17375. // Mix based on metalness
  17376. const singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, metalness );
  17377. const multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, metalness );
  17378. // Diffuse energy conservation uses dielectric path
  17379. const totalScatteringDielectric = singleScatteringDielectric.add( multiScatteringDielectric );
  17380. const diffuse = diffuseContribution.mul( totalScatteringDielectric.oneMinus() );
  17381. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  17382. const indirectSpecular = radiance.mul( singleScattering ).add( multiScattering.mul( cosineWeightedIrradiance ) ).toVar();
  17383. const indirectDiffuse = diffuse.mul( cosineWeightedIrradiance ).toVar();
  17384. if ( this.sheen === true ) {
  17385. const sheenAlbedo = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17386. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedo ).oneMinus();
  17387. indirectSpecular.mulAssign( sheenEnergyComp );
  17388. indirectDiffuse.mulAssign( sheenEnergyComp );
  17389. }
  17390. reflectedLight.indirectSpecular.addAssign( indirectSpecular );
  17391. reflectedLight.indirectDiffuse.addAssign( indirectDiffuse );
  17392. }
  17393. /**
  17394. * Implements the ambient occlusion term.
  17395. *
  17396. * @param {NodeBuilder} builder - The current node builder.
  17397. */
  17398. ambientOcclusion( builder ) {
  17399. const { ambientOcclusion, reflectedLight } = builder.context;
  17400. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17401. const aoNV = dotNV.add( ambientOcclusion );
  17402. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  17403. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  17404. if ( this.clearcoat === true ) {
  17405. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  17406. }
  17407. if ( this.sheen === true ) {
  17408. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  17409. }
  17410. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  17411. reflectedLight.indirectSpecular.mulAssign( aoNode );
  17412. }
  17413. /**
  17414. * Used for final lighting accumulations depending on the requested features.
  17415. *
  17416. * @param {NodeBuilder} builder - The current node builder.
  17417. */
  17418. finish( { context } ) {
  17419. const { outgoingLight } = context;
  17420. if ( this.clearcoat === true ) {
  17421. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17422. const Fcc = F_Schlick( {
  17423. dotVH: dotNVcc,
  17424. f0: clearcoatF0,
  17425. f90: clearcoatF90
  17426. } );
  17427. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  17428. outgoingLight.assign( clearcoatLight );
  17429. }
  17430. if ( this.sheen === true ) {
  17431. const sheenLight = outgoingLight.add( this.sheenSpecularDirect, this.sheenSpecularIndirect.mul( 1.0 / Math.PI ) );
  17432. outgoingLight.assign( sheenLight );
  17433. }
  17434. }
  17435. }
  17436. // These defines must match with PMREMGenerator
  17437. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  17438. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  17439. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  17440. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  17441. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  17442. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  17443. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  17444. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  17445. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  17446. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  17447. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  17448. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  17449. // These shader functions convert between the UV coordinates of a single face of
  17450. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  17451. // sampling a textureCube (not generally normalized ).
  17452. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  17453. const absDirection = vec3( abs( direction ) ).toVar();
  17454. const face = float( -1 ).toVar();
  17455. If( absDirection.x.greaterThan( absDirection.z ), () => {
  17456. If( absDirection.x.greaterThan( absDirection.y ), () => {
  17457. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  17458. } ).Else( () => {
  17459. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17460. } );
  17461. } ).Else( () => {
  17462. If( absDirection.z.greaterThan( absDirection.y ), () => {
  17463. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  17464. } ).Else( () => {
  17465. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17466. } );
  17467. } );
  17468. return face;
  17469. } ).setLayout( {
  17470. name: 'getFace',
  17471. type: 'float',
  17472. inputs: [
  17473. { name: 'direction', type: 'vec3' }
  17474. ]
  17475. } );
  17476. // RH coordinate system; PMREM face-indexing convention
  17477. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  17478. const uv = vec2().toVar();
  17479. If( face.equal( 0.0 ), () => {
  17480. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  17481. } ).ElseIf( face.equal( 1.0 ), () => {
  17482. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  17483. } ).ElseIf( face.equal( 2.0 ), () => {
  17484. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  17485. } ).ElseIf( face.equal( 3.0 ), () => {
  17486. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  17487. } ).ElseIf( face.equal( 4.0 ), () => {
  17488. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  17489. } ).Else( () => {
  17490. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  17491. } );
  17492. return mul( 0.5, uv.add( 1.0 ) );
  17493. } ).setLayout( {
  17494. name: 'getUV',
  17495. type: 'vec2',
  17496. inputs: [
  17497. { name: 'direction', type: 'vec3' },
  17498. { name: 'face', type: 'float' }
  17499. ]
  17500. } );
  17501. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  17502. const mip = float( 0.0 ).toVar();
  17503. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  17504. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  17505. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  17506. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  17507. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  17508. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  17509. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  17510. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  17511. } ).Else( () => {
  17512. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  17513. } );
  17514. return mip;
  17515. } ).setLayout( {
  17516. name: 'roughnessToMip',
  17517. type: 'float',
  17518. inputs: [
  17519. { name: 'roughness', type: 'float' }
  17520. ]
  17521. } );
  17522. // RH coordinate system; PMREM face-indexing convention
  17523. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  17524. const uv = uv_immutable.toVar();
  17525. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  17526. const direction = vec3( uv, 1.0 ).toVar();
  17527. If( face.equal( 0.0 ), () => {
  17528. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  17529. } ).ElseIf( face.equal( 1.0 ), () => {
  17530. direction.assign( direction.xzy );
  17531. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  17532. } ).ElseIf( face.equal( 2.0 ), () => {
  17533. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  17534. } ).ElseIf( face.equal( 3.0 ), () => {
  17535. direction.assign( direction.zyx );
  17536. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  17537. } ).ElseIf( face.equal( 4.0 ), () => {
  17538. direction.assign( direction.xzy );
  17539. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  17540. } ).ElseIf( face.equal( 5.0 ), () => {
  17541. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  17542. } );
  17543. return direction;
  17544. } ).setLayout( {
  17545. name: 'getDirection',
  17546. type: 'vec3',
  17547. inputs: [
  17548. { name: 'uv', type: 'vec2' },
  17549. { name: 'face', type: 'float' }
  17550. ]
  17551. } );
  17552. //
  17553. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17554. const roughness = float( roughness_immutable );
  17555. const sampleDir = vec3( sampleDir_immutable );
  17556. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  17557. const mipF = fract( mip );
  17558. const mipInt = floor( mip );
  17559. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17560. If( mipF.notEqual( 0.0 ), () => {
  17561. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17562. color0.assign( mix( color0, color1, mipF ) );
  17563. } );
  17564. return color0;
  17565. } );
  17566. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17567. const mipInt = float( mipInt_immutable ).toVar();
  17568. const direction = vec3( direction_immutable );
  17569. const face = float( getFace( direction ) ).toVar();
  17570. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  17571. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  17572. const faceSize = float( exp2( mipInt ) ).toVar();
  17573. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  17574. If( face.greaterThan( 2.0 ), () => {
  17575. uv.y.addAssign( faceSize );
  17576. face.subAssign( 3.0 );
  17577. } );
  17578. uv.x.addAssign( face.mul( faceSize ) );
  17579. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  17580. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  17581. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  17582. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  17583. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  17584. } );
  17585. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17586. const cosTheta = cos( theta );
  17587. // Rodrigues' axis-angle rotation
  17588. const sampleDirection = outputDirection.mul( cosTheta )
  17589. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  17590. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  17591. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  17592. } );
  17593. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17594. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  17595. If( axis.equal( vec3( 0.0 ) ), () => {
  17596. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  17597. } );
  17598. axis.assign( normalize( axis ) );
  17599. const gl_FragColor = vec3().toVar();
  17600. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17601. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  17602. If( i.greaterThanEqual( samples ), () => {
  17603. Break();
  17604. } );
  17605. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  17606. 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 } ) ) );
  17607. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17608. } );
  17609. return vec4( gl_FragColor, 1 );
  17610. } );
  17611. // GGX VNDF importance sampling functions
  17612. // Van der Corput radical inverse for generating quasi-random sequences
  17613. const radicalInverse_VdC = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  17614. const bits = uint( bits_immutable ).toVar();
  17615. bits.assign( bits.shiftLeft( uint( 16 ) ).bitOr( bits.shiftRight( uint( 16 ) ) ) );
  17616. bits.assign( bits.bitAnd( uint( 0x55555555 ) ).shiftLeft( uint( 1 ) ).bitOr( bits.bitAnd( uint( 0xAAAAAAAA ) ).shiftRight( uint( 1 ) ) ) );
  17617. bits.assign( bits.bitAnd( uint( 0x33333333 ) ).shiftLeft( uint( 2 ) ).bitOr( bits.bitAnd( uint( 0xCCCCCCCC ) ).shiftRight( uint( 2 ) ) ) );
  17618. bits.assign( bits.bitAnd( uint( 0x0F0F0F0F ) ).shiftLeft( uint( 4 ) ).bitOr( bits.bitAnd( uint( 0xF0F0F0F0 ) ).shiftRight( uint( 4 ) ) ) );
  17619. bits.assign( bits.bitAnd( uint( 0x00FF00FF ) ).shiftLeft( uint( 8 ) ).bitOr( bits.bitAnd( uint( 0xFF00FF00 ) ).shiftRight( uint( 8 ) ) ) );
  17620. return float( bits ).mul( 2.3283064365386963e-10 ); // / 0x100000000
  17621. } );
  17622. // Hammersley sequence for quasi-Monte Carlo sampling
  17623. const hammersley = /*@__PURE__*/ Fn( ( [ i, N ] ) => {
  17624. return vec2( float( i ).div( float( N ) ), radicalInverse_VdC( i ) );
  17625. } );
  17626. // GGX VNDF importance sampling (Eric Heitz 2018)
  17627. // "Sampling the GGX Distribution of Visible Normals"
  17628. // https://jcgt.org/published/0007/04/01/
  17629. const importanceSampleGGX_VNDF = /*@__PURE__*/ Fn( ( [ Xi, V_immutable, roughness_immutable ] ) => {
  17630. const V = vec3( V_immutable ).toVar();
  17631. const roughness = float( roughness_immutable );
  17632. const alpha = roughness.mul( roughness ).toVar();
  17633. // Section 3.2: Transform view direction to hemisphere configuration
  17634. const Vh = normalize( vec3( alpha.mul( V.x ), alpha.mul( V.y ), V.z ) ).toVar();
  17635. // Section 4.1: Orthonormal basis
  17636. const lensq = Vh.x.mul( Vh.x ).add( Vh.y.mul( Vh.y ) );
  17637. 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();
  17638. const T2 = cross( Vh, T1 ).toVar();
  17639. // Section 4.2: Parameterization of projected area
  17640. const r = sqrt( Xi.x );
  17641. const phi = mul( 2.0, 3.14159265359 ).mul( Xi.y );
  17642. const t1 = r.mul( cos( phi ) ).toVar();
  17643. const t2 = r.mul( sin( phi ) ).toVar();
  17644. const s = mul( 0.5, Vh.z.add( 1.0 ) );
  17645. t2.assign( s.oneMinus().mul( sqrt( t1.mul( t1 ).oneMinus() ) ).add( s.mul( t2 ) ) );
  17646. // Section 4.3: Reprojection onto hemisphere
  17647. 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() ) ) ) );
  17648. // Section 3.4: Transform back to ellipsoid configuration
  17649. return normalize( vec3( alpha.mul( Nh.x ), alpha.mul( Nh.y ), max$1( 0.0, Nh.z ) ) );
  17650. } );
  17651. // GGX convolution using VNDF importance sampling
  17652. const ggxConvolution = /*@__PURE__*/ Fn( ( { roughness, mipInt, envMap, N_immutable, GGX_SAMPLES, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17653. const N = vec3( N_immutable ).toVar();
  17654. const prefilteredColor = vec3( 0.0 ).toVar();
  17655. const totalWeight = float( 0.0 ).toVar();
  17656. // For very low roughness, just sample the environment directly
  17657. If( roughness.lessThan( 0.001 ), () => {
  17658. prefilteredColor.assign( bilinearCubeUV( envMap, N, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) );
  17659. } ).Else( () => {
  17660. // Tangent space basis for VNDF sampling
  17661. const up = select( abs( N.z ).lessThan( 0.999 ), vec3( 0.0, 0.0, 1.0 ), vec3( 1.0, 0.0, 0.0 ) );
  17662. const tangent = normalize( cross( up, N ) ).toVar();
  17663. const bitangent = cross( N, tangent ).toVar();
  17664. Loop( { start: uint( 0 ), end: GGX_SAMPLES }, ( { i } ) => {
  17665. const Xi = hammersley( i, GGX_SAMPLES );
  17666. // For PMREM, V = N, so in tangent space V is always (0, 0, 1)
  17667. const H_tangent = importanceSampleGGX_VNDF( Xi, vec3( 0.0, 0.0, 1.0 ), roughness );
  17668. // Transform H back to world space
  17669. const H = normalize( tangent.mul( H_tangent.x ).add( bitangent.mul( H_tangent.y ) ).add( N.mul( H_tangent.z ) ) );
  17670. const L = normalize( H.mul( dot( N, H ).mul( 2.0 ) ).sub( N ) );
  17671. const NdotL = max$1( dot( N, L ), 0.0 );
  17672. If( NdotL.greaterThan( 0.0 ), () => {
  17673. // Sample environment at fixed mip level
  17674. // VNDF importance sampling handles the distribution filtering
  17675. const sampleColor = bilinearCubeUV( envMap, L, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  17676. // Weight by NdotL for the split-sum approximation
  17677. // VNDF PDF naturally accounts for the visible microfacet distribution
  17678. prefilteredColor.addAssign( sampleColor.mul( NdotL ) );
  17679. totalWeight.addAssign( NdotL );
  17680. } );
  17681. } );
  17682. If( totalWeight.greaterThan( 0.0 ), () => {
  17683. prefilteredColor.assign( prefilteredColor.div( totalWeight ) );
  17684. } );
  17685. } );
  17686. return vec4( prefilteredColor, 1.0 );
  17687. } );
  17688. const LOD_MIN = 4;
  17689. // The standard deviations (radians) associated with the extra mips.
  17690. // Used for scene blur in fromScene() method.
  17691. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  17692. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  17693. // samples and exit early, but not recompile the shader.
  17694. // Used for scene blur in fromScene() method.
  17695. const MAX_SAMPLES = 20;
  17696. // GGX VNDF importance sampling configuration
  17697. const GGX_SAMPLES = 512;
  17698. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  17699. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  17700. const _clearColor$2 = /*@__PURE__*/ new Color();
  17701. let _oldTarget = null;
  17702. let _oldActiveCubeFace = 0;
  17703. let _oldActiveMipmapLevel = 0;
  17704. const _origin = /*@__PURE__*/ new Vector3();
  17705. // maps blur materials to their uniforms dictionary
  17706. const _uniformsMap = new WeakMap();
  17707. // WebGPU Face indices
  17708. const _faceLib = [
  17709. 3, 1, 5,
  17710. 0, 4, 2
  17711. ];
  17712. const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize();
  17713. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  17714. /**
  17715. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  17716. * (PMREM) from a cubeMap environment texture. This allows different levels of
  17717. * blur to be quickly accessed based on material roughness. It is packed into a
  17718. * special CubeUV format that allows us to perform custom interpolation so that
  17719. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  17720. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  17721. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  17722. * higher roughness levels. In this way we maintain resolution to smoothly
  17723. * interpolate diffuse lighting while limiting sampling computation.
  17724. *
  17725. * The prefiltering uses GGX VNDF (Visible Normal Distribution Function)
  17726. * importance sampling based on "Sampling the GGX Distribution of Visible Normals"
  17727. * (Heitz, 2018) to generate environment maps that accurately match the GGX BRDF
  17728. * used in material rendering for physically-based image-based lighting.
  17729. */
  17730. class PMREMGenerator {
  17731. /**
  17732. * Constructs a new PMREM generator.
  17733. *
  17734. * @param {Renderer} renderer - The renderer.
  17735. */
  17736. constructor( renderer ) {
  17737. this._renderer = renderer;
  17738. this._pingPongRenderTarget = null;
  17739. this._lodMax = 0;
  17740. this._cubeSize = 0;
  17741. this._sizeLods = [];
  17742. this._sigmas = [];
  17743. this._lodMeshes = [];
  17744. this._blurMaterial = null;
  17745. this._ggxMaterial = null;
  17746. this._cubemapMaterial = null;
  17747. this._equirectMaterial = null;
  17748. this._backgroundBox = null;
  17749. }
  17750. get _hasInitialized() {
  17751. return this._renderer.hasInitialized();
  17752. }
  17753. /**
  17754. * Generates a PMREM from a supplied Scene, which can be faster than using an
  17755. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  17756. * in radians to be applied to the scene before PMREM generation. Optional near
  17757. * and far planes ensure the scene is rendered in its entirety.
  17758. *
  17759. * @param {Scene} scene - The scene to be captured.
  17760. * @param {number} [sigma=0] - The blur radius in radians.
  17761. * @param {number} [near=0.1] - The near plane distance.
  17762. * @param {number} [far=100] - The far plane distance.
  17763. * @param {Object} [options={}] - The configuration options.
  17764. * @param {number} [options.size=256] - The texture size of the PMREM.
  17765. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  17766. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17767. * @return {RenderTarget} The resulting PMREM.
  17768. * @see {@link PMREMGenerator#fromScene}
  17769. */
  17770. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17771. const {
  17772. size = 256,
  17773. position = _origin,
  17774. renderTarget = null,
  17775. } = options;
  17776. this._setSize( size );
  17777. if ( this._hasInitialized === false ) {
  17778. warn( 'PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.' );
  17779. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17780. options.renderTarget = cubeUVRenderTarget;
  17781. this.fromSceneAsync( scene, sigma, near, far, options );
  17782. return cubeUVRenderTarget;
  17783. }
  17784. _oldTarget = this._renderer.getRenderTarget();
  17785. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17786. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17787. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17788. cubeUVRenderTarget.depthBuffer = true;
  17789. this._init( cubeUVRenderTarget );
  17790. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  17791. if ( sigma > 0 ) {
  17792. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  17793. }
  17794. this._applyPMREM( cubeUVRenderTarget );
  17795. this._cleanup( cubeUVRenderTarget );
  17796. return cubeUVRenderTarget;
  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 (the cubeCamera
  17803. * is placed at the origin).
  17804. *
  17805. * @deprecated
  17806. * @param {Scene} scene - The scene to be captured.
  17807. * @param {number} [sigma=0] - The blur radius in radians.
  17808. * @param {number} [near=0.1] - The near plane distance.
  17809. * @param {number} [far=100] - The far plane distance.
  17810. * @param {Object} [options={}] - The configuration options.
  17811. * @param {number} [options.size=256] - The texture size of the PMREM.
  17812. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  17813. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17814. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  17815. * @see {@link PMREMGenerator#fromScene}
  17816. */
  17817. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17818. warnOnce( 'PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  17819. await this._renderer.init();
  17820. return this.fromScene( scene, sigma, near, far, options );
  17821. }
  17822. /**
  17823. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17824. * or HDR. The ideal input image size is 1k (1024 x 512),
  17825. * as this matches best with the 256 x 256 cubemap output.
  17826. *
  17827. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17828. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17829. * @return {RenderTarget} The resulting PMREM.
  17830. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  17831. */
  17832. fromEquirectangular( equirectangular, renderTarget = null ) {
  17833. if ( this._hasInitialized === false ) {
  17834. warn( 'PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" instead.' );
  17835. this._setSizeFromTexture( equirectangular );
  17836. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17837. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  17838. return cubeUVRenderTarget;
  17839. }
  17840. return this._fromTexture( equirectangular, renderTarget );
  17841. }
  17842. /**
  17843. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17844. * or HDR. The ideal input image size is 1k (1024 x 512),
  17845. * as this matches best with the 256 x 256 cubemap output.
  17846. *
  17847. * @deprecated
  17848. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17849. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17850. * @return {Promise<RenderTarget>} The resulting PMREM.
  17851. * @see {@link PMREMGenerator#fromEquirectangular}
  17852. */
  17853. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  17854. warnOnce( 'PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  17855. await this._renderer.init();
  17856. return this._fromTexture( equirectangular, renderTarget );
  17857. }
  17858. /**
  17859. * Generates a PMREM from an cubemap texture, which can be either LDR
  17860. * or HDR. The ideal input cube size is 256 x 256,
  17861. * as this matches best with the 256 x 256 cubemap output.
  17862. *
  17863. * @param {Texture} cubemap - The cubemap texture to be converted.
  17864. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17865. * @return {RenderTarget} The resulting PMREM.
  17866. * @see {@link PMREMGenerator#fromCubemapAsync}
  17867. */
  17868. fromCubemap( cubemap, renderTarget = null ) {
  17869. if ( this._hasInitialized === false ) {
  17870. warn( 'PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  17871. this._setSizeFromTexture( cubemap );
  17872. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17873. this.fromCubemapAsync( cubemap, renderTarget );
  17874. return cubeUVRenderTarget;
  17875. }
  17876. return this._fromTexture( cubemap, renderTarget );
  17877. }
  17878. /**
  17879. * Generates a PMREM from an cubemap texture, which can be either LDR
  17880. * or HDR. The ideal input cube size is 256 x 256,
  17881. * with the 256 x 256 cubemap output.
  17882. *
  17883. * @deprecated
  17884. * @param {Texture} cubemap - The cubemap texture to be converted.
  17885. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17886. * @return {Promise<RenderTarget>} The resulting PMREM.
  17887. * @see {@link PMREMGenerator#fromCubemap}
  17888. */
  17889. async fromCubemapAsync( cubemap, renderTarget = null ) {
  17890. warnOnce( 'PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  17891. await this._renderer.init();
  17892. return this._fromTexture( cubemap, renderTarget );
  17893. }
  17894. /**
  17895. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  17896. * your texture's network fetch for increased concurrency.
  17897. *
  17898. * @returns {Promise}
  17899. */
  17900. async compileCubemapShader() {
  17901. if ( this._cubemapMaterial === null ) {
  17902. this._cubemapMaterial = _getCubemapMaterial();
  17903. await this._compileMaterial( this._cubemapMaterial );
  17904. }
  17905. }
  17906. /**
  17907. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  17908. * your texture's network fetch for increased concurrency.
  17909. *
  17910. * @returns {Promise}
  17911. */
  17912. async compileEquirectangularShader() {
  17913. if ( this._equirectMaterial === null ) {
  17914. this._equirectMaterial = _getEquirectMaterial();
  17915. await this._compileMaterial( this._equirectMaterial );
  17916. }
  17917. }
  17918. /**
  17919. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  17920. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  17921. * one of them will cause any others to also become unusable.
  17922. */
  17923. dispose() {
  17924. this._dispose();
  17925. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  17926. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  17927. if ( this._backgroundBox !== null ) {
  17928. this._backgroundBox.geometry.dispose();
  17929. this._backgroundBox.material.dispose();
  17930. }
  17931. }
  17932. // private interface
  17933. _setSizeFromTexture( texture ) {
  17934. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  17935. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  17936. } else { // Equirectangular
  17937. this._setSize( texture.image.width / 4 );
  17938. }
  17939. }
  17940. _setSize( cubeSize ) {
  17941. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  17942. this._cubeSize = Math.pow( 2, this._lodMax );
  17943. }
  17944. _dispose() {
  17945. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  17946. if ( this._ggxMaterial !== null ) this._ggxMaterial.dispose();
  17947. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  17948. for ( let i = 0; i < this._lodMeshes.length; i ++ ) {
  17949. this._lodMeshes[ i ].geometry.dispose();
  17950. }
  17951. }
  17952. _cleanup( outputTarget ) {
  17953. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  17954. outputTarget.scissorTest = false;
  17955. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  17956. }
  17957. _fromTexture( texture, renderTarget ) {
  17958. this._setSizeFromTexture( texture );
  17959. _oldTarget = this._renderer.getRenderTarget();
  17960. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17961. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17962. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17963. this._init( cubeUVRenderTarget );
  17964. this._textureToCubeUV( texture, cubeUVRenderTarget );
  17965. this._applyPMREM( cubeUVRenderTarget );
  17966. this._cleanup( cubeUVRenderTarget );
  17967. return cubeUVRenderTarget;
  17968. }
  17969. _allocateTarget() {
  17970. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  17971. const height = 4 * this._cubeSize;
  17972. const cubeUVRenderTarget = _createRenderTarget( width, height );
  17973. return cubeUVRenderTarget;
  17974. }
  17975. _init( renderTarget ) {
  17976. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  17977. if ( this._pingPongRenderTarget !== null ) {
  17978. this._dispose();
  17979. }
  17980. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  17981. const { _lodMax } = this;
  17982. ( { lodMeshes: this._lodMeshes, sizeLods: this._sizeLods, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  17983. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  17984. this._ggxMaterial = _getGGXShader( _lodMax, renderTarget.width, renderTarget.height );
  17985. }
  17986. }
  17987. async _compileMaterial( material ) {
  17988. const mesh = new Mesh( new BufferGeometry(), material );
  17989. await this._renderer.compile( mesh, _flatCamera );
  17990. }
  17991. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  17992. const cubeCamera = _cubeCamera;
  17993. cubeCamera.near = near;
  17994. cubeCamera.far = far;
  17995. // px, py, pz, nx, ny, nz
  17996. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  17997. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  17998. const renderer = this._renderer;
  17999. const originalAutoClear = renderer.autoClear;
  18000. renderer.getClearColor( _clearColor$2 );
  18001. renderer.autoClear = false;
  18002. if ( this._backgroundBox === null ) {
  18003. this._backgroundBox = new Mesh(
  18004. new BoxGeometry(),
  18005. new MeshBasicMaterial( {
  18006. name: 'PMREM.Background',
  18007. side: BackSide,
  18008. depthWrite: false,
  18009. depthTest: false,
  18010. } )
  18011. );
  18012. }
  18013. const backgroundBox = this._backgroundBox;
  18014. const backgroundMaterial = backgroundBox.material;
  18015. let useSolidColor = false;
  18016. const background = scene.background;
  18017. if ( background ) {
  18018. if ( background.isColor ) {
  18019. backgroundMaterial.color.copy( background );
  18020. scene.background = null;
  18021. useSolidColor = true;
  18022. }
  18023. } else {
  18024. backgroundMaterial.color.copy( _clearColor$2 );
  18025. useSolidColor = true;
  18026. }
  18027. renderer.setRenderTarget( cubeUVRenderTarget );
  18028. renderer.clear();
  18029. if ( useSolidColor ) {
  18030. renderer.render( backgroundBox, cubeCamera );
  18031. }
  18032. for ( let i = 0; i < 6; i ++ ) {
  18033. const col = i % 3;
  18034. if ( col === 0 ) {
  18035. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18036. cubeCamera.position.set( position.x, position.y, position.z );
  18037. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  18038. } else if ( col === 1 ) {
  18039. cubeCamera.up.set( 0, 0, upSign[ i ] );
  18040. cubeCamera.position.set( position.x, position.y, position.z );
  18041. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  18042. } else {
  18043. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18044. cubeCamera.position.set( position.x, position.y, position.z );
  18045. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  18046. }
  18047. const size = this._cubeSize;
  18048. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  18049. renderer.render( scene, cubeCamera );
  18050. }
  18051. renderer.autoClear = originalAutoClear;
  18052. scene.background = background;
  18053. }
  18054. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  18055. const renderer = this._renderer;
  18056. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  18057. if ( isCubeTexture ) {
  18058. if ( this._cubemapMaterial === null ) {
  18059. this._cubemapMaterial = _getCubemapMaterial( texture );
  18060. }
  18061. } else {
  18062. if ( this._equirectMaterial === null ) {
  18063. this._equirectMaterial = _getEquirectMaterial( texture );
  18064. }
  18065. }
  18066. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  18067. material.fragmentNode.value = texture;
  18068. const mesh = this._lodMeshes[ 0 ];
  18069. mesh.material = material;
  18070. const size = this._cubeSize;
  18071. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  18072. renderer.setRenderTarget( cubeUVRenderTarget );
  18073. renderer.render( mesh, _flatCamera );
  18074. }
  18075. _applyPMREM( cubeUVRenderTarget ) {
  18076. const renderer = this._renderer;
  18077. const autoClear = renderer.autoClear;
  18078. renderer.autoClear = false;
  18079. const n = this._lodMeshes.length;
  18080. // Use GGX VNDF importance sampling
  18081. for ( let i = 1; i < n; i ++ ) {
  18082. this._applyGGXFilter( cubeUVRenderTarget, i - 1, i );
  18083. }
  18084. renderer.autoClear = autoClear;
  18085. }
  18086. /**
  18087. * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map.
  18088. * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the
  18089. * GGX BRDF for physically-based rendering. Reads from the previous LOD level and
  18090. * applies incremental roughness filtering to avoid over-blurring.
  18091. *
  18092. * @private
  18093. * @param {RenderTarget} cubeUVRenderTarget
  18094. * @param {number} lodIn - Source LOD level to read from
  18095. * @param {number} lodOut - Target LOD level to write to
  18096. */
  18097. _applyGGXFilter( cubeUVRenderTarget, lodIn, lodOut ) {
  18098. const renderer = this._renderer;
  18099. const pingPongRenderTarget = this._pingPongRenderTarget;
  18100. const ggxMaterial = this._ggxMaterial;
  18101. const ggxMesh = this._lodMeshes[ lodOut ];
  18102. ggxMesh.material = ggxMaterial;
  18103. const ggxUniforms = _uniformsMap.get( ggxMaterial );
  18104. // Calculate incremental roughness between LOD levels
  18105. const targetRoughness = lodOut / ( this._lodMeshes.length - 1 );
  18106. const sourceRoughness = lodIn / ( this._lodMeshes.length - 1 );
  18107. const incrementalRoughness = Math.sqrt( targetRoughness * targetRoughness - sourceRoughness * sourceRoughness );
  18108. // Apply blur strength mapping for better quality across the roughness range
  18109. const blurStrength = 0.0 + targetRoughness * 1.25;
  18110. const adjustedRoughness = incrementalRoughness * blurStrength;
  18111. // Calculate viewport position based on output LOD level
  18112. const { _lodMax } = this;
  18113. const outputSize = this._sizeLods[ lodOut ];
  18114. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  18115. const y = 4 * ( this._cubeSize - outputSize );
  18116. // Read from previous LOD with incremental roughness
  18117. cubeUVRenderTarget.texture.frame = ( cubeUVRenderTarget.texture.frame || 0 ) + 1;
  18118. ggxUniforms.envMap.value = cubeUVRenderTarget.texture;
  18119. ggxUniforms.roughness.value = adjustedRoughness;
  18120. ggxUniforms.mipInt.value = _lodMax - lodIn; // Sample from input LOD
  18121. _setViewport( pingPongRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  18122. renderer.setRenderTarget( pingPongRenderTarget );
  18123. renderer.render( ggxMesh, _flatCamera );
  18124. // Copy from pingPong back to cubeUV (simple direct copy)
  18125. pingPongRenderTarget.texture.frame = ( pingPongRenderTarget.texture.frame || 0 ) + 1;
  18126. ggxUniforms.envMap.value = pingPongRenderTarget.texture;
  18127. ggxUniforms.roughness.value = 0.0; // Direct copy
  18128. ggxUniforms.mipInt.value = _lodMax - lodOut; // Read from the level we just wrote
  18129. _setViewport( cubeUVRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  18130. renderer.setRenderTarget( cubeUVRenderTarget );
  18131. renderer.render( ggxMesh, _flatCamera );
  18132. }
  18133. /**
  18134. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  18135. * vertically and horizontally, but this breaks down on a cube. Here we apply
  18136. * the blur latitudinally (around the poles), and then longitudinally (towards
  18137. * the poles) to approximate the orthogonally-separable blur. It is least
  18138. * accurate at the poles, but still does a decent job.
  18139. *
  18140. * Used for initial scene blur in fromScene() method when sigma > 0.
  18141. *
  18142. * @private
  18143. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  18144. * @param {number} lodIn - The input level-of-detail.
  18145. * @param {number} lodOut - The output level-of-detail.
  18146. * @param {number} sigma - The blur radius in radians.
  18147. * @param {Vector3} [poleAxis] - The pole axis.
  18148. */
  18149. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  18150. const pingPongRenderTarget = this._pingPongRenderTarget;
  18151. this._halfBlur(
  18152. cubeUVRenderTarget,
  18153. pingPongRenderTarget,
  18154. lodIn,
  18155. lodOut,
  18156. sigma,
  18157. 'latitudinal',
  18158. poleAxis );
  18159. this._halfBlur(
  18160. pingPongRenderTarget,
  18161. cubeUVRenderTarget,
  18162. lodOut,
  18163. lodOut,
  18164. sigma,
  18165. 'longitudinal',
  18166. poleAxis );
  18167. }
  18168. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  18169. const renderer = this._renderer;
  18170. const blurMaterial = this._blurMaterial;
  18171. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  18172. error( 'blur direction must be either latitudinal or longitudinal!' );
  18173. }
  18174. // Number of standard deviations at which to cut off the discrete approximation.
  18175. const STANDARD_DEVIATIONS = 3;
  18176. const blurMesh = this._lodMeshes[ lodOut ];
  18177. blurMesh.material = blurMaterial;
  18178. const blurUniforms = _uniformsMap.get( blurMaterial );
  18179. const pixels = this._sizeLods[ lodIn ] - 1;
  18180. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  18181. const sigmaPixels = sigmaRadians / radiansPerPixel;
  18182. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  18183. if ( samples > MAX_SAMPLES ) {
  18184. warn( `sigmaRadians, ${
  18185. sigmaRadians}, is too large and will clip, as it requested ${
  18186. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  18187. }
  18188. const weights = [];
  18189. let sum = 0;
  18190. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  18191. const x = i / sigmaPixels;
  18192. const weight = Math.exp( - x * x / 2 );
  18193. weights.push( weight );
  18194. if ( i === 0 ) {
  18195. sum += weight;
  18196. } else if ( i < samples ) {
  18197. sum += 2 * weight;
  18198. }
  18199. }
  18200. for ( let i = 0; i < weights.length; i ++ ) {
  18201. weights[ i ] = weights[ i ] / sum;
  18202. }
  18203. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  18204. blurUniforms.envMap.value = targetIn.texture;
  18205. blurUniforms.samples.value = samples;
  18206. blurUniforms.weights.array = weights;
  18207. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  18208. if ( poleAxis ) {
  18209. blurUniforms.poleAxis.value = poleAxis;
  18210. }
  18211. const { _lodMax } = this;
  18212. blurUniforms.dTheta.value = radiansPerPixel;
  18213. blurUniforms.mipInt.value = _lodMax - lodIn;
  18214. const outputSize = this._sizeLods[ lodOut ];
  18215. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  18216. const y = 4 * ( this._cubeSize - outputSize );
  18217. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  18218. renderer.setRenderTarget( targetOut );
  18219. renderer.render( blurMesh, _flatCamera );
  18220. }
  18221. }
  18222. function _createPlanes( lodMax ) {
  18223. const sizeLods = [];
  18224. const sigmas = [];
  18225. const lodMeshes = [];
  18226. let lod = lodMax;
  18227. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  18228. for ( let i = 0; i < totalLods; i ++ ) {
  18229. const sizeLod = Math.pow( 2, lod );
  18230. sizeLods.push( sizeLod );
  18231. let sigma = 1.0 / sizeLod;
  18232. if ( i > lodMax - LOD_MIN ) {
  18233. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  18234. } else if ( i === 0 ) {
  18235. sigma = 0;
  18236. }
  18237. sigmas.push( sigma );
  18238. const texelSize = 1.0 / ( sizeLod - 2 );
  18239. const min = - texelSize;
  18240. const max = 1 + texelSize;
  18241. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  18242. const cubeFaces = 6;
  18243. const vertices = 6;
  18244. const positionSize = 3;
  18245. const uvSize = 2;
  18246. const faceIndexSize = 1;
  18247. const position = new Float32Array( positionSize * vertices * cubeFaces );
  18248. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  18249. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  18250. for ( let face = 0; face < cubeFaces; face ++ ) {
  18251. const x = ( face % 3 ) * 2 / 3 - 1;
  18252. const y = face > 2 ? 0 : -1;
  18253. const coordinates = [
  18254. x, y, 0,
  18255. x + 2 / 3, y, 0,
  18256. x + 2 / 3, y + 1, 0,
  18257. x, y, 0,
  18258. x + 2 / 3, y + 1, 0,
  18259. x, y + 1, 0
  18260. ];
  18261. const faceIdx = _faceLib[ face ];
  18262. position.set( coordinates, positionSize * vertices * faceIdx );
  18263. uv.set( uv1, uvSize * vertices * faceIdx );
  18264. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  18265. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  18266. }
  18267. const planes = new BufferGeometry();
  18268. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  18269. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  18270. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  18271. lodMeshes.push( new Mesh( planes, null ) );
  18272. if ( lod > LOD_MIN ) {
  18273. lod --;
  18274. }
  18275. }
  18276. return { lodMeshes, sizeLods, sigmas };
  18277. }
  18278. function _createRenderTarget( width, height ) {
  18279. const params = {
  18280. magFilter: LinearFilter,
  18281. minFilter: LinearFilter,
  18282. generateMipmaps: false,
  18283. type: HalfFloatType,
  18284. format: RGBAFormat,
  18285. colorSpace: LinearSRGBColorSpace,
  18286. //depthBuffer: false
  18287. };
  18288. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  18289. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  18290. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  18291. cubeUVRenderTarget.texture.isPMREMTexture = true;
  18292. cubeUVRenderTarget.scissorTest = true;
  18293. return cubeUVRenderTarget;
  18294. }
  18295. function _setViewport( target, x, y, width, height ) {
  18296. target.viewport.set( x, y, width, height );
  18297. target.scissor.set( x, y, width, height );
  18298. }
  18299. function _getMaterial( type ) {
  18300. const material = new NodeMaterial();
  18301. material.depthTest = false;
  18302. material.depthWrite = false;
  18303. material.blending = NoBlending;
  18304. material.name = `PMREM_${ type }`;
  18305. return material;
  18306. }
  18307. function _getBlurShader( lodMax, width, height ) {
  18308. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  18309. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  18310. const dTheta = uniform( 0 );
  18311. const n = float( MAX_SAMPLES );
  18312. const latitudinal = uniform( 0 ); // false, bool
  18313. const samples = uniform( 1 ); // int
  18314. const envMap = texture();
  18315. const mipInt = uniform( 0 ); // int
  18316. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18317. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18318. const CUBEUV_MAX_MIP = float( lodMax );
  18319. const materialUniforms = {
  18320. n,
  18321. latitudinal,
  18322. weights,
  18323. poleAxis,
  18324. outputDirection: _outputDirection,
  18325. dTheta,
  18326. samples,
  18327. envMap,
  18328. mipInt,
  18329. CUBEUV_TEXEL_WIDTH,
  18330. CUBEUV_TEXEL_HEIGHT,
  18331. CUBEUV_MAX_MIP
  18332. };
  18333. const material = _getMaterial( 'blur' );
  18334. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  18335. _uniformsMap.set( material, materialUniforms );
  18336. return material;
  18337. }
  18338. function _getGGXShader( lodMax, width, height ) {
  18339. const envMap = texture();
  18340. const roughness = uniform( 0 );
  18341. const mipInt = uniform( 0 );
  18342. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18343. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18344. const CUBEUV_MAX_MIP = float( lodMax );
  18345. const materialUniforms = {
  18346. envMap,
  18347. roughness,
  18348. mipInt,
  18349. CUBEUV_TEXEL_WIDTH,
  18350. CUBEUV_TEXEL_HEIGHT,
  18351. CUBEUV_MAX_MIP
  18352. };
  18353. const material = _getMaterial( 'ggx' );
  18354. material.fragmentNode = ggxConvolution( {
  18355. ...materialUniforms,
  18356. N_immutable: _outputDirection,
  18357. GGX_SAMPLES: uint( GGX_SAMPLES )
  18358. } );
  18359. _uniformsMap.set( material, materialUniforms );
  18360. return material;
  18361. }
  18362. function _getCubemapMaterial( envTexture ) {
  18363. const material = _getMaterial( 'cubemap' );
  18364. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  18365. return material;
  18366. }
  18367. function _getEquirectMaterial( envTexture ) {
  18368. const material = _getMaterial( 'equirect' );
  18369. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  18370. return material;
  18371. }
  18372. const _cache = new WeakMap();
  18373. /**
  18374. * Generates the cubeUV size based on the given image height.
  18375. *
  18376. * @private
  18377. * @param {number} imageHeight - The image height.
  18378. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  18379. */
  18380. function _generateCubeUVSize( imageHeight ) {
  18381. const maxMip = Math.log2( imageHeight ) - 2;
  18382. const texelHeight = 1.0 / imageHeight;
  18383. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  18384. return { texelWidth, texelHeight, maxMip };
  18385. }
  18386. /**
  18387. * Generates a PMREM from the given texture.
  18388. *
  18389. * @private
  18390. * @param {Texture} texture - The texture to create the PMREM for.
  18391. * @param {Renderer} renderer - The renderer.
  18392. * @param {PMREMGenerator} generator - The PMREM generator.
  18393. * @return {?Texture} The PMREM.
  18394. */
  18395. function _getPMREMFromTexture( texture, renderer, generator ) {
  18396. const cache = _getCache( renderer );
  18397. let cacheTexture = cache.get( texture );
  18398. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  18399. if ( pmremVersion !== texture.pmremVersion ) {
  18400. const image = texture.image;
  18401. if ( texture.isCubeTexture ) {
  18402. if ( isCubeMapReady( image ) ) {
  18403. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  18404. } else {
  18405. return null;
  18406. }
  18407. } else {
  18408. if ( isEquirectangularMapReady( image ) ) {
  18409. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  18410. } else {
  18411. return null;
  18412. }
  18413. }
  18414. cacheTexture.pmremVersion = texture.pmremVersion;
  18415. cache.set( texture, cacheTexture );
  18416. }
  18417. return cacheTexture.texture;
  18418. }
  18419. /**
  18420. * Returns a cache that stores generated PMREMs for the respective textures.
  18421. * A cache must be maintained per renderer since PMREMs are render target textures
  18422. * which can't be shared across render contexts.
  18423. *
  18424. * @private
  18425. * @param {Renderer} renderer - The renderer.
  18426. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  18427. */
  18428. function _getCache( renderer ) {
  18429. let rendererCache = _cache.get( renderer );
  18430. if ( rendererCache === undefined ) {
  18431. rendererCache = new WeakMap();
  18432. _cache.set( renderer, rendererCache );
  18433. }
  18434. return rendererCache;
  18435. }
  18436. /**
  18437. * This node represents a PMREM which is a special type of preprocessed
  18438. * environment map intended for PBR materials.
  18439. *
  18440. * ```js
  18441. * const material = new MeshStandardNodeMaterial();
  18442. * material.envNode = pmremTexture( envMap );
  18443. * ```
  18444. *
  18445. * @augments TempNode
  18446. */
  18447. class PMREMNode extends TempNode {
  18448. static get type() {
  18449. return 'PMREMNode';
  18450. }
  18451. /**
  18452. * Constructs a new function overloading node.
  18453. *
  18454. * @param {Texture} value - The input texture.
  18455. * @param {Node<vec2>} [uvNode=null] - The uv node.
  18456. * @param {Node<float>} [levelNode=null] - The level node.
  18457. */
  18458. constructor( value, uvNode = null, levelNode = null ) {
  18459. super( 'vec3' );
  18460. /**
  18461. * Reference to the input texture.
  18462. *
  18463. * @private
  18464. * @type {Texture}
  18465. */
  18466. this._value = value;
  18467. /**
  18468. * Reference to the generated PMREM.
  18469. *
  18470. * @private
  18471. * @type {Texture | null}
  18472. * @default null
  18473. */
  18474. this._pmrem = null;
  18475. /**
  18476. * The uv node.
  18477. *
  18478. * @type {Node<vec2>}
  18479. */
  18480. this.uvNode = uvNode;
  18481. /**
  18482. * The level node.
  18483. *
  18484. * @type {Node<float>}
  18485. */
  18486. this.levelNode = levelNode;
  18487. /**
  18488. * Reference to a PMREM generator.
  18489. *
  18490. * @private
  18491. * @type {?PMREMGenerator}
  18492. * @default null
  18493. */
  18494. this._generator = null;
  18495. const defaultTexture = new Texture();
  18496. defaultTexture.isRenderTargetTexture = true;
  18497. /**
  18498. * The texture node holding the generated PMREM.
  18499. *
  18500. * @private
  18501. * @type {TextureNode}
  18502. */
  18503. this._texture = texture( defaultTexture );
  18504. /**
  18505. * A uniform representing the PMREM's width.
  18506. *
  18507. * @private
  18508. * @type {UniformNode<float>}
  18509. */
  18510. this._width = uniform( 0 );
  18511. /**
  18512. * A uniform representing the PMREM's height.
  18513. *
  18514. * @private
  18515. * @type {UniformNode<float>}
  18516. */
  18517. this._height = uniform( 0 );
  18518. /**
  18519. * A uniform representing the PMREM's max Mip.
  18520. *
  18521. * @private
  18522. * @type {UniformNode<float>}
  18523. */
  18524. this._maxMip = uniform( 0 );
  18525. /**
  18526. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  18527. *
  18528. * @type {string}
  18529. * @default 'render'
  18530. */
  18531. this.updateBeforeType = NodeUpdateType.RENDER;
  18532. }
  18533. set value( value ) {
  18534. this._value = value;
  18535. this._pmrem = null;
  18536. }
  18537. /**
  18538. * The node's texture value.
  18539. *
  18540. * @type {Texture}
  18541. */
  18542. get value() {
  18543. return this._value;
  18544. }
  18545. /**
  18546. * Uses the given PMREM texture to update internal values.
  18547. *
  18548. * @param {Texture} texture - The PMREM texture.
  18549. */
  18550. updateFromTexture( texture ) {
  18551. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  18552. this._texture.value = texture;
  18553. this._width.value = cubeUVSize.texelWidth;
  18554. this._height.value = cubeUVSize.texelHeight;
  18555. this._maxMip.value = cubeUVSize.maxMip;
  18556. }
  18557. updateBefore( frame ) {
  18558. let pmrem = this._pmrem;
  18559. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  18560. const texture = this._value;
  18561. if ( pmremVersion !== texture.pmremVersion ) {
  18562. if ( texture.isPMREMTexture === true ) {
  18563. pmrem = texture;
  18564. } else {
  18565. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  18566. }
  18567. if ( pmrem !== null ) {
  18568. this._pmrem = pmrem;
  18569. this.updateFromTexture( pmrem );
  18570. }
  18571. }
  18572. }
  18573. setup( builder ) {
  18574. if ( this._generator === null ) {
  18575. this._generator = new PMREMGenerator( builder.renderer );
  18576. }
  18577. this.updateBefore( builder );
  18578. //
  18579. let uvNode = this.uvNode;
  18580. if ( uvNode === null && builder.context.getUV ) {
  18581. uvNode = builder.context.getUV( this, builder );
  18582. }
  18583. //
  18584. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  18585. //
  18586. let levelNode = this.levelNode;
  18587. if ( levelNode === null && builder.context.getTextureLevel ) {
  18588. levelNode = builder.context.getTextureLevel( this );
  18589. }
  18590. //
  18591. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  18592. }
  18593. dispose() {
  18594. super.dispose();
  18595. if ( this._generator !== null ) this._generator.dispose();
  18596. }
  18597. }
  18598. /**
  18599. * Returns `true` if the given cube map image has been fully loaded.
  18600. *
  18601. * @private
  18602. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  18603. * @return {boolean} Whether the given cube map is ready or not.
  18604. */
  18605. function isCubeMapReady( image ) {
  18606. if ( image === null || image === undefined ) return false;
  18607. let count = 0;
  18608. const length = 6;
  18609. for ( let i = 0; i < length; i ++ ) {
  18610. if ( image[ i ] !== undefined ) count ++;
  18611. }
  18612. return count === length;
  18613. }
  18614. /**
  18615. * Returns `true` if the given equirectangular image has been fully loaded.
  18616. *
  18617. * @private
  18618. * @param {(Image|Object)} image - The equirectangular image.
  18619. * @return {boolean} Whether the given cube map is ready or not.
  18620. */
  18621. function isEquirectangularMapReady( image ) {
  18622. if ( image === null || image === undefined ) return false;
  18623. return image.height > 0;
  18624. }
  18625. /**
  18626. * TSL function for creating a PMREM node.
  18627. *
  18628. * @tsl
  18629. * @function
  18630. * @param {Texture} value - The input texture.
  18631. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  18632. * @param {?Node<float>} [levelNode=null] - The level node.
  18633. * @returns {PMREMNode}
  18634. */
  18635. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  18636. const _envNodeCache = new WeakMap();
  18637. /**
  18638. * Represents a physical model for Image-based lighting (IBL). The environment
  18639. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  18640. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  18641. *
  18642. * @augments LightingNode
  18643. */
  18644. class EnvironmentNode extends LightingNode {
  18645. static get type() {
  18646. return 'EnvironmentNode';
  18647. }
  18648. /**
  18649. * Constructs a new environment node.
  18650. *
  18651. * @param {Node} [envNode=null] - A node representing the environment.
  18652. */
  18653. constructor( envNode = null ) {
  18654. super();
  18655. /**
  18656. * A node representing the environment.
  18657. *
  18658. * @type {?Node}
  18659. * @default null
  18660. */
  18661. this.envNode = envNode;
  18662. }
  18663. setup( builder ) {
  18664. const { material } = builder;
  18665. let envNode = this.envNode;
  18666. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  18667. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  18668. let cacheEnvNode = _envNodeCache.get( value );
  18669. if ( cacheEnvNode === undefined ) {
  18670. cacheEnvNode = pmremTexture( value );
  18671. _envNodeCache.set( value, cacheEnvNode );
  18672. }
  18673. envNode = cacheEnvNode;
  18674. }
  18675. //
  18676. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  18677. const radianceNormalView = useAnisotropy ? bentNormalView : normalView;
  18678. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  18679. const irradiance = envNode.context( createIrradianceContext( normalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  18680. const isolateRadiance = isolate( radiance );
  18681. const isolateIrradiance = isolate( irradiance );
  18682. //
  18683. builder.context.radiance.addAssign( isolateRadiance );
  18684. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  18685. //
  18686. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  18687. if ( clearcoatRadiance ) {
  18688. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, clearcoatNormalView ) ).mul( materialEnvIntensity );
  18689. const isolateClearcoatRadiance = isolate( clearcoatRadianceContext );
  18690. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  18691. }
  18692. }
  18693. }
  18694. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  18695. let reflectVec = null;
  18696. return {
  18697. getUV: () => {
  18698. if ( reflectVec === null ) {
  18699. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  18700. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  18701. reflectVec = pow4( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  18702. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  18703. }
  18704. return reflectVec;
  18705. },
  18706. getTextureLevel: () => {
  18707. return roughnessNode;
  18708. }
  18709. };
  18710. };
  18711. const createIrradianceContext = ( normalWorldNode ) => {
  18712. return {
  18713. getUV: () => {
  18714. return normalWorldNode;
  18715. },
  18716. getTextureLevel: () => {
  18717. return float( 1.0 );
  18718. }
  18719. };
  18720. };
  18721. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  18722. /**
  18723. * Node material version of {@link MeshStandardMaterial}.
  18724. *
  18725. * @augments NodeMaterial
  18726. */
  18727. class MeshStandardNodeMaterial extends NodeMaterial {
  18728. static get type() {
  18729. return 'MeshStandardNodeMaterial';
  18730. }
  18731. /**
  18732. * Constructs a new mesh standard node material.
  18733. *
  18734. * @param {Object} [parameters] - The configuration parameter.
  18735. */
  18736. constructor( parameters ) {
  18737. super();
  18738. /**
  18739. * This flag can be used for type testing.
  18740. *
  18741. * @type {boolean}
  18742. * @readonly
  18743. * @default true
  18744. */
  18745. this.isMeshStandardNodeMaterial = true;
  18746. /**
  18747. * Set to `true` because standard materials react on lights.
  18748. *
  18749. * @type {boolean}
  18750. * @default true
  18751. */
  18752. this.lights = true;
  18753. /**
  18754. * The emissive color of standard materials is by default inferred from the `emissive`,
  18755. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  18756. * overwrite the default and define the emissive color with a node instead.
  18757. *
  18758. * If you don't want to overwrite the emissive color but modify the existing
  18759. * value instead, use {@link materialEmissive}.
  18760. *
  18761. * @type {?Node<vec3>}
  18762. * @default null
  18763. */
  18764. this.emissiveNode = null;
  18765. /**
  18766. * The metalness of standard materials is by default inferred from the `metalness`,
  18767. * and `metalnessMap` properties. This node property allows to
  18768. * overwrite the default and define the metalness with a node instead.
  18769. *
  18770. * If you don't want to overwrite the metalness but modify the existing
  18771. * value instead, use {@link materialMetalness}.
  18772. *
  18773. * @type {?Node<float>}
  18774. * @default null
  18775. */
  18776. this.metalnessNode = null;
  18777. /**
  18778. * The roughness of standard materials is by default inferred from the `roughness`,
  18779. * and `roughnessMap` properties. This node property allows to
  18780. * overwrite the default and define the roughness with a node instead.
  18781. *
  18782. * If you don't want to overwrite the roughness but modify the existing
  18783. * value instead, use {@link materialRoughness}.
  18784. *
  18785. * @type {?Node<float>}
  18786. * @default null
  18787. */
  18788. this.roughnessNode = null;
  18789. this.setDefaultValues( _defaultValues$6 );
  18790. this.setValues( parameters );
  18791. }
  18792. /**
  18793. * Overwritten since this type of material uses {@link EnvironmentNode}
  18794. * to implement the PBR (PMREM based) environment mapping. Besides, the
  18795. * method honors `Scene.environment`.
  18796. *
  18797. * @param {NodeBuilder} builder - The current node builder.
  18798. * @return {?EnvironmentNode<vec3>} The environment node.
  18799. */
  18800. setupEnvironment( builder ) {
  18801. let envNode = super.setupEnvironment( builder );
  18802. if ( envNode === null && builder.environmentNode ) {
  18803. envNode = builder.environmentNode;
  18804. }
  18805. return envNode ? new EnvironmentNode( envNode ) : null;
  18806. }
  18807. /**
  18808. * Setups the lighting model.
  18809. *
  18810. * @return {PhysicalLightingModel} The lighting model.
  18811. */
  18812. setupLightingModel( /*builder*/ ) {
  18813. return new PhysicalLightingModel();
  18814. }
  18815. /**
  18816. * Setups the specular related node variables.
  18817. */
  18818. setupSpecular() {
  18819. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  18820. specularColor.assign( vec3( 0.04 ) );
  18821. specularColorBlended.assign( specularColorNode );
  18822. specularF90.assign( 1.0 );
  18823. }
  18824. /**
  18825. * Setups the standard specific node variables.
  18826. *
  18827. * @param {NodeBuilder} builder - The current node builder.
  18828. */
  18829. setupVariants() {
  18830. // METALNESS
  18831. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  18832. metalness.assign( metalnessNode );
  18833. // ROUGHNESS
  18834. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  18835. roughnessNode = getRoughness( { roughness: roughnessNode } );
  18836. roughness.assign( roughnessNode );
  18837. // SPECULAR COLOR
  18838. this.setupSpecular();
  18839. // DIFFUSE COLOR
  18840. diffuseContribution.assign( diffuseColor.rgb.mul( metalnessNode.oneMinus() ) );
  18841. }
  18842. copy( source ) {
  18843. this.emissiveNode = source.emissiveNode;
  18844. this.metalnessNode = source.metalnessNode;
  18845. this.roughnessNode = source.roughnessNode;
  18846. return super.copy( source );
  18847. }
  18848. }
  18849. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  18850. /**
  18851. * Node material version of {@link MeshPhysicalMaterial}.
  18852. *
  18853. * @augments MeshStandardNodeMaterial
  18854. */
  18855. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  18856. static get type() {
  18857. return 'MeshPhysicalNodeMaterial';
  18858. }
  18859. /**
  18860. * Constructs a new mesh physical node material.
  18861. *
  18862. * @param {Object} [parameters] - The configuration parameter.
  18863. */
  18864. constructor( parameters ) {
  18865. super();
  18866. /**
  18867. * This flag can be used for type testing.
  18868. *
  18869. * @type {boolean}
  18870. * @readonly
  18871. * @default true
  18872. */
  18873. this.isMeshPhysicalNodeMaterial = true;
  18874. /**
  18875. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  18876. * and `clearcoatMap` properties. This node property allows to overwrite the default
  18877. * and define the clearcoat with a node instead.
  18878. *
  18879. * If you don't want to overwrite the clearcoat but modify the existing
  18880. * value instead, use {@link materialClearcoat}.
  18881. *
  18882. * @type {?Node<float>}
  18883. * @default null
  18884. */
  18885. this.clearcoatNode = null;
  18886. /**
  18887. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  18888. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  18889. * and define the clearcoat roughness with a node instead.
  18890. *
  18891. * If you don't want to overwrite the clearcoat roughness but modify the existing
  18892. * value instead, use {@link materialClearcoatRoughness}.
  18893. *
  18894. * @type {?Node<float>}
  18895. * @default null
  18896. */
  18897. this.clearcoatRoughnessNode = null;
  18898. /**
  18899. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  18900. * property. This node property allows to overwrite the default
  18901. * and define the clearcoat normal with a node instead.
  18902. *
  18903. * If you don't want to overwrite the clearcoat normal but modify the existing
  18904. * value instead, use {@link materialClearcoatNormal}.
  18905. *
  18906. * @type {?Node<vec3>}
  18907. * @default null
  18908. */
  18909. this.clearcoatNormalNode = null;
  18910. /**
  18911. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  18912. * and `sheenColorMap` properties. This node property allows to overwrite the default
  18913. * and define the sheen with a node instead.
  18914. *
  18915. * If you don't want to overwrite the sheen but modify the existing
  18916. * value instead, use {@link materialSheen}.
  18917. *
  18918. * @type {?Node<vec3>}
  18919. * @default null
  18920. */
  18921. this.sheenNode = null;
  18922. /**
  18923. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  18924. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  18925. * and define the sheen roughness with a node instead.
  18926. *
  18927. * If you don't want to overwrite the sheen roughness but modify the existing
  18928. * value instead, use {@link materialSheenRoughness}.
  18929. *
  18930. * @type {?Node<float>}
  18931. * @default null
  18932. */
  18933. this.sheenRoughnessNode = null;
  18934. /**
  18935. * The iridescence of physical materials is by default inferred from the `iridescence`
  18936. * property. This node property allows to overwrite the default
  18937. * and define the iridescence with a node instead.
  18938. *
  18939. * If you don't want to overwrite the iridescence but modify the existing
  18940. * value instead, use {@link materialIridescence}.
  18941. *
  18942. * @type {?Node<float>}
  18943. * @default null
  18944. */
  18945. this.iridescenceNode = null;
  18946. /**
  18947. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  18948. * property. This node property allows to overwrite the default
  18949. * and define the iridescence IOR with a node instead.
  18950. *
  18951. * If you don't want to overwrite the iridescence IOR but modify the existing
  18952. * value instead, use {@link materialIridescenceIOR}.
  18953. *
  18954. * @type {?Node<float>}
  18955. * @default null
  18956. */
  18957. this.iridescenceIORNode = null;
  18958. /**
  18959. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  18960. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  18961. * and define the iridescence thickness with a node instead.
  18962. *
  18963. * If you don't want to overwrite the iridescence thickness but modify the existing
  18964. * value instead, use {@link materialIridescenceThickness}.
  18965. *
  18966. * @type {?Node<float>}
  18967. * @default null
  18968. */
  18969. this.iridescenceThicknessNode = null;
  18970. /**
  18971. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  18972. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  18973. * and define the specular intensity with a node instead.
  18974. *
  18975. * If you don't want to overwrite the specular intensity but modify the existing
  18976. * value instead, use {@link materialSpecularIntensity}.
  18977. *
  18978. * @type {?Node<float>}
  18979. * @default null
  18980. */
  18981. this.specularIntensityNode = null;
  18982. /**
  18983. * The specular color of physical materials is by default inferred from the `specularColor`
  18984. * and `specularColorMap` properties. This node property allows to overwrite the default
  18985. * and define the specular color with a node instead.
  18986. *
  18987. * If you don't want to overwrite the specular color but modify the existing
  18988. * value instead, use {@link materialSpecularColor}.
  18989. *
  18990. * @type {?Node<vec3>}
  18991. * @default null
  18992. */
  18993. this.specularColorNode = null;
  18994. /**
  18995. * The ior of physical materials is by default inferred from the `ior`
  18996. * property. This node property allows to overwrite the default
  18997. * and define the ior with a node instead.
  18998. *
  18999. * If you don't want to overwrite the ior but modify the existing
  19000. * value instead, use {@link materialIOR}.
  19001. *
  19002. * @type {?Node<float>}
  19003. * @default null
  19004. */
  19005. this.iorNode = null;
  19006. /**
  19007. * The transmission of physical materials is by default inferred from the `transmission` and
  19008. * `transmissionMap` properties. This node property allows to overwrite the default
  19009. * and define the transmission with a node instead.
  19010. *
  19011. * If you don't want to overwrite the transmission but modify the existing
  19012. * value instead, use {@link materialTransmission}.
  19013. *
  19014. * @type {?Node<float>}
  19015. * @default null
  19016. */
  19017. this.transmissionNode = null;
  19018. /**
  19019. * The thickness of physical materials is by default inferred from the `thickness` and
  19020. * `thicknessMap` properties. This node property allows to overwrite the default
  19021. * and define the thickness with a node instead.
  19022. *
  19023. * If you don't want to overwrite the thickness but modify the existing
  19024. * value instead, use {@link materialThickness}.
  19025. *
  19026. * @type {?Node<float>}
  19027. * @default null
  19028. */
  19029. this.thicknessNode = null;
  19030. /**
  19031. * The attenuation distance of physical materials is by default inferred from the
  19032. * `attenuationDistance` property. This node property allows to overwrite the default
  19033. * and define the attenuation distance with a node instead.
  19034. *
  19035. * If you don't want to overwrite the attenuation distance but modify the existing
  19036. * value instead, use {@link materialAttenuationDistance}.
  19037. *
  19038. * @type {?Node<float>}
  19039. * @default null
  19040. */
  19041. this.attenuationDistanceNode = null;
  19042. /**
  19043. * The attenuation color of physical materials is by default inferred from the
  19044. * `attenuationColor` property. This node property allows to overwrite the default
  19045. * and define the attenuation color with a node instead.
  19046. *
  19047. * If you don't want to overwrite the attenuation color but modify the existing
  19048. * value instead, use {@link materialAttenuationColor}.
  19049. *
  19050. * @type {?Node<vec3>}
  19051. * @default null
  19052. */
  19053. this.attenuationColorNode = null;
  19054. /**
  19055. * The dispersion of physical materials is by default inferred from the
  19056. * `dispersion` property. This node property allows to overwrite the default
  19057. * and define the dispersion with a node instead.
  19058. *
  19059. * If you don't want to overwrite the dispersion but modify the existing
  19060. * value instead, use {@link materialDispersion}.
  19061. *
  19062. * @type {?Node<float>}
  19063. * @default null
  19064. */
  19065. this.dispersionNode = null;
  19066. /**
  19067. * The anisotropy of physical materials is by default inferred from the
  19068. * `anisotropy` property. This node property allows to overwrite the default
  19069. * and define the anisotropy with a node instead.
  19070. *
  19071. * If you don't want to overwrite the anisotropy but modify the existing
  19072. * value instead, use {@link materialAnisotropy}.
  19073. *
  19074. * @type {?Node<float>}
  19075. * @default null
  19076. */
  19077. this.anisotropyNode = null;
  19078. this.setDefaultValues( _defaultValues$5 );
  19079. this.setValues( parameters );
  19080. }
  19081. /**
  19082. * Whether the lighting model should use clearcoat or not.
  19083. *
  19084. * @type {boolean}
  19085. * @default true
  19086. */
  19087. get useClearcoat() {
  19088. return this.clearcoat > 0 || this.clearcoatNode !== null;
  19089. }
  19090. /**
  19091. * Whether the lighting model should use iridescence or not.
  19092. *
  19093. * @type {boolean}
  19094. * @default true
  19095. */
  19096. get useIridescence() {
  19097. return this.iridescence > 0 || this.iridescenceNode !== null;
  19098. }
  19099. /**
  19100. * Whether the lighting model should use sheen or not.
  19101. *
  19102. * @type {boolean}
  19103. * @default true
  19104. */
  19105. get useSheen() {
  19106. return this.sheen > 0 || this.sheenNode !== null;
  19107. }
  19108. /**
  19109. * Whether the lighting model should use anisotropy or not.
  19110. *
  19111. * @type {boolean}
  19112. * @default true
  19113. */
  19114. get useAnisotropy() {
  19115. return this.anisotropy > 0 || this.anisotropyNode !== null;
  19116. }
  19117. /**
  19118. * Whether the lighting model should use transmission or not.
  19119. *
  19120. * @type {boolean}
  19121. * @default true
  19122. */
  19123. get useTransmission() {
  19124. return this.transmission > 0 || this.transmissionNode !== null;
  19125. }
  19126. /**
  19127. * Whether the lighting model should use dispersion or not.
  19128. *
  19129. * @type {boolean}
  19130. * @default true
  19131. */
  19132. get useDispersion() {
  19133. return this.dispersion > 0 || this.dispersionNode !== null;
  19134. }
  19135. /**
  19136. * Setups the specular related node variables.
  19137. */
  19138. setupSpecular() {
  19139. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  19140. ior.assign( iorNode );
  19141. specularColor.assign( min$1( pow2( ior.sub( 1.0 ).div( ior.add( 1.0 ) ) ).mul( materialSpecularColor ), vec3( 1.0 ) ).mul( materialSpecularIntensity ) );
  19142. specularColorBlended.assign( mix( specularColor, diffuseColor.rgb, metalness ) );
  19143. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  19144. }
  19145. /**
  19146. * Setups the lighting model.
  19147. *
  19148. * @return {PhysicalLightingModel} The lighting model.
  19149. */
  19150. setupLightingModel( /*builder*/ ) {
  19151. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  19152. }
  19153. /**
  19154. * Setups the physical specific node variables.
  19155. *
  19156. * @param {NodeBuilder} builder - The current node builder.
  19157. */
  19158. setupVariants( builder ) {
  19159. super.setupVariants( builder );
  19160. // CLEARCOAT
  19161. if ( this.useClearcoat ) {
  19162. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  19163. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  19164. clearcoat.assign( clearcoatNode );
  19165. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  19166. }
  19167. // SHEEN
  19168. if ( this.useSheen ) {
  19169. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  19170. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  19171. sheen.assign( sheenNode );
  19172. sheenRoughness.assign( sheenRoughnessNode );
  19173. }
  19174. // IRIDESCENCE
  19175. if ( this.useIridescence ) {
  19176. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  19177. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  19178. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  19179. iridescence.assign( iridescenceNode );
  19180. iridescenceIOR.assign( iridescenceIORNode );
  19181. iridescenceThickness.assign( iridescenceThicknessNode );
  19182. }
  19183. // ANISOTROPY
  19184. if ( this.useAnisotropy ) {
  19185. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  19186. anisotropy.assign( anisotropyV.length() );
  19187. If( anisotropy.equal( 0.0 ), () => {
  19188. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  19189. } ).Else( () => {
  19190. anisotropyV.divAssign( vec2( anisotropy ) );
  19191. anisotropy.assign( anisotropy.saturate() );
  19192. } );
  19193. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  19194. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  19195. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  19196. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  19197. }
  19198. // TRANSMISSION
  19199. if ( this.useTransmission ) {
  19200. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  19201. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  19202. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  19203. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  19204. transmission.assign( transmissionNode );
  19205. thickness.assign( thicknessNode );
  19206. attenuationDistance.assign( attenuationDistanceNode );
  19207. attenuationColor.assign( attenuationColorNode );
  19208. if ( this.useDispersion ) {
  19209. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  19210. dispersion.assign( dispersionNode );
  19211. }
  19212. }
  19213. }
  19214. /**
  19215. * Setups the clearcoat normal node.
  19216. *
  19217. * @return {Node<vec3>} The clearcoat normal.
  19218. */
  19219. setupClearcoatNormal() {
  19220. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  19221. }
  19222. setup( builder ) {
  19223. builder.context.setupClearcoatNormal = () => subBuild( this.setupClearcoatNormal( builder ), 'NORMAL', 'vec3' );
  19224. super.setup( builder );
  19225. }
  19226. copy( source ) {
  19227. this.clearcoatNode = source.clearcoatNode;
  19228. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  19229. this.clearcoatNormalNode = source.clearcoatNormalNode;
  19230. this.sheenNode = source.sheenNode;
  19231. this.sheenRoughnessNode = source.sheenRoughnessNode;
  19232. this.iridescenceNode = source.iridescenceNode;
  19233. this.iridescenceIORNode = source.iridescenceIORNode;
  19234. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  19235. this.specularIntensityNode = source.specularIntensityNode;
  19236. this.specularColorNode = source.specularColorNode;
  19237. this.transmissionNode = source.transmissionNode;
  19238. this.thicknessNode = source.thicknessNode;
  19239. this.attenuationDistanceNode = source.attenuationDistanceNode;
  19240. this.attenuationColorNode = source.attenuationColorNode;
  19241. this.dispersionNode = source.dispersionNode;
  19242. this.anisotropyNode = source.anisotropyNode;
  19243. return super.copy( source );
  19244. }
  19245. }
  19246. /**
  19247. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  19248. *
  19249. * @augments PhysicalLightingModel
  19250. */
  19251. class SSSLightingModel extends PhysicalLightingModel {
  19252. /**
  19253. * Constructs a new physical lighting model.
  19254. *
  19255. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  19256. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  19257. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  19258. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  19259. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  19260. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  19261. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  19262. */
  19263. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  19264. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  19265. /**
  19266. * Whether the lighting model should use SSS or not.
  19267. *
  19268. * @type {boolean}
  19269. * @default false
  19270. */
  19271. this.useSSS = sss;
  19272. }
  19273. /**
  19274. * Extends the default implementation with a SSS term.
  19275. *
  19276. * 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/)
  19277. *
  19278. * @param {Object} input - The input data.
  19279. * @param {NodeBuilder} builder - The current node builder.
  19280. */
  19281. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  19282. if ( this.useSSS === true ) {
  19283. const material = builder.material;
  19284. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  19285. const scatteringHalf = lightDirection.add( normalView.mul( thicknessDistortionNode ) ).normalize();
  19286. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  19287. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  19288. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  19289. }
  19290. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  19291. }
  19292. }
  19293. /**
  19294. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  19295. * that implements a Subsurface scattering (SSS) term.
  19296. *
  19297. * @augments MeshPhysicalNodeMaterial
  19298. */
  19299. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  19300. static get type() {
  19301. return 'MeshSSSNodeMaterial';
  19302. }
  19303. /**
  19304. * Constructs a new mesh SSS node material.
  19305. *
  19306. * @param {Object} [parameters] - The configuration parameter.
  19307. */
  19308. constructor( parameters ) {
  19309. super( parameters );
  19310. /**
  19311. * Represents the thickness color.
  19312. *
  19313. * @type {?Node<vec3>}
  19314. * @default null
  19315. */
  19316. this.thicknessColorNode = null;
  19317. /**
  19318. * Represents the distortion factor.
  19319. *
  19320. * @type {?Node<float>}
  19321. */
  19322. this.thicknessDistortionNode = float( 0.1 );
  19323. /**
  19324. * Represents the thickness ambient factor.
  19325. *
  19326. * @type {?Node<float>}
  19327. */
  19328. this.thicknessAmbientNode = float( 0.0 );
  19329. /**
  19330. * Represents the thickness attenuation.
  19331. *
  19332. * @type {?Node<float>}
  19333. */
  19334. this.thicknessAttenuationNode = float( .1 );
  19335. /**
  19336. * Represents the thickness power.
  19337. *
  19338. * @type {?Node<float>}
  19339. */
  19340. this.thicknessPowerNode = float( 2.0 );
  19341. /**
  19342. * Represents the thickness scale.
  19343. *
  19344. * @type {?Node<float>}
  19345. */
  19346. this.thicknessScaleNode = float( 10.0 );
  19347. }
  19348. /**
  19349. * Whether the lighting model should use SSS or not.
  19350. *
  19351. * @type {boolean}
  19352. * @default true
  19353. */
  19354. get useSSS() {
  19355. return this.thicknessColorNode !== null;
  19356. }
  19357. /**
  19358. * Setups the lighting model.
  19359. *
  19360. * @return {SSSLightingModel} The lighting model.
  19361. */
  19362. setupLightingModel( /*builder*/ ) {
  19363. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  19364. }
  19365. copy( source ) {
  19366. this.thicknessColorNode = source.thicknessColorNode;
  19367. this.thicknessDistortionNode = source.thicknessDistortionNode;
  19368. this.thicknessAmbientNode = source.thicknessAmbientNode;
  19369. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  19370. this.thicknessPowerNode = source.thicknessPowerNode;
  19371. this.thicknessScaleNode = source.thicknessScaleNode;
  19372. return super.copy( source );
  19373. }
  19374. }
  19375. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  19376. // dotNL will be from -1.0 to 1.0
  19377. const dotNL = normal.dot( lightDirection );
  19378. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  19379. if ( builder.material.gradientMap ) {
  19380. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  19381. return vec3( gradientMap.r );
  19382. } else {
  19383. const fw = coord.fwidth().mul( 0.5 );
  19384. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  19385. }
  19386. } );
  19387. /**
  19388. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  19389. *
  19390. * @augments LightingModel
  19391. */
  19392. class ToonLightingModel extends LightingModel {
  19393. /**
  19394. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  19395. * reduced to a small number of discrete shades to create a comic-like, flat look.
  19396. *
  19397. * @param {Object} lightData - The light data.
  19398. * @param {NodeBuilder} builder - The current node builder.
  19399. */
  19400. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  19401. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  19402. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  19403. }
  19404. /**
  19405. * Implements the indirect lighting.
  19406. *
  19407. * @param {NodeBuilder} builder - The current node builder.
  19408. */
  19409. indirect( builder ) {
  19410. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  19411. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  19412. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  19413. }
  19414. }
  19415. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  19416. /**
  19417. * Node material version of {@link MeshToonMaterial}.
  19418. *
  19419. * @augments NodeMaterial
  19420. */
  19421. class MeshToonNodeMaterial extends NodeMaterial {
  19422. static get type() {
  19423. return 'MeshToonNodeMaterial';
  19424. }
  19425. /**
  19426. * Constructs a new mesh toon node material.
  19427. *
  19428. * @param {Object} [parameters] - The configuration parameter.
  19429. */
  19430. constructor( parameters ) {
  19431. super();
  19432. /**
  19433. * This flag can be used for type testing.
  19434. *
  19435. * @type {boolean}
  19436. * @readonly
  19437. * @default true
  19438. */
  19439. this.isMeshToonNodeMaterial = true;
  19440. /**
  19441. * Set to `true` because toon materials react on lights.
  19442. *
  19443. * @type {boolean}
  19444. * @default true
  19445. */
  19446. this.lights = true;
  19447. this.setDefaultValues( _defaultValues$4 );
  19448. this.setValues( parameters );
  19449. }
  19450. /**
  19451. * Setups the lighting model.
  19452. *
  19453. * @return {ToonLightingModel} The lighting model.
  19454. */
  19455. setupLightingModel( /*builder*/ ) {
  19456. return new ToonLightingModel();
  19457. }
  19458. }
  19459. /**
  19460. * TSL function for creating a matcap uv node.
  19461. *
  19462. * Can be used to compute texture coordinates for projecting a
  19463. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  19464. *
  19465. * @tsl
  19466. * @function
  19467. * @returns {Node<vec2>} The matcap UV coordinates.
  19468. */
  19469. const matcapUV = /*@__PURE__*/ Fn( () => {
  19470. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  19471. const y = positionViewDirection.cross( x );
  19472. return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  19473. } ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' );
  19474. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  19475. /**
  19476. * Node material version of {@link MeshMatcapMaterial}.
  19477. *
  19478. * @augments NodeMaterial
  19479. */
  19480. class MeshMatcapNodeMaterial extends NodeMaterial {
  19481. static get type() {
  19482. return 'MeshMatcapNodeMaterial';
  19483. }
  19484. /**
  19485. * Constructs a new mesh normal node material.
  19486. *
  19487. * @param {Object} [parameters] - The configuration parameter.
  19488. */
  19489. constructor( parameters ) {
  19490. super();
  19491. /**
  19492. * This flag can be used for type testing.
  19493. *
  19494. * @type {boolean}
  19495. * @readonly
  19496. * @default true
  19497. */
  19498. this.isMeshMatcapNodeMaterial = true;
  19499. this.setDefaultValues( _defaultValues$3 );
  19500. this.setValues( parameters );
  19501. }
  19502. /**
  19503. * Setups the matcap specific node variables.
  19504. *
  19505. * @param {NodeBuilder} builder - The current node builder.
  19506. */
  19507. setupVariants( builder ) {
  19508. const uv = matcapUV;
  19509. let matcapColor;
  19510. if ( builder.material.matcap ) {
  19511. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  19512. } else {
  19513. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  19514. }
  19515. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  19516. }
  19517. }
  19518. /**
  19519. * Applies a rotation to the given position node.
  19520. *
  19521. * @augments TempNode
  19522. */
  19523. class RotateNode extends TempNode {
  19524. static get type() {
  19525. return 'RotateNode';
  19526. }
  19527. /**
  19528. * Constructs a new rotate node.
  19529. *
  19530. * @param {Node} positionNode - The position node.
  19531. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  19532. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19533. */
  19534. constructor( positionNode, rotationNode ) {
  19535. super();
  19536. /**
  19537. * The position node.
  19538. *
  19539. * @type {Node}
  19540. */
  19541. this.positionNode = positionNode;
  19542. /**
  19543. * Represents the rotation that is applied to the position node.
  19544. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19545. *
  19546. * @type {Node}
  19547. */
  19548. this.rotationNode = rotationNode;
  19549. }
  19550. /**
  19551. * The type of the {@link RotateNode#positionNode} defines the node's type.
  19552. *
  19553. * @param {NodeBuilder} builder - The current node builder.
  19554. * @return {string} The node's type.
  19555. */
  19556. getNodeType( builder ) {
  19557. return this.positionNode.getNodeType( builder );
  19558. }
  19559. setup( builder ) {
  19560. const { rotationNode, positionNode } = this;
  19561. const nodeType = this.getNodeType( builder );
  19562. if ( nodeType === 'vec2' ) {
  19563. const cosAngle = rotationNode.cos();
  19564. const sinAngle = rotationNode.sin();
  19565. const rotationMatrix = mat2(
  19566. cosAngle, sinAngle,
  19567. sinAngle.negate(), cosAngle
  19568. );
  19569. return rotationMatrix.mul( positionNode );
  19570. } else {
  19571. const rotation = rotationNode;
  19572. 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 ) );
  19573. 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 ) );
  19574. 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 ) );
  19575. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  19576. }
  19577. }
  19578. }
  19579. /**
  19580. * TSL function for creating a rotate node.
  19581. *
  19582. * @tsl
  19583. * @function
  19584. * @param {Node} positionNode - The position node.
  19585. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  19586. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19587. * @returns {RotateNode}
  19588. */
  19589. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  19590. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  19591. /**
  19592. * Node material version of {@link SpriteMaterial}.
  19593. *
  19594. * @augments NodeMaterial
  19595. */
  19596. class SpriteNodeMaterial extends NodeMaterial {
  19597. static get type() {
  19598. return 'SpriteNodeMaterial';
  19599. }
  19600. /**
  19601. * Constructs a new sprite node material.
  19602. *
  19603. * @param {Object} [parameters] - The configuration parameter.
  19604. */
  19605. constructor( parameters ) {
  19606. super();
  19607. /**
  19608. * This flag can be used for type testing.
  19609. *
  19610. * @type {boolean}
  19611. * @readonly
  19612. * @default true
  19613. */
  19614. this.isSpriteNodeMaterial = true;
  19615. this._useSizeAttenuation = true;
  19616. /**
  19617. * This property makes it possible to define the position of the sprite with a
  19618. * node. That can be useful when the material is used with instanced rendering
  19619. * and node data are defined with an instanced attribute node:
  19620. * ```js
  19621. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  19622. * material.positionNode = instancedBufferAttribute( positionAttribute );
  19623. * ```
  19624. * Another possibility is to compute the instanced data with a compute shader:
  19625. * ```js
  19626. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  19627. * particleMaterial.positionNode = positionBuffer.toAttribute();
  19628. * ```
  19629. *
  19630. * @type {?Node<vec2>}
  19631. * @default null
  19632. */
  19633. this.positionNode = null;
  19634. /**
  19635. * The rotation of sprite materials is by default inferred from the `rotation`,
  19636. * property. This node property allows to overwrite the default and define
  19637. * the rotation with a node instead.
  19638. *
  19639. * If you don't want to overwrite the rotation but modify the existing
  19640. * value instead, use {@link materialRotation}.
  19641. *
  19642. * @type {?Node<float>}
  19643. * @default null
  19644. */
  19645. this.rotationNode = null;
  19646. /**
  19647. * This node property provides an additional way to scale sprites next to
  19648. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  19649. * is multiplied with the scale value of this node in the vertex shader.
  19650. *
  19651. * @type {?Node<vec2>}
  19652. * @default null
  19653. */
  19654. this.scaleNode = null;
  19655. /**
  19656. * In Sprites, the transparent property is enabled by default.
  19657. *
  19658. * @type {boolean}
  19659. * @default true
  19660. */
  19661. this.transparent = true;
  19662. this.setDefaultValues( _defaultValues$2 );
  19663. this.setValues( parameters );
  19664. }
  19665. /**
  19666. * Setups the position node in view space. This method implements
  19667. * the sprite specific vertex shader.
  19668. *
  19669. * @param {NodeBuilder} builder - The current node builder.
  19670. * @return {Node<vec3>} The position in view space.
  19671. */
  19672. setupPositionView( builder ) {
  19673. const { object, camera } = builder;
  19674. const { positionNode, rotationNode, scaleNode, sizeAttenuation } = this;
  19675. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  19676. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  19677. if ( scaleNode !== null ) {
  19678. scale = scale.mul( vec2( scaleNode ) );
  19679. }
  19680. if ( camera.isPerspectiveCamera && sizeAttenuation === false ) {
  19681. scale = scale.mul( mvPosition.z.negate() );
  19682. }
  19683. let alignedPosition = positionGeometry.xy;
  19684. if ( object.center && object.center.isVector2 === true ) {
  19685. const center = reference$1( 'center', 'vec2', object );
  19686. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  19687. }
  19688. alignedPosition = alignedPosition.mul( scale );
  19689. const rotation = float( rotationNode || materialRotation );
  19690. const rotatedPosition = rotate( alignedPosition, rotation );
  19691. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  19692. }
  19693. copy( source ) {
  19694. this.positionNode = source.positionNode;
  19695. this.rotationNode = source.rotationNode;
  19696. this.scaleNode = source.scaleNode;
  19697. return super.copy( source );
  19698. }
  19699. /**
  19700. * Whether to use size attenuation or not.
  19701. *
  19702. * @type {boolean}
  19703. * @default true
  19704. */
  19705. get sizeAttenuation() {
  19706. return this._useSizeAttenuation;
  19707. }
  19708. set sizeAttenuation( value ) {
  19709. if ( this._useSizeAttenuation !== value ) {
  19710. this._useSizeAttenuation = value;
  19711. this.needsUpdate = true;
  19712. }
  19713. }
  19714. }
  19715. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  19716. const _size$4 = /*@__PURE__*/ new Vector2();
  19717. /**
  19718. * Node material version of {@link PointsMaterial}.
  19719. *
  19720. * This material can be used in two ways:
  19721. *
  19722. * - By rendering point primitives with {@link Points}. Since WebGPU only supports point primitives
  19723. * with a pixel size of `1`, it's not possible to define a size.
  19724. *
  19725. * ```js
  19726. * const pointCloud = new THREE.Points( geometry, new THREE.PointsNodeMaterial() );
  19727. * ```
  19728. *
  19729. * - By rendering point primitives with {@link Sprites}. In this case, size is honored,
  19730. * see {@link PointsNodeMaterial#sizeNode}.
  19731. *
  19732. * ```js
  19733. * const instancedPoints = new THREE.Sprite( new THREE.PointsNodeMaterial( { positionNode: instancedBufferAttribute( positionAttribute ) } ) );
  19734. * ```
  19735. *
  19736. * @augments SpriteNodeMaterial
  19737. */
  19738. class PointsNodeMaterial extends SpriteNodeMaterial {
  19739. static get type() {
  19740. return 'PointsNodeMaterial';
  19741. }
  19742. /**
  19743. * Constructs a new points node material.
  19744. *
  19745. * @param {Object} [parameters] - The configuration parameter.
  19746. */
  19747. constructor( parameters ) {
  19748. super();
  19749. /**
  19750. * This node property provides an additional way to set the point size.
  19751. *
  19752. * Note that WebGPU only supports point primitives with 1 pixel size. Consequently,
  19753. * this node has no effect when the material is used with {@link Points} and a WebGPU
  19754. * backend. If an application wants to render points with a size larger than 1 pixel,
  19755. * the material should be used with {@link Sprite} and instancing.
  19756. *
  19757. * @type {?Node<vec2>}
  19758. * @default null
  19759. */
  19760. this.sizeNode = null;
  19761. /**
  19762. * This flag can be used for type testing.
  19763. *
  19764. * @type {boolean}
  19765. * @readonly
  19766. * @default true
  19767. */
  19768. this.isPointsNodeMaterial = true;
  19769. this.setDefaultValues( _defaultValues$1 );
  19770. this.setValues( parameters );
  19771. }
  19772. setupPositionView() {
  19773. const { positionNode } = this;
  19774. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  19775. }
  19776. setupVertexSprite( builder ) {
  19777. const { material, camera } = builder;
  19778. const { rotationNode, scaleNode, sizeNode, sizeAttenuation } = this;
  19779. let mvp = super.setupVertex( builder );
  19780. // skip further processing if the material is not a node material
  19781. if ( material.isNodeMaterial !== true ) {
  19782. return mvp;
  19783. }
  19784. // point size
  19785. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  19786. pointSize = pointSize.mul( screenDPR );
  19787. // size attenuation
  19788. if ( camera.isPerspectiveCamera && sizeAttenuation === true ) {
  19789. // follow WebGLRenderer's implementation, and scale by half the canvas height in logical units
  19790. pointSize = pointSize.mul( scale.div( positionView.z.negate() ) );
  19791. }
  19792. // scale
  19793. if ( scaleNode && scaleNode.isNode ) {
  19794. pointSize = pointSize.mul( vec2( scaleNode ) );
  19795. }
  19796. // compute offset
  19797. let offset = positionGeometry.xy;
  19798. // apply rotation
  19799. if ( rotationNode && rotationNode.isNode ) {
  19800. const rotation = float( rotationNode );
  19801. offset = rotate( offset, rotation );
  19802. }
  19803. // account for point size
  19804. offset = offset.mul( pointSize );
  19805. // scale by viewport size
  19806. offset = offset.div( viewportSize.div( 2 ) );
  19807. // compensate for the perspective divide
  19808. offset = offset.mul( mvp.w );
  19809. // add offset
  19810. mvp = mvp.add( vec4( offset, 0, 0 ) );
  19811. return mvp;
  19812. }
  19813. setupVertex( builder ) {
  19814. if ( builder.object.isPoints ) {
  19815. return super.setupVertex( builder );
  19816. } else {
  19817. return this.setupVertexSprite( builder );
  19818. }
  19819. }
  19820. /**
  19821. * Whether alpha to coverage should be used or not.
  19822. *
  19823. * @type {boolean}
  19824. * @default true
  19825. */
  19826. get alphaToCoverage() {
  19827. return this._useAlphaToCoverage;
  19828. }
  19829. set alphaToCoverage( value ) {
  19830. if ( this._useAlphaToCoverage !== value ) {
  19831. this._useAlphaToCoverage = value;
  19832. this.needsUpdate = true;
  19833. }
  19834. }
  19835. }
  19836. const scale = /*@__PURE__*/ uniform( 1 ).onFrameUpdate( function ( { renderer } ) {
  19837. const size = renderer.getSize( _size$4 ); // logical units
  19838. this.value = 0.5 * size.y;
  19839. } );
  19840. /**
  19841. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  19842. *
  19843. * @augments LightingModel
  19844. */
  19845. class ShadowMaskModel extends LightingModel {
  19846. /**
  19847. * Constructs a new shadow mask model.
  19848. */
  19849. constructor() {
  19850. super();
  19851. /**
  19852. * The shadow mask node.
  19853. *
  19854. * @type {Node}
  19855. */
  19856. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  19857. }
  19858. /**
  19859. * Only used to save the shadow mask.
  19860. *
  19861. * @param {Object} input - The input data.
  19862. */
  19863. direct( { lightNode } ) {
  19864. if ( lightNode.shadowNode !== null ) {
  19865. this.shadowNode.mulAssign( lightNode.shadowNode );
  19866. }
  19867. }
  19868. /**
  19869. * Uses the shadow mask to produce the final color.
  19870. *
  19871. * @param {NodeBuilder} builder - The current node builder.
  19872. */
  19873. finish( { context } ) {
  19874. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  19875. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  19876. }
  19877. }
  19878. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  19879. /**
  19880. * Node material version of {@link ShadowMaterial}.
  19881. *
  19882. * @augments NodeMaterial
  19883. */
  19884. class ShadowNodeMaterial extends NodeMaterial {
  19885. static get type() {
  19886. return 'ShadowNodeMaterial';
  19887. }
  19888. /**
  19889. * Constructs a new shadow node material.
  19890. *
  19891. * @param {Object} [parameters] - The configuration parameter.
  19892. */
  19893. constructor( parameters ) {
  19894. super();
  19895. /**
  19896. * This flag can be used for type testing.
  19897. *
  19898. * @type {boolean}
  19899. * @readonly
  19900. * @default true
  19901. */
  19902. this.isShadowNodeMaterial = true;
  19903. /**
  19904. * Set to `true` because so it's possible to implement
  19905. * the shadow mask effect.
  19906. *
  19907. * @type {boolean}
  19908. * @default true
  19909. */
  19910. this.lights = true;
  19911. /**
  19912. * Overwritten since shadow materials are transparent
  19913. * by default.
  19914. *
  19915. * @type {boolean}
  19916. * @default true
  19917. */
  19918. this.transparent = true;
  19919. this.setDefaultValues( _defaultValues );
  19920. this.setValues( parameters );
  19921. }
  19922. /**
  19923. * Setups the lighting model.
  19924. *
  19925. * @return {ShadowMaskModel} The lighting model.
  19926. */
  19927. setupLightingModel( /*builder*/ ) {
  19928. return new ShadowMaskModel();
  19929. }
  19930. }
  19931. const scatteringDensity = property( 'vec3' );
  19932. const linearDepthRay = property( 'vec3' );
  19933. const outgoingRayLight = property( 'vec3' );
  19934. /**
  19935. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  19936. * This model calculates the scattering and transmittance of light through a volumetric medium.
  19937. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  19938. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  19939. *
  19940. * @augments LightingModel
  19941. */
  19942. class VolumetricLightingModel extends LightingModel {
  19943. constructor() {
  19944. super();
  19945. }
  19946. start( builder ) {
  19947. const { material } = builder;
  19948. const startPos = property( 'vec3' );
  19949. const endPos = property( 'vec3' );
  19950. // This approach dynamically changes the direction of the ray,
  19951. // 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.
  19952. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  19953. startPos.assign( cameraPosition );
  19954. endPos.assign( positionWorld );
  19955. } ).Else( () => {
  19956. startPos.assign( positionWorld );
  19957. endPos.assign( cameraPosition );
  19958. } );
  19959. //
  19960. const viewVector = endPos.sub( startPos );
  19961. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  19962. const stepSize = viewVector.length().div( steps ).toVar();
  19963. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  19964. const distTravelled = float( 0.0 ).toVar();
  19965. const transmittance = vec3( 1 ).toVar();
  19966. if ( material.offsetNode ) {
  19967. // reduce banding
  19968. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  19969. }
  19970. Loop( steps, () => {
  19971. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  19972. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  19973. if ( material.depthNode !== null ) {
  19974. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  19975. builder.context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  19976. }
  19977. builder.context.positionWorld = positionRay;
  19978. builder.context.shadowPositionWorld = positionRay;
  19979. builder.context.positionView = positionViewRay;
  19980. scatteringDensity.assign( 0 );
  19981. let scatteringNode;
  19982. if ( material.scatteringNode ) {
  19983. scatteringNode = material.scatteringNode( {
  19984. positionRay
  19985. } );
  19986. }
  19987. super.start( builder );
  19988. if ( scatteringNode ) {
  19989. scatteringDensity.mulAssign( scatteringNode );
  19990. }
  19991. // beer's law
  19992. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  19993. transmittance.mulAssign( falloff );
  19994. // move along the ray
  19995. distTravelled.addAssign( stepSize );
  19996. } );
  19997. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  19998. }
  19999. scatteringLight( lightColor, builder ) {
  20000. const sceneDepthNode = builder.context.sceneDepthNode;
  20001. if ( sceneDepthNode ) {
  20002. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  20003. scatteringDensity.addAssign( lightColor );
  20004. } );
  20005. } else {
  20006. scatteringDensity.addAssign( lightColor );
  20007. }
  20008. }
  20009. direct( { lightNode, lightColor }, builder ) {
  20010. // Ignore lights with infinite distance
  20011. if ( lightNode.light.distance === undefined ) return;
  20012. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  20013. const directLight = lightColor.xyz.toVar();
  20014. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  20015. this.scatteringLight( directLight, builder );
  20016. }
  20017. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  20018. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  20019. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  20020. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  20021. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  20022. const P = builder.context.positionView;
  20023. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  20024. this.scatteringLight( directLight, builder );
  20025. }
  20026. finish( builder ) {
  20027. builder.context.outgoingLight.assign( outgoingRayLight );
  20028. }
  20029. }
  20030. /**
  20031. * Volume node material.
  20032. *
  20033. * @augments NodeMaterial
  20034. */
  20035. class VolumeNodeMaterial extends NodeMaterial {
  20036. static get type() {
  20037. return 'VolumeNodeMaterial';
  20038. }
  20039. /**
  20040. * Constructs a new volume node material.
  20041. *
  20042. * @param {Object} [parameters] - The configuration parameter.
  20043. */
  20044. constructor( parameters ) {
  20045. super();
  20046. /**
  20047. * This flag can be used for type testing.
  20048. *
  20049. * @type {boolean}
  20050. * @readonly
  20051. * @default true
  20052. */
  20053. this.isVolumeNodeMaterial = true;
  20054. /**
  20055. * Number of steps used for raymarching.
  20056. *
  20057. * @type {number}
  20058. * @default 25
  20059. */
  20060. this.steps = 25;
  20061. /**
  20062. * Offsets the distance a ray has been traveled through a volume.
  20063. * Can be used to implement dithering to reduce banding.
  20064. *
  20065. * @type {Node<float>}
  20066. * @default null
  20067. */
  20068. this.offsetNode = null;
  20069. /**
  20070. * Node used for scattering calculations.
  20071. *
  20072. * @type {Function|FunctionNode<vec4>}
  20073. * @default null
  20074. */
  20075. this.scatteringNode = null;
  20076. this.lights = true;
  20077. this.transparent = true;
  20078. this.side = BackSide;
  20079. this.depthTest = false;
  20080. this.depthWrite = false;
  20081. this.setValues( parameters );
  20082. }
  20083. setupLightingModel() {
  20084. return new VolumetricLightingModel();
  20085. }
  20086. }
  20087. /**
  20088. * This module manages the internal animation loop of the renderer.
  20089. *
  20090. * @private
  20091. */
  20092. class Animation {
  20093. /**
  20094. * Constructs a new animation loop management component.
  20095. *
  20096. * @param {Renderer} renderer - A reference to the main renderer.
  20097. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20098. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20099. */
  20100. constructor( renderer, nodes, info ) {
  20101. /**
  20102. * A reference to the main renderer.
  20103. *
  20104. * @type {Renderer}
  20105. */
  20106. this.renderer = renderer;
  20107. /**
  20108. * Renderer component for managing nodes related logic.
  20109. *
  20110. * @type {Nodes}
  20111. */
  20112. this.nodes = nodes;
  20113. /**
  20114. * Renderer component for managing metrics and monitoring data.
  20115. *
  20116. * @type {Info}
  20117. */
  20118. this.info = info;
  20119. /**
  20120. * A reference to the context from `requestAnimationFrame()` can
  20121. * be called (usually `window`).
  20122. *
  20123. * @type {?(Window|XRSession)}
  20124. */
  20125. this._context = typeof self !== 'undefined' ? self : null;
  20126. /**
  20127. * The user-defined animation loop.
  20128. *
  20129. * @type {?Function}
  20130. * @default null
  20131. */
  20132. this._animationLoop = null;
  20133. /**
  20134. * The requestId which is returned from the `requestAnimationFrame()` call.
  20135. * Can be used to cancel the stop the animation loop.
  20136. *
  20137. * @type {?number}
  20138. * @default null
  20139. */
  20140. this._requestId = null;
  20141. }
  20142. /**
  20143. * Starts the internal animation loop.
  20144. */
  20145. start() {
  20146. const update = ( time, xrFrame ) => {
  20147. this._requestId = this._context.requestAnimationFrame( update );
  20148. if ( this.info.autoReset === true ) this.info.reset();
  20149. this.nodes.nodeFrame.update();
  20150. this.info.frame = this.nodes.nodeFrame.frameId;
  20151. this.renderer._inspector.begin();
  20152. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  20153. this.renderer._inspector.finish();
  20154. };
  20155. update();
  20156. }
  20157. /**
  20158. * Stops the internal animation loop.
  20159. */
  20160. stop() {
  20161. this._context.cancelAnimationFrame( this._requestId );
  20162. this._requestId = null;
  20163. }
  20164. /**
  20165. * Returns the user-level animation loop.
  20166. *
  20167. * @return {?Function} The animation loop.
  20168. */
  20169. getAnimationLoop() {
  20170. return this._animationLoop;
  20171. }
  20172. /**
  20173. * Defines the user-level animation loop.
  20174. *
  20175. * @param {?Function} callback - The animation loop.
  20176. */
  20177. setAnimationLoop( callback ) {
  20178. this._animationLoop = callback;
  20179. }
  20180. /**
  20181. * Returns the animation context.
  20182. *
  20183. * @return {Window|XRSession} The animation context.
  20184. */
  20185. getContext() {
  20186. return this._context;
  20187. }
  20188. /**
  20189. * Defines the context in which `requestAnimationFrame()` is executed.
  20190. *
  20191. * @param {Window|XRSession} context - The context to set.
  20192. */
  20193. setContext( context ) {
  20194. this._context = context;
  20195. }
  20196. /**
  20197. * Frees all internal resources and stops the animation loop.
  20198. */
  20199. dispose() {
  20200. this.stop();
  20201. }
  20202. }
  20203. /**
  20204. * Data structure for the renderer. It allows defining values
  20205. * with chained, hierarchical keys. Keys are meant to be
  20206. * objects since the module internally works with Weak Maps
  20207. * for performance reasons.
  20208. *
  20209. * @private
  20210. */
  20211. class ChainMap {
  20212. /**
  20213. * Constructs a new Chain Map.
  20214. */
  20215. constructor() {
  20216. /**
  20217. * The root Weak Map.
  20218. *
  20219. * @type {WeakMap<Object, WeakMap>}
  20220. */
  20221. this.weakMap = new WeakMap();
  20222. }
  20223. /**
  20224. * Returns the value for the given array of keys.
  20225. *
  20226. * @param {Array<Object>} keys - List of keys.
  20227. * @return {any} The value. Returns `undefined` if no value was found.
  20228. */
  20229. get( keys ) {
  20230. let map = this.weakMap;
  20231. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20232. map = map.get( keys[ i ] );
  20233. if ( map === undefined ) return undefined;
  20234. }
  20235. return map.get( keys[ keys.length - 1 ] );
  20236. }
  20237. /**
  20238. * Sets the value for the given keys.
  20239. *
  20240. * @param {Array<Object>} keys - List of keys.
  20241. * @param {any} value - The value to set.
  20242. * @return {ChainMap} A reference to this Chain Map.
  20243. */
  20244. set( keys, value ) {
  20245. let map = this.weakMap;
  20246. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20247. const key = keys[ i ];
  20248. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  20249. map = map.get( key );
  20250. }
  20251. map.set( keys[ keys.length - 1 ], value );
  20252. return this;
  20253. }
  20254. /**
  20255. * Deletes a value for the given keys.
  20256. *
  20257. * @param {Array<Object>} keys - The keys.
  20258. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  20259. */
  20260. delete( keys ) {
  20261. let map = this.weakMap;
  20262. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20263. map = map.get( keys[ i ] );
  20264. if ( map === undefined ) return false;
  20265. }
  20266. return map.delete( keys[ keys.length - 1 ] );
  20267. }
  20268. }
  20269. let _id$a = 0;
  20270. function getKeys( obj ) {
  20271. const keys = Object.keys( obj );
  20272. let proto = Object.getPrototypeOf( obj );
  20273. while ( proto ) {
  20274. const descriptors = Object.getOwnPropertyDescriptors( proto );
  20275. for ( const key in descriptors ) {
  20276. if ( descriptors[ key ] !== undefined ) {
  20277. const descriptor = descriptors[ key ];
  20278. if ( descriptor && typeof descriptor.get === 'function' ) {
  20279. keys.push( key );
  20280. }
  20281. }
  20282. }
  20283. proto = Object.getPrototypeOf( proto );
  20284. }
  20285. return keys;
  20286. }
  20287. /**
  20288. * A render object is the renderer's representation of single entity that gets drawn
  20289. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  20290. * scene since render objects also depend from the used material, the current render context
  20291. * and the current scene's lighting.
  20292. *
  20293. * In general, the basic process of the renderer is:
  20294. *
  20295. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  20296. * - Process the render lists by calling one or more render commands for each render item.
  20297. * - For each render command, request a render object and perform the draw.
  20298. *
  20299. * The module provides an interface to get data required for the draw command like the actual
  20300. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  20301. * creating render objects should only be done when necessary.
  20302. *
  20303. * @private
  20304. */
  20305. class RenderObject {
  20306. /**
  20307. * Constructs a new render object.
  20308. *
  20309. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20310. * @param {Geometries} geometries - Renderer component for managing geometries.
  20311. * @param {Renderer} renderer - The renderer.
  20312. * @param {Object3D} object - The 3D object.
  20313. * @param {Material} material - The 3D object's material.
  20314. * @param {Scene} scene - The scene the 3D object belongs to.
  20315. * @param {Camera} camera - The camera the object should be rendered with.
  20316. * @param {LightsNode} lightsNode - The lights node.
  20317. * @param {RenderContext} renderContext - The render context.
  20318. * @param {ClippingContext} clippingContext - The clipping context.
  20319. */
  20320. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  20321. this.id = _id$a ++;
  20322. /**
  20323. * Renderer component for managing nodes related logic.
  20324. *
  20325. * @type {Nodes}
  20326. * @private
  20327. */
  20328. this._nodes = nodes;
  20329. /**
  20330. * Renderer component for managing geometries.
  20331. *
  20332. * @type {Geometries}
  20333. * @private
  20334. */
  20335. this._geometries = geometries;
  20336. /**
  20337. * The renderer.
  20338. *
  20339. * @type {Renderer}
  20340. */
  20341. this.renderer = renderer;
  20342. /**
  20343. * The 3D object.
  20344. *
  20345. * @type {Object3D}
  20346. */
  20347. this.object = object;
  20348. /**
  20349. * The 3D object's material.
  20350. *
  20351. * @type {Material}
  20352. */
  20353. this.material = material;
  20354. /**
  20355. * The scene the 3D object belongs to.
  20356. *
  20357. * @type {Scene}
  20358. */
  20359. this.scene = scene;
  20360. /**
  20361. * The camera the 3D object should be rendered with.
  20362. *
  20363. * @type {Camera}
  20364. */
  20365. this.camera = camera;
  20366. /**
  20367. * The lights node.
  20368. *
  20369. * @type {LightsNode}
  20370. */
  20371. this.lightsNode = lightsNode;
  20372. /**
  20373. * The render context.
  20374. *
  20375. * @type {RenderContext}
  20376. */
  20377. this.context = renderContext;
  20378. /**
  20379. * The 3D object's geometry.
  20380. *
  20381. * @type {BufferGeometry}
  20382. */
  20383. this.geometry = object.geometry;
  20384. /**
  20385. * The render object's version.
  20386. *
  20387. * @type {number}
  20388. */
  20389. this.version = material.version;
  20390. /**
  20391. * The draw range of the geometry.
  20392. *
  20393. * @type {?Object}
  20394. * @default null
  20395. */
  20396. this.drawRange = null;
  20397. /**
  20398. * An array holding the buffer attributes
  20399. * of the render object. This entails attribute
  20400. * definitions on geometry and node level.
  20401. *
  20402. * @type {?Array<BufferAttribute>}
  20403. * @default null
  20404. */
  20405. this.attributes = null;
  20406. /**
  20407. * An object holding the version of the
  20408. * attributes. The keys are the attribute names
  20409. * and the values are the attribute versions.
  20410. *
  20411. * @type {?Object<string, number>}
  20412. * @default null
  20413. */
  20414. this.attributesId = null;
  20415. /**
  20416. * A reference to a render pipeline the render
  20417. * object is processed with.
  20418. *
  20419. * @type {RenderPipeline}
  20420. * @default null
  20421. */
  20422. this.pipeline = null;
  20423. /**
  20424. * Only relevant for objects using
  20425. * multiple materials. This represents a group entry
  20426. * from the respective `BufferGeometry`.
  20427. *
  20428. * @type {?{start: number, count: number}}
  20429. * @default null
  20430. */
  20431. this.group = null;
  20432. /**
  20433. * An array holding the vertex buffers which can
  20434. * be buffer attributes but also interleaved buffers.
  20435. *
  20436. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  20437. * @default null
  20438. */
  20439. this.vertexBuffers = null;
  20440. /**
  20441. * The parameters for the draw command.
  20442. *
  20443. * @type {?Object}
  20444. * @default null
  20445. */
  20446. this.drawParams = null;
  20447. /**
  20448. * If this render object is used inside a render bundle,
  20449. * this property points to the respective bundle group.
  20450. *
  20451. * @type {?BundleGroup}
  20452. * @default null
  20453. */
  20454. this.bundle = null;
  20455. /**
  20456. * The clipping context.
  20457. *
  20458. * @type {ClippingContext}
  20459. */
  20460. this.clippingContext = clippingContext;
  20461. /**
  20462. * The clipping context's cache key.
  20463. *
  20464. * @type {string}
  20465. */
  20466. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  20467. /**
  20468. * The initial node cache key.
  20469. *
  20470. * @type {number}
  20471. */
  20472. this.initialNodesCacheKey = this.getDynamicCacheKey();
  20473. /**
  20474. * The initial cache key.
  20475. *
  20476. * @type {number}
  20477. */
  20478. this.initialCacheKey = this.getCacheKey();
  20479. /**
  20480. * The node builder state.
  20481. *
  20482. * @type {?NodeBuilderState}
  20483. * @private
  20484. * @default null
  20485. */
  20486. this._nodeBuilderState = null;
  20487. /**
  20488. * An array of bindings.
  20489. *
  20490. * @type {?Array<BindGroup>}
  20491. * @private
  20492. * @default null
  20493. */
  20494. this._bindings = null;
  20495. /**
  20496. * Reference to the node material observer.
  20497. *
  20498. * @type {?NodeMaterialObserver}
  20499. * @private
  20500. * @default null
  20501. */
  20502. this._monitor = null;
  20503. /**
  20504. * An event listener which is defined by `RenderObjects`. It performs
  20505. * clean up tasks when `dispose()` on this render object.
  20506. *
  20507. * @method
  20508. */
  20509. this.onDispose = null;
  20510. /**
  20511. * This flag can be used for type testing.
  20512. *
  20513. * @type {boolean}
  20514. * @readonly
  20515. * @default true
  20516. */
  20517. this.isRenderObject = true;
  20518. /**
  20519. * An event listener which is executed when `dispose()` is called on
  20520. * the material of this render object.
  20521. *
  20522. * @method
  20523. */
  20524. this.onMaterialDispose = () => {
  20525. this.dispose();
  20526. };
  20527. /**
  20528. * An event listener which is executed when `dispose()` is called on
  20529. * the geometry of this render object.
  20530. *
  20531. * @method
  20532. */
  20533. this.onGeometryDispose = () => {
  20534. // clear geometry cache attributes
  20535. this.attributes = null;
  20536. this.attributesId = null;
  20537. };
  20538. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  20539. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  20540. }
  20541. /**
  20542. * Updates the clipping context.
  20543. *
  20544. * @param {ClippingContext} context - The clipping context to set.
  20545. */
  20546. updateClipping( context ) {
  20547. this.clippingContext = context;
  20548. }
  20549. /**
  20550. * Whether the clipping requires an update or not.
  20551. *
  20552. * @type {boolean}
  20553. * @readonly
  20554. */
  20555. get clippingNeedsUpdate() {
  20556. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  20557. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  20558. return true;
  20559. }
  20560. /**
  20561. * The number of clipping planes defined in context of hardware clipping.
  20562. *
  20563. * @type {number}
  20564. * @readonly
  20565. */
  20566. get hardwareClippingPlanes() {
  20567. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  20568. }
  20569. /**
  20570. * Returns the node builder state of this render object.
  20571. *
  20572. * @return {NodeBuilderState} The node builder state.
  20573. */
  20574. getNodeBuilderState() {
  20575. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  20576. }
  20577. /**
  20578. * Returns the node material observer of this render object.
  20579. *
  20580. * @return {NodeMaterialObserver} The node material observer.
  20581. */
  20582. getMonitor() {
  20583. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  20584. }
  20585. /**
  20586. * Returns an array of bind groups of this render object.
  20587. *
  20588. * @return {Array<BindGroup>} The bindings.
  20589. */
  20590. getBindings() {
  20591. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  20592. }
  20593. /**
  20594. * Returns a binding group by group name of this render object.
  20595. *
  20596. * @param {string} name - The name of the binding group.
  20597. * @return {?BindGroup} The bindings.
  20598. */
  20599. getBindingGroup( name ) {
  20600. for ( const bindingGroup of this.getBindings() ) {
  20601. if ( bindingGroup.name === name ) {
  20602. return bindingGroup;
  20603. }
  20604. }
  20605. }
  20606. /**
  20607. * Returns the index of the render object's geometry.
  20608. *
  20609. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  20610. */
  20611. getIndex() {
  20612. return this._geometries.getIndex( this );
  20613. }
  20614. /**
  20615. * Returns the indirect buffer attribute.
  20616. *
  20617. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  20618. */
  20619. getIndirect() {
  20620. return this._geometries.getIndirect( this );
  20621. }
  20622. /**
  20623. * Returns the byte offset into the indirect attribute buffer.
  20624. *
  20625. * @return {number} The byte offset into the indirect attribute buffer.
  20626. */
  20627. getIndirectOffset() {
  20628. return this._geometries.getIndirectOffset( this );
  20629. }
  20630. /**
  20631. * Returns an array that acts as a key for identifying the render object in a chain map.
  20632. *
  20633. * @return {Array<Object>} An array with object references.
  20634. */
  20635. getChainArray() {
  20636. return [ this.object, this.material, this.context, this.lightsNode ];
  20637. }
  20638. /**
  20639. * This method is used when the geometry of a 3D object has been exchanged and the
  20640. * respective render object now requires an update.
  20641. *
  20642. * @param {BufferGeometry} geometry - The geometry to set.
  20643. */
  20644. setGeometry( geometry ) {
  20645. this.geometry = geometry;
  20646. this.attributes = null;
  20647. this.attributesId = null;
  20648. }
  20649. /**
  20650. * Returns the buffer attributes of the render object. The returned array holds
  20651. * attribute definitions on geometry and node level.
  20652. *
  20653. * @return {Array<BufferAttribute>} An array with buffer attributes.
  20654. */
  20655. getAttributes() {
  20656. if ( this.attributes !== null ) return this.attributes;
  20657. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  20658. const geometry = this.geometry;
  20659. const attributes = [];
  20660. const vertexBuffers = new Set();
  20661. const attributesId = {};
  20662. for ( const nodeAttribute of nodeAttributes ) {
  20663. let attribute;
  20664. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  20665. // node attribute
  20666. attribute = nodeAttribute.node.attribute;
  20667. } else {
  20668. // geometry attribute
  20669. attribute = geometry.getAttribute( nodeAttribute.name );
  20670. attributesId[ nodeAttribute.name ] = attribute.version;
  20671. }
  20672. if ( attribute === undefined ) continue;
  20673. attributes.push( attribute );
  20674. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  20675. vertexBuffers.add( bufferAttribute );
  20676. }
  20677. this.attributes = attributes;
  20678. this.attributesId = attributesId;
  20679. this.vertexBuffers = Array.from( vertexBuffers.values() );
  20680. return attributes;
  20681. }
  20682. /**
  20683. * Returns the vertex buffers of the render object.
  20684. *
  20685. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  20686. */
  20687. getVertexBuffers() {
  20688. if ( this.vertexBuffers === null ) this.getAttributes();
  20689. return this.vertexBuffers;
  20690. }
  20691. /**
  20692. * Returns the draw parameters for the render object.
  20693. *
  20694. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  20695. */
  20696. getDrawParameters() {
  20697. const { object, material, geometry, group, drawRange } = this;
  20698. const drawParams = this.drawParams || ( this.drawParams = {
  20699. vertexCount: 0,
  20700. firstVertex: 0,
  20701. instanceCount: 0,
  20702. firstInstance: 0
  20703. } );
  20704. const index = this.getIndex();
  20705. const hasIndex = ( index !== null );
  20706. let instanceCount = 1;
  20707. if ( geometry.isInstancedBufferGeometry === true ) {
  20708. instanceCount = geometry.instanceCount;
  20709. } else if ( object.count !== undefined ) {
  20710. instanceCount = Math.max( 0, object.count );
  20711. }
  20712. if ( instanceCount === 0 ) return null;
  20713. drawParams.instanceCount = instanceCount;
  20714. if ( object.isBatchedMesh === true ) return drawParams;
  20715. let rangeFactor = 1;
  20716. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  20717. rangeFactor = 2;
  20718. }
  20719. let firstVertex = drawRange.start * rangeFactor;
  20720. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  20721. if ( group !== null ) {
  20722. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  20723. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  20724. }
  20725. const position = geometry.attributes.position;
  20726. let itemCount = Infinity;
  20727. if ( hasIndex ) {
  20728. itemCount = index.count;
  20729. } else if ( position !== undefined && position !== null ) {
  20730. itemCount = position.count;
  20731. }
  20732. firstVertex = Math.max( firstVertex, 0 );
  20733. lastVertex = Math.min( lastVertex, itemCount );
  20734. const count = lastVertex - firstVertex;
  20735. if ( count < 0 || count === Infinity ) return null;
  20736. drawParams.vertexCount = count;
  20737. drawParams.firstVertex = firstVertex;
  20738. return drawParams;
  20739. }
  20740. /**
  20741. * Returns the render object's geometry cache key.
  20742. *
  20743. * The geometry cache key is part of the material cache key.
  20744. *
  20745. * @return {string} The geometry cache key.
  20746. */
  20747. getGeometryCacheKey() {
  20748. const { geometry } = this;
  20749. let cacheKey = '';
  20750. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  20751. const attribute = geometry.attributes[ name ];
  20752. cacheKey += name + ',';
  20753. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  20754. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  20755. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  20756. if ( attribute.normalized ) cacheKey += 'n,';
  20757. }
  20758. // structural equality isn't sufficient for morph targets since the
  20759. // data are maintained in textures. only if the targets are all equal
  20760. // the texture and thus the instance of `MorphNode` can be shared.
  20761. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  20762. const targets = geometry.morphAttributes[ name ];
  20763. cacheKey += 'morph-' + name + ',';
  20764. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  20765. const attribute = targets[ i ];
  20766. cacheKey += attribute.id + ',';
  20767. }
  20768. }
  20769. if ( geometry.index ) {
  20770. cacheKey += 'index,';
  20771. }
  20772. return cacheKey;
  20773. }
  20774. /**
  20775. * Returns the render object's material cache key.
  20776. *
  20777. * The material cache key is part of the render object cache key.
  20778. *
  20779. * @return {number} The material cache key.
  20780. */
  20781. getMaterialCacheKey() {
  20782. const { object, material, renderer } = this;
  20783. let cacheKey = material.customProgramCacheKey();
  20784. for ( const property of getKeys( material ) ) {
  20785. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  20786. const value = material[ property ];
  20787. let valueKey;
  20788. if ( value !== null ) {
  20789. // some material values require a formatting
  20790. const type = typeof value;
  20791. if ( type === 'number' ) {
  20792. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  20793. } else if ( type === 'object' ) {
  20794. valueKey = '{';
  20795. if ( value.isTexture ) {
  20796. valueKey += value.mapping;
  20797. // WebGPU must honor the sampler data because they are part of the bindings
  20798. if ( renderer.backend.isWebGPUBackend === true ) {
  20799. valueKey += value.magFilter;
  20800. valueKey += value.minFilter;
  20801. valueKey += value.wrapS;
  20802. valueKey += value.wrapT;
  20803. valueKey += value.wrapR;
  20804. }
  20805. }
  20806. valueKey += '}';
  20807. } else {
  20808. valueKey = String( value );
  20809. }
  20810. } else {
  20811. valueKey = String( value );
  20812. }
  20813. cacheKey += /*property + ':' +*/ valueKey + ',';
  20814. }
  20815. cacheKey += this.clippingContextCacheKey + ',';
  20816. if ( object.geometry ) {
  20817. cacheKey += this.getGeometryCacheKey();
  20818. }
  20819. if ( object.skeleton ) {
  20820. cacheKey += object.skeleton.bones.length + ',';
  20821. }
  20822. if ( object.isBatchedMesh ) {
  20823. cacheKey += object._matricesTexture.uuid + ',';
  20824. if ( object._colorsTexture !== null ) {
  20825. cacheKey += object._colorsTexture.uuid + ',';
  20826. }
  20827. }
  20828. if ( object.isInstancedMesh || object.count > 1 || Array.isArray( object.morphTargetInfluences ) ) {
  20829. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  20830. cacheKey += object.uuid + ',';
  20831. }
  20832. cacheKey += this.context.id + ',';
  20833. cacheKey += object.receiveShadow + ',';
  20834. return hashString( cacheKey );
  20835. }
  20836. /**
  20837. * Whether the geometry requires an update or not.
  20838. *
  20839. * @type {boolean}
  20840. * @readonly
  20841. */
  20842. get needsGeometryUpdate() {
  20843. if ( this.geometry.id !== this.object.geometry.id ) return true;
  20844. if ( this.attributes !== null ) {
  20845. const attributesId = this.attributesId;
  20846. for ( const name in attributesId ) {
  20847. const attribute = this.geometry.getAttribute( name );
  20848. if ( attribute === undefined || attributesId[ name ] !== attribute.id ) {
  20849. return true;
  20850. }
  20851. }
  20852. }
  20853. return false;
  20854. }
  20855. /**
  20856. * Whether the render object requires an update or not.
  20857. *
  20858. * Note: There are two distinct places where render objects are checked for an update.
  20859. *
  20860. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  20861. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  20862. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  20863. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  20864. * a need for a refresh due to material, geometry or object related value changes.
  20865. *
  20866. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  20867. * that performs the 'needsUpdate' check.
  20868. *
  20869. * @type {boolean}
  20870. * @readonly
  20871. */
  20872. get needsUpdate() {
  20873. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  20874. }
  20875. /**
  20876. * Returns the dynamic cache key which represents a key that is computed per draw command.
  20877. *
  20878. * @return {number} The cache key.
  20879. */
  20880. getDynamicCacheKey() {
  20881. let cacheKey = 0;
  20882. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  20883. // the renderer is inside a shadow pass.
  20884. if ( this.material.isShadowPassMaterial !== true ) {
  20885. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  20886. }
  20887. if ( this.camera.isArrayCamera ) {
  20888. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  20889. }
  20890. if ( this.object.receiveShadow ) {
  20891. cacheKey = hash$1( cacheKey, 1 );
  20892. }
  20893. cacheKey = hash$1( cacheKey, this.camera.id, this.renderer.contextNode.id, this.renderer.contextNode.version );
  20894. return cacheKey;
  20895. }
  20896. /**
  20897. * Returns the render object's cache key.
  20898. *
  20899. * @return {number} The cache key.
  20900. */
  20901. getCacheKey() {
  20902. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  20903. }
  20904. /**
  20905. * Frees internal resources.
  20906. */
  20907. dispose() {
  20908. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  20909. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  20910. this.onDispose();
  20911. }
  20912. }
  20913. const _chainKeys$5 = [];
  20914. /**
  20915. * This module manages the render objects of the renderer.
  20916. *
  20917. * @private
  20918. */
  20919. class RenderObjects {
  20920. /**
  20921. * Constructs a new render object management component.
  20922. *
  20923. * @param {Renderer} renderer - The renderer.
  20924. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20925. * @param {Geometries} geometries - Renderer component for managing geometries.
  20926. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  20927. * @param {Bindings} bindings - Renderer component for managing bindings.
  20928. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20929. */
  20930. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  20931. /**
  20932. * The renderer.
  20933. *
  20934. * @type {Renderer}
  20935. */
  20936. this.renderer = renderer;
  20937. /**
  20938. * Renderer component for managing nodes related logic.
  20939. *
  20940. * @type {Nodes}
  20941. */
  20942. this.nodes = nodes;
  20943. /**
  20944. * Renderer component for managing geometries.
  20945. *
  20946. * @type {Geometries}
  20947. */
  20948. this.geometries = geometries;
  20949. /**
  20950. * Renderer component for managing pipelines.
  20951. *
  20952. * @type {Pipelines}
  20953. */
  20954. this.pipelines = pipelines;
  20955. /**
  20956. * Renderer component for managing bindings.
  20957. *
  20958. * @type {Bindings}
  20959. */
  20960. this.bindings = bindings;
  20961. /**
  20962. * Renderer component for managing metrics and monitoring data.
  20963. *
  20964. * @type {Info}
  20965. */
  20966. this.info = info;
  20967. /**
  20968. * A dictionary that manages render contexts in chain maps
  20969. * for each pass ID.
  20970. *
  20971. * @type {Object<string,ChainMap>}
  20972. */
  20973. this.chainMaps = {};
  20974. }
  20975. /**
  20976. * Returns a render object for the given object and state data.
  20977. *
  20978. * @param {Object3D} object - The 3D object.
  20979. * @param {Material} material - The 3D object's material.
  20980. * @param {Scene} scene - The scene the 3D object belongs to.
  20981. * @param {Camera} camera - The camera the 3D object should be rendered with.
  20982. * @param {LightsNode} lightsNode - The lights node.
  20983. * @param {RenderContext} renderContext - The render context.
  20984. * @param {ClippingContext} clippingContext - The clipping context.
  20985. * @param {string} [passId] - An optional ID for identifying the pass.
  20986. * @return {RenderObject} The render object.
  20987. */
  20988. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  20989. const chainMap = this.getChainMap( passId );
  20990. // reuse chainArray
  20991. _chainKeys$5[ 0 ] = object;
  20992. _chainKeys$5[ 1 ] = material;
  20993. _chainKeys$5[ 2 ] = renderContext;
  20994. _chainKeys$5[ 3 ] = lightsNode;
  20995. let renderObject = chainMap.get( _chainKeys$5 );
  20996. if ( renderObject === undefined ) {
  20997. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  20998. chainMap.set( _chainKeys$5, renderObject );
  20999. } else {
  21000. renderObject.updateClipping( clippingContext );
  21001. if ( renderObject.needsGeometryUpdate ) {
  21002. renderObject.setGeometry( object.geometry );
  21003. }
  21004. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  21005. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  21006. renderObject.dispose();
  21007. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  21008. } else {
  21009. renderObject.version = material.version;
  21010. }
  21011. }
  21012. }
  21013. _chainKeys$5.length = 0;
  21014. return renderObject;
  21015. }
  21016. /**
  21017. * Returns a chain map for the given pass ID.
  21018. *
  21019. * @param {string} [passId='default'] - The pass ID.
  21020. * @return {ChainMap} The chain map.
  21021. */
  21022. getChainMap( passId = 'default' ) {
  21023. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  21024. }
  21025. /**
  21026. * Frees internal resources.
  21027. */
  21028. dispose() {
  21029. this.chainMaps = {};
  21030. }
  21031. /**
  21032. * Factory method for creating render objects with the given list of parameters.
  21033. *
  21034. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21035. * @param {Geometries} geometries - Renderer component for managing geometries.
  21036. * @param {Renderer} renderer - The renderer.
  21037. * @param {Object3D} object - The 3D object.
  21038. * @param {Material} material - The object's material.
  21039. * @param {Scene} scene - The scene the 3D object belongs to.
  21040. * @param {Camera} camera - The camera the object should be rendered with.
  21041. * @param {LightsNode} lightsNode - The lights node.
  21042. * @param {RenderContext} renderContext - The render context.
  21043. * @param {ClippingContext} clippingContext - The clipping context.
  21044. * @param {string} [passId] - An optional ID for identifying the pass.
  21045. * @return {RenderObject} The render object.
  21046. */
  21047. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  21048. const chainMap = this.getChainMap( passId );
  21049. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  21050. renderObject.onDispose = () => {
  21051. this.pipelines.delete( renderObject );
  21052. this.bindings.deleteForRender( renderObject );
  21053. this.nodes.delete( renderObject );
  21054. chainMap.delete( renderObject.getChainArray() );
  21055. };
  21056. return renderObject;
  21057. }
  21058. }
  21059. /**
  21060. * Data structure for the renderer. It is intended to manage
  21061. * data of objects in dictionaries.
  21062. *
  21063. * @private
  21064. */
  21065. class DataMap {
  21066. /**
  21067. * Constructs a new data map.
  21068. */
  21069. constructor() {
  21070. /**
  21071. * `DataMap` internally uses a weak map
  21072. * to manage its data.
  21073. *
  21074. * @type {WeakMap<Object, Object>}
  21075. */
  21076. this.data = new WeakMap();
  21077. }
  21078. /**
  21079. * Returns the dictionary for the given object.
  21080. *
  21081. * @param {Object} object - The object.
  21082. * @return {Object} The dictionary.
  21083. */
  21084. get( object ) {
  21085. let map = this.data.get( object );
  21086. if ( map === undefined ) {
  21087. map = {};
  21088. this.data.set( object, map );
  21089. }
  21090. return map;
  21091. }
  21092. /**
  21093. * Deletes the dictionary for the given object.
  21094. *
  21095. * @param {Object} object - The object.
  21096. * @return {?Object} The deleted dictionary.
  21097. */
  21098. delete( object ) {
  21099. let map = null;
  21100. if ( this.data.has( object ) ) {
  21101. map = this.data.get( object );
  21102. this.data.delete( object );
  21103. }
  21104. return map;
  21105. }
  21106. /**
  21107. * Returns `true` if the given object has a dictionary defined.
  21108. *
  21109. * @param {Object} object - The object to test.
  21110. * @return {boolean} Whether a dictionary is defined or not.
  21111. */
  21112. has( object ) {
  21113. return this.data.has( object );
  21114. }
  21115. /**
  21116. * Frees internal resources.
  21117. */
  21118. dispose() {
  21119. this.data = new WeakMap();
  21120. }
  21121. }
  21122. const AttributeType = {
  21123. VERTEX: 1,
  21124. INDEX: 2,
  21125. STORAGE: 3,
  21126. INDIRECT: 4
  21127. };
  21128. // size of a chunk in bytes (STD140 layout)
  21129. const GPU_CHUNK_BYTES = 16;
  21130. // @TODO: Move to src/constants.js
  21131. const BlendColorFactor = 211;
  21132. const OneMinusBlendColorFactor = 212;
  21133. /**
  21134. * This renderer module manages geometry attributes.
  21135. *
  21136. * @private
  21137. * @augments DataMap
  21138. */
  21139. class Attributes extends DataMap {
  21140. /**
  21141. * Constructs a new attribute management component.
  21142. *
  21143. * @param {Backend} backend - The renderer's backend.
  21144. */
  21145. constructor( backend ) {
  21146. super();
  21147. /**
  21148. * The renderer's backend.
  21149. *
  21150. * @type {Backend}
  21151. */
  21152. this.backend = backend;
  21153. }
  21154. /**
  21155. * Deletes the data for the given attribute.
  21156. *
  21157. * @param {BufferAttribute} attribute - The attribute.
  21158. * @return {?Object} The deleted attribute data.
  21159. */
  21160. delete( attribute ) {
  21161. const attributeData = super.delete( attribute );
  21162. if ( attributeData !== null ) {
  21163. this.backend.destroyAttribute( attribute );
  21164. }
  21165. return attributeData;
  21166. }
  21167. /**
  21168. * Updates the given attribute. This method creates attribute buffers
  21169. * for new attributes and updates data for existing ones.
  21170. *
  21171. * @param {BufferAttribute} attribute - The attribute to update.
  21172. * @param {number} type - The attribute type.
  21173. */
  21174. update( attribute, type ) {
  21175. const data = this.get( attribute );
  21176. if ( data.version === undefined ) {
  21177. if ( type === AttributeType.VERTEX ) {
  21178. this.backend.createAttribute( attribute );
  21179. } else if ( type === AttributeType.INDEX ) {
  21180. this.backend.createIndexAttribute( attribute );
  21181. } else if ( type === AttributeType.STORAGE ) {
  21182. this.backend.createStorageAttribute( attribute );
  21183. } else if ( type === AttributeType.INDIRECT ) {
  21184. this.backend.createIndirectStorageAttribute( attribute );
  21185. }
  21186. data.version = this._getBufferAttribute( attribute ).version;
  21187. } else {
  21188. const bufferAttribute = this._getBufferAttribute( attribute );
  21189. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  21190. this.backend.updateAttribute( attribute );
  21191. data.version = bufferAttribute.version;
  21192. }
  21193. }
  21194. }
  21195. /**
  21196. * Utility method for handling interleaved buffer attributes correctly.
  21197. * To process them, their `InterleavedBuffer` is returned.
  21198. *
  21199. * @param {BufferAttribute} attribute - The attribute.
  21200. * @return {BufferAttribute|InterleavedBuffer}
  21201. */
  21202. _getBufferAttribute( attribute ) {
  21203. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  21204. return attribute;
  21205. }
  21206. }
  21207. /**
  21208. * Returns the wireframe version for the given geometry.
  21209. *
  21210. * @private
  21211. * @function
  21212. * @param {BufferGeometry} geometry - The geometry.
  21213. * @return {number} The version.
  21214. */
  21215. function getWireframeVersion( geometry ) {
  21216. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  21217. }
  21218. /**
  21219. * Returns a wireframe index attribute for the given geometry.
  21220. *
  21221. * @private
  21222. * @function
  21223. * @param {BufferGeometry} geometry - The geometry.
  21224. * @return {BufferAttribute} The wireframe index attribute.
  21225. */
  21226. function getWireframeIndex( geometry ) {
  21227. const indices = [];
  21228. const geometryIndex = geometry.index;
  21229. const geometryPosition = geometry.attributes.position;
  21230. if ( geometryIndex !== null ) {
  21231. const array = geometryIndex.array;
  21232. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  21233. const a = array[ i + 0 ];
  21234. const b = array[ i + 1 ];
  21235. const c = array[ i + 2 ];
  21236. indices.push( a, b, b, c, c, a );
  21237. }
  21238. } else {
  21239. const array = geometryPosition.array;
  21240. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  21241. const a = i + 0;
  21242. const b = i + 1;
  21243. const c = i + 2;
  21244. indices.push( a, b, b, c, c, a );
  21245. }
  21246. }
  21247. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  21248. attribute.version = getWireframeVersion( geometry );
  21249. return attribute;
  21250. }
  21251. /**
  21252. * This renderer module manages geometries.
  21253. *
  21254. * @private
  21255. * @augments DataMap
  21256. */
  21257. class Geometries extends DataMap {
  21258. /**
  21259. * Constructs a new geometry management component.
  21260. *
  21261. * @param {Attributes} attributes - Renderer component for managing attributes.
  21262. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21263. */
  21264. constructor( attributes, info ) {
  21265. super();
  21266. /**
  21267. * Renderer component for managing attributes.
  21268. *
  21269. * @type {Attributes}
  21270. */
  21271. this.attributes = attributes;
  21272. /**
  21273. * Renderer component for managing metrics and monitoring data.
  21274. *
  21275. * @type {Info}
  21276. */
  21277. this.info = info;
  21278. /**
  21279. * Weak Map for managing attributes for wireframe rendering.
  21280. *
  21281. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  21282. */
  21283. this.wireframes = new WeakMap();
  21284. /**
  21285. * This Weak Map is used to make sure buffer attributes are
  21286. * updated only once per render call.
  21287. *
  21288. * @type {WeakMap<BufferAttribute,number>}
  21289. */
  21290. this.attributeCall = new WeakMap();
  21291. /**
  21292. * Stores the event listeners attached to geometries.
  21293. *
  21294. * @private
  21295. * @type {Map<BufferGeometry,Function>}
  21296. */
  21297. this._geometryDisposeListeners = new Map();
  21298. }
  21299. /**
  21300. * Returns `true` if the given render object has an initialized geometry.
  21301. *
  21302. * @param {RenderObject} renderObject - The render object.
  21303. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  21304. */
  21305. has( renderObject ) {
  21306. const geometry = renderObject.geometry;
  21307. return super.has( geometry ) && this.get( geometry ).initialized === true;
  21308. }
  21309. /**
  21310. * Prepares the geometry of the given render object for rendering.
  21311. *
  21312. * @param {RenderObject} renderObject - The render object.
  21313. */
  21314. updateForRender( renderObject ) {
  21315. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  21316. this.updateAttributes( renderObject );
  21317. }
  21318. /**
  21319. * Initializes the geometry of the given render object.
  21320. *
  21321. * @param {RenderObject} renderObject - The render object.
  21322. */
  21323. initGeometry( renderObject ) {
  21324. const geometry = renderObject.geometry;
  21325. const geometryData = this.get( geometry );
  21326. geometryData.initialized = true;
  21327. this.info.memory.geometries ++;
  21328. const onDispose = () => {
  21329. this.info.memory.geometries --;
  21330. const index = geometry.index;
  21331. const geometryAttributes = renderObject.getAttributes();
  21332. if ( index !== null ) {
  21333. this.attributes.delete( index );
  21334. }
  21335. for ( const geometryAttribute of geometryAttributes ) {
  21336. this.attributes.delete( geometryAttribute );
  21337. }
  21338. const wireframeAttribute = this.wireframes.get( geometry );
  21339. if ( wireframeAttribute !== undefined ) {
  21340. this.attributes.delete( wireframeAttribute );
  21341. }
  21342. geometry.removeEventListener( 'dispose', onDispose );
  21343. this._geometryDisposeListeners.delete( geometry );
  21344. };
  21345. geometry.addEventListener( 'dispose', onDispose );
  21346. // see #31798 why tracking separate remove listeners is required right now
  21347. // TODO: Re-evaluate how onDispose() is managed in this component
  21348. this._geometryDisposeListeners.set( geometry, onDispose );
  21349. }
  21350. /**
  21351. * Updates the geometry attributes of the given render object.
  21352. *
  21353. * @param {RenderObject} renderObject - The render object.
  21354. */
  21355. updateAttributes( renderObject ) {
  21356. // attributes
  21357. const attributes = renderObject.getAttributes();
  21358. for ( const attribute of attributes ) {
  21359. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  21360. this.updateAttribute( attribute, AttributeType.STORAGE );
  21361. } else {
  21362. this.updateAttribute( attribute, AttributeType.VERTEX );
  21363. }
  21364. }
  21365. // indexes
  21366. const index = this.getIndex( renderObject );
  21367. if ( index !== null ) {
  21368. this.updateAttribute( index, AttributeType.INDEX );
  21369. }
  21370. // indirect
  21371. const indirect = renderObject.geometry.indirect;
  21372. if ( indirect !== null ) {
  21373. this.updateAttribute( indirect, AttributeType.INDIRECT );
  21374. }
  21375. }
  21376. /**
  21377. * Updates the given attribute.
  21378. *
  21379. * @param {BufferAttribute} attribute - The attribute to update.
  21380. * @param {number} type - The attribute type.
  21381. */
  21382. updateAttribute( attribute, type ) {
  21383. const callId = this.info.render.calls;
  21384. if ( ! attribute.isInterleavedBufferAttribute ) {
  21385. if ( this.attributeCall.get( attribute ) !== callId ) {
  21386. this.attributes.update( attribute, type );
  21387. this.attributeCall.set( attribute, callId );
  21388. }
  21389. } else {
  21390. if ( this.attributeCall.get( attribute ) === undefined ) {
  21391. this.attributes.update( attribute, type );
  21392. this.attributeCall.set( attribute, callId );
  21393. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  21394. this.attributes.update( attribute, type );
  21395. this.attributeCall.set( attribute.data, callId );
  21396. this.attributeCall.set( attribute, callId );
  21397. }
  21398. }
  21399. }
  21400. /**
  21401. * Returns the indirect buffer attribute of the given render object.
  21402. *
  21403. * @param {RenderObject} renderObject - The render object.
  21404. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  21405. */
  21406. getIndirect( renderObject ) {
  21407. return renderObject.geometry.indirect;
  21408. }
  21409. /**
  21410. * Returns the byte offset into the indirect attribute buffer of the given render object.
  21411. *
  21412. * @param {RenderObject} renderObject - The render object.
  21413. * @return {number} The byte offset into the indirect attribute buffer.
  21414. */
  21415. getIndirectOffset( renderObject ) {
  21416. return renderObject.geometry.indirectOffset;
  21417. }
  21418. /**
  21419. * Returns the index of the given render object's geometry. This is implemented
  21420. * in a method to return a wireframe index if necessary.
  21421. *
  21422. * @param {RenderObject} renderObject - The render object.
  21423. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  21424. */
  21425. getIndex( renderObject ) {
  21426. const { geometry, material } = renderObject;
  21427. let index = geometry.index;
  21428. if ( material.wireframe === true ) {
  21429. const wireframes = this.wireframes;
  21430. let wireframeAttribute = wireframes.get( geometry );
  21431. if ( wireframeAttribute === undefined ) {
  21432. wireframeAttribute = getWireframeIndex( geometry );
  21433. wireframes.set( geometry, wireframeAttribute );
  21434. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  21435. this.attributes.delete( wireframeAttribute );
  21436. wireframeAttribute = getWireframeIndex( geometry );
  21437. wireframes.set( geometry, wireframeAttribute );
  21438. }
  21439. index = wireframeAttribute;
  21440. }
  21441. return index;
  21442. }
  21443. dispose() {
  21444. for ( const [ geometry, onDispose ] of this._geometryDisposeListeners.entries() ) {
  21445. geometry.removeEventListener( 'dispose', onDispose );
  21446. }
  21447. this._geometryDisposeListeners.clear();
  21448. }
  21449. }
  21450. /**
  21451. * This renderer module provides a series of statistical information
  21452. * about the GPU memory and the rendering process. Useful for debugging
  21453. * and monitoring.
  21454. */
  21455. class Info {
  21456. /**
  21457. * Constructs a new info component.
  21458. */
  21459. constructor() {
  21460. /**
  21461. * Whether frame related metrics should automatically
  21462. * be resetted or not. This property should be set to `false`
  21463. * by apps which manage their own animation loop. They must
  21464. * then call `renderer.info.reset()` once per frame manually.
  21465. *
  21466. * @type {boolean}
  21467. * @default true
  21468. */
  21469. this.autoReset = true;
  21470. /**
  21471. * The current frame ID. This ID is managed
  21472. * by `NodeFrame`.
  21473. *
  21474. * @type {number}
  21475. * @readonly
  21476. * @default 0
  21477. */
  21478. this.frame = 0;
  21479. /**
  21480. * The number of render calls since the
  21481. * app has been started.
  21482. *
  21483. * @type {number}
  21484. * @readonly
  21485. * @default 0
  21486. */
  21487. this.calls = 0;
  21488. /**
  21489. * Render related metrics.
  21490. *
  21491. * @type {Object}
  21492. * @readonly
  21493. * @property {number} calls - The number of render calls since the app has been started.
  21494. * @property {number} frameCalls - The number of render calls of the current frame.
  21495. * @property {number} drawCalls - The number of draw calls of the current frame.
  21496. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  21497. * @property {number} points - The number of rendered point primitives of the current frame.
  21498. * @property {number} lines - The number of rendered line primitives of the current frame.
  21499. * @property {number} timestamp - The timestamp of the frame.
  21500. */
  21501. this.render = {
  21502. calls: 0,
  21503. frameCalls: 0,
  21504. drawCalls: 0,
  21505. triangles: 0,
  21506. points: 0,
  21507. lines: 0,
  21508. timestamp: 0,
  21509. };
  21510. /**
  21511. * Compute related metrics.
  21512. *
  21513. * @type {Object}
  21514. * @readonly
  21515. * @property {number} calls - The number of compute calls since the app has been started.
  21516. * @property {number} frameCalls - The number of compute calls of the current frame.
  21517. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  21518. */
  21519. this.compute = {
  21520. calls: 0,
  21521. frameCalls: 0,
  21522. timestamp: 0
  21523. };
  21524. /**
  21525. * Memory related metrics.
  21526. *
  21527. * @type {Object}
  21528. * @readonly
  21529. * @property {number} geometries - The number of active geometries.
  21530. * @property {number} frameCalls - The number of active textures.
  21531. */
  21532. this.memory = {
  21533. geometries: 0,
  21534. textures: 0
  21535. };
  21536. }
  21537. /**
  21538. * This method should be executed per draw call and updates the corresponding metrics.
  21539. *
  21540. * @param {Object3D} object - The 3D object that is going to be rendered.
  21541. * @param {number} count - The vertex or index count.
  21542. * @param {number} instanceCount - The instance count.
  21543. */
  21544. update( object, count, instanceCount ) {
  21545. this.render.drawCalls ++;
  21546. if ( object.isMesh || object.isSprite ) {
  21547. this.render.triangles += instanceCount * ( count / 3 );
  21548. } else if ( object.isPoints ) {
  21549. this.render.points += instanceCount * count;
  21550. } else if ( object.isLineSegments ) {
  21551. this.render.lines += instanceCount * ( count / 2 );
  21552. } else if ( object.isLine ) {
  21553. this.render.lines += instanceCount * ( count - 1 );
  21554. } else {
  21555. error( 'WebGPUInfo: Unknown object type.' );
  21556. }
  21557. }
  21558. /**
  21559. * Resets frame related metrics.
  21560. */
  21561. reset() {
  21562. this.render.drawCalls = 0;
  21563. this.render.frameCalls = 0;
  21564. this.compute.frameCalls = 0;
  21565. this.render.triangles = 0;
  21566. this.render.points = 0;
  21567. this.render.lines = 0;
  21568. }
  21569. /**
  21570. * Performs a complete reset of the object.
  21571. */
  21572. dispose() {
  21573. this.reset();
  21574. this.calls = 0;
  21575. this.render.calls = 0;
  21576. this.compute.calls = 0;
  21577. this.render.timestamp = 0;
  21578. this.compute.timestamp = 0;
  21579. this.memory.geometries = 0;
  21580. this.memory.textures = 0;
  21581. }
  21582. }
  21583. /**
  21584. * Abstract class for representing pipelines.
  21585. *
  21586. * @private
  21587. * @abstract
  21588. */
  21589. class Pipeline {
  21590. /**
  21591. * Constructs a new pipeline.
  21592. *
  21593. * @param {string} cacheKey - The pipeline's cache key.
  21594. */
  21595. constructor( cacheKey ) {
  21596. /**
  21597. * The pipeline's cache key.
  21598. *
  21599. * @type {string}
  21600. */
  21601. this.cacheKey = cacheKey;
  21602. /**
  21603. * How often the pipeline is currently in use.
  21604. *
  21605. * @type {number}
  21606. * @default 0
  21607. */
  21608. this.usedTimes = 0;
  21609. }
  21610. }
  21611. /**
  21612. * Class for representing render pipelines.
  21613. *
  21614. * @private
  21615. * @augments Pipeline
  21616. */
  21617. class RenderPipeline extends Pipeline {
  21618. /**
  21619. * Constructs a new render pipeline.
  21620. *
  21621. * @param {string} cacheKey - The pipeline's cache key.
  21622. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  21623. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  21624. */
  21625. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  21626. super( cacheKey );
  21627. /**
  21628. * The pipeline's vertex shader.
  21629. *
  21630. * @type {ProgrammableStage}
  21631. */
  21632. this.vertexProgram = vertexProgram;
  21633. /**
  21634. * The pipeline's fragment shader.
  21635. *
  21636. * @type {ProgrammableStage}
  21637. */
  21638. this.fragmentProgram = fragmentProgram;
  21639. }
  21640. }
  21641. /**
  21642. * Class for representing compute pipelines.
  21643. *
  21644. * @private
  21645. * @augments Pipeline
  21646. */
  21647. class ComputePipeline extends Pipeline {
  21648. /**
  21649. * Constructs a new render pipeline.
  21650. *
  21651. * @param {string} cacheKey - The pipeline's cache key.
  21652. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  21653. */
  21654. constructor( cacheKey, computeProgram ) {
  21655. super( cacheKey );
  21656. /**
  21657. * The pipeline's compute shader.
  21658. *
  21659. * @type {ProgrammableStage}
  21660. */
  21661. this.computeProgram = computeProgram;
  21662. /**
  21663. * This flag can be used for type testing.
  21664. *
  21665. * @type {boolean}
  21666. * @readonly
  21667. * @default true
  21668. */
  21669. this.isComputePipeline = true;
  21670. }
  21671. }
  21672. let _id$9 = 0;
  21673. /**
  21674. * Class for representing programmable stages which are vertex,
  21675. * fragment or compute shaders. Unlike fixed-function states (like blending),
  21676. * they represent the programmable part of a pipeline.
  21677. *
  21678. * @private
  21679. */
  21680. class ProgrammableStage {
  21681. /**
  21682. * Constructs a new programmable stage.
  21683. *
  21684. * @param {string} code - The shader code.
  21685. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  21686. * @param {string} name - The name of the shader.
  21687. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21688. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21689. */
  21690. constructor( code, stage, name, transforms = null, attributes = null ) {
  21691. /**
  21692. * The id of the programmable stage.
  21693. *
  21694. * @type {number}
  21695. */
  21696. this.id = _id$9 ++;
  21697. /**
  21698. * The shader code.
  21699. *
  21700. * @type {string}
  21701. */
  21702. this.code = code;
  21703. /**
  21704. * The type of stage.
  21705. *
  21706. * @type {string}
  21707. */
  21708. this.stage = stage;
  21709. /**
  21710. * The name of the stage.
  21711. * This is used for debugging purposes.
  21712. *
  21713. * @type {string}
  21714. */
  21715. this.name = name;
  21716. /**
  21717. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21718. *
  21719. * @type {?Array<Object>}
  21720. */
  21721. this.transforms = transforms;
  21722. /**
  21723. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21724. *
  21725. * @type {?Array<Object>}
  21726. */
  21727. this.attributes = attributes;
  21728. /**
  21729. * How often the programmable stage is currently in use.
  21730. *
  21731. * @type {number}
  21732. * @default 0
  21733. */
  21734. this.usedTimes = 0;
  21735. }
  21736. }
  21737. /**
  21738. * This renderer module manages the pipelines of the renderer.
  21739. *
  21740. * @private
  21741. * @augments DataMap
  21742. */
  21743. class Pipelines extends DataMap {
  21744. /**
  21745. * Constructs a new pipeline management component.
  21746. *
  21747. * @param {Backend} backend - The renderer's backend.
  21748. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21749. */
  21750. constructor( backend, nodes ) {
  21751. super();
  21752. /**
  21753. * The renderer's backend.
  21754. *
  21755. * @type {Backend}
  21756. */
  21757. this.backend = backend;
  21758. /**
  21759. * Renderer component for managing nodes related logic.
  21760. *
  21761. * @type {Nodes}
  21762. */
  21763. this.nodes = nodes;
  21764. /**
  21765. * A references to the bindings management component.
  21766. * This reference will be set inside the `Bindings`
  21767. * constructor.
  21768. *
  21769. * @type {?Bindings}
  21770. * @default null
  21771. */
  21772. this.bindings = null;
  21773. /**
  21774. * Internal cache for maintaining pipelines.
  21775. * The key of the map is a cache key, the value the pipeline.
  21776. *
  21777. * @type {Map<string,Pipeline>}
  21778. */
  21779. this.caches = new Map();
  21780. /**
  21781. * This dictionary maintains for each shader stage type (vertex,
  21782. * fragment and compute) the programmable stage objects which
  21783. * represent the actual shader code.
  21784. *
  21785. * @type {Object<string,Map<string, ProgrammableStage>>}
  21786. */
  21787. this.programs = {
  21788. vertex: new Map(),
  21789. fragment: new Map(),
  21790. compute: new Map()
  21791. };
  21792. }
  21793. /**
  21794. * Returns a compute pipeline for the given compute node.
  21795. *
  21796. * @param {Node} computeNode - The compute node.
  21797. * @param {Array<BindGroup>} bindings - The bindings.
  21798. * @return {ComputePipeline} The compute pipeline.
  21799. */
  21800. getForCompute( computeNode, bindings ) {
  21801. const { backend } = this;
  21802. const data = this.get( computeNode );
  21803. if ( this._needsComputeUpdate( computeNode ) ) {
  21804. const previousPipeline = data.pipeline;
  21805. if ( previousPipeline ) {
  21806. previousPipeline.usedTimes --;
  21807. previousPipeline.computeProgram.usedTimes --;
  21808. }
  21809. // get shader
  21810. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  21811. // programmable stage
  21812. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  21813. if ( stageCompute === undefined ) {
  21814. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  21815. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  21816. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  21817. backend.createProgram( stageCompute );
  21818. }
  21819. // determine compute pipeline
  21820. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  21821. let pipeline = this.caches.get( cacheKey );
  21822. if ( pipeline === undefined ) {
  21823. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21824. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  21825. }
  21826. // keep track of all used times
  21827. pipeline.usedTimes ++;
  21828. stageCompute.usedTimes ++;
  21829. //
  21830. data.version = computeNode.version;
  21831. data.pipeline = pipeline;
  21832. }
  21833. return data.pipeline;
  21834. }
  21835. /**
  21836. * Returns a render pipeline for the given render object.
  21837. *
  21838. * @param {RenderObject} renderObject - The render object.
  21839. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  21840. * @return {RenderPipeline} The render pipeline.
  21841. */
  21842. getForRender( renderObject, promises = null ) {
  21843. const { backend } = this;
  21844. const data = this.get( renderObject );
  21845. if ( this._needsRenderUpdate( renderObject ) ) {
  21846. const previousPipeline = data.pipeline;
  21847. if ( previousPipeline ) {
  21848. previousPipeline.usedTimes --;
  21849. previousPipeline.vertexProgram.usedTimes --;
  21850. previousPipeline.fragmentProgram.usedTimes --;
  21851. }
  21852. // get shader
  21853. const nodeBuilderState = renderObject.getNodeBuilderState();
  21854. const name = renderObject.material ? renderObject.material.name : '';
  21855. // programmable stages
  21856. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  21857. if ( stageVertex === undefined ) {
  21858. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  21859. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  21860. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  21861. backend.createProgram( stageVertex );
  21862. }
  21863. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  21864. if ( stageFragment === undefined ) {
  21865. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  21866. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  21867. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  21868. backend.createProgram( stageFragment );
  21869. }
  21870. // determine render pipeline
  21871. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  21872. let pipeline = this.caches.get( cacheKey );
  21873. if ( pipeline === undefined ) {
  21874. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21875. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  21876. } else {
  21877. renderObject.pipeline = pipeline;
  21878. }
  21879. // keep track of all used times
  21880. pipeline.usedTimes ++;
  21881. stageVertex.usedTimes ++;
  21882. stageFragment.usedTimes ++;
  21883. //
  21884. data.pipeline = pipeline;
  21885. }
  21886. return data.pipeline;
  21887. }
  21888. /**
  21889. * Deletes the pipeline for the given render object.
  21890. *
  21891. * @param {RenderObject} object - The render object.
  21892. * @return {?Object} The deleted dictionary.
  21893. */
  21894. delete( object ) {
  21895. const pipeline = this.get( object ).pipeline;
  21896. if ( pipeline ) {
  21897. // pipeline
  21898. pipeline.usedTimes --;
  21899. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  21900. // programs
  21901. if ( pipeline.isComputePipeline ) {
  21902. pipeline.computeProgram.usedTimes --;
  21903. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  21904. } else {
  21905. pipeline.fragmentProgram.usedTimes --;
  21906. pipeline.vertexProgram.usedTimes --;
  21907. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  21908. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  21909. }
  21910. }
  21911. return super.delete( object );
  21912. }
  21913. /**
  21914. * Frees internal resources.
  21915. */
  21916. dispose() {
  21917. super.dispose();
  21918. this.caches = new Map();
  21919. this.programs = {
  21920. vertex: new Map(),
  21921. fragment: new Map(),
  21922. compute: new Map()
  21923. };
  21924. }
  21925. /**
  21926. * Updates the pipeline for the given render object.
  21927. *
  21928. * @param {RenderObject} renderObject - The render object.
  21929. */
  21930. updateForRender( renderObject ) {
  21931. this.getForRender( renderObject );
  21932. }
  21933. /**
  21934. * Returns a compute pipeline for the given parameters.
  21935. *
  21936. * @private
  21937. * @param {Node} computeNode - The compute node.
  21938. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21939. * @param {string} cacheKey - The cache key.
  21940. * @param {Array<BindGroup>} bindings - The bindings.
  21941. * @return {ComputePipeline} The compute pipeline.
  21942. */
  21943. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  21944. // check for existing pipeline
  21945. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  21946. let pipeline = this.caches.get( cacheKey );
  21947. if ( pipeline === undefined ) {
  21948. pipeline = new ComputePipeline( cacheKey, stageCompute );
  21949. this.caches.set( cacheKey, pipeline );
  21950. this.backend.createComputePipeline( pipeline, bindings );
  21951. }
  21952. return pipeline;
  21953. }
  21954. /**
  21955. * Returns a render pipeline for the given parameters.
  21956. *
  21957. * @private
  21958. * @param {RenderObject} renderObject - The render object.
  21959. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  21960. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  21961. * @param {string} cacheKey - The cache key.
  21962. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  21963. * @return {ComputePipeline} The compute pipeline.
  21964. */
  21965. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  21966. // check for existing pipeline
  21967. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  21968. let pipeline = this.caches.get( cacheKey );
  21969. if ( pipeline === undefined ) {
  21970. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  21971. this.caches.set( cacheKey, pipeline );
  21972. renderObject.pipeline = pipeline;
  21973. // The `promises` array is `null` by default and only set to an empty array when
  21974. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  21975. // pending promises that resolve when the render pipelines are ready for rendering.
  21976. this.backend.createRenderPipeline( renderObject, promises );
  21977. }
  21978. return pipeline;
  21979. }
  21980. /**
  21981. * Computes a cache key representing a compute pipeline.
  21982. *
  21983. * @private
  21984. * @param {Node} computeNode - The compute node.
  21985. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21986. * @return {string} The cache key.
  21987. */
  21988. _getComputeCacheKey( computeNode, stageCompute ) {
  21989. return computeNode.id + ',' + stageCompute.id;
  21990. }
  21991. /**
  21992. * Computes a cache key representing a render pipeline.
  21993. *
  21994. * @private
  21995. * @param {RenderObject} renderObject - The render object.
  21996. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  21997. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  21998. * @return {string} The cache key.
  21999. */
  22000. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  22001. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  22002. }
  22003. /**
  22004. * Releases the given pipeline.
  22005. *
  22006. * @private
  22007. * @param {Pipeline} pipeline - The pipeline to release.
  22008. */
  22009. _releasePipeline( pipeline ) {
  22010. this.caches.delete( pipeline.cacheKey );
  22011. }
  22012. /**
  22013. * Releases the shader program.
  22014. *
  22015. * @private
  22016. * @param {Object} program - The shader program to release.
  22017. */
  22018. _releaseProgram( program ) {
  22019. const code = program.code;
  22020. const stage = program.stage;
  22021. this.programs[ stage ].delete( code );
  22022. }
  22023. /**
  22024. * Returns `true` if the compute pipeline for the given compute node requires an update.
  22025. *
  22026. * @private
  22027. * @param {Node} computeNode - The compute node.
  22028. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  22029. */
  22030. _needsComputeUpdate( computeNode ) {
  22031. const data = this.get( computeNode );
  22032. return data.pipeline === undefined || data.version !== computeNode.version;
  22033. }
  22034. /**
  22035. * Returns `true` if the render pipeline for the given render object requires an update.
  22036. *
  22037. * @private
  22038. * @param {RenderObject} renderObject - The render object.
  22039. * @return {boolean} Whether the render object for the given render object requires an update or not.
  22040. */
  22041. _needsRenderUpdate( renderObject ) {
  22042. const data = this.get( renderObject );
  22043. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  22044. }
  22045. }
  22046. /**
  22047. * This renderer module manages the bindings of the renderer.
  22048. *
  22049. * @private
  22050. * @augments DataMap
  22051. */
  22052. class Bindings extends DataMap {
  22053. /**
  22054. * Constructs a new bindings management component.
  22055. *
  22056. * @param {Backend} backend - The renderer's backend.
  22057. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  22058. * @param {Textures} textures - Renderer component for managing textures.
  22059. * @param {Attributes} attributes - Renderer component for managing attributes.
  22060. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  22061. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22062. */
  22063. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  22064. super();
  22065. /**
  22066. * The renderer's backend.
  22067. *
  22068. * @type {Backend}
  22069. */
  22070. this.backend = backend;
  22071. /**
  22072. * Renderer component for managing textures.
  22073. *
  22074. * @type {Textures}
  22075. */
  22076. this.textures = textures;
  22077. /**
  22078. * Renderer component for managing pipelines.
  22079. *
  22080. * @type {Pipelines}
  22081. */
  22082. this.pipelines = pipelines;
  22083. /**
  22084. * Renderer component for managing attributes.
  22085. *
  22086. * @type {Attributes}
  22087. */
  22088. this.attributes = attributes;
  22089. /**
  22090. * Renderer component for managing nodes related logic.
  22091. *
  22092. * @type {Nodes}
  22093. */
  22094. this.nodes = nodes;
  22095. /**
  22096. * Renderer component for managing metrics and monitoring data.
  22097. *
  22098. * @type {Info}
  22099. */
  22100. this.info = info;
  22101. this.pipelines.bindings = this; // assign bindings to pipelines
  22102. }
  22103. /**
  22104. * Returns the bind groups for the given render object.
  22105. *
  22106. * @param {RenderObject} renderObject - The render object.
  22107. * @return {Array<BindGroup>} The bind groups.
  22108. */
  22109. getForRender( renderObject ) {
  22110. const bindings = renderObject.getBindings();
  22111. for ( const bindGroup of bindings ) {
  22112. const groupData = this.get( bindGroup );
  22113. if ( groupData.bindGroup === undefined ) {
  22114. // each object defines an array of bindings (ubos, textures, samplers etc.)
  22115. this._init( bindGroup );
  22116. this.backend.createBindings( bindGroup, bindings, 0 );
  22117. groupData.bindGroup = bindGroup;
  22118. }
  22119. }
  22120. return bindings;
  22121. }
  22122. /**
  22123. * Returns the bind groups for the given compute node.
  22124. *
  22125. * @param {Node} computeNode - The compute node.
  22126. * @return {Array<BindGroup>} The bind groups.
  22127. */
  22128. getForCompute( computeNode ) {
  22129. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  22130. for ( const bindGroup of bindings ) {
  22131. const groupData = this.get( bindGroup );
  22132. if ( groupData.bindGroup === undefined ) {
  22133. this._init( bindGroup );
  22134. this.backend.createBindings( bindGroup, bindings, 0 );
  22135. groupData.bindGroup = bindGroup;
  22136. }
  22137. }
  22138. return bindings;
  22139. }
  22140. /**
  22141. * Updates the bindings for the given compute node.
  22142. *
  22143. * @param {Node} computeNode - The compute node.
  22144. */
  22145. updateForCompute( computeNode ) {
  22146. this._updateBindings( this.getForCompute( computeNode ) );
  22147. }
  22148. /**
  22149. * Updates the bindings for the given render object.
  22150. *
  22151. * @param {RenderObject} renderObject - The render object.
  22152. */
  22153. updateForRender( renderObject ) {
  22154. this._updateBindings( this.getForRender( renderObject ) );
  22155. }
  22156. /**
  22157. * Deletes the bindings for the given compute node.
  22158. *
  22159. * @param {Node} computeNode - The compute node.
  22160. */
  22161. deleteForCompute( computeNode ) {
  22162. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  22163. for ( const bindGroup of bindings ) {
  22164. this.delete( bindGroup );
  22165. }
  22166. }
  22167. /**
  22168. * Deletes the bindings for the given renderObject node.
  22169. *
  22170. * @param {RenderObject} renderObject - The renderObject.
  22171. */
  22172. deleteForRender( renderObject ) {
  22173. const bindings = renderObject.getBindings();
  22174. for ( const bindGroup of bindings ) {
  22175. this.delete( bindGroup );
  22176. }
  22177. }
  22178. /**
  22179. * Updates the given array of bindings.
  22180. *
  22181. * @param {Array<BindGroup>} bindings - The bind groups.
  22182. */
  22183. _updateBindings( bindings ) {
  22184. for ( const bindGroup of bindings ) {
  22185. this._update( bindGroup, bindings );
  22186. }
  22187. }
  22188. /**
  22189. * Initializes the given bind group.
  22190. *
  22191. * @param {BindGroup} bindGroup - The bind group to initialize.
  22192. */
  22193. _init( bindGroup ) {
  22194. for ( const binding of bindGroup.bindings ) {
  22195. if ( binding.isSampledTexture ) {
  22196. this.textures.updateTexture( binding.texture );
  22197. } else if ( binding.isSampler ) {
  22198. this.textures.updateSampler( binding.texture );
  22199. } else if ( binding.isStorageBuffer ) {
  22200. const attribute = binding.attribute;
  22201. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  22202. this.attributes.update( attribute, attributeType );
  22203. }
  22204. }
  22205. }
  22206. /**
  22207. * Updates the given bind group.
  22208. *
  22209. * @param {BindGroup} bindGroup - The bind group to update.
  22210. * @param {Array<BindGroup>} bindings - The bind groups.
  22211. */
  22212. _update( bindGroup, bindings ) {
  22213. const { backend } = this;
  22214. let needsBindingsUpdate = false;
  22215. let cacheBindings = true;
  22216. let cacheIndex = 0;
  22217. let version = 0;
  22218. // iterate over all bindings and check if buffer updates or a new binding group is required
  22219. for ( const binding of bindGroup.bindings ) {
  22220. const updatedGroup = this.nodes.updateGroup( binding );
  22221. // every uniforms group is a uniform buffer. So if no update is required,
  22222. // we move one with the next binding. Otherwise the next if block will update the group.
  22223. if ( updatedGroup === false ) continue;
  22224. //
  22225. if ( binding.isStorageBuffer ) {
  22226. const attribute = binding.attribute;
  22227. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  22228. this.attributes.update( attribute, attributeType );
  22229. }
  22230. if ( binding.isUniformBuffer ) {
  22231. const updated = binding.update();
  22232. if ( updated ) {
  22233. backend.updateBinding( binding );
  22234. }
  22235. } else if ( binding.isSampledTexture ) {
  22236. const updated = binding.update();
  22237. // get the texture data after the update, to sync the texture reference from node
  22238. const texture = binding.texture;
  22239. const texturesTextureData = this.textures.get( texture );
  22240. if ( updated ) {
  22241. // version: update the texture data or create a new one
  22242. this.textures.updateTexture( texture );
  22243. // generation: update the bindings if a new texture has been created
  22244. if ( binding.generation !== texturesTextureData.generation ) {
  22245. binding.generation = texturesTextureData.generation;
  22246. needsBindingsUpdate = true;
  22247. cacheBindings = false;
  22248. }
  22249. }
  22250. const textureData = backend.get( texture );
  22251. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  22252. cacheBindings = false;
  22253. } else {
  22254. cacheIndex = cacheIndex * 10 + texture.id;
  22255. version += texture.version;
  22256. }
  22257. if ( texture.isStorageTexture === true && texture.mipmapsAutoUpdate === true ) {
  22258. const textureData = this.get( texture );
  22259. if ( binding.store === true ) {
  22260. textureData.needsMipmap = true;
  22261. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  22262. this.backend.generateMipmaps( texture );
  22263. textureData.needsMipmap = false;
  22264. }
  22265. }
  22266. } else if ( binding.isSampler ) {
  22267. const updated = binding.update();
  22268. if ( updated ) {
  22269. const samplerKey = this.textures.updateSampler( binding.texture );
  22270. if ( binding.samplerKey !== samplerKey ) {
  22271. binding.samplerKey = samplerKey;
  22272. needsBindingsUpdate = true;
  22273. cacheBindings = false;
  22274. }
  22275. }
  22276. }
  22277. }
  22278. if ( needsBindingsUpdate === true ) {
  22279. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  22280. }
  22281. }
  22282. }
  22283. /**
  22284. * Default sorting function for opaque render items.
  22285. *
  22286. * @private
  22287. * @function
  22288. * @param {Object} a - The first render item.
  22289. * @param {Object} b - The second render item.
  22290. * @return {number} A numeric value which defines the sort order.
  22291. */
  22292. function painterSortStable( a, b ) {
  22293. if ( a.groupOrder !== b.groupOrder ) {
  22294. return a.groupOrder - b.groupOrder;
  22295. } else if ( a.renderOrder !== b.renderOrder ) {
  22296. return a.renderOrder - b.renderOrder;
  22297. } else if ( a.z !== b.z ) {
  22298. return a.z - b.z;
  22299. } else {
  22300. return a.id - b.id;
  22301. }
  22302. }
  22303. /**
  22304. * Default sorting function for transparent render items.
  22305. *
  22306. * @private
  22307. * @function
  22308. * @param {Object} a - The first render item.
  22309. * @param {Object} b - The second render item.
  22310. * @return {number} A numeric value which defines the sort order.
  22311. */
  22312. function reversePainterSortStable( a, b ) {
  22313. if ( a.groupOrder !== b.groupOrder ) {
  22314. return a.groupOrder - b.groupOrder;
  22315. } else if ( a.renderOrder !== b.renderOrder ) {
  22316. return a.renderOrder - b.renderOrder;
  22317. } else if ( a.z !== b.z ) {
  22318. return b.z - a.z;
  22319. } else {
  22320. return a.id - b.id;
  22321. }
  22322. }
  22323. /**
  22324. * Returns `true` if the given transparent material requires a double pass.
  22325. *
  22326. * @private
  22327. * @function
  22328. * @param {Material} material - The transparent material.
  22329. * @return {boolean} Whether the given material requires a double pass or not.
  22330. */
  22331. function needsDoublePass( material ) {
  22332. const hasTransmission = material.transmission > 0 || ( material.transmissionNode && material.transmissionNode.isNode );
  22333. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  22334. }
  22335. /**
  22336. * When the renderer analyzes the scene at the beginning of a render call,
  22337. * it stores 3D object for further processing in render lists. Depending on the
  22338. * properties of a 3D objects (like their transformation or material state), the
  22339. * objects are maintained in ordered lists for the actual rendering.
  22340. *
  22341. * Render lists are unique per scene and camera combination.
  22342. *
  22343. * @private
  22344. * @augments Pipeline
  22345. */
  22346. class RenderList {
  22347. /**
  22348. * Constructs a render list.
  22349. *
  22350. * @param {Lighting} lighting - The lighting management component.
  22351. * @param {Scene} scene - The scene.
  22352. * @param {Camera} camera - The camera the scene is rendered with.
  22353. */
  22354. constructor( lighting, scene, camera ) {
  22355. /**
  22356. * 3D objects are transformed into render items and stored in this array.
  22357. *
  22358. * @type {Array<Object>}
  22359. */
  22360. this.renderItems = [];
  22361. /**
  22362. * The current render items index.
  22363. *
  22364. * @type {number}
  22365. * @default 0
  22366. */
  22367. this.renderItemsIndex = 0;
  22368. /**
  22369. * A list with opaque render items.
  22370. *
  22371. * @type {Array<Object>}
  22372. */
  22373. this.opaque = [];
  22374. /**
  22375. * A list with transparent render items which require
  22376. * double pass rendering (e.g. transmissive objects).
  22377. *
  22378. * @type {Array<Object>}
  22379. */
  22380. this.transparentDoublePass = [];
  22381. /**
  22382. * A list with transparent render items.
  22383. *
  22384. * @type {Array<Object>}
  22385. */
  22386. this.transparent = [];
  22387. /**
  22388. * A list with transparent render bundle data.
  22389. *
  22390. * @type {Array<Object>}
  22391. */
  22392. this.bundles = [];
  22393. /**
  22394. * The render list's lights node. This node is later
  22395. * relevant for the actual analytical light nodes which
  22396. * compute the scene's lighting in the shader.
  22397. *
  22398. * @type {LightsNode}
  22399. */
  22400. this.lightsNode = lighting.getNode( scene, camera );
  22401. /**
  22402. * The scene's lights stored in an array. This array
  22403. * is used to setup the lights node.
  22404. *
  22405. * @type {Array<Light>}
  22406. */
  22407. this.lightsArray = [];
  22408. /**
  22409. * The scene.
  22410. *
  22411. * @type {Scene}
  22412. */
  22413. this.scene = scene;
  22414. /**
  22415. * The camera the scene is rendered with.
  22416. *
  22417. * @type {Camera}
  22418. */
  22419. this.camera = camera;
  22420. /**
  22421. * How many objects perform occlusion query tests.
  22422. *
  22423. * @type {number}
  22424. * @default 0
  22425. */
  22426. this.occlusionQueryCount = 0;
  22427. }
  22428. /**
  22429. * This method is called right at the beginning of a render call
  22430. * before the scene is analyzed. It prepares the internal data
  22431. * structures for the upcoming render lists generation.
  22432. *
  22433. * @return {RenderList} A reference to this render list.
  22434. */
  22435. begin() {
  22436. this.renderItemsIndex = 0;
  22437. this.opaque.length = 0;
  22438. this.transparentDoublePass.length = 0;
  22439. this.transparent.length = 0;
  22440. this.bundles.length = 0;
  22441. this.lightsArray.length = 0;
  22442. this.occlusionQueryCount = 0;
  22443. return this;
  22444. }
  22445. /**
  22446. * Returns a render item for the giving render item state. The state is defined
  22447. * by a series of object-related parameters.
  22448. *
  22449. * The method avoids object creation by holding render items and reusing them in
  22450. * subsequent render calls (just with different property values).
  22451. *
  22452. * @param {Object3D} object - The 3D object.
  22453. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22454. * @param {Material} material - The 3D object's material.
  22455. * @param {number} groupOrder - The current group order.
  22456. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22457. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22458. * @param {ClippingContext} clippingContext - The current clipping context.
  22459. * @return {Object} The render item.
  22460. */
  22461. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22462. let renderItem = this.renderItems[ this.renderItemsIndex ];
  22463. if ( renderItem === undefined ) {
  22464. renderItem = {
  22465. id: object.id,
  22466. object: object,
  22467. geometry: geometry,
  22468. material: material,
  22469. groupOrder: groupOrder,
  22470. renderOrder: object.renderOrder,
  22471. z: z,
  22472. group: group,
  22473. clippingContext: clippingContext
  22474. };
  22475. this.renderItems[ this.renderItemsIndex ] = renderItem;
  22476. } else {
  22477. renderItem.id = object.id;
  22478. renderItem.object = object;
  22479. renderItem.geometry = geometry;
  22480. renderItem.material = material;
  22481. renderItem.groupOrder = groupOrder;
  22482. renderItem.renderOrder = object.renderOrder;
  22483. renderItem.z = z;
  22484. renderItem.group = group;
  22485. renderItem.clippingContext = clippingContext;
  22486. }
  22487. this.renderItemsIndex ++;
  22488. return renderItem;
  22489. }
  22490. /**
  22491. * Pushes the given object as a render item to the internal render lists.
  22492. * The selected lists depend on the object properties.
  22493. *
  22494. * @param {Object3D} object - The 3D object.
  22495. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22496. * @param {Material} material - The 3D object's material.
  22497. * @param {number} groupOrder - The current group order.
  22498. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22499. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22500. * @param {ClippingContext} clippingContext - The current clipping context.
  22501. */
  22502. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22503. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  22504. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  22505. if ( material.transparent === true || material.transmission > 0 ||
  22506. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  22507. ( material.backdropNode && material.backdropNode.isNode ) ) {
  22508. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  22509. this.transparent.push( renderItem );
  22510. } else {
  22511. this.opaque.push( renderItem );
  22512. }
  22513. }
  22514. /**
  22515. * Inserts the given object as a render item at the start of the internal render lists.
  22516. * The selected lists depend on the object properties.
  22517. *
  22518. * @param {Object3D} object - The 3D object.
  22519. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22520. * @param {Material} material - The 3D object's material.
  22521. * @param {number} groupOrder - The current group order.
  22522. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22523. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22524. * @param {ClippingContext} clippingContext - The current clipping context.
  22525. */
  22526. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22527. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  22528. if ( material.transparent === true || material.transmission > 0 ||
  22529. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  22530. ( material.backdropNode && material.backdropNode.isNode ) ) {
  22531. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  22532. this.transparent.unshift( renderItem );
  22533. } else {
  22534. this.opaque.unshift( renderItem );
  22535. }
  22536. }
  22537. /**
  22538. * Pushes render bundle group data into the render list.
  22539. *
  22540. * @param {Object} group - Bundle group data.
  22541. */
  22542. pushBundle( group ) {
  22543. this.bundles.push( group );
  22544. }
  22545. /**
  22546. * Pushes a light into the render list.
  22547. *
  22548. * @param {Light} light - The light.
  22549. */
  22550. pushLight( light ) {
  22551. this.lightsArray.push( light );
  22552. }
  22553. /**
  22554. * Sorts the internal render lists.
  22555. *
  22556. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  22557. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  22558. */
  22559. sort( customOpaqueSort, customTransparentSort ) {
  22560. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  22561. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  22562. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  22563. }
  22564. /**
  22565. * This method performs finalizing tasks right after the render lists
  22566. * have been generated.
  22567. */
  22568. finish() {
  22569. // update lights
  22570. this.lightsNode.setLights( this.lightsArray );
  22571. // Clear references from inactive renderItems in the list
  22572. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  22573. const renderItem = this.renderItems[ i ];
  22574. if ( renderItem.id === null ) break;
  22575. renderItem.id = null;
  22576. renderItem.object = null;
  22577. renderItem.geometry = null;
  22578. renderItem.material = null;
  22579. renderItem.groupOrder = null;
  22580. renderItem.renderOrder = null;
  22581. renderItem.z = null;
  22582. renderItem.group = null;
  22583. renderItem.clippingContext = null;
  22584. }
  22585. }
  22586. }
  22587. const _chainKeys$4 = [];
  22588. /**
  22589. * This renderer module manages the render lists which are unique
  22590. * per scene and camera combination.
  22591. *
  22592. * @private
  22593. */
  22594. class RenderLists {
  22595. /**
  22596. * Constructs a render lists management component.
  22597. *
  22598. * @param {Lighting} lighting - The lighting management component.
  22599. */
  22600. constructor( lighting ) {
  22601. /**
  22602. * The lighting management component.
  22603. *
  22604. * @type {Lighting}
  22605. */
  22606. this.lighting = lighting;
  22607. /**
  22608. * The internal chain map which holds the render lists.
  22609. *
  22610. * @type {ChainMap}
  22611. */
  22612. this.lists = new ChainMap();
  22613. }
  22614. /**
  22615. * Returns a render list for the given scene and camera.
  22616. *
  22617. * @param {Scene} scene - The scene.
  22618. * @param {Camera} camera - The camera.
  22619. * @return {RenderList} The render list.
  22620. */
  22621. get( scene, camera ) {
  22622. const lists = this.lists;
  22623. _chainKeys$4[ 0 ] = scene;
  22624. _chainKeys$4[ 1 ] = camera;
  22625. let list = lists.get( _chainKeys$4 );
  22626. if ( list === undefined ) {
  22627. list = new RenderList( this.lighting, scene, camera );
  22628. lists.set( _chainKeys$4, list );
  22629. }
  22630. _chainKeys$4.length = 0;
  22631. return list;
  22632. }
  22633. /**
  22634. * Frees all internal resources.
  22635. */
  22636. dispose() {
  22637. this.lists = new ChainMap();
  22638. }
  22639. }
  22640. let _id$8 = 0;
  22641. /**
  22642. * Any render or compute command is executed in a specific context that defines
  22643. * the state of the renderer and its backend. Typical examples for such context
  22644. * data are the current clear values or data from the active framebuffer. This
  22645. * module is used to represent these contexts as objects.
  22646. *
  22647. * @private
  22648. */
  22649. class RenderContext {
  22650. /**
  22651. * Constructs a new render context.
  22652. */
  22653. constructor() {
  22654. /**
  22655. * The context's ID.
  22656. *
  22657. * @type {number}
  22658. */
  22659. this.id = _id$8 ++;
  22660. /**
  22661. * Whether the current active framebuffer has a color attachment.
  22662. *
  22663. * @type {boolean}
  22664. * @default true
  22665. */
  22666. this.color = true;
  22667. /**
  22668. * Whether the color attachment should be cleared or not.
  22669. *
  22670. * @type {boolean}
  22671. * @default true
  22672. */
  22673. this.clearColor = true;
  22674. /**
  22675. * The clear color value.
  22676. *
  22677. * @type {Object}
  22678. * @default true
  22679. */
  22680. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  22681. /**
  22682. * Whether the current active framebuffer has a depth attachment.
  22683. *
  22684. * @type {boolean}
  22685. * @default true
  22686. */
  22687. this.depth = true;
  22688. /**
  22689. * Whether the depth attachment should be cleared or not.
  22690. *
  22691. * @type {boolean}
  22692. * @default true
  22693. */
  22694. this.clearDepth = true;
  22695. /**
  22696. * The clear depth value.
  22697. *
  22698. * @type {number}
  22699. * @default 1
  22700. */
  22701. this.clearDepthValue = 1;
  22702. /**
  22703. * Whether the current active framebuffer has a stencil attachment.
  22704. *
  22705. * @type {boolean}
  22706. * @default false
  22707. */
  22708. this.stencil = false;
  22709. /**
  22710. * Whether the stencil attachment should be cleared or not.
  22711. *
  22712. * @type {boolean}
  22713. * @default true
  22714. */
  22715. this.clearStencil = true;
  22716. /**
  22717. * The clear stencil value.
  22718. *
  22719. * @type {number}
  22720. * @default 1
  22721. */
  22722. this.clearStencilValue = 1;
  22723. /**
  22724. * By default the viewport encloses the entire framebuffer If a smaller
  22725. * viewport is manually defined, this property is to `true` by the renderer.
  22726. *
  22727. * @type {boolean}
  22728. * @default false
  22729. */
  22730. this.viewport = false;
  22731. /**
  22732. * The viewport value. This value is in physical pixels meaning it incorporates
  22733. * the renderer's pixel ratio. The viewport property of render targets or
  22734. * the renderer is in logical pixels.
  22735. *
  22736. * @type {Vector4}
  22737. */
  22738. this.viewportValue = new Vector4();
  22739. /**
  22740. * When the scissor test is active and scissor rectangle smaller than the
  22741. * framebuffers dimensions, this property is to `true` by the renderer.
  22742. *
  22743. * @type {boolean}
  22744. * @default false
  22745. */
  22746. this.scissor = false;
  22747. /**
  22748. * The scissor rectangle.
  22749. *
  22750. * @type {Vector4}
  22751. */
  22752. this.scissorValue = new Vector4();
  22753. /**
  22754. * The active render target.
  22755. *
  22756. * @type {?RenderTarget}
  22757. * @default null
  22758. */
  22759. this.renderTarget = null;
  22760. /**
  22761. * The textures of the active render target.
  22762. * `null` when no render target is set.
  22763. *
  22764. * @type {?Array<Texture>}
  22765. * @default null
  22766. */
  22767. this.textures = null;
  22768. /**
  22769. * The depth texture of the active render target.
  22770. * `null` when no render target is set.
  22771. *
  22772. * @type {?DepthTexture}
  22773. * @default null
  22774. */
  22775. this.depthTexture = null;
  22776. /**
  22777. * The active cube face.
  22778. *
  22779. * @type {number}
  22780. * @default 0
  22781. */
  22782. this.activeCubeFace = 0;
  22783. /**
  22784. * The active mipmap level.
  22785. *
  22786. * @type {number}
  22787. * @default 0
  22788. */
  22789. this.activeMipmapLevel = 0;
  22790. /**
  22791. * The number of MSAA samples. This value is always `1` when
  22792. * MSAA isn't used.
  22793. *
  22794. * @type {number}
  22795. * @default 1
  22796. */
  22797. this.sampleCount = 1;
  22798. /**
  22799. * The active render target's width in physical pixels.
  22800. *
  22801. * @type {number}
  22802. * @default 0
  22803. */
  22804. this.width = 0;
  22805. /**
  22806. * The active render target's height in physical pixels.
  22807. *
  22808. * @type {number}
  22809. * @default 0
  22810. */
  22811. this.height = 0;
  22812. /**
  22813. * The occlusion query count.
  22814. *
  22815. * @type {number}
  22816. * @default 0
  22817. */
  22818. this.occlusionQueryCount = 0;
  22819. /**
  22820. * The current clipping context.
  22821. *
  22822. * @type {?ClippingContext}
  22823. * @default null
  22824. */
  22825. this.clippingContext = null;
  22826. /**
  22827. * This flag can be used for type testing.
  22828. *
  22829. * @type {boolean}
  22830. * @readonly
  22831. * @default true
  22832. */
  22833. this.isRenderContext = true;
  22834. }
  22835. /**
  22836. * Returns the cache key of this render context.
  22837. *
  22838. * @return {number} The cache key.
  22839. */
  22840. getCacheKey() {
  22841. return getCacheKey( this );
  22842. }
  22843. }
  22844. /**
  22845. * Computes a cache key for the given render context. This key
  22846. * should identify the render target state so it is possible to
  22847. * configure the correct attachments in the respective backend.
  22848. *
  22849. * @param {RenderContext} renderContext - The render context.
  22850. * @return {number} The cache key.
  22851. */
  22852. function getCacheKey( renderContext ) {
  22853. const { textures, activeCubeFace, activeMipmapLevel } = renderContext;
  22854. const values = [ activeCubeFace, activeMipmapLevel ];
  22855. for ( const texture of textures ) {
  22856. values.push( texture.id );
  22857. }
  22858. return hashArray( values );
  22859. }
  22860. const _chainKeys$3 = [];
  22861. const _defaultScene = /*@__PURE__*/ new Scene();
  22862. const _defaultCamera = /*@__PURE__*/ new Camera();
  22863. /**
  22864. * This module manages the render contexts of the renderer.
  22865. *
  22866. * @private
  22867. */
  22868. class RenderContexts {
  22869. /**
  22870. * Constructs a new render context management component.
  22871. */
  22872. constructor() {
  22873. /**
  22874. * A dictionary that manages render contexts in chain maps
  22875. * for each attachment state.
  22876. *
  22877. * @type {Object<string,ChainMap>}
  22878. */
  22879. this.chainMaps = {};
  22880. }
  22881. /**
  22882. * Returns a render context for the given scene, camera and render target.
  22883. *
  22884. * @param {Scene} scene - The scene.
  22885. * @param {Camera} camera - The camera that is used to render the scene.
  22886. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  22887. * @param {?MRT} [mrt=null] - The active multiple render target.
  22888. * @return {RenderContext} The render context.
  22889. */
  22890. get( scene, camera, renderTarget = null, mrt = null ) {
  22891. let index = 0;
  22892. if ( mrt !== null ) {
  22893. // TODO: Improve ChainMap so that it only matches submaps corresponding to the key lengths.
  22894. // For we use: if ( mrt !== null ) _chainKeys[ 2 ] = mrt;
  22895. _chainKeys$3[ index ++ ] = mrt;
  22896. }
  22897. _chainKeys$3[ index ++ ] = scene;
  22898. _chainKeys$3[ index ++ ] = camera;
  22899. let attachmentState;
  22900. if ( renderTarget === null ) {
  22901. attachmentState = 'default';
  22902. } else {
  22903. const format = renderTarget.texture.format;
  22904. const count = renderTarget.textures.length;
  22905. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  22906. }
  22907. const chainMap = this._getChainMap( attachmentState );
  22908. let renderState = chainMap.get( _chainKeys$3 );
  22909. if ( renderState === undefined ) {
  22910. renderState = new RenderContext();
  22911. chainMap.set( _chainKeys$3, renderState );
  22912. }
  22913. _chainKeys$3.length = 0;
  22914. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  22915. return renderState;
  22916. }
  22917. /**
  22918. * Returns a render context intended for clear operations.
  22919. *
  22920. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  22921. * @return {RenderContext} The render context.
  22922. */
  22923. getForClear( renderTarget = null ) {
  22924. return this.get( _defaultScene, _defaultCamera, renderTarget );
  22925. }
  22926. /**
  22927. * Returns a chain map for the given attachment state.
  22928. *
  22929. * @private
  22930. * @param {string} attachmentState - The attachment state.
  22931. * @return {ChainMap} The chain map.
  22932. */
  22933. _getChainMap( attachmentState ) {
  22934. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  22935. }
  22936. /**
  22937. * Frees internal resources.
  22938. */
  22939. dispose() {
  22940. this.chainMaps = {};
  22941. }
  22942. }
  22943. const _size$3 = /*@__PURE__*/ new Vector3();
  22944. /**
  22945. * This module manages the textures of the renderer.
  22946. *
  22947. * @private
  22948. * @augments DataMap
  22949. */
  22950. class Textures extends DataMap {
  22951. /**
  22952. * Constructs a new texture management component.
  22953. *
  22954. * @param {Renderer} renderer - The renderer.
  22955. * @param {Backend} backend - The renderer's backend.
  22956. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22957. */
  22958. constructor( renderer, backend, info ) {
  22959. super();
  22960. /**
  22961. * The renderer.
  22962. *
  22963. * @type {Renderer}
  22964. */
  22965. this.renderer = renderer;
  22966. /**
  22967. * The backend.
  22968. *
  22969. * @type {Backend}
  22970. */
  22971. this.backend = backend;
  22972. /**
  22973. * Renderer component for managing metrics and monitoring data.
  22974. *
  22975. * @type {Info}
  22976. */
  22977. this.info = info;
  22978. }
  22979. /**
  22980. * Updates the given render target. Based on the given render target configuration,
  22981. * it updates the texture states representing the attachments of the framebuffer.
  22982. *
  22983. * @param {RenderTarget} renderTarget - The render target to update.
  22984. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  22985. */
  22986. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  22987. const renderTargetData = this.get( renderTarget );
  22988. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  22989. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  22990. const textures = renderTarget.textures;
  22991. const size = this.getSize( textures[ 0 ] );
  22992. const mipWidth = size.width >> activeMipmapLevel;
  22993. const mipHeight = size.height >> activeMipmapLevel;
  22994. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  22995. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  22996. let textureNeedsUpdate = false;
  22997. if ( depthTexture === undefined && useDepthTexture ) {
  22998. depthTexture = new DepthTexture();
  22999. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  23000. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  23001. depthTexture.image.width = mipWidth;
  23002. depthTexture.image.height = mipHeight;
  23003. depthTexture.image.depth = size.depth;
  23004. depthTexture.renderTarget = renderTarget;
  23005. depthTexture.isArrayTexture = renderTarget.multiview === true && size.depth > 1;
  23006. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  23007. }
  23008. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  23009. textureNeedsUpdate = true;
  23010. if ( depthTexture ) {
  23011. depthTexture.needsUpdate = true;
  23012. depthTexture.image.width = mipWidth;
  23013. depthTexture.image.height = mipHeight;
  23014. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  23015. }
  23016. }
  23017. renderTargetData.width = size.width;
  23018. renderTargetData.height = size.height;
  23019. renderTargetData.textures = textures;
  23020. renderTargetData.depthTexture = depthTexture || null;
  23021. renderTargetData.depth = renderTarget.depthBuffer;
  23022. renderTargetData.stencil = renderTarget.stencilBuffer;
  23023. renderTargetData.renderTarget = renderTarget;
  23024. if ( renderTargetData.sampleCount !== sampleCount ) {
  23025. textureNeedsUpdate = true;
  23026. if ( depthTexture ) {
  23027. depthTexture.needsUpdate = true;
  23028. }
  23029. renderTargetData.sampleCount = sampleCount;
  23030. }
  23031. //
  23032. const options = { sampleCount };
  23033. // XR render targets require no texture updates
  23034. if ( renderTarget.isXRRenderTarget !== true ) {
  23035. for ( let i = 0; i < textures.length; i ++ ) {
  23036. const texture = textures[ i ];
  23037. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  23038. this.updateTexture( texture, options );
  23039. }
  23040. if ( depthTexture ) {
  23041. this.updateTexture( depthTexture, options );
  23042. }
  23043. }
  23044. // dispose handler
  23045. if ( renderTargetData.initialized !== true ) {
  23046. renderTargetData.initialized = true;
  23047. // dispose
  23048. renderTargetData.onDispose = () => {
  23049. this._destroyRenderTarget( renderTarget );
  23050. };
  23051. renderTarget.addEventListener( 'dispose', renderTargetData.onDispose );
  23052. }
  23053. }
  23054. /**
  23055. * Updates the given texture. Depending on the texture state, this method
  23056. * triggers the upload of texture data to the GPU memory. If the texture data are
  23057. * not yet ready for the upload, it uses default texture data for as a placeholder.
  23058. *
  23059. * @param {Texture} texture - The texture to update.
  23060. * @param {Object} [options={}] - The options.
  23061. */
  23062. updateTexture( texture, options = {} ) {
  23063. const textureData = this.get( texture );
  23064. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  23065. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  23066. const backend = this.backend;
  23067. if ( isRenderTarget && textureData.initialized === true ) {
  23068. // it's an update
  23069. backend.destroyTexture( texture );
  23070. }
  23071. //
  23072. if ( texture.isFramebufferTexture ) {
  23073. const renderTarget = this.renderer.getRenderTarget();
  23074. if ( renderTarget ) {
  23075. texture.type = renderTarget.texture.type;
  23076. } else {
  23077. texture.type = UnsignedByteType;
  23078. }
  23079. }
  23080. //
  23081. const { width, height, depth } = this.getSize( texture );
  23082. options.width = width;
  23083. options.height = height;
  23084. options.depth = depth;
  23085. options.needsMipmaps = this.needsMipmaps( texture );
  23086. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  23087. // TODO: Uniformly handle mipmap definitions
  23088. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  23089. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  23090. if ( texture.isCubeTexture && texture.mipmaps.length > 0 ) options.levels ++;
  23091. //
  23092. if ( isRenderTarget || texture.isStorageTexture === true || texture.isExternalTexture === true ) {
  23093. backend.createTexture( texture, options );
  23094. textureData.generation = texture.version;
  23095. } else {
  23096. if ( texture.version > 0 ) {
  23097. const image = texture.image;
  23098. if ( image === undefined ) {
  23099. warn( 'Renderer: Texture marked for update but image is undefined.' );
  23100. } else if ( image.complete === false ) {
  23101. warn( 'Renderer: Texture marked for update but image is incomplete.' );
  23102. } else {
  23103. if ( texture.images ) {
  23104. const images = [];
  23105. for ( const image of texture.images ) {
  23106. images.push( image );
  23107. }
  23108. options.images = images;
  23109. } else {
  23110. options.image = image;
  23111. }
  23112. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  23113. backend.createTexture( texture, options );
  23114. textureData.isDefaultTexture = false;
  23115. textureData.generation = texture.version;
  23116. }
  23117. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  23118. const skipAutoGeneration = texture.isStorageTexture === true && texture.mipmapsAutoUpdate === false;
  23119. if ( options.needsMipmaps && texture.mipmaps.length === 0 && ! skipAutoGeneration ) {
  23120. backend.generateMipmaps( texture );
  23121. }
  23122. if ( texture.onUpdate ) texture.onUpdate( texture );
  23123. }
  23124. } else {
  23125. // async update
  23126. backend.createDefaultTexture( texture );
  23127. textureData.isDefaultTexture = true;
  23128. textureData.generation = texture.version;
  23129. }
  23130. }
  23131. // dispose handler
  23132. if ( textureData.initialized !== true ) {
  23133. textureData.initialized = true;
  23134. textureData.generation = texture.version;
  23135. //
  23136. this.info.memory.textures ++;
  23137. //
  23138. if ( texture.isVideoTexture && ColorManagement.getTransfer( texture.colorSpace ) !== SRGBTransfer ) {
  23139. warn( 'WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace.' );
  23140. }
  23141. // dispose
  23142. textureData.onDispose = () => {
  23143. this._destroyTexture( texture );
  23144. };
  23145. texture.addEventListener( 'dispose', textureData.onDispose );
  23146. }
  23147. //
  23148. textureData.version = texture.version;
  23149. }
  23150. /**
  23151. * Updates the sampler for the given texture. This method has no effect
  23152. * for the WebGL backend since it has no concept of samplers. Texture
  23153. * parameters are configured with the `texParameter()` command for each
  23154. * texture.
  23155. *
  23156. * In WebGPU, samplers are objects like textures and it's possible to share
  23157. * them when the texture parameters match.
  23158. *
  23159. * @param {Texture} texture - The texture to update the sampler for.
  23160. * @return {string} The current sampler key.
  23161. */
  23162. updateSampler( texture ) {
  23163. return this.backend.updateSampler( texture );
  23164. }
  23165. /**
  23166. * Computes the size of the given texture and writes the result
  23167. * into the target vector. This vector is also returned by the
  23168. * method.
  23169. *
  23170. * If no texture data are available for the compute yet, the method
  23171. * returns default size values.
  23172. *
  23173. * @param {Texture} texture - The texture to compute the size for.
  23174. * @param {Vector3} target - The target vector.
  23175. * @return {Vector3} The target vector.
  23176. */
  23177. getSize( texture, target = _size$3 ) {
  23178. let image = texture.images ? texture.images[ 0 ] : texture.image;
  23179. if ( image ) {
  23180. if ( image.image !== undefined ) image = image.image;
  23181. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( image instanceof HTMLVideoElement ) ) {
  23182. target.width = image.videoWidth || 1;
  23183. target.height = image.videoHeight || 1;
  23184. target.depth = 1;
  23185. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( image instanceof VideoFrame ) ) {
  23186. target.width = image.displayWidth || 1;
  23187. target.height = image.displayHeight || 1;
  23188. target.depth = 1;
  23189. } else {
  23190. target.width = image.width || 1;
  23191. target.height = image.height || 1;
  23192. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  23193. }
  23194. } else {
  23195. target.width = target.height = target.depth = 1;
  23196. }
  23197. return target;
  23198. }
  23199. /**
  23200. * Computes the number of mipmap levels for the given texture.
  23201. *
  23202. * @param {Texture} texture - The texture.
  23203. * @param {number} width - The texture's width.
  23204. * @param {number} height - The texture's height.
  23205. * @return {number} The number of mipmap levels.
  23206. */
  23207. getMipLevels( texture, width, height ) {
  23208. let mipLevelCount;
  23209. if ( texture.mipmaps.length > 0 ) {
  23210. mipLevelCount = texture.mipmaps.length;
  23211. } else {
  23212. if ( texture.isCompressedTexture === true ) {
  23213. // it is not possible to compute mipmaps for compressed textures. So
  23214. // when no mipmaps are defined in "texture.mipmaps", force a texture
  23215. // level of 1
  23216. mipLevelCount = 1;
  23217. } else {
  23218. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  23219. }
  23220. }
  23221. return mipLevelCount;
  23222. }
  23223. /**
  23224. * Returns `true` if the given texture makes use of mipmapping.
  23225. *
  23226. * @param {Texture} texture - The texture.
  23227. * @return {boolean} Whether mipmaps are required or not.
  23228. */
  23229. needsMipmaps( texture ) {
  23230. return texture.generateMipmaps === true || texture.mipmaps.length > 0;
  23231. }
  23232. /**
  23233. * Frees internal resources when the given render target isn't
  23234. * required anymore.
  23235. *
  23236. * @param {RenderTarget} renderTarget - The render target to destroy.
  23237. */
  23238. _destroyRenderTarget( renderTarget ) {
  23239. if ( this.has( renderTarget ) === true ) {
  23240. const renderTargetData = this.get( renderTarget );
  23241. const textures = renderTargetData.textures;
  23242. const depthTexture = renderTargetData.depthTexture;
  23243. //
  23244. renderTarget.removeEventListener( 'dispose', renderTargetData.onDispose );
  23245. //
  23246. for ( let i = 0; i < textures.length; i ++ ) {
  23247. this._destroyTexture( textures[ i ] );
  23248. }
  23249. if ( depthTexture ) {
  23250. this._destroyTexture( depthTexture );
  23251. }
  23252. this.delete( renderTarget );
  23253. this.backend.delete( renderTarget );
  23254. }
  23255. }
  23256. /**
  23257. * Frees internal resource when the given texture isn't
  23258. * required anymore.
  23259. *
  23260. * @param {Texture} texture - The texture to destroy.
  23261. */
  23262. _destroyTexture( texture ) {
  23263. if ( this.has( texture ) === true ) {
  23264. const textureData = this.get( texture );
  23265. //
  23266. texture.removeEventListener( 'dispose', textureData.onDispose );
  23267. // if a texture is not ready for use, it falls back to a default texture so it's possible
  23268. // to use it for rendering. If a texture in this state is disposed, it's important to
  23269. // not destroy/delete the underlying GPU texture object since it is cached and shared with
  23270. // other textures.
  23271. const isDefaultTexture = textureData.isDefaultTexture;
  23272. this.backend.destroyTexture( texture, isDefaultTexture );
  23273. this.delete( texture );
  23274. this.info.memory.textures --;
  23275. }
  23276. }
  23277. }
  23278. /**
  23279. * A four-component version of {@link Color} which is internally
  23280. * used by the renderer to represents clear color with alpha as
  23281. * one object.
  23282. *
  23283. * @private
  23284. * @augments Color
  23285. */
  23286. class Color4 extends Color {
  23287. /**
  23288. * Constructs a new four-component color.
  23289. * You can also pass a single THREE.Color, hex or
  23290. * string argument to this constructor.
  23291. *
  23292. * @param {number|string} [r=1] - The red value.
  23293. * @param {number} [g=1] - The green value.
  23294. * @param {number} [b=1] - The blue value.
  23295. * @param {number} [a=1] - The alpha value.
  23296. */
  23297. constructor( r, g, b, a = 1 ) {
  23298. super( r, g, b );
  23299. this.a = a;
  23300. }
  23301. /**
  23302. * Overwrites the default to honor alpha.
  23303. * You can also pass a single THREE.Color, hex or
  23304. * string argument to this method.
  23305. *
  23306. * @param {number|string|Color} r - The red value.
  23307. * @param {number} [g] - The green value.
  23308. * @param {number} [b] - The blue value.
  23309. * @param {number} [a=1] - The alpha value.
  23310. * @return {Color4} A reference to this object.
  23311. */
  23312. set( r, g, b, a = 1 ) {
  23313. this.a = a;
  23314. return super.set( r, g, b );
  23315. }
  23316. /**
  23317. * Overwrites the default to honor alpha.
  23318. *
  23319. * @param {Color4} color - The color to copy.
  23320. * @return {Color4} A reference to this object.
  23321. */
  23322. copy( color ) {
  23323. if ( color.a !== undefined ) this.a = color.a;
  23324. return super.copy( color );
  23325. }
  23326. /**
  23327. * Overwrites the default to honor alpha.
  23328. *
  23329. * @return {Color4} The cloned color.
  23330. */
  23331. clone() {
  23332. return new this.constructor( this.r, this.g, this.b, this.a );
  23333. }
  23334. }
  23335. /**
  23336. * Special version of {@link PropertyNode} which is used for parameters.
  23337. *
  23338. * @augments PropertyNode
  23339. */
  23340. class ParameterNode extends PropertyNode {
  23341. static get type() {
  23342. return 'ParameterNode';
  23343. }
  23344. /**
  23345. * Constructs a new parameter node.
  23346. *
  23347. * @param {string} nodeType - The type of the node.
  23348. * @param {?string} [name=null] - The name of the parameter in the shader.
  23349. */
  23350. constructor( nodeType, name = null ) {
  23351. super( nodeType, name );
  23352. /**
  23353. * This flag can be used for type testing.
  23354. *
  23355. * @type {boolean}
  23356. * @readonly
  23357. * @default true
  23358. */
  23359. this.isParameterNode = true;
  23360. }
  23361. /**
  23362. * Gets the type of a member variable in the parameter node.
  23363. *
  23364. * @param {NodeBuilder} builder - The node builder.
  23365. * @param {string} name - The name of the member variable.
  23366. * @returns {string}
  23367. */
  23368. getMemberType( builder, name ) {
  23369. const type = this.getNodeType( builder );
  23370. const struct = builder.getStructTypeNode( type );
  23371. let memberType;
  23372. if ( struct !== null ) {
  23373. memberType = struct.getMemberType( builder, name );
  23374. } else {
  23375. error( `TSL: Member "${ name }" not found in struct "${ type }".` );
  23376. memberType = 'float';
  23377. }
  23378. return memberType;
  23379. }
  23380. getHash() {
  23381. return this.uuid;
  23382. }
  23383. generate() {
  23384. return this.name;
  23385. }
  23386. }
  23387. /**
  23388. * TSL function for creating a parameter node.
  23389. *
  23390. * @tsl
  23391. * @function
  23392. * @param {string} type - The type of the node.
  23393. * @param {?string} name - The name of the parameter in the shader.
  23394. * @returns {ParameterNode}
  23395. */
  23396. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  23397. /**
  23398. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  23399. * They are usually needed in cases like `If`, `Else`.
  23400. *
  23401. * @augments Node
  23402. */
  23403. class StackNode extends Node {
  23404. static get type() {
  23405. return 'StackNode';
  23406. }
  23407. /**
  23408. * Constructs a new stack node.
  23409. *
  23410. * @param {?StackNode} [parent=null] - The parent stack node.
  23411. */
  23412. constructor( parent = null ) {
  23413. super();
  23414. /**
  23415. * List of nodes.
  23416. *
  23417. * @type {Array<Node>}
  23418. */
  23419. this.nodes = [];
  23420. /**
  23421. * The output node.
  23422. *
  23423. * @type {?Node}
  23424. * @default null
  23425. */
  23426. this.outputNode = null;
  23427. /**
  23428. * The parent stack node.
  23429. *
  23430. * @type {?StackNode}
  23431. * @default null
  23432. */
  23433. this.parent = parent;
  23434. /**
  23435. * The current conditional node.
  23436. *
  23437. * @private
  23438. * @type {ConditionalNode}
  23439. * @default null
  23440. */
  23441. this._currentCond = null;
  23442. /**
  23443. * The expression node. Only
  23444. * relevant for Switch/Case.
  23445. *
  23446. * @private
  23447. * @type {Node}
  23448. * @default null
  23449. */
  23450. this._expressionNode = null;
  23451. /**
  23452. * This flag can be used for type testing.
  23453. *
  23454. * @type {boolean}
  23455. * @readonly
  23456. * @default true
  23457. */
  23458. this.isStackNode = true;
  23459. }
  23460. getElementType( builder ) {
  23461. return this.hasOutput ? this.outputNode.getElementType( builder ) : 'void';
  23462. }
  23463. getNodeType( builder ) {
  23464. return this.hasOutput ? this.outputNode.getNodeType( builder ) : 'void';
  23465. }
  23466. getMemberType( builder, name ) {
  23467. return this.hasOutput ? this.outputNode.getMemberType( builder, name ) : 'void';
  23468. }
  23469. /**
  23470. * Adds a node to this stack.
  23471. *
  23472. * @param {Node} node - The node to add.
  23473. * @return {StackNode} A reference to this stack node.
  23474. */
  23475. addToStack( node ) {
  23476. if ( node.isNode !== true ) {
  23477. error( 'TSL: Invalid node added to stack.' );
  23478. return this;
  23479. }
  23480. this.nodes.push( node );
  23481. return this;
  23482. }
  23483. /**
  23484. * Represent an `if` statement in TSL.
  23485. *
  23486. * @param {Node} boolNode - Represents the condition.
  23487. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23488. * @return {StackNode} A reference to this stack node.
  23489. */
  23490. If( boolNode, method ) {
  23491. const methodNode = new ShaderNode( method );
  23492. this._currentCond = select( boolNode, methodNode );
  23493. return this.addToStack( this._currentCond );
  23494. }
  23495. /**
  23496. * Represent an `elseif` statement in TSL.
  23497. *
  23498. * @param {Node} boolNode - Represents the condition.
  23499. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23500. * @return {StackNode} A reference to this stack node.
  23501. */
  23502. ElseIf( boolNode, method ) {
  23503. const methodNode = new ShaderNode( method );
  23504. const ifNode = select( boolNode, methodNode );
  23505. this._currentCond.elseNode = ifNode;
  23506. this._currentCond = ifNode;
  23507. return this;
  23508. }
  23509. /**
  23510. * Represent an `else` statement in TSL.
  23511. *
  23512. * @param {Function} method - TSL code which is executed in the `else` case.
  23513. * @return {StackNode} A reference to this stack node.
  23514. */
  23515. Else( method ) {
  23516. this._currentCond.elseNode = new ShaderNode( method );
  23517. return this;
  23518. }
  23519. /**
  23520. * Represents a `switch` statement in TSL.
  23521. *
  23522. * @param {any} expression - Represents the expression.
  23523. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23524. * @return {StackNode} A reference to this stack node.
  23525. */
  23526. Switch( expression ) {
  23527. this._expressionNode = nodeObject( expression );
  23528. return this;
  23529. }
  23530. /**
  23531. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  23532. * The last parameter must be the callback method that should be executed in the `true` case.
  23533. *
  23534. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  23535. * @return {StackNode} A reference to this stack node.
  23536. */
  23537. Case( ...params ) {
  23538. const caseNodes = [];
  23539. // extract case nodes from the parameter list
  23540. if ( params.length >= 2 ) {
  23541. for ( let i = 0; i < params.length - 1; i ++ ) {
  23542. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  23543. }
  23544. } else {
  23545. error( 'TSL: Invalid parameter length. Case() requires at least two parameters.' );
  23546. }
  23547. // extract method
  23548. const method = params[ params.length - 1 ];
  23549. const methodNode = new ShaderNode( method );
  23550. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  23551. let caseNode = caseNodes[ 0 ];
  23552. for ( let i = 1; i < caseNodes.length; i ++ ) {
  23553. caseNode = caseNode.or( caseNodes[ i ] );
  23554. }
  23555. // build condition
  23556. const condNode = select( caseNode, methodNode );
  23557. if ( this._currentCond === null ) {
  23558. this._currentCond = condNode;
  23559. return this.addToStack( this._currentCond );
  23560. } else {
  23561. this._currentCond.elseNode = condNode;
  23562. this._currentCond = condNode;
  23563. return this;
  23564. }
  23565. }
  23566. /**
  23567. * Represents the default code block of a Switch/Case statement.
  23568. *
  23569. * @param {Function} method - TSL code which is executed in the `else` case.
  23570. * @return {StackNode} A reference to this stack node.
  23571. */
  23572. Default( method ) {
  23573. this.Else( method );
  23574. return this;
  23575. }
  23576. setup( builder ) {
  23577. const nodeProperties = builder.getNodeProperties( this );
  23578. let index = 0;
  23579. for ( const childNode of this.getChildren() ) {
  23580. if ( childNode.isVarNode && childNode.intent === true ) {
  23581. if ( childNode.isAssign( builder ) !== true ) {
  23582. continue;
  23583. }
  23584. }
  23585. nodeProperties[ 'node' + index ++ ] = childNode;
  23586. }
  23587. // return a outputNode if exists or null
  23588. return nodeProperties.outputNode || null;
  23589. }
  23590. get hasOutput() {
  23591. return this.outputNode && this.outputNode.isNode;
  23592. }
  23593. build( builder, ...params ) {
  23594. const previousStack = getCurrentStack();
  23595. setCurrentStack( this );
  23596. builder.setActiveStack( this );
  23597. const buildStage = builder.buildStage;
  23598. for ( const node of this.nodes ) {
  23599. if ( node.isVarNode && node.intent === true ) {
  23600. if ( node.isAssign( builder ) !== true ) {
  23601. continue;
  23602. }
  23603. }
  23604. if ( buildStage === 'setup' ) {
  23605. node.build( builder );
  23606. } else if ( buildStage === 'analyze' ) {
  23607. node.build( builder, this );
  23608. } else if ( buildStage === 'generate' ) {
  23609. const stages = builder.getDataFromNode( node, 'any' ).stages;
  23610. const parents = stages && stages[ builder.shaderStage ];
  23611. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  23612. continue; // skip var nodes that are only used in .toVarying()
  23613. }
  23614. node.build( builder, 'void' );
  23615. }
  23616. }
  23617. //
  23618. let result;
  23619. if ( this.hasOutput ) {
  23620. result = this.outputNode.build( builder, ...params );
  23621. } else {
  23622. result = super.build( builder, ...params );
  23623. }
  23624. setCurrentStack( previousStack );
  23625. builder.removeActiveStack( this );
  23626. return result;
  23627. }
  23628. }
  23629. /**
  23630. * TSL function for creating a stack node.
  23631. *
  23632. * @tsl
  23633. * @function
  23634. * @param {?StackNode} [parent=null] - The parent stack node.
  23635. * @returns {StackNode}
  23636. */
  23637. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  23638. /**
  23639. * Generates a layout for struct members.
  23640. * This function takes an object representing struct members and returns an array of member layouts.
  23641. * Each member layout includes the member's name, type, and whether it is atomic.
  23642. *
  23643. * @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.
  23644. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  23645. */
  23646. function getMembersLayout( members ) {
  23647. return Object.entries( members ).map( ( [ name, value ] ) => {
  23648. if ( typeof value === 'string' ) {
  23649. return { name, type: value, atomic: false };
  23650. }
  23651. return { name, type: value.type, atomic: value.atomic || false };
  23652. } );
  23653. }
  23654. /**
  23655. * Represents a struct type node in the node-based system.
  23656. * This class is used to define and manage the layout and types of struct members.
  23657. * It extends the base Node class and provides methods to get the length of the struct,
  23658. * retrieve member types, and generate the struct type for a builder.
  23659. *
  23660. * @augments Node
  23661. */
  23662. class StructTypeNode extends Node {
  23663. static get type() {
  23664. return 'StructTypeNode';
  23665. }
  23666. /**
  23667. * Creates an instance of StructTypeNode.
  23668. *
  23669. * @param {Object} membersLayout - The layout of the members for the struct.
  23670. * @param {?string} [name=null] - The optional name of the struct.
  23671. */
  23672. constructor( membersLayout, name = null ) {
  23673. super( 'struct' );
  23674. /**
  23675. * The layout of the members for the struct
  23676. *
  23677. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  23678. */
  23679. this.membersLayout = getMembersLayout( membersLayout );
  23680. /**
  23681. * The name of the struct.
  23682. *
  23683. * @type {?string}
  23684. * @default null
  23685. */
  23686. this.name = name;
  23687. /**
  23688. * This flag can be used for type testing.
  23689. *
  23690. * @type {boolean}
  23691. * @readonly
  23692. * @default true
  23693. */
  23694. this.isStructLayoutNode = true;
  23695. }
  23696. /**
  23697. * Returns the length of the struct.
  23698. * The length is calculated by summing the lengths of the struct's members.
  23699. *
  23700. * @returns {number} The length of the struct.
  23701. */
  23702. getLength() {
  23703. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  23704. let maxAlignment = 1; // maximum alignment value in this struct
  23705. let offset = 0; // global buffer offset in 4 byte elements
  23706. for ( const member of this.membersLayout ) {
  23707. const type = member.type;
  23708. const itemSize = getMemoryLengthFromType( type );
  23709. const alignment = getAlignmentFromType( type ) / BYTES_PER_ELEMENT;
  23710. maxAlignment = Math.max( maxAlignment, alignment );
  23711. const chunkOffset = offset % maxAlignment; // offset in the current chunk of maxAlignment elements
  23712. const overhang = chunkOffset % alignment; // distance from the last aligned offset
  23713. if ( overhang !== 0 ) {
  23714. offset += alignment - overhang; // move to next aligned offset
  23715. }
  23716. offset += itemSize;
  23717. }
  23718. return ( Math.ceil( offset / maxAlignment ) * maxAlignment ); // ensure length is a multiple of maxAlignment
  23719. }
  23720. getMemberType( builder, name ) {
  23721. const member = this.membersLayout.find( m => m.name === name );
  23722. return member ? member.type : 'void';
  23723. }
  23724. getNodeType( builder ) {
  23725. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  23726. return structType.name;
  23727. }
  23728. setup( builder ) {
  23729. builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  23730. builder.addInclude( this );
  23731. }
  23732. generate( builder ) {
  23733. return this.getNodeType( builder );
  23734. }
  23735. }
  23736. /**
  23737. * StructNode allows to create custom structures with multiple members.
  23738. * This can also be used to define structures in attribute and uniform data.
  23739. *
  23740. * ```js
  23741. * // Define a custom struct
  23742. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  23743. *
  23744. * // Create a new instance of the struct
  23745. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  23746. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  23747. *
  23748. * // Access the struct members
  23749. * const min = bb.get( 'min' );
  23750. *
  23751. * // Assign a new value to a member
  23752. * min.assign( vec3() );
  23753. * ```
  23754. * @augments Node
  23755. */
  23756. class StructNode extends Node {
  23757. static get type() {
  23758. return 'StructNode';
  23759. }
  23760. constructor( structTypeNode, values ) {
  23761. super( 'vec3' );
  23762. this.structTypeNode = structTypeNode;
  23763. this.values = values;
  23764. this.isStructNode = true;
  23765. }
  23766. getNodeType( builder ) {
  23767. return this.structTypeNode.getNodeType( builder );
  23768. }
  23769. getMemberType( builder, name ) {
  23770. return this.structTypeNode.getMemberType( builder, name );
  23771. }
  23772. generate( builder ) {
  23773. const nodeVar = builder.getVarFromNode( this );
  23774. const structType = nodeVar.type;
  23775. const propertyName = builder.getPropertyName( nodeVar );
  23776. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structTypeNode.membersLayout, this.values ) }`, this );
  23777. return nodeVar.name;
  23778. }
  23779. }
  23780. /**
  23781. * TSL function for creating a struct node.
  23782. *
  23783. * @tsl
  23784. * @function
  23785. * @param {Object} membersLayout - The layout of the struct members.
  23786. * @param {?string} [name=null] - The name of the struct.
  23787. * @returns {Function} The struct function.
  23788. */
  23789. const struct = ( membersLayout, name = null ) => {
  23790. const structLayout = new StructTypeNode( membersLayout, name );
  23791. const struct = ( ...params ) => {
  23792. let values = null;
  23793. if ( params.length > 0 ) {
  23794. if ( params[ 0 ].isNode ) {
  23795. values = {};
  23796. const names = Object.keys( membersLayout );
  23797. for ( let i = 0; i < params.length; i ++ ) {
  23798. values[ names[ i ] ] = params[ i ];
  23799. }
  23800. } else {
  23801. values = params[ 0 ];
  23802. }
  23803. }
  23804. return nodeObject( new StructNode( structLayout, values ) );
  23805. };
  23806. struct.layout = structLayout;
  23807. struct.isStruct = true;
  23808. return struct;
  23809. };
  23810. /**
  23811. * This node can be used to define multiple outputs in a shader programs.
  23812. *
  23813. * @augments Node
  23814. */
  23815. class OutputStructNode extends Node {
  23816. static get type() {
  23817. return 'OutputStructNode';
  23818. }
  23819. /**
  23820. * Constructs a new output struct node. The constructor can be invoked with an
  23821. * arbitrary number of nodes representing the members.
  23822. *
  23823. * @param {...Node} members - A parameter list of nodes.
  23824. */
  23825. constructor( ...members ) {
  23826. super();
  23827. /**
  23828. * An array of nodes which defines the output.
  23829. *
  23830. * @type {Array<Node>}
  23831. */
  23832. this.members = members;
  23833. /**
  23834. * This flag can be used for type testing.
  23835. *
  23836. * @type {boolean}
  23837. * @readonly
  23838. * @default true
  23839. */
  23840. this.isOutputStructNode = true;
  23841. }
  23842. getNodeType( builder ) {
  23843. const properties = builder.getNodeProperties( this );
  23844. if ( properties.membersLayout === undefined ) {
  23845. const members = this.members;
  23846. const membersLayout = [];
  23847. for ( let i = 0; i < members.length; i ++ ) {
  23848. const name = 'm' + i;
  23849. const type = members[ i ].getNodeType( builder );
  23850. membersLayout.push( { name, type, index: i } );
  23851. }
  23852. properties.membersLayout = membersLayout;
  23853. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  23854. }
  23855. return properties.structType.name;
  23856. }
  23857. generate( builder ) {
  23858. const propertyName = builder.getOutputStructName();
  23859. const members = this.members;
  23860. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  23861. for ( let i = 0; i < members.length; i ++ ) {
  23862. const snippet = members[ i ].build( builder );
  23863. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  23864. }
  23865. return propertyName;
  23866. }
  23867. }
  23868. /**
  23869. * TSL function for creating an output struct node.
  23870. *
  23871. * @tsl
  23872. * @function
  23873. * @param {...Node} members - A parameter list of nodes.
  23874. * @returns {OutputStructNode}
  23875. */
  23876. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  23877. /**
  23878. * Returns the MRT texture index for the given name.
  23879. *
  23880. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  23881. * @param {string} name - The name of the MRT texture which index is requested.
  23882. * @return {number} The texture index.
  23883. */
  23884. function getTextureIndex( textures, name ) {
  23885. for ( let i = 0; i < textures.length; i ++ ) {
  23886. if ( textures[ i ].name === name ) {
  23887. return i;
  23888. }
  23889. }
  23890. return -1;
  23891. }
  23892. /**
  23893. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  23894. * post-processing is shown below:
  23895. * ```js
  23896. * const mrtNode = mrt( {
  23897. * output: output,
  23898. * normal: normalView
  23899. * } ) );
  23900. * ```
  23901. * The MRT output is defined as a dictionary.
  23902. *
  23903. * @augments OutputStructNode
  23904. */
  23905. class MRTNode extends OutputStructNode {
  23906. static get type() {
  23907. return 'MRTNode';
  23908. }
  23909. /**
  23910. * Constructs a new output struct node.
  23911. *
  23912. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  23913. */
  23914. constructor( outputNodes ) {
  23915. super();
  23916. /**
  23917. * A dictionary representing the MRT outputs. The key
  23918. * is the name of the output, the value the node which produces
  23919. * the output result.
  23920. *
  23921. * @type {Object<string, Node>}
  23922. */
  23923. this.outputNodes = outputNodes;
  23924. /**
  23925. * This flag can be used for type testing.
  23926. *
  23927. * @type {boolean}
  23928. * @readonly
  23929. * @default true
  23930. */
  23931. this.isMRTNode = true;
  23932. }
  23933. /**
  23934. * Returns `true` if the MRT node has an output with the given name.
  23935. *
  23936. * @param {string} name - The name of the output.
  23937. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  23938. */
  23939. has( name ) {
  23940. return this.outputNodes[ name ] !== undefined;
  23941. }
  23942. /**
  23943. * Returns the output node for the given name.
  23944. *
  23945. * @param {string} name - The name of the output.
  23946. * @return {Node} The output node.
  23947. */
  23948. get( name ) {
  23949. return this.outputNodes[ name ];
  23950. }
  23951. /**
  23952. * Merges the outputs of the given MRT node with the outputs of this node.
  23953. *
  23954. * @param {MRTNode} mrtNode - The MRT to merge.
  23955. * @return {MRTNode} A new MRT node with merged outputs..
  23956. */
  23957. merge( mrtNode ) {
  23958. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  23959. return mrt( outputs );
  23960. }
  23961. setup( builder ) {
  23962. const outputNodes = this.outputNodes;
  23963. const mrt = builder.renderer.getRenderTarget();
  23964. const members = [];
  23965. const textures = mrt.textures;
  23966. for ( const name in outputNodes ) {
  23967. const index = getTextureIndex( textures, name );
  23968. members[ index ] = vec4( outputNodes[ name ] );
  23969. }
  23970. this.members = members;
  23971. return super.setup( builder );
  23972. }
  23973. }
  23974. /**
  23975. * TSL function for creating a MRT node.
  23976. *
  23977. * @tsl
  23978. * @function
  23979. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  23980. * @returns {MRTNode}
  23981. */
  23982. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  23983. /**
  23984. * This node represents an operation that reinterprets the bit representation of a value
  23985. * in one type as a value in another type.
  23986. *
  23987. * @augments TempNode
  23988. */
  23989. class BitcastNode extends TempNode {
  23990. static get type() {
  23991. return 'BitcastNode';
  23992. }
  23993. /**
  23994. * Constructs a new bitcast node.
  23995. *
  23996. * @param {Node} valueNode - The value to convert.
  23997. * @param {string} conversionType - The type to convert to.
  23998. * @param {?string} [inputType = null] - The expected input data type of the bitcast operation.
  23999. */
  24000. constructor( valueNode, conversionType, inputType = null ) {
  24001. super();
  24002. /**
  24003. * The data to bitcast to a new type.
  24004. *
  24005. * @type {Node}
  24006. */
  24007. this.valueNode = valueNode;
  24008. /**
  24009. * The type the value will be converted to.
  24010. *
  24011. * @type {string}
  24012. */
  24013. this.conversionType = conversionType;
  24014. /**
  24015. * The expected input data type of the bitcast operation.
  24016. *
  24017. *
  24018. * @type {string}
  24019. * @default null
  24020. */
  24021. this.inputType = inputType;
  24022. /**
  24023. * This flag can be used for type testing.
  24024. *
  24025. * @type {boolean}
  24026. * @readonly
  24027. * @default true
  24028. */
  24029. this.isBitcastNode = true;
  24030. }
  24031. getNodeType( builder ) {
  24032. // GLSL aliasing
  24033. if ( this.inputType !== null ) {
  24034. const valueType = this.valueNode.getNodeType( builder );
  24035. const valueLength = builder.getTypeLength( valueType );
  24036. return builder.getTypeFromLength( valueLength, this.conversionType );
  24037. }
  24038. return this.conversionType;
  24039. }
  24040. generate( builder ) {
  24041. const type = this.getNodeType( builder );
  24042. let inputType = '';
  24043. if ( this.inputType !== null ) {
  24044. const valueType = this.valueNode.getNodeType( builder );
  24045. const valueTypeLength = builder.getTypeLength( valueType );
  24046. inputType = valueTypeLength === 1 ? this.inputType : builder.changeComponentType( valueType, this.inputType );
  24047. } else {
  24048. inputType = this.valueNode.getNodeType( builder );
  24049. }
  24050. return `${ builder.getBitcastMethod( type, inputType ) }( ${ this.valueNode.build( builder, inputType ) } )`;
  24051. }
  24052. }
  24053. /**
  24054. * Reinterpret the bit representation of a value in one type as a value in another type.
  24055. *
  24056. * @tsl
  24057. * @function
  24058. * @param {Node | number} x - The parameter.
  24059. * @param {string} y - The new type.
  24060. * @returns {Node}
  24061. */
  24062. const bitcast = /*@__PURE__*/ nodeProxyIntent( BitcastNode ).setParameterLength( 2 );
  24063. /**
  24064. * Bitcasts a float or a vector of floats to a corresponding integer type with the same element size.
  24065. *
  24066. * @tsl
  24067. * @function
  24068. * @param {Node<float>} value - The float or vector of floats to bitcast.
  24069. * @returns {BitcastNode}
  24070. */
  24071. const floatBitsToInt = ( value ) => new BitcastNode( value, 'int', 'float' );
  24072. /**
  24073. * Bitcasts a float or a vector of floats to a corresponding unsigned integer type with the same element size.
  24074. *
  24075. * @tsl
  24076. * @function
  24077. * @param {Node<float>} value - The float or vector of floats to bitcast.
  24078. * @returns {BitcastNode}
  24079. */
  24080. const floatBitsToUint = ( value ) => new BitcastNode( value, 'uint', 'float' );
  24081. /**
  24082. * Bitcasts an integer or a vector of integers to a corresponding float type with the same element size.
  24083. *
  24084. * @tsl
  24085. * @function
  24086. * @param {Node<int>} value - The integer or vector of integers to bitcast.
  24087. * @returns {BitcastNode}
  24088. */
  24089. const intBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'int' );
  24090. /**
  24091. * Bitcast an unsigned integer or a vector of unsigned integers to a corresponding float type with the same element size.
  24092. *
  24093. * @tsl
  24094. * @function
  24095. * @param {Node<uint>} value - The unsigned integer or vector of unsigned integers to bitcast.
  24096. * @returns {BitcastNode}
  24097. */
  24098. const uintBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'uint' );
  24099. const registeredBitcountFunctions = {};
  24100. /**
  24101. * This node represents an operation that counts the bits of a piece of shader data.
  24102. *
  24103. * @augments MathNode
  24104. */
  24105. class BitcountNode extends MathNode {
  24106. static get type() {
  24107. return 'BitcountNode';
  24108. }
  24109. /**
  24110. * Constructs a new math node.
  24111. *
  24112. * @param {'countTrailingZeros'|'countLeadingZeros'|'countOneBits'} method - The method name.
  24113. * @param {Node} aNode - The first input.
  24114. */
  24115. constructor( method, aNode ) {
  24116. super( method, aNode );
  24117. /**
  24118. * This flag can be used for type testing.
  24119. *
  24120. * @type {boolean}
  24121. * @readonly
  24122. * @default true
  24123. */
  24124. this.isBitcountNode = true;
  24125. }
  24126. /**
  24127. * Casts the input value of the function to an integer if necessary.
  24128. *
  24129. * @private
  24130. * @param {Node<uint>|Node<int>} inputNode - The input value.
  24131. * @param {Node<uint>} outputNode - The output value.
  24132. * @param {string} elementType - The type of the input value.
  24133. */
  24134. _resolveElementType( inputNode, outputNode, elementType ) {
  24135. if ( elementType === 'int' ) {
  24136. outputNode.assign( bitcast( inputNode, 'uint' ) );
  24137. } else {
  24138. outputNode.assign( inputNode );
  24139. }
  24140. }
  24141. _returnDataNode( inputType ) {
  24142. switch ( inputType ) {
  24143. case 'uint': {
  24144. return uint;
  24145. }
  24146. case 'int': {
  24147. return int;
  24148. }
  24149. case 'uvec2': {
  24150. return uvec2;
  24151. }
  24152. case 'uvec3': {
  24153. return uvec3;
  24154. }
  24155. case 'uvec4': {
  24156. return uvec4;
  24157. }
  24158. case 'ivec2': {
  24159. return ivec2;
  24160. }
  24161. case 'ivec3': {
  24162. return ivec3;
  24163. }
  24164. case 'ivec4': {
  24165. return ivec4;
  24166. }
  24167. }
  24168. }
  24169. /**
  24170. * Creates and registers a reusable GLSL function that emulates the behavior of countTrailingZeros.
  24171. *
  24172. * @private
  24173. * @param {string} method - The name of the function to create.
  24174. * @param {string} elementType - The type of the input value.
  24175. * @returns {Function} - The generated function
  24176. */
  24177. _createTrailingZerosBaseLayout( method, elementType ) {
  24178. const outputConvertNode = this._returnDataNode( elementType );
  24179. const fnDef = Fn( ( [ value ] ) => {
  24180. const v = uint( 0.0 );
  24181. this._resolveElementType( value, v, elementType );
  24182. const f = float( v.bitAnd( negate( v ) ) );
  24183. const uintBits = floatBitsToUint( f );
  24184. const numTrailingZeros = ( uintBits.shiftRight( 23 ) ).sub( 127 );
  24185. return outputConvertNode( numTrailingZeros );
  24186. } ).setLayout( {
  24187. name: method,
  24188. type: elementType,
  24189. inputs: [
  24190. { name: 'value', type: elementType }
  24191. ]
  24192. } );
  24193. return fnDef;
  24194. }
  24195. /**
  24196. * Creates and registers a reusable GLSL function that emulates the behavior of countLeadingZeros.
  24197. *
  24198. * @private
  24199. * @param {string} method - The name of the function to create.
  24200. * @param {string} elementType - The type of the input value.
  24201. * @returns {Function} - The generated function
  24202. */
  24203. _createLeadingZerosBaseLayout( method, elementType ) {
  24204. const outputConvertNode = this._returnDataNode( elementType );
  24205. const fnDef = Fn( ( [ value ] ) => {
  24206. If( value.equal( uint( 0 ) ), () => {
  24207. return uint( 32 );
  24208. } );
  24209. const v = uint( 0 );
  24210. const n = uint( 0 );
  24211. this._resolveElementType( value, v, elementType );
  24212. If( v.shiftRight( 16 ).equal( 0 ), () => {
  24213. n.addAssign( 16 );
  24214. v.shiftLeftAssign( 16 );
  24215. } );
  24216. If( v.shiftRight( 24 ).equal( 0 ), () => {
  24217. n.addAssign( 8 );
  24218. v.shiftLeftAssign( 8 );
  24219. } );
  24220. If( v.shiftRight( 28 ).equal( 0 ), () => {
  24221. n.addAssign( 4 );
  24222. v.shiftLeftAssign( 4 );
  24223. } );
  24224. If( v.shiftRight( 30 ).equal( 0 ), () => {
  24225. n.addAssign( 2 );
  24226. v.shiftLeftAssign( 2 );
  24227. } );
  24228. If( v.shiftRight( 31 ).equal( 0 ), () => {
  24229. n.addAssign( 1 );
  24230. } );
  24231. return outputConvertNode( n );
  24232. } ).setLayout( {
  24233. name: method,
  24234. type: elementType,
  24235. inputs: [
  24236. { name: 'value', type: elementType }
  24237. ]
  24238. } );
  24239. return fnDef;
  24240. }
  24241. /**
  24242. * Creates and registers a reusable GLSL function that emulates the behavior of countOneBits.
  24243. *
  24244. * @private
  24245. * @param {string} method - The name of the function to create.
  24246. * @param {string} elementType - The type of the input value.
  24247. * @returns {Function} - The generated function
  24248. */
  24249. _createOneBitsBaseLayout( method, elementType ) {
  24250. const outputConvertNode = this._returnDataNode( elementType );
  24251. const fnDef = Fn( ( [ value ] ) => {
  24252. const v = uint( 0.0 );
  24253. this._resolveElementType( value, v, elementType );
  24254. v.assign( v.sub( v.shiftRight( uint( 1 ) ).bitAnd( uint( 0x55555555 ) ) ) );
  24255. v.assign( v.bitAnd( uint( 0x33333333 ) ).add( v.shiftRight( uint( 2 ) ).bitAnd( uint( 0x33333333 ) ) ) );
  24256. const numBits = v.add( v.shiftRight( uint( 4 ) ) ).bitAnd( uint( 0xF0F0F0F ) ).mul( uint( 0x1010101 ) ).shiftRight( uint( 24 ) );
  24257. return outputConvertNode( numBits );
  24258. } ).setLayout( {
  24259. name: method,
  24260. type: elementType,
  24261. inputs: [
  24262. { name: 'value', type: elementType }
  24263. ]
  24264. } );
  24265. return fnDef;
  24266. }
  24267. /**
  24268. * Creates and registers a reusable GLSL function that emulates the behavior of the specified bitcount function.
  24269. * including considerations for component-wise bitcounts on vector type inputs.
  24270. *
  24271. * @private
  24272. * @param {string} method - The name of the function to create.
  24273. * @param {string} inputType - The type of the input value.
  24274. * @param {number} typeLength - The vec length of the input value.
  24275. * @param {Function} baseFn - The base function that operates on an individual component of the vector.
  24276. * @returns {Function} - The alias function for the specified bitcount method.
  24277. */
  24278. _createMainLayout( method, inputType, typeLength, baseFn ) {
  24279. const outputConvertNode = this._returnDataNode( inputType );
  24280. const fnDef = Fn( ( [ value ] ) => {
  24281. if ( typeLength === 1 ) {
  24282. return outputConvertNode( baseFn( value ) );
  24283. } else {
  24284. const vec = outputConvertNode( 0 );
  24285. const components = [ 'x', 'y', 'z', 'w' ];
  24286. for ( let i = 0; i < typeLength; i ++ ) {
  24287. const component = components[ i ];
  24288. vec[ component ].assign( baseFn( value[ component ] ) );
  24289. }
  24290. return vec;
  24291. }
  24292. } ).setLayout( {
  24293. name: method,
  24294. type: inputType,
  24295. inputs: [
  24296. { name: 'value', type: inputType }
  24297. ]
  24298. } );
  24299. return fnDef;
  24300. }
  24301. setup( builder ) {
  24302. const { method, aNode } = this;
  24303. const { renderer } = builder;
  24304. if ( renderer.backend.isWebGPUBackend ) {
  24305. // use built-in WGSL functions for WebGPU
  24306. return super.setup( builder );
  24307. }
  24308. const inputType = this.getInputType( builder );
  24309. const elementType = builder.getElementType( inputType );
  24310. const typeLength = builder.getTypeLength( inputType );
  24311. const baseMethod = `${method}_base_${elementType}`;
  24312. const newMethod = `${method}_${inputType}`;
  24313. let baseFn = registeredBitcountFunctions[ baseMethod ];
  24314. if ( baseFn === undefined ) {
  24315. switch ( method ) {
  24316. case BitcountNode.COUNT_LEADING_ZEROS: {
  24317. baseFn = this._createLeadingZerosBaseLayout( baseMethod, elementType );
  24318. break;
  24319. }
  24320. case BitcountNode.COUNT_TRAILING_ZEROS: {
  24321. baseFn = this._createTrailingZerosBaseLayout( baseMethod, elementType );
  24322. break;
  24323. }
  24324. case BitcountNode.COUNT_ONE_BITS: {
  24325. baseFn = this._createOneBitsBaseLayout( baseMethod, elementType );
  24326. break;
  24327. }
  24328. }
  24329. registeredBitcountFunctions[ baseMethod ] = baseFn;
  24330. }
  24331. let fn = registeredBitcountFunctions[ newMethod ];
  24332. if ( fn === undefined ) {
  24333. fn = this._createMainLayout( newMethod, inputType, typeLength, baseFn );
  24334. registeredBitcountFunctions[ newMethod ] = fn;
  24335. }
  24336. const output = Fn( () => {
  24337. return fn(
  24338. aNode,
  24339. );
  24340. } );
  24341. return output();
  24342. }
  24343. }
  24344. BitcountNode.COUNT_TRAILING_ZEROS = 'countTrailingZeros';
  24345. BitcountNode.COUNT_LEADING_ZEROS = 'countLeadingZeros';
  24346. BitcountNode.COUNT_ONE_BITS = 'countOneBits';
  24347. /**
  24348. * Finds the number of consecutive 0 bits from the least significant bit of the input value,
  24349. * which is also the index of the least significant bit of the input value.
  24350. *
  24351. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  24352. *
  24353. * @tsl
  24354. * @function
  24355. * @param {Node | number} x - The input value.
  24356. * @returns {Node}
  24357. */
  24358. const countTrailingZeros = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_TRAILING_ZEROS ).setParameterLength( 1 );
  24359. /**
  24360. * Finds the number of consecutive 0 bits starting from the most significant bit of the input value.
  24361. *
  24362. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  24363. *
  24364. * @tsl
  24365. * @function
  24366. * @param {Node | number} x - The input value.
  24367. * @returns {Node}
  24368. */
  24369. const countLeadingZeros = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_LEADING_ZEROS ).setParameterLength( 1 );
  24370. /**
  24371. * Finds the number of '1' bits set in the input value
  24372. *
  24373. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  24374. *
  24375. * @tsl
  24376. * @function
  24377. * @returns {Node}
  24378. */
  24379. const countOneBits = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_ONE_BITS ).setParameterLength( 1 );
  24380. /**
  24381. * Generates a hash value in the range `[0, 1]` from the given seed.
  24382. *
  24383. * @tsl
  24384. * @function
  24385. * @param {Node<float>} seed - The seed.
  24386. * @return {Node<float>} The hash value.
  24387. */
  24388. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  24389. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  24390. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  24391. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  24392. const result = word.shiftRight( 22 ).bitXor( word );
  24393. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  24394. } );
  24395. /**
  24396. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  24397. * The corners are mapped to `0` and the center to `1`.
  24398. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24399. *
  24400. * @tsl
  24401. * @function
  24402. * @param {Node<float>} x - The value to remap.
  24403. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  24404. * @return {Node<float>} The remapped value.
  24405. */
  24406. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  24407. /**
  24408. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  24409. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  24410. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24411. *
  24412. * @tsl
  24413. * @function
  24414. * @param {Node<float>} x - The value to remap.
  24415. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  24416. * @return {Node<float>} The remapped value.
  24417. */
  24418. 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 ) );
  24419. /**
  24420. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  24421. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  24422. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24423. *
  24424. * @tsl
  24425. * @function
  24426. * @param {Node<float>} x - The value to remap.
  24427. * @param {Node<float>} a - First control parameter.
  24428. * @param {Node<float>} b - Second control parameter.
  24429. * @return {Node<float>} The remapped value.
  24430. */
  24431. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  24432. /**
  24433. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  24434. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24435. *
  24436. * @tsl
  24437. * @function
  24438. * @param {Node<float>} x - The value to compute the sin for.
  24439. * @param {Node<float>} k - Controls the amount of bounces.
  24440. * @return {Node<float>} The result value.
  24441. */
  24442. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  24443. /**
  24444. * This node represents an operation that packs floating-point values of a vector into an unsigned 32-bit integer
  24445. *
  24446. * @augments TempNode
  24447. */
  24448. class PackFloatNode extends TempNode {
  24449. static get type() {
  24450. return 'PackFloatNode';
  24451. }
  24452. /**
  24453. *
  24454. * @param {'snorm' | 'unorm' | 'float16'} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  24455. * @param {Node} vectorNode - The vector node to be packed
  24456. */
  24457. constructor( encoding, vectorNode ) {
  24458. super();
  24459. /**
  24460. * The vector to be packed.
  24461. *
  24462. * @type {Node}
  24463. */
  24464. this.vectorNode = vectorNode;
  24465. /**
  24466. * The numeric encoding.
  24467. *
  24468. * @type {string}
  24469. */
  24470. this.encoding = encoding;
  24471. /**
  24472. * This flag can be used for type testing.
  24473. *
  24474. * @type {boolean}
  24475. * @readonly
  24476. * @default true
  24477. */
  24478. this.isPackFloatNode = true;
  24479. }
  24480. getNodeType() {
  24481. return 'uint';
  24482. }
  24483. generate( builder ) {
  24484. const inputType = this.vectorNode.getNodeType( builder );
  24485. return `${ builder.getFloatPackingMethod( this.encoding ) }(${ this.vectorNode.build( builder, inputType )})`;
  24486. }
  24487. }
  24488. /**
  24489. * Converts each component of the normalized float to 16-bit integer values. The results are packed into a single unsigned integer.
  24490. * round(clamp(c, -1, +1) * 32767.0)
  24491. *
  24492. * @tsl
  24493. * @function
  24494. * @param {Node<vec2>} value - The 2-component vector to be packed
  24495. * @returns {Node}
  24496. */
  24497. const packSnorm2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'snorm' ).setParameterLength( 1 );
  24498. /**
  24499. * Converts each component of the normalized float to 16-bit integer values. The results are packed into a single unsigned integer.
  24500. * round(clamp(c, 0, +1) * 65535.0)
  24501. *
  24502. * @tsl
  24503. * @function
  24504. * @param {Node<vec2>} value - The 2-component vector to be packed
  24505. * @returns {Node}
  24506. */
  24507. const packUnorm2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'unorm' ).setParameterLength( 1 );
  24508. /**
  24509. * Converts each component of the vec2 to 16-bit floating-point values. The results are packed into a single unsigned integer.
  24510. *
  24511. * @tsl
  24512. * @function
  24513. * @param {Node<vec2>} value - The 2-component vector to be packed
  24514. * @returns {Node}
  24515. */
  24516. const packHalf2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'float16' ).setParameterLength( 1 );
  24517. /**
  24518. * This node represents an operation that unpacks values from a 32-bit unsigned integer, reinterpreting the results as a floating-point vector
  24519. *
  24520. * @augments TempNode
  24521. */
  24522. class UnpackFloatNode extends TempNode {
  24523. static get type() {
  24524. return 'UnpackFloatNode';
  24525. }
  24526. /**
  24527. *
  24528. * @param {'snorm' | 'unorm' | 'float16'} encoding - The numeric encoding that describes how the integer values are mapped to the float range
  24529. * @param {Node} uintNode - The uint node to be unpacked
  24530. */
  24531. constructor( encoding, uintNode ) {
  24532. super();
  24533. /**
  24534. * The unsigned integer to be unpacked.
  24535. *
  24536. * @type {Node}
  24537. */
  24538. this.uintNode = uintNode;
  24539. /**
  24540. * The numeric encoding.
  24541. *
  24542. * @type {string}
  24543. */
  24544. this.encoding = encoding;
  24545. /**
  24546. * This flag can be used for type testing.
  24547. *
  24548. * @type {boolean}
  24549. * @readonly
  24550. * @default true
  24551. */
  24552. this.isUnpackFloatNode = true;
  24553. }
  24554. getNodeType() {
  24555. return 'vec2';
  24556. }
  24557. generate( builder ) {
  24558. const inputType = this.uintNode.getNodeType( builder );
  24559. return `${ builder.getFloatUnpackingMethod( this.encoding ) }(${ this.uintNode.build( builder, inputType )})`;
  24560. }
  24561. }
  24562. /**
  24563. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as normalized signed integers. Returns a vec2 with both values.
  24564. *
  24565. * @tsl
  24566. * @function
  24567. * @param {Node<uint>} value - The unsigned integer to be unpacked
  24568. * @returns {Node}
  24569. */
  24570. const unpackSnorm2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'snorm' ).setParameterLength( 1 );
  24571. /**
  24572. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as normalized unsigned integers. Returns a vec2 with both values.
  24573. *
  24574. * @tsl
  24575. * @function
  24576. * @param {Node<uint>} value - The unsigned integer to be unpacked
  24577. * @returns {Node}
  24578. */
  24579. const unpackUnorm2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'unorm' ).setParameterLength( 1 );
  24580. /**
  24581. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as 16-bit floating-point numbers. Returns a vec2 with both values.
  24582. *
  24583. * @tsl
  24584. * @function
  24585. * @param {Node<uint>} value - The unsigned integer to be unpacked
  24586. * @returns {Node}
  24587. */
  24588. const unpackHalf2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'float16' ).setParameterLength( 1 );
  24589. // https://github.com/cabbibo/glsl-tri-noise-3d
  24590. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  24591. return x.fract().sub( .5 ).abs();
  24592. } ).setLayout( {
  24593. name: 'tri',
  24594. type: 'float',
  24595. inputs: [
  24596. { name: 'x', type: 'float' }
  24597. ]
  24598. } );
  24599. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  24600. 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. ) ) ) ) );
  24601. } ).setLayout( {
  24602. name: 'tri3',
  24603. type: 'vec3',
  24604. inputs: [
  24605. { name: 'p', type: 'vec3' }
  24606. ]
  24607. } );
  24608. /**
  24609. * Generates a noise value from the given position, speed and time parameters.
  24610. *
  24611. * @tsl
  24612. * @function
  24613. * @param {Node<vec3>} position - The position.
  24614. * @param {Node<float>} speed - The speed.
  24615. * @param {Node<float>} time - The time.
  24616. * @return {Node<float>} The generated noise.
  24617. */
  24618. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  24619. const p = vec3( position ).toVar();
  24620. const z = float( 1.4 ).toVar();
  24621. const rz = float( 0.0 ).toVar();
  24622. const bp = vec3( p ).toVar();
  24623. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  24624. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  24625. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  24626. bp.mulAssign( 1.8 );
  24627. z.mulAssign( 1.5 );
  24628. p.mulAssign( 1.2 );
  24629. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  24630. rz.addAssign( t.div( z ) );
  24631. bp.addAssign( 0.14 );
  24632. } );
  24633. return rz;
  24634. } ).setLayout( {
  24635. name: 'triNoise3D',
  24636. type: 'float',
  24637. inputs: [
  24638. { name: 'position', type: 'vec3' },
  24639. { name: 'speed', type: 'float' },
  24640. { name: 'time', type: 'float' }
  24641. ]
  24642. } );
  24643. /**
  24644. * This class allows to define multiple overloaded versions
  24645. * of the same function. Depending on the parameters of the function
  24646. * call, the node picks the best-fit overloaded version.
  24647. *
  24648. * @augments Node
  24649. */
  24650. class FunctionOverloadingNode extends Node {
  24651. static get type() {
  24652. return 'FunctionOverloadingNode';
  24653. }
  24654. /**
  24655. * Constructs a new function overloading node.
  24656. *
  24657. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  24658. * @param {...Node} parametersNodes - A list of parameter nodes.
  24659. */
  24660. constructor( functionNodes = [], ...parametersNodes ) {
  24661. super();
  24662. /**
  24663. * Array of `Fn` function definitions.
  24664. *
  24665. * @type {Array<Function>}
  24666. */
  24667. this.functionNodes = functionNodes;
  24668. /**
  24669. * A list of parameter nodes.
  24670. *
  24671. * @type {Array<Node>}
  24672. */
  24673. this.parametersNodes = parametersNodes;
  24674. /**
  24675. * The selected overloaded function call.
  24676. *
  24677. * @private
  24678. * @type {ShaderCallNodeInternal}
  24679. */
  24680. this._candidateFn = null;
  24681. /**
  24682. * This node is marked as global.
  24683. *
  24684. * @type {boolean}
  24685. * @default true
  24686. */
  24687. this.global = true;
  24688. }
  24689. /**
  24690. * This method is overwritten since the node type is inferred from
  24691. * the function's return type.
  24692. *
  24693. * @param {NodeBuilder} builder - The current node builder.
  24694. * @return {string} The node type.
  24695. */
  24696. getNodeType( builder ) {
  24697. const candidateFn = this.getCandidateFn( builder );
  24698. return candidateFn.shaderNode.layout.type;
  24699. }
  24700. /**
  24701. * Returns the candidate function for the current parameters.
  24702. *
  24703. * @param {NodeBuilder} builder - The current node builder.
  24704. * @return {FunctionNode} The candidate function.
  24705. */
  24706. getCandidateFn( builder ) {
  24707. const params = this.parametersNodes;
  24708. let candidateFn = this._candidateFn;
  24709. if ( candidateFn === null ) {
  24710. let bestCandidateFn = null;
  24711. let bestScore = -1;
  24712. for ( const functionNode of this.functionNodes ) {
  24713. const shaderNode = functionNode.shaderNode;
  24714. const layout = shaderNode.layout;
  24715. if ( layout === null ) {
  24716. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  24717. }
  24718. const inputs = layout.inputs;
  24719. if ( params.length === inputs.length ) {
  24720. let currentScore = 0;
  24721. for ( let i = 0; i < params.length; i ++ ) {
  24722. const param = params[ i ];
  24723. const input = inputs[ i ];
  24724. if ( param.getNodeType( builder ) === input.type ) {
  24725. currentScore ++;
  24726. }
  24727. }
  24728. if ( currentScore > bestScore ) {
  24729. bestCandidateFn = functionNode;
  24730. bestScore = currentScore;
  24731. }
  24732. }
  24733. }
  24734. this._candidateFn = candidateFn = bestCandidateFn;
  24735. }
  24736. return candidateFn;
  24737. }
  24738. /**
  24739. * Sets up the node for the current parameters.
  24740. *
  24741. * @param {NodeBuilder} builder - The current node builder.
  24742. * @return {Node} The setup node.
  24743. */
  24744. setup( builder ) {
  24745. const candidateFn = this.getCandidateFn( builder );
  24746. return candidateFn( ...this.parametersNodes );
  24747. }
  24748. }
  24749. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  24750. /**
  24751. * TSL function for creating a function overloading node.
  24752. *
  24753. * @tsl
  24754. * @function
  24755. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  24756. * @returns {FunctionOverloadingNode}
  24757. */
  24758. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  24759. /**
  24760. * Represents the elapsed time in seconds.
  24761. *
  24762. * @tsl
  24763. * @type {UniformNode<float>}
  24764. */
  24765. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  24766. /**
  24767. * Represents the delta time in seconds.
  24768. *
  24769. * @tsl
  24770. * @type {UniformNode<float>}
  24771. */
  24772. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  24773. /**
  24774. * Represents the current frame ID.
  24775. *
  24776. * @tsl
  24777. * @type {UniformNode<uint>}
  24778. */
  24779. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  24780. /**
  24781. * Generates a sine wave oscillation based on a timer.
  24782. *
  24783. * @tsl
  24784. * @function
  24785. * @param {Node<float>} t - The timer to generate the oscillation with.
  24786. * @return {Node<float>} The oscillation node.
  24787. */
  24788. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  24789. /**
  24790. * Generates a square wave oscillation based on a timer.
  24791. *
  24792. * @tsl
  24793. * @function
  24794. * @param {Node<float>} t - The timer to generate the oscillation with.
  24795. * @return {Node<float>} The oscillation node.
  24796. */
  24797. const oscSquare = ( t = time ) => t.fract().round();
  24798. /**
  24799. * Generates a triangle wave oscillation based on a timer.
  24800. *
  24801. * @tsl
  24802. * @function
  24803. * @param {Node<float>} t - The timer to generate the oscillation with.
  24804. * @return {Node<float>} The oscillation node.
  24805. */
  24806. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  24807. /**
  24808. * Generates a sawtooth wave oscillation based on a timer.
  24809. *
  24810. * @tsl
  24811. * @function
  24812. * @param {Node<float>} t - The timer to generate the oscillation with.
  24813. * @return {Node<float>} The oscillation node.
  24814. */
  24815. const oscSawtooth = ( t = time ) => t.fract();
  24816. /**
  24817. * Replaces the default UV coordinates used in texture lookups.
  24818. *
  24819. * ```js
  24820. *material.contextNode = replaceDefaultUV( ( textureNode ) => {
  24821. *
  24822. * // ...
  24823. * return customUVCoordinates;
  24824. *
  24825. *} );
  24826. *```
  24827. *
  24828. * @tsl
  24829. * @function
  24830. * @param {function(Node):Node<vec2>} callback - A callback that receives the texture node
  24831. * and must return the new uv coordinates.
  24832. * @param {Node} [node=null] - An optional node to which the context will be applied.
  24833. * @return {ContextNode} A context node that replaces the default UV coordinates.
  24834. */
  24835. function replaceDefaultUV( callback, node = null ) {
  24836. return context( node, { getUV: callback } );
  24837. }
  24838. /**
  24839. * Rotates the given uv coordinates around a center point
  24840. *
  24841. * @tsl
  24842. * @function
  24843. * @param {Node<vec2>} uv - The uv coordinates.
  24844. * @param {Node<float>} rotation - The rotation defined in radians.
  24845. * @param {Node<vec2>} center - The center of rotation
  24846. * @return {Node<vec2>} The rotated uv coordinates.
  24847. */
  24848. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  24849. return rotate( uv.sub( center ), rotation ).add( center );
  24850. } );
  24851. /**
  24852. * Applies a spherical warping effect to the given uv coordinates.
  24853. *
  24854. * @tsl
  24855. * @function
  24856. * @param {Node<vec2>} uv - The uv coordinates.
  24857. * @param {Node<float>} strength - The strength of the effect.
  24858. * @param {Node<vec2>} center - The center point
  24859. * @return {Node<vec2>} The updated uv coordinates.
  24860. */
  24861. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  24862. const delta = uv.sub( center );
  24863. const delta2 = delta.dot( delta );
  24864. const delta4 = delta2.mul( delta2 );
  24865. const deltaOffset = delta4.mul( strength );
  24866. return uv.add( delta.mul( deltaOffset ) );
  24867. } );
  24868. /**
  24869. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  24870. * oriented always towards the camera.
  24871. *
  24872. * ```js
  24873. * material.vertexNode = billboarding();
  24874. * ```
  24875. *
  24876. * @tsl
  24877. * @function
  24878. * @param {Object} config - The configuration object.
  24879. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  24880. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  24881. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  24882. * @return {Node<vec3>} The updated vertex position in clip space.
  24883. */
  24884. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  24885. let worldMatrix;
  24886. if ( position !== null ) {
  24887. worldMatrix = modelWorldMatrix.toVar();
  24888. worldMatrix[ 3 ][ 0 ] = position.x;
  24889. worldMatrix[ 3 ][ 1 ] = position.y;
  24890. worldMatrix[ 3 ][ 2 ] = position.z;
  24891. } else {
  24892. worldMatrix = modelWorldMatrix;
  24893. }
  24894. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  24895. if ( defined( horizontal ) ) {
  24896. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  24897. modelViewMatrix[ 0 ][ 1 ] = 0;
  24898. modelViewMatrix[ 0 ][ 2 ] = 0;
  24899. }
  24900. if ( defined( vertical ) ) {
  24901. modelViewMatrix[ 1 ][ 0 ] = 0;
  24902. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  24903. modelViewMatrix[ 1 ][ 2 ] = 0;
  24904. }
  24905. modelViewMatrix[ 2 ][ 0 ] = 0;
  24906. modelViewMatrix[ 2 ][ 1 ] = 0;
  24907. modelViewMatrix[ 2 ][ 2 ] = 1;
  24908. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  24909. } );
  24910. /**
  24911. * A special version of a screen uv function that involves a depth comparison
  24912. * when computing the final uvs. The function mitigates visual errors when
  24913. * using viewport texture nodes for refraction purposes. Without this function
  24914. * objects in front of a refractive surface might appear on the refractive surface
  24915. * which is incorrect.
  24916. *
  24917. * @tsl
  24918. * @function
  24919. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  24920. * @return {Node<vec2>} The update uv coordinates.
  24921. */
  24922. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  24923. const depth = linearDepth();
  24924. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  24925. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  24926. return finalUV;
  24927. } );
  24928. /**
  24929. * Can be used to compute texture coordinates for animated sprite sheets.
  24930. *
  24931. * ```js
  24932. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  24933. *
  24934. * material.colorNode = texture( spriteSheet, uvNode );
  24935. * ```
  24936. *
  24937. * @augments Node
  24938. */
  24939. class SpriteSheetUVNode extends Node {
  24940. static get type() {
  24941. return 'SpriteSheetUVNode';
  24942. }
  24943. /**
  24944. * Constructs a new sprite sheet uv node.
  24945. *
  24946. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  24947. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  24948. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  24949. */
  24950. constructor( countNode, uvNode = uv$1(), frameNode = float( 0 ) ) {
  24951. super( 'vec2' );
  24952. /**
  24953. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  24954. *
  24955. * @type {Node<vec2>}
  24956. */
  24957. this.countNode = countNode;
  24958. /**
  24959. * The uv node.
  24960. *
  24961. * @type {Node<vec2>}
  24962. */
  24963. this.uvNode = uvNode;
  24964. /**
  24965. * The node that defines the current frame/sprite.
  24966. *
  24967. * @type {Node<float>}
  24968. */
  24969. this.frameNode = frameNode;
  24970. }
  24971. setup() {
  24972. const { frameNode, uvNode, countNode } = this;
  24973. const { width, height } = countNode;
  24974. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  24975. const column = frameNum.mod( width );
  24976. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  24977. const scale = countNode.reciprocal();
  24978. const uvFrameOffset = vec2( column, row );
  24979. return uvNode.add( uvFrameOffset ).mul( scale );
  24980. }
  24981. }
  24982. /**
  24983. * TSL function for creating a sprite sheet uv node.
  24984. *
  24985. * @tsl
  24986. * @function
  24987. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  24988. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  24989. * @param {?Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  24990. * @returns {SpriteSheetUVNode}
  24991. */
  24992. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 );
  24993. /**
  24994. * TSL function for creating a triplanar textures node.
  24995. *
  24996. * Can be used for triplanar texture mapping.
  24997. *
  24998. * ```js
  24999. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  25000. * ```
  25001. *
  25002. * @tsl
  25003. * @function
  25004. * @param {Node} textureXNode - First texture node.
  25005. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  25006. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  25007. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  25008. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  25009. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  25010. * @returns {Node<vec4>}
  25011. */
  25012. const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => {
  25013. // Reference: https://github.com/keijiro/StandardTriplanar
  25014. // Blending factor of triplanar mapping
  25015. let bf = normalNode.abs().normalize();
  25016. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  25017. // Triplanar mapping
  25018. const tx = positionNode.yz.mul( scaleNode );
  25019. const ty = positionNode.zx.mul( scaleNode );
  25020. const tz = positionNode.xy.mul( scaleNode );
  25021. // Base color
  25022. const textureX = textureXNode.value;
  25023. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  25024. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  25025. const cx = texture( textureX, tx ).mul( bf.x );
  25026. const cy = texture( textureY, ty ).mul( bf.y );
  25027. const cz = texture( textureZ, tz ).mul( bf.z );
  25028. return add( cx, cy, cz );
  25029. } );
  25030. /**
  25031. * TSL function for creating a triplanar textures node.
  25032. *
  25033. * @tsl
  25034. * @function
  25035. * @param {Node} textureXNode - First texture node.
  25036. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  25037. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  25038. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  25039. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  25040. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  25041. * @returns {Node<vec4>}
  25042. */
  25043. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  25044. const _reflectorPlane = new Plane();
  25045. const _normal = new Vector3();
  25046. const _reflectorWorldPosition = new Vector3();
  25047. const _cameraWorldPosition = new Vector3();
  25048. const _rotationMatrix = new Matrix4();
  25049. const _lookAtPosition = new Vector3( 0, 0, -1 );
  25050. const clipPlane = new Vector4();
  25051. const _view = new Vector3();
  25052. const _target = new Vector3();
  25053. const _q = new Vector4();
  25054. const _size$2 = new Vector2();
  25055. const _defaultRT = new RenderTarget();
  25056. const _defaultUV = screenUV.flipX();
  25057. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  25058. let _inReflector = false;
  25059. /**
  25060. * This node can be used to implement mirror-like flat reflective surfaces.
  25061. *
  25062. * ```js
  25063. * const groundReflector = reflector();
  25064. * material.colorNode = groundReflector;
  25065. *
  25066. * const plane = new Mesh( geometry, material );
  25067. * plane.add( groundReflector.target );
  25068. * ```
  25069. *
  25070. * @augments TextureNode
  25071. */
  25072. class ReflectorNode extends TextureNode {
  25073. static get type() {
  25074. return 'ReflectorNode';
  25075. }
  25076. /**
  25077. * Constructs a new reflector node.
  25078. *
  25079. * @param {Object} [parameters={}] - An object holding configuration parameters.
  25080. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  25081. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  25082. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  25083. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  25084. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  25085. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  25086. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  25087. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  25088. */
  25089. constructor( parameters = {} ) {
  25090. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  25091. /**
  25092. * A reference to the internal reflector base node which holds the actual implementation.
  25093. *
  25094. * @private
  25095. * @type {ReflectorBaseNode}
  25096. * @default ReflectorBaseNode
  25097. */
  25098. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  25099. /**
  25100. * A reference to the internal depth node.
  25101. *
  25102. * @private
  25103. * @type {?Node}
  25104. * @default null
  25105. */
  25106. this._depthNode = null;
  25107. this.setUpdateMatrix( false );
  25108. }
  25109. /**
  25110. * A reference to the internal reflector node.
  25111. *
  25112. * @type {ReflectorBaseNode}
  25113. */
  25114. get reflector() {
  25115. return this._reflectorBaseNode;
  25116. }
  25117. /**
  25118. * A reference to 3D object the reflector is linked to.
  25119. *
  25120. * @type {Object3D}
  25121. */
  25122. get target() {
  25123. return this._reflectorBaseNode.target;
  25124. }
  25125. /**
  25126. * Returns a node representing the mirror's depth. That can be used
  25127. * to implement more advanced reflection effects like distance attenuation.
  25128. *
  25129. * @return {Node} The depth node.
  25130. */
  25131. getDepthNode() {
  25132. if ( this._depthNode === null ) {
  25133. if ( this._reflectorBaseNode.depth !== true ) {
  25134. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  25135. }
  25136. this._depthNode = nodeObject( new ReflectorNode( {
  25137. defaultTexture: _defaultRT.depthTexture,
  25138. reflector: this._reflectorBaseNode
  25139. } ) );
  25140. }
  25141. return this._depthNode;
  25142. }
  25143. setup( builder ) {
  25144. // ignore if used in post-processing
  25145. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  25146. return super.setup( builder );
  25147. }
  25148. clone() {
  25149. const newNode = new this.constructor( this.reflectorNode );
  25150. newNode.uvNode = this.uvNode;
  25151. newNode.levelNode = this.levelNode;
  25152. newNode.biasNode = this.biasNode;
  25153. newNode.sampler = this.sampler;
  25154. newNode.depthNode = this.depthNode;
  25155. newNode.compareNode = this.compareNode;
  25156. newNode.gradNode = this.gradNode;
  25157. newNode.offsetNode = this.offsetNode;
  25158. newNode._reflectorBaseNode = this._reflectorBaseNode;
  25159. return newNode;
  25160. }
  25161. /**
  25162. * Frees internal resources. Should be called when the node is no longer in use.
  25163. */
  25164. dispose() {
  25165. super.dispose();
  25166. this._reflectorBaseNode.dispose();
  25167. }
  25168. }
  25169. /**
  25170. * Holds the actual implementation of the reflector.
  25171. *
  25172. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  25173. * in `ReflectorNode`, see #29619.
  25174. *
  25175. * @private
  25176. * @augments Node
  25177. */
  25178. class ReflectorBaseNode extends Node {
  25179. static get type() {
  25180. return 'ReflectorBaseNode';
  25181. }
  25182. /**
  25183. * Constructs a new reflector base node.
  25184. *
  25185. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  25186. * @param {Object} [parameters={}] - An object holding configuration parameters.
  25187. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  25188. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  25189. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  25190. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  25191. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  25192. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  25193. */
  25194. constructor( textureNode, parameters = {} ) {
  25195. super();
  25196. const {
  25197. target = new Object3D(),
  25198. resolutionScale = 1,
  25199. generateMipmaps = false,
  25200. bounces = true,
  25201. depth = false,
  25202. samples = 0
  25203. } = parameters;
  25204. /**
  25205. * Represents the rendered reflections as a texture node.
  25206. *
  25207. * @type {TextureNode}
  25208. */
  25209. this.textureNode = textureNode;
  25210. /**
  25211. * The 3D object the reflector is linked to.
  25212. *
  25213. * @type {Object3D}
  25214. * @default {new Object3D()}
  25215. */
  25216. this.target = target;
  25217. /**
  25218. * The resolution scale.
  25219. *
  25220. * @type {number}
  25221. * @default {1}
  25222. */
  25223. this.resolutionScale = resolutionScale;
  25224. if ( parameters.resolution !== undefined ) {
  25225. warnOnce( 'ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".' ); // @deprecated r180
  25226. this.resolutionScale = parameters.resolution;
  25227. }
  25228. /**
  25229. * Whether mipmaps should be generated or not.
  25230. *
  25231. * @type {boolean}
  25232. * @default {false}
  25233. */
  25234. this.generateMipmaps = generateMipmaps;
  25235. /**
  25236. * Whether reflectors can render other reflector nodes or not.
  25237. *
  25238. * @type {boolean}
  25239. * @default {true}
  25240. */
  25241. this.bounces = bounces;
  25242. /**
  25243. * Whether depth data should be generated or not.
  25244. *
  25245. * @type {boolean}
  25246. * @default {false}
  25247. */
  25248. this.depth = depth;
  25249. /**
  25250. * The number of anti-aliasing samples for the render-target
  25251. *
  25252. * @type {number}
  25253. * @default {0}
  25254. */
  25255. this.samples = samples;
  25256. /**
  25257. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  25258. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  25259. *
  25260. * @type {string}
  25261. * @default 'render'
  25262. */
  25263. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  25264. /**
  25265. * Weak map for managing virtual cameras.
  25266. *
  25267. * @type {WeakMap<Camera, Camera>}
  25268. */
  25269. this.virtualCameras = new WeakMap();
  25270. /**
  25271. * Weak map for managing render targets.
  25272. *
  25273. * @type {Map<Camera, RenderTarget>}
  25274. */
  25275. this.renderTargets = new Map();
  25276. /**
  25277. * Force render even if reflector is facing away from camera.
  25278. *
  25279. * @type {boolean}
  25280. * @default {false}
  25281. */
  25282. this.forceUpdate = false;
  25283. /**
  25284. * Whether the reflector has been rendered or not.
  25285. *
  25286. * When the reflector is facing away from the camera,
  25287. * this flag is set to `false` and the texture will be empty(black).
  25288. *
  25289. * @type {boolean}
  25290. * @default {false}
  25291. */
  25292. this.hasOutput = false;
  25293. }
  25294. /**
  25295. * Updates the resolution of the internal render target.
  25296. *
  25297. * @private
  25298. * @param {RenderTarget} renderTarget - The render target to resize.
  25299. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  25300. */
  25301. _updateResolution( renderTarget, renderer ) {
  25302. const resolution = this.resolutionScale;
  25303. renderer.getDrawingBufferSize( _size$2 );
  25304. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  25305. }
  25306. setup( builder ) {
  25307. this._updateResolution( _defaultRT, builder.renderer );
  25308. return super.setup( builder );
  25309. }
  25310. /**
  25311. * Frees internal resources. Should be called when the node is no longer in use.
  25312. */
  25313. dispose() {
  25314. super.dispose();
  25315. for ( const renderTarget of this.renderTargets.values() ) {
  25316. renderTarget.dispose();
  25317. }
  25318. }
  25319. /**
  25320. * Returns a virtual camera for the given camera. The virtual camera is used to
  25321. * render the scene from the reflector's view so correct reflections can be produced.
  25322. *
  25323. * @param {Camera} camera - The scene's camera.
  25324. * @return {Camera} The corresponding virtual camera.
  25325. */
  25326. getVirtualCamera( camera ) {
  25327. let virtualCamera = this.virtualCameras.get( camera );
  25328. if ( virtualCamera === undefined ) {
  25329. virtualCamera = camera.clone();
  25330. this.virtualCameras.set( camera, virtualCamera );
  25331. }
  25332. return virtualCamera;
  25333. }
  25334. /**
  25335. * Returns a render target for the given camera. The reflections are rendered
  25336. * into this render target.
  25337. *
  25338. * @param {Camera} camera - The scene's camera.
  25339. * @return {RenderTarget} The render target.
  25340. */
  25341. getRenderTarget( camera ) {
  25342. let renderTarget = this.renderTargets.get( camera );
  25343. if ( renderTarget === undefined ) {
  25344. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType, samples: this.samples } );
  25345. if ( this.generateMipmaps === true ) {
  25346. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  25347. renderTarget.texture.generateMipmaps = true;
  25348. }
  25349. if ( this.depth === true ) {
  25350. renderTarget.depthTexture = new DepthTexture();
  25351. }
  25352. this.renderTargets.set( camera, renderTarget );
  25353. }
  25354. return renderTarget;
  25355. }
  25356. updateBefore( frame ) {
  25357. if ( this.bounces === false && _inReflector ) return false;
  25358. _inReflector = true;
  25359. const { scene, camera, renderer, material } = frame;
  25360. const { target } = this;
  25361. const virtualCamera = this.getVirtualCamera( camera );
  25362. const renderTarget = this.getRenderTarget( virtualCamera );
  25363. renderer.getDrawingBufferSize( _size$2 );
  25364. this._updateResolution( renderTarget, renderer );
  25365. //
  25366. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  25367. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  25368. _rotationMatrix.extractRotation( target.matrixWorld );
  25369. _normal.set( 0, 0, 1 );
  25370. _normal.applyMatrix4( _rotationMatrix );
  25371. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  25372. // Avoid rendering when reflector is facing away unless forcing an update
  25373. const isFacingAway = _view.dot( _normal ) > 0;
  25374. let needsClear = false;
  25375. if ( isFacingAway === true && this.forceUpdate === false ) {
  25376. if ( this.hasOutput === false ) {
  25377. _inReflector = false;
  25378. return;
  25379. }
  25380. needsClear = true;
  25381. }
  25382. _view.reflect( _normal ).negate();
  25383. _view.add( _reflectorWorldPosition );
  25384. _rotationMatrix.extractRotation( camera.matrixWorld );
  25385. _lookAtPosition.set( 0, 0, -1 );
  25386. _lookAtPosition.applyMatrix4( _rotationMatrix );
  25387. _lookAtPosition.add( _cameraWorldPosition );
  25388. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  25389. _target.reflect( _normal ).negate();
  25390. _target.add( _reflectorWorldPosition );
  25391. //
  25392. virtualCamera.coordinateSystem = camera.coordinateSystem;
  25393. virtualCamera.position.copy( _view );
  25394. virtualCamera.up.set( 0, 1, 0 );
  25395. virtualCamera.up.applyMatrix4( _rotationMatrix );
  25396. virtualCamera.up.reflect( _normal );
  25397. virtualCamera.lookAt( _target );
  25398. virtualCamera.near = camera.near;
  25399. virtualCamera.far = camera.far;
  25400. virtualCamera.updateMatrixWorld();
  25401. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  25402. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  25403. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  25404. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  25405. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  25406. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  25407. const projectionMatrix = virtualCamera.projectionMatrix;
  25408. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  25409. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  25410. _q.z = -1;
  25411. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  25412. // Calculate the scaled plane vector
  25413. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  25414. const clipBias = 0;
  25415. // Replacing the third row of the projection matrix
  25416. projectionMatrix.elements[ 2 ] = clipPlane.x;
  25417. projectionMatrix.elements[ 6 ] = clipPlane.y;
  25418. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  25419. projectionMatrix.elements[ 14 ] = clipPlane.w;
  25420. //
  25421. this.textureNode.value = renderTarget.texture;
  25422. if ( this.depth === true ) {
  25423. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  25424. }
  25425. material.visible = false;
  25426. const currentRenderTarget = renderer.getRenderTarget();
  25427. const currentMRT = renderer.getMRT();
  25428. const currentAutoClear = renderer.autoClear;
  25429. renderer.setMRT( null );
  25430. renderer.setRenderTarget( renderTarget );
  25431. renderer.autoClear = true;
  25432. const previousName = scene.name;
  25433. scene.name = ( scene.name || 'Scene' ) + ' [ Reflector ]'; // TODO: Add bounce index
  25434. if ( needsClear ) {
  25435. renderer.clear();
  25436. this.hasOutput = false;
  25437. } else {
  25438. renderer.render( scene, virtualCamera );
  25439. this.hasOutput = true;
  25440. }
  25441. scene.name = previousName;
  25442. renderer.setMRT( currentMRT );
  25443. renderer.setRenderTarget( currentRenderTarget );
  25444. renderer.autoClear = currentAutoClear;
  25445. material.visible = true;
  25446. _inReflector = false;
  25447. this.forceUpdate = false;
  25448. }
  25449. /**
  25450. * The resolution scale.
  25451. *
  25452. * @deprecated
  25453. * @type {number}
  25454. * @default {1}
  25455. */
  25456. get resolution() {
  25457. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  25458. return this.resolutionScale;
  25459. }
  25460. set resolution( value ) {
  25461. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  25462. this.resolutionScale = value;
  25463. }
  25464. }
  25465. /**
  25466. * TSL function for creating a reflector node.
  25467. *
  25468. * @tsl
  25469. * @function
  25470. * @param {Object} [parameters={}] - An object holding configuration parameters.
  25471. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  25472. * @param {number} [parameters.resolution=1] - The resolution scale.
  25473. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  25474. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  25475. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  25476. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  25477. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  25478. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  25479. * @returns {ReflectorNode}
  25480. */
  25481. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  25482. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  25483. /**
  25484. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  25485. *
  25486. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  25487. *
  25488. * @private
  25489. * @augments BufferGeometry
  25490. */
  25491. class QuadGeometry extends BufferGeometry {
  25492. /**
  25493. * Constructs a new quad geometry.
  25494. *
  25495. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  25496. */
  25497. constructor( flipY = false ) {
  25498. super();
  25499. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  25500. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  25501. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  25502. }
  25503. }
  25504. const _geometry = /*@__PURE__*/ new QuadGeometry();
  25505. /**
  25506. * This module is a helper for passes which need to render a full
  25507. * screen effect which is quite common in context of post processing.
  25508. *
  25509. * The intended usage is to reuse a single quad mesh for rendering
  25510. * subsequent passes by just reassigning the `material` reference.
  25511. *
  25512. * Note: This module can only be used with `WebGPURenderer`.
  25513. *
  25514. * @augments Mesh
  25515. */
  25516. class QuadMesh extends Mesh {
  25517. /**
  25518. * Constructs a new quad mesh.
  25519. *
  25520. * @param {?Material} [material=null] - The material to render the quad mesh with.
  25521. */
  25522. constructor( material = null ) {
  25523. super( _geometry, material );
  25524. /**
  25525. * The camera to render the quad mesh with.
  25526. *
  25527. * @type {OrthographicCamera}
  25528. * @readonly
  25529. */
  25530. this.camera = _camera;
  25531. /**
  25532. * This flag can be used for type testing.
  25533. *
  25534. * @type {boolean}
  25535. * @readonly
  25536. * @default true
  25537. */
  25538. this.isQuadMesh = true;
  25539. }
  25540. /**
  25541. * Async version of `render()`.
  25542. *
  25543. * @async
  25544. * @deprecated
  25545. * @param {Renderer} renderer - The renderer.
  25546. * @return {Promise} A Promise that resolves when the render has been finished.
  25547. */
  25548. async renderAsync( renderer ) {
  25549. warnOnce( 'QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  25550. await renderer.init();
  25551. renderer.render( this, _camera );
  25552. }
  25553. /**
  25554. * Renders the quad mesh
  25555. *
  25556. * @param {Renderer} renderer - The renderer.
  25557. */
  25558. render( renderer ) {
  25559. renderer.render( this, _camera );
  25560. }
  25561. }
  25562. const _size$1 = /*@__PURE__*/ new Vector2();
  25563. /**
  25564. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  25565. * This module is especially relevant in context of post processing where certain nodes require
  25566. * texture input for their effects. With the helper function `convertToTexture()` which is based
  25567. * on this module, the node system can automatically ensure texture input if required.
  25568. *
  25569. * @augments TextureNode
  25570. */
  25571. class RTTNode extends TextureNode {
  25572. static get type() {
  25573. return 'RTTNode';
  25574. }
  25575. /**
  25576. * Constructs a new RTT node.
  25577. *
  25578. * @param {Node} node - The node to render a texture with.
  25579. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  25580. * @param {?number} [height=null] - The height of the internal render target.
  25581. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  25582. */
  25583. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  25584. const renderTarget = new RenderTarget( width, height, options );
  25585. super( renderTarget.texture, uv$1() );
  25586. /**
  25587. * This flag can be used for type testing.
  25588. *
  25589. * @type {boolean}
  25590. * @readonly
  25591. * @default true
  25592. */
  25593. this.isRTTNode = true;
  25594. /**
  25595. * The node to render a texture with.
  25596. *
  25597. * @type {Node}
  25598. */
  25599. this.node = node;
  25600. /**
  25601. * The width of the internal render target.
  25602. * If not width is applied, the render target is automatically resized.
  25603. *
  25604. * @type {?number}
  25605. * @default null
  25606. */
  25607. this.width = width;
  25608. /**
  25609. * The height of the internal render target.
  25610. *
  25611. * @type {?number}
  25612. * @default null
  25613. */
  25614. this.height = height;
  25615. /**
  25616. * The pixel ratio
  25617. *
  25618. * @type {number}
  25619. * @default 1
  25620. */
  25621. this.pixelRatio = 1;
  25622. /**
  25623. * The render target
  25624. *
  25625. * @type {RenderTarget}
  25626. */
  25627. this.renderTarget = renderTarget;
  25628. /**
  25629. * Whether the texture requires an update or not.
  25630. *
  25631. * @type {boolean}
  25632. * @default true
  25633. */
  25634. this.textureNeedsUpdate = true;
  25635. /**
  25636. * Whether the texture should automatically be updated or not.
  25637. *
  25638. * @type {boolean}
  25639. * @default true
  25640. */
  25641. this.autoUpdate = true;
  25642. /**
  25643. * The node which is used with the quad mesh for RTT.
  25644. *
  25645. * @private
  25646. * @type {Node}
  25647. * @default null
  25648. */
  25649. this._rttNode = null;
  25650. /**
  25651. * The internal quad mesh for RTT.
  25652. *
  25653. * @private
  25654. * @type {QuadMesh}
  25655. */
  25656. this._quadMesh = new QuadMesh( new NodeMaterial() );
  25657. /**
  25658. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  25659. * the texture once per render in its {@link RTTNode#updateBefore} method.
  25660. *
  25661. * @type {string}
  25662. * @default 'render'
  25663. */
  25664. this.updateBeforeType = NodeUpdateType.RENDER;
  25665. }
  25666. /**
  25667. * Whether the internal render target should automatically be resized or not.
  25668. *
  25669. * @type {boolean}
  25670. * @readonly
  25671. * @default true
  25672. */
  25673. get autoResize() {
  25674. return this.width === null;
  25675. }
  25676. setup( builder ) {
  25677. this._rttNode = this.node.context( builder.getSharedContext() );
  25678. this._quadMesh.material.name = 'RTT';
  25679. this._quadMesh.material.needsUpdate = true;
  25680. return super.setup( builder );
  25681. }
  25682. /**
  25683. * Sets the size of the internal render target
  25684. *
  25685. * @param {number} width - The width to set.
  25686. * @param {number} height - The width to set.
  25687. */
  25688. setSize( width, height ) {
  25689. this.width = width;
  25690. this.height = height;
  25691. const effectiveWidth = width * this.pixelRatio;
  25692. const effectiveHeight = height * this.pixelRatio;
  25693. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  25694. this.textureNeedsUpdate = true;
  25695. }
  25696. /**
  25697. * Sets the pixel ratio. This will also resize the render target.
  25698. *
  25699. * @param {number} pixelRatio - The pixel ratio to set.
  25700. */
  25701. setPixelRatio( pixelRatio ) {
  25702. this.pixelRatio = pixelRatio;
  25703. this.setSize( this.width, this.height );
  25704. }
  25705. updateBefore( { renderer } ) {
  25706. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  25707. this.textureNeedsUpdate = false;
  25708. //
  25709. if ( this.autoResize === true ) {
  25710. const pixelRatio = renderer.getPixelRatio();
  25711. const size = renderer.getSize( _size$1 );
  25712. const effectiveWidth = Math.floor( size.width * pixelRatio );
  25713. const effectiveHeight = Math.floor( size.height * pixelRatio );
  25714. if ( effectiveWidth !== this.renderTarget.width || effectiveHeight !== this.renderTarget.height ) {
  25715. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  25716. this.textureNeedsUpdate = true;
  25717. }
  25718. }
  25719. //
  25720. let name = 'RTT';
  25721. if ( this.node.name ) {
  25722. name = this.node.name + ' [ ' + name + ' ]';
  25723. }
  25724. this._quadMesh.material.fragmentNode = this._rttNode;
  25725. this._quadMesh.name = name;
  25726. //
  25727. const currentRenderTarget = renderer.getRenderTarget();
  25728. renderer.setRenderTarget( this.renderTarget );
  25729. this._quadMesh.render( renderer );
  25730. renderer.setRenderTarget( currentRenderTarget );
  25731. }
  25732. clone() {
  25733. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  25734. newNode.sampler = this.sampler;
  25735. newNode.referenceNode = this;
  25736. return newNode;
  25737. }
  25738. }
  25739. /**
  25740. * TSL function for creating a RTT node.
  25741. *
  25742. * @tsl
  25743. * @function
  25744. * @param {Node} node - The node to render a texture with.
  25745. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  25746. * @param {?number} [height=null] - The height of the internal render target.
  25747. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  25748. * @returns {RTTNode}
  25749. */
  25750. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  25751. /**
  25752. * TSL function for converting nodes to textures nodes.
  25753. *
  25754. * @tsl
  25755. * @function
  25756. * @param {Node} node - The node to render a texture with.
  25757. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  25758. * @param {?number} [height=null] - The height of the internal render target.
  25759. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  25760. * @returns {RTTNode}
  25761. */
  25762. const convertToTexture = ( node, ...params ) => {
  25763. if ( node.isSampleNode || node.isTextureNode ) return node;
  25764. if ( node.isPassNode ) return node.getTextureNode();
  25765. return rtt( node, ...params );
  25766. };
  25767. /**
  25768. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  25769. * depth value and the camera's inverse projection matrix.
  25770. *
  25771. * @tsl
  25772. * @function
  25773. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  25774. * @param {Node<float>} depth - The fragment's depth value.
  25775. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  25776. * @return {Node<vec3>} The fragments position in view space.
  25777. */
  25778. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  25779. let clipSpacePosition;
  25780. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  25781. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  25782. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  25783. } else {
  25784. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  25785. }
  25786. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  25787. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  25788. } );
  25789. /**
  25790. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  25791. * and the camera's projection matrix
  25792. *
  25793. * @tsl
  25794. * @function
  25795. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  25796. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  25797. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  25798. */
  25799. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  25800. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  25801. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  25802. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  25803. } );
  25804. /**
  25805. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  25806. * target is available or if flat surface normals are required.
  25807. *
  25808. * @tsl
  25809. * @function
  25810. * @param {Node<vec2>} uv - The texture coordinate.
  25811. * @param {DepthTexture} depthTexture - The depth texture.
  25812. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  25813. * @return {Node<vec3>} The computed normal vector.
  25814. */
  25815. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  25816. const size = textureSize( textureLoad( depthTexture ) );
  25817. const p = ivec2( uv.mul( size ) ).toVar();
  25818. const c0 = textureLoad( depthTexture, p ).toVar();
  25819. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  25820. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  25821. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  25822. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  25823. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  25824. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  25825. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  25826. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  25827. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  25828. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  25829. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  25830. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  25831. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  25832. 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 ) ) );
  25833. 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 ) ) );
  25834. return normalize( cross( dpdx, dpdy ) );
  25835. } );
  25836. /**
  25837. * Interleaved Gradient Noise (IGN) from Jimenez 2014.
  25838. *
  25839. * IGN has "low discrepancy" resulting in evenly distributed samples. It's superior compared to
  25840. * default white noise, blue noise or Bayer.
  25841. *
  25842. * References:
  25843. * - {@link https://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare/}
  25844. * - {@link https://blog.demofox.org/2022/01/01/interleaved-gradient-noise-a-different-kind-of-low-discrepancy-sequence/}
  25845. *
  25846. * @tsl
  25847. * @function
  25848. * @param {Node<vec2>} position - The input position, usually screen coordinates.
  25849. * @return {Node<float>} The noise value.
  25850. */
  25851. const interleavedGradientNoise = Fn( ( [ position ] ) => {
  25852. return fract( float( 52.9829189 ).mul( fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) ) );
  25853. } ).setLayout( {
  25854. name: 'interleavedGradientNoise',
  25855. type: 'float',
  25856. inputs: [
  25857. { name: 'position', type: 'vec2' }
  25858. ]
  25859. } );
  25860. /**
  25861. * Vogel disk sampling for uniform circular distribution.
  25862. *
  25863. * This function generates sample points distributed uniformly on a disk using the golden angle,
  25864. * resulting in an efficient low-discrepancy sequence for sampling. The rotation parameter (phi)
  25865. * allows randomizing the pattern per-pixel when combined with IGN.
  25866. *
  25867. * @tsl
  25868. * @function
  25869. * @param {Node<int>} sampleIndex - The index of the current sample (0-based).
  25870. * @param {Node<int>} samplesCount - The total number of samples.
  25871. * @param {Node<float>} phi - Rotation angle in radians (typically from IGN * 2π).
  25872. * @return {Node<vec2>} A 2D point on the unit disk.
  25873. */
  25874. const vogelDiskSample = Fn( ( [ sampleIndex, samplesCount, phi ] ) => {
  25875. const goldenAngle = float( 2.399963229728653 ); // 2π * (2 - φ) where φ is golden ratio
  25876. const r = sqrt( float( sampleIndex ).add( 0.5 ) ).div( sqrt( float( samplesCount ) ) );
  25877. const theta = float( sampleIndex ).mul( goldenAngle ).add( phi );
  25878. return vec2( cos( theta ), sin( theta ) ).mul( r );
  25879. } ).setLayout( {
  25880. name: 'vogelDiskSample',
  25881. type: 'vec2',
  25882. inputs: [
  25883. { name: 'sampleIndex', type: 'int' },
  25884. { name: 'samplesCount', type: 'int' },
  25885. { name: 'phi', type: 'float' }
  25886. ]
  25887. } );
  25888. /**
  25889. * Class representing a node that samples a value using a provided callback function.
  25890. *
  25891. * @extends Node
  25892. */
  25893. class SampleNode extends Node {
  25894. /**
  25895. * Returns the type of the node.
  25896. *
  25897. * @type {string}
  25898. * @readonly
  25899. * @static
  25900. */
  25901. static get type() {
  25902. return 'SampleNode';
  25903. }
  25904. /**
  25905. * Creates an instance of SampleNode.
  25906. *
  25907. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  25908. * @param {?Node<vec2>} [uvNode=null] - The UV node to be used in the texture sampling.
  25909. */
  25910. constructor( callback, uvNode = null ) {
  25911. super();
  25912. this.callback = callback;
  25913. /**
  25914. * Represents the texture coordinates.
  25915. *
  25916. * @type {?Node<vec2|vec3>}
  25917. * @default null
  25918. */
  25919. this.uvNode = uvNode;
  25920. /**
  25921. * This flag can be used for type testing.
  25922. *
  25923. * @type {boolean}
  25924. * @readonly
  25925. * @default true
  25926. */
  25927. this.isSampleNode = true;
  25928. }
  25929. /**
  25930. * Sets up the node by sampling with the default UV accessor.
  25931. *
  25932. * @returns {Node} The result of the callback function when called with the UV node.
  25933. */
  25934. setup() {
  25935. return this.sample( uv$1() );
  25936. }
  25937. /**
  25938. * Calls the callback function with the provided UV node.
  25939. *
  25940. * @param {Node<vec2>} uv - The UV node or value to be passed to the callback.
  25941. * @returns {Node} The result of the callback function.
  25942. */
  25943. sample( uv ) {
  25944. return this.callback( uv );
  25945. }
  25946. }
  25947. /**
  25948. * Helper function to create a SampleNode wrapped as a node object.
  25949. *
  25950. * @function
  25951. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  25952. * @param {?Node<vec2>} [uv=null] - The UV node to be used in the texture sampling.
  25953. * @returns {SampleNode} The created SampleNode instance wrapped as a node object.
  25954. */
  25955. const sample = ( callback, uv = null ) => nodeObject( new SampleNode( callback, nodeObject( uv ) ) );
  25956. /**
  25957. * EventNode is a node that executes a callback during specific update phases.
  25958. *
  25959. * @augments Node
  25960. */
  25961. class EventNode extends Node {
  25962. static get type() {
  25963. return 'EventNode';
  25964. }
  25965. /**
  25966. * Creates an EventNode.
  25967. *
  25968. * @param {string} eventType - The type of event
  25969. * @param {Function} callback - The callback to execute on update.
  25970. */
  25971. constructor( eventType, callback ) {
  25972. super( 'void' );
  25973. this.eventType = eventType;
  25974. this.callback = callback;
  25975. if ( eventType === EventNode.OBJECT ) {
  25976. this.updateType = NodeUpdateType.OBJECT;
  25977. } else if ( eventType === EventNode.MATERIAL ) {
  25978. this.updateType = NodeUpdateType.RENDER;
  25979. } else if ( eventType === EventNode.BEFORE_OBJECT ) {
  25980. this.updateBeforeType = NodeUpdateType.OBJECT;
  25981. } else if ( eventType === EventNode.BEFORE_MATERIAL ) {
  25982. this.updateBeforeType = NodeUpdateType.RENDER;
  25983. }
  25984. }
  25985. update( frame ) {
  25986. this.callback( frame );
  25987. }
  25988. updateBefore( frame ) {
  25989. this.callback( frame );
  25990. }
  25991. }
  25992. EventNode.OBJECT = 'object';
  25993. EventNode.MATERIAL = 'material';
  25994. EventNode.BEFORE_OBJECT = 'beforeObject';
  25995. EventNode.BEFORE_MATERIAL = 'beforeMaterial';
  25996. /**
  25997. * Helper to create an EventNode and add it to the stack.
  25998. *
  25999. * @param {string} type - The event type.
  26000. * @param {Function} callback - The callback function.
  26001. * @returns {EventNode}
  26002. */
  26003. const createEvent = ( type, callback ) => nodeObject( new EventNode( type, callback ) ).toStack();
  26004. /**
  26005. * Creates an event that triggers a function every time an object (Mesh|Sprite) is rendered.
  26006. *
  26007. * 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.
  26008. *
  26009. * @param {Function} callback - The callback function.
  26010. * @returns {EventNode}
  26011. */
  26012. const OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback );
  26013. /**
  26014. * Creates an event that triggers a function when the first object that uses the material is rendered.
  26015. *
  26016. * 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.
  26017. *
  26018. * @param {Function} callback - The callback function.
  26019. * @returns {EventNode}
  26020. */
  26021. const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback );
  26022. /**
  26023. * Creates an event that triggers a function before an object (Mesh|Sprite) is updated.
  26024. *
  26025. * 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.
  26026. *
  26027. * @param {Function} callback - The callback function.
  26028. * @returns {EventNode}
  26029. */
  26030. const OnBeforeObjectUpdate = ( callback ) => createEvent( EventNode.BEFORE_OBJECT, callback );
  26031. /**
  26032. * Creates an event that triggers a function before the material is updated.
  26033. *
  26034. * 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.
  26035. *
  26036. * @param {Function} callback - The callback function.
  26037. * @returns {EventNode}
  26038. */
  26039. const OnBeforeMaterialUpdate = ( callback ) => createEvent( EventNode.BEFORE_MATERIAL, callback );
  26040. /**
  26041. * This special type of instanced buffer attribute is intended for compute shaders.
  26042. * In earlier three.js versions it was only possible to update attribute data
  26043. * on the CPU via JavaScript and then upload the data to the GPU. With the
  26044. * new material system and renderer it is now possible to use compute shaders
  26045. * to compute the data for an attribute more efficiently on the GPU.
  26046. *
  26047. * The idea is to create an instance of this class and provide it as an input
  26048. * to {@link StorageBufferNode}.
  26049. *
  26050. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  26051. *
  26052. * @augments InstancedBufferAttribute
  26053. */
  26054. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  26055. /**
  26056. * Constructs a new storage instanced buffer attribute.
  26057. *
  26058. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  26059. * The subsequent parameters are then obsolete.
  26060. * @param {number} itemSize - The item size.
  26061. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  26062. */
  26063. constructor( count, itemSize, typeClass = Float32Array ) {
  26064. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  26065. super( array, itemSize );
  26066. /**
  26067. * This flag can be used for type testing.
  26068. *
  26069. * @type {boolean}
  26070. * @readonly
  26071. * @default true
  26072. */
  26073. this.isStorageInstancedBufferAttribute = true;
  26074. }
  26075. }
  26076. /**
  26077. * This special type of buffer attribute is intended for compute shaders.
  26078. * In earlier three.js versions it was only possible to update attribute data
  26079. * on the CPU via JavaScript and then upload the data to the GPU. With the
  26080. * new material system and renderer it is now possible to use compute shaders
  26081. * to compute the data for an attribute more efficiently on the GPU.
  26082. *
  26083. * The idea is to create an instance of this class and provide it as an input
  26084. * to {@link StorageBufferNode}.
  26085. *
  26086. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  26087. *
  26088. * @augments BufferAttribute
  26089. */
  26090. class StorageBufferAttribute extends BufferAttribute {
  26091. /**
  26092. * Constructs a new storage buffer attribute.
  26093. *
  26094. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  26095. * The subsequent parameters are then obsolete.
  26096. * @param {number} itemSize - The item size.
  26097. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  26098. */
  26099. constructor( count, itemSize, typeClass = Float32Array ) {
  26100. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  26101. super( array, itemSize );
  26102. /**
  26103. * This flag can be used for type testing.
  26104. *
  26105. * @type {boolean}
  26106. * @readonly
  26107. * @default true
  26108. */
  26109. this.isStorageBufferAttribute = true;
  26110. }
  26111. }
  26112. /**
  26113. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  26114. *
  26115. * @tsl
  26116. * @function
  26117. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  26118. * @param {string|Struct} [type='float'] - The data type.
  26119. * @returns {StorageBufferNode}
  26120. */
  26121. const attributeArray = ( count, type = 'float' ) => {
  26122. let itemSize, typedArray;
  26123. if ( type.isStruct === true ) {
  26124. itemSize = type.layout.getLength();
  26125. typedArray = getTypedArrayFromType( 'float' );
  26126. } else {
  26127. itemSize = getLengthFromType( type );
  26128. typedArray = getTypedArrayFromType( type );
  26129. }
  26130. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  26131. const node = storage( buffer, type, count );
  26132. return node;
  26133. };
  26134. /**
  26135. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  26136. *
  26137. * @tsl
  26138. * @function
  26139. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  26140. * @param {string|Struct} [type='float'] - The data type.
  26141. * @returns {StorageBufferNode}
  26142. */
  26143. const instancedArray = ( count, type = 'float' ) => {
  26144. let itemSize, typedArray;
  26145. if ( type.isStruct === true ) {
  26146. itemSize = type.layout.getLength();
  26147. typedArray = getTypedArrayFromType( 'float' );
  26148. } else {
  26149. itemSize = getLengthFromType( type );
  26150. typedArray = getTypedArrayFromType( type );
  26151. }
  26152. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  26153. const node = storage( buffer, type, count );
  26154. return node;
  26155. };
  26156. /**
  26157. * A node for representing the uv coordinates of points.
  26158. *
  26159. * Can only be used with a WebGL backend. In WebGPU, point
  26160. * primitives always have the size of one pixel and can thus
  26161. * can't be used as sprite-like objects that display textures.
  26162. *
  26163. * @augments Node
  26164. */
  26165. class PointUVNode extends Node {
  26166. static get type() {
  26167. return 'PointUVNode';
  26168. }
  26169. /**
  26170. * Constructs a new point uv node.
  26171. */
  26172. constructor() {
  26173. super( 'vec2' );
  26174. /**
  26175. * This flag can be used for type testing.
  26176. *
  26177. * @type {boolean}
  26178. * @readonly
  26179. * @default true
  26180. */
  26181. this.isPointUVNode = true;
  26182. }
  26183. generate( /*builder*/ ) {
  26184. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  26185. }
  26186. }
  26187. /**
  26188. * TSL object that represents the uv coordinates of points.
  26189. *
  26190. * @tsl
  26191. * @type {PointUVNode}
  26192. */
  26193. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  26194. const _e1 = /*@__PURE__*/ new Euler();
  26195. const _m1 = /*@__PURE__*/ new Matrix4();
  26196. /**
  26197. * This module allows access to a collection of scene properties. The following predefined TSL objects
  26198. * are available for easier use:
  26199. *
  26200. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  26201. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  26202. * - `backgroundRotation`: A node that represents the scene's background rotation.
  26203. *
  26204. * @augments Node
  26205. */
  26206. class SceneNode extends Node {
  26207. static get type() {
  26208. return 'SceneNode';
  26209. }
  26210. /**
  26211. * Constructs a new scene node.
  26212. *
  26213. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  26214. * @param {?Scene} [scene=null] - A reference to the scene.
  26215. */
  26216. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  26217. super();
  26218. /**
  26219. * The scope defines the type of scene property that is accessed.
  26220. *
  26221. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  26222. */
  26223. this.scope = scope;
  26224. /**
  26225. * A reference to the scene that is going to be accessed.
  26226. *
  26227. * @type {?Scene}
  26228. * @default null
  26229. */
  26230. this.scene = scene;
  26231. }
  26232. /**
  26233. * Depending on the scope, the method returns a different type of node that represents
  26234. * the respective scene property.
  26235. *
  26236. * @param {NodeBuilder} builder - The current node builder.
  26237. * @return {Node} The output node.
  26238. */
  26239. setup( builder ) {
  26240. const scope = this.scope;
  26241. const scene = this.scene !== null ? this.scene : builder.scene;
  26242. let output;
  26243. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  26244. output = reference( 'backgroundBlurriness', 'float', scene );
  26245. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  26246. output = reference( 'backgroundIntensity', 'float', scene );
  26247. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  26248. output = uniform( 'mat4' ).setName( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  26249. const background = scene.background;
  26250. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  26251. _e1.copy( scene.backgroundRotation );
  26252. // accommodate left-handed frame
  26253. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  26254. _m1.makeRotationFromEuler( _e1 );
  26255. } else {
  26256. _m1.identity();
  26257. }
  26258. return _m1;
  26259. } );
  26260. } else {
  26261. error( 'SceneNode: Unknown scope:', scope );
  26262. }
  26263. return output;
  26264. }
  26265. }
  26266. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  26267. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  26268. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  26269. /**
  26270. * TSL object that represents the scene's background blurriness.
  26271. *
  26272. * @tsl
  26273. * @type {SceneNode}
  26274. */
  26275. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  26276. /**
  26277. * TSL object that represents the scene's background intensity.
  26278. *
  26279. * @tsl
  26280. * @type {SceneNode}
  26281. */
  26282. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  26283. /**
  26284. * TSL object that represents the scene's background rotation.
  26285. *
  26286. * @tsl
  26287. * @type {SceneNode}
  26288. */
  26289. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  26290. /**
  26291. * This special version of a texture node can be used to
  26292. * write data into a storage texture with a compute shader.
  26293. *
  26294. * ```js
  26295. * const storageTexture = new THREE.StorageTexture( width, height );
  26296. *
  26297. * const computeTexture = Fn( ( { storageTexture } ) => {
  26298. *
  26299. * const posX = instanceIndex.mod( width );
  26300. * const posY = instanceIndex.div( width );
  26301. * const indexUV = uvec2( posX, posY );
  26302. *
  26303. * // generate RGB values
  26304. *
  26305. * const r = 1;
  26306. * const g = 1;
  26307. * const b = 1;
  26308. *
  26309. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  26310. *
  26311. * } );
  26312. *
  26313. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  26314. * renderer.computeAsync( computeNode );
  26315. * ```
  26316. *
  26317. * This node can only be used with a WebGPU backend.
  26318. *
  26319. * @augments TextureNode
  26320. */
  26321. class StorageTextureNode extends TextureNode {
  26322. static get type() {
  26323. return 'StorageTextureNode';
  26324. }
  26325. /**
  26326. * Constructs a new storage texture node.
  26327. *
  26328. * @param {StorageTexture} value - The storage texture.
  26329. * @param {Node<vec2|vec3>} uvNode - The uv node.
  26330. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  26331. */
  26332. constructor( value, uvNode, storeNode = null ) {
  26333. super( value, uvNode );
  26334. /**
  26335. * The value node that should be stored in the texture.
  26336. *
  26337. * @type {?Node}
  26338. * @default null
  26339. */
  26340. this.storeNode = storeNode;
  26341. /**
  26342. * The mip level to write to for storage textures.
  26343. *
  26344. * @type {number}
  26345. * @default 0
  26346. */
  26347. this.mipLevel = 0;
  26348. /**
  26349. * This flag can be used for type testing.
  26350. *
  26351. * @type {boolean}
  26352. * @readonly
  26353. * @default true
  26354. */
  26355. this.isStorageTextureNode = true;
  26356. /**
  26357. * The access type of the texture node.
  26358. *
  26359. * @type {string}
  26360. * @default 'writeOnly'
  26361. */
  26362. this.access = NodeAccess.WRITE_ONLY;
  26363. }
  26364. /**
  26365. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  26366. *
  26367. * @param {NodeBuilder} builder - The current node builder.
  26368. * @return {string} The input type.
  26369. */
  26370. getInputType( /*builder*/ ) {
  26371. return 'storageTexture';
  26372. }
  26373. setup( builder ) {
  26374. super.setup( builder );
  26375. const properties = builder.getNodeProperties( this );
  26376. properties.storeNode = this.storeNode;
  26377. return properties;
  26378. }
  26379. /**
  26380. * Defines the node access.
  26381. *
  26382. * @param {string} value - The node access.
  26383. * @return {StorageTextureNode} A reference to this node.
  26384. */
  26385. setAccess( value ) {
  26386. this.access = value;
  26387. return this;
  26388. }
  26389. /**
  26390. * Sets the mip level to write to.
  26391. *
  26392. * @param {number} level - The mip level.
  26393. * @return {StorageTextureNode} A reference to this node.
  26394. */
  26395. setMipLevel( level ) {
  26396. this.mipLevel = level;
  26397. return this;
  26398. }
  26399. /**
  26400. * Generates the code snippet of the storage node. If no `storeNode`
  26401. * is defined, the texture node is generated as normal texture.
  26402. *
  26403. * @param {NodeBuilder} builder - The current node builder.
  26404. * @param {string} output - The current output.
  26405. * @return {string} The generated code snippet.
  26406. */
  26407. generate( builder, output ) {
  26408. let snippet;
  26409. if ( this.storeNode !== null ) {
  26410. snippet = this.generateStore( builder );
  26411. } else {
  26412. snippet = super.generate( builder, output );
  26413. }
  26414. return snippet;
  26415. }
  26416. /**
  26417. * Convenience method for configuring a read/write node access.
  26418. *
  26419. * @return {StorageTextureNode} A reference to this node.
  26420. */
  26421. toReadWrite() {
  26422. return this.setAccess( NodeAccess.READ_WRITE );
  26423. }
  26424. /**
  26425. * Convenience method for configuring a read-only node access.
  26426. *
  26427. * @return {StorageTextureNode} A reference to this node.
  26428. */
  26429. toReadOnly() {
  26430. return this.setAccess( NodeAccess.READ_ONLY );
  26431. }
  26432. /**
  26433. * Convenience method for configuring a write-only node access.
  26434. *
  26435. * @return {StorageTextureNode} A reference to this node.
  26436. */
  26437. toWriteOnly() {
  26438. return this.setAccess( NodeAccess.WRITE_ONLY );
  26439. }
  26440. /**
  26441. * Generates the code snippet of the storage texture node.
  26442. *
  26443. * @param {NodeBuilder} builder - The current node builder.
  26444. */
  26445. generateStore( builder ) {
  26446. const properties = builder.getNodeProperties( this );
  26447. const { uvNode, storeNode, depthNode } = properties;
  26448. const textureProperty = super.generate( builder, 'property' );
  26449. const uvSnippet = uvNode.build( builder, this.value.is3DTexture === true ? 'uvec3' : 'uvec2' );
  26450. const storeSnippet = storeNode.build( builder, 'vec4' );
  26451. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  26452. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  26453. builder.addLineFlowCode( snippet, this );
  26454. }
  26455. clone() {
  26456. const newNode = super.clone();
  26457. newNode.storeNode = this.storeNode;
  26458. newNode.mipLevel = this.mipLevel;
  26459. return newNode;
  26460. }
  26461. }
  26462. /**
  26463. * TSL function for creating a storage texture node.
  26464. *
  26465. * @tsl
  26466. * @function
  26467. * @param {StorageTexture} value - The storage texture.
  26468. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  26469. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  26470. * @returns {StorageTextureNode}
  26471. */
  26472. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  26473. /**
  26474. * TODO: Explain difference to `storageTexture()`.
  26475. *
  26476. * @tsl
  26477. * @function
  26478. * @param {StorageTexture} value - The storage texture.
  26479. * @param {Node<vec2|vec3>} uvNode - The uv node.
  26480. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  26481. * @returns {StorageTextureNode}
  26482. */
  26483. const textureStore = ( value, uvNode, storeNode ) => {
  26484. const node = storageTexture( value, uvNode, storeNode );
  26485. if ( storeNode !== null ) node.toStack();
  26486. return node;
  26487. };
  26488. const normal = Fn( ( { texture, uv } ) => {
  26489. const epsilon = 0.0001;
  26490. const ret = vec3().toVar();
  26491. If( uv.x.lessThan( epsilon ), () => {
  26492. ret.assign( vec3( 1, 0, 0 ) );
  26493. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  26494. ret.assign( vec3( 0, 1, 0 ) );
  26495. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  26496. ret.assign( vec3( 0, 0, 1 ) );
  26497. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  26498. ret.assign( vec3( -1, 0, 0 ) );
  26499. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  26500. ret.assign( vec3( 0, -1, 0 ) );
  26501. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  26502. ret.assign( vec3( 0, 0, -1 ) );
  26503. } ).Else( () => {
  26504. const step = 0.01;
  26505. 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 );
  26506. 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 );
  26507. 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 );
  26508. ret.assign( vec3( x, y, z ) );
  26509. } );
  26510. return ret.normalize();
  26511. } );
  26512. /**
  26513. * This type of uniform node represents a 3D texture.
  26514. *
  26515. * @augments TextureNode
  26516. */
  26517. class Texture3DNode extends TextureNode {
  26518. static get type() {
  26519. return 'Texture3DNode';
  26520. }
  26521. /**
  26522. * Constructs a new 3D texture node.
  26523. *
  26524. * @param {Data3DTexture} value - The 3D texture.
  26525. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  26526. * @param {?Node<int>} [levelNode=null] - The level node.
  26527. */
  26528. constructor( value, uvNode = null, levelNode = null ) {
  26529. super( value, uvNode, levelNode );
  26530. /**
  26531. * This flag can be used for type testing.
  26532. *
  26533. * @type {boolean}
  26534. * @readonly
  26535. * @default true
  26536. */
  26537. this.isTexture3DNode = true;
  26538. }
  26539. /**
  26540. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  26541. *
  26542. * @param {NodeBuilder} builder - The current node builder.
  26543. * @return {string} The input type.
  26544. */
  26545. getInputType( /*builder*/ ) {
  26546. return 'texture3D';
  26547. }
  26548. /**
  26549. * Returns a default uv node which is in context of 3D textures a three-dimensional
  26550. * uv node.
  26551. *
  26552. * @return {Node<vec3>} The default uv node.
  26553. */
  26554. getDefaultUV() {
  26555. return vec3( 0.5, 0.5, 0.5 );
  26556. }
  26557. /**
  26558. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  26559. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  26560. *
  26561. * @param {boolean} value - The update toggle.
  26562. */
  26563. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  26564. /**
  26565. * Overwrites the default implementation to return the unmodified uv node.
  26566. *
  26567. * @param {NodeBuilder} builder - The current node builder.
  26568. * @param {Node} uvNode - The uv node to setup.
  26569. * @return {Node} The unmodified uv node.
  26570. */
  26571. setupUV( builder, uvNode ) {
  26572. const texture = this.value;
  26573. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  26574. if ( this.sampler ) {
  26575. uvNode = uvNode.flipY();
  26576. } else {
  26577. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  26578. }
  26579. }
  26580. return uvNode;
  26581. }
  26582. /**
  26583. * Generates the uv code snippet.
  26584. *
  26585. * @param {NodeBuilder} builder - The current node builder.
  26586. * @param {Node} uvNode - The uv node to generate code for.
  26587. * @return {string} The generated code snippet.
  26588. */
  26589. generateUV( builder, uvNode ) {
  26590. return uvNode.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  26591. }
  26592. /**
  26593. * Generates the offset code snippet.
  26594. *
  26595. * @param {NodeBuilder} builder - The current node builder.
  26596. * @param {Node} offsetNode - The offset node to generate code for.
  26597. * @return {string} The generated code snippet.
  26598. */
  26599. generateOffset( builder, offsetNode ) {
  26600. return offsetNode.build( builder, 'ivec3' );
  26601. }
  26602. /**
  26603. * TODO.
  26604. *
  26605. * @param {Node<vec3>} uvNode - The uv node .
  26606. * @return {Node<vec3>} TODO.
  26607. */
  26608. normal( uvNode ) {
  26609. return normal( { texture: this, uv: uvNode } );
  26610. }
  26611. }
  26612. /**
  26613. * TSL function for creating a 3D texture node.
  26614. *
  26615. * @tsl
  26616. * @function
  26617. * @param {Data3DTexture} value - The 3D texture.
  26618. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  26619. * @param {?Node<int>} [levelNode=null] - The level node.
  26620. * @returns {Texture3DNode}
  26621. */
  26622. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  26623. /**
  26624. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  26625. *
  26626. * @tsl
  26627. * @function
  26628. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  26629. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  26630. * @param {?Node<int>} [levelNode=null] - The level node.
  26631. * @param {?Node<float>} [biasNode=null] - The bias node.
  26632. * @returns {TextureNode}
  26633. */
  26634. const texture3DLoad = ( ...params ) => texture3D( ...params ).setSampler( false );
  26635. /**
  26636. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  26637. *
  26638. * @tsl
  26639. * @function
  26640. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  26641. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  26642. * @param {?Node<int>} [levelNode=null] - The level node.
  26643. * @returns {TextureNode}
  26644. */
  26645. const texture3DLevel = ( value, uvNode, levelNode ) => texture3D( value, uvNode ).level( levelNode );
  26646. /**
  26647. * A special type of reference node that allows to link values in
  26648. * `userData` fields to node objects.
  26649. * ```js
  26650. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  26651. *
  26652. * const material = new THREE.SpriteNodeMaterial();
  26653. * material.rotationNode = userData( 'rotation', 'float' );
  26654. * ```
  26655. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  26656. * will automatically be updated when the `rotation` user data field changes.
  26657. *
  26658. * @augments ReferenceNode
  26659. */
  26660. class UserDataNode extends ReferenceNode {
  26661. static get type() {
  26662. return 'UserDataNode';
  26663. }
  26664. /**
  26665. * Constructs a new user data node.
  26666. *
  26667. * @param {string} property - The property name that should be referenced by the node.
  26668. * @param {string} inputType - The node data type of the reference.
  26669. * @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.
  26670. */
  26671. constructor( property, inputType, userData = null ) {
  26672. super( property, inputType, userData );
  26673. /**
  26674. * A reference to the `userData` object. If not provided, the `userData`
  26675. * property of the 3D object that uses the node material is evaluated.
  26676. *
  26677. * @type {?Object}
  26678. * @default null
  26679. */
  26680. this.userData = userData;
  26681. }
  26682. /**
  26683. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  26684. * `userData` field.
  26685. *
  26686. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  26687. * @return {Object} A reference to the `userData` field.
  26688. */
  26689. updateReference( state ) {
  26690. this.reference = this.userData !== null ? this.userData : state.object.userData;
  26691. return this.reference;
  26692. }
  26693. }
  26694. /**
  26695. * TSL function for creating a user data node.
  26696. *
  26697. * @tsl
  26698. * @function
  26699. * @param {string} name - The property name that should be referenced by the node.
  26700. * @param {string} inputType - The node data type of the reference.
  26701. * @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.
  26702. * @returns {UserDataNode}
  26703. */
  26704. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  26705. const _objectData = new WeakMap();
  26706. /**
  26707. * A node for representing motion or velocity vectors. Foundation
  26708. * for advanced post processing effects like motion blur or TRAA.
  26709. *
  26710. * The node keeps track of the model, view and projection matrices
  26711. * of the previous frame and uses them to compute offsets in NDC space.
  26712. * These offsets represent the final velocity.
  26713. *
  26714. * @augments TempNode
  26715. */
  26716. class VelocityNode extends TempNode {
  26717. static get type() {
  26718. return 'VelocityNode';
  26719. }
  26720. /**
  26721. * Constructs a new vertex color node.
  26722. */
  26723. constructor() {
  26724. super( 'vec2' );
  26725. /**
  26726. * The current projection matrix.
  26727. *
  26728. * @type {?Matrix4}
  26729. * @default null
  26730. */
  26731. this.projectionMatrix = null;
  26732. /**
  26733. * Overwritten since velocity nodes are updated per object.
  26734. *
  26735. * @type {string}
  26736. * @default 'object'
  26737. */
  26738. this.updateType = NodeUpdateType.OBJECT;
  26739. /**
  26740. * Overwritten since velocity nodes save data after the update.
  26741. *
  26742. * @type {string}
  26743. * @default 'object'
  26744. */
  26745. this.updateAfterType = NodeUpdateType.OBJECT;
  26746. /**
  26747. * Uniform node representing the previous model matrix in world space.
  26748. *
  26749. * @type {UniformNode<mat4>}
  26750. * @default null
  26751. */
  26752. this.previousModelWorldMatrix = uniform( new Matrix4() );
  26753. /**
  26754. * Uniform node representing the previous projection matrix.
  26755. *
  26756. * @type {UniformNode<mat4>}
  26757. * @default null
  26758. */
  26759. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  26760. /**
  26761. * Uniform node representing the previous view matrix.
  26762. *
  26763. * @type {UniformNode<mat4>}
  26764. * @default null
  26765. */
  26766. this.previousCameraViewMatrix = uniform( new Matrix4() );
  26767. }
  26768. /**
  26769. * Sets the given projection matrix.
  26770. *
  26771. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  26772. */
  26773. setProjectionMatrix( projectionMatrix ) {
  26774. this.projectionMatrix = projectionMatrix;
  26775. }
  26776. /**
  26777. * Updates velocity specific uniforms.
  26778. *
  26779. * @param {NodeFrame} frame - A reference to the current node frame.
  26780. */
  26781. update( { frameId, camera, object } ) {
  26782. const previousModelMatrix = getPreviousMatrix( object );
  26783. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  26784. //
  26785. const cameraData = getData( camera );
  26786. if ( cameraData.frameId !== frameId ) {
  26787. cameraData.frameId = frameId;
  26788. if ( cameraData.previousProjectionMatrix === undefined ) {
  26789. cameraData.previousProjectionMatrix = new Matrix4();
  26790. cameraData.previousCameraViewMatrix = new Matrix4();
  26791. cameraData.currentProjectionMatrix = new Matrix4();
  26792. cameraData.currentCameraViewMatrix = new Matrix4();
  26793. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  26794. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  26795. } else {
  26796. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  26797. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  26798. }
  26799. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  26800. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  26801. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  26802. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  26803. }
  26804. }
  26805. /**
  26806. * Overwritten to updated velocity specific uniforms.
  26807. *
  26808. * @param {NodeFrame} frame - A reference to the current node frame.
  26809. */
  26810. updateAfter( { object } ) {
  26811. getPreviousMatrix( object ).copy( object.matrixWorld );
  26812. }
  26813. /**
  26814. * Implements the velocity computation based on the previous and current vertex data.
  26815. *
  26816. * @param {NodeBuilder} builder - A reference to the current node builder.
  26817. * @return {Node<vec2>} The motion vector.
  26818. */
  26819. setup( /*builder*/ ) {
  26820. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  26821. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  26822. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  26823. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  26824. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  26825. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  26826. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  26827. return velocity;
  26828. }
  26829. }
  26830. function getData( object ) {
  26831. let objectData = _objectData.get( object );
  26832. if ( objectData === undefined ) {
  26833. objectData = {};
  26834. _objectData.set( object, objectData );
  26835. }
  26836. return objectData;
  26837. }
  26838. function getPreviousMatrix( object, index = 0 ) {
  26839. const objectData = getData( object );
  26840. let matrix = objectData[ index ];
  26841. if ( matrix === undefined ) {
  26842. objectData[ index ] = matrix = new Matrix4();
  26843. objectData[ index ].copy( object.matrixWorld );
  26844. }
  26845. return matrix;
  26846. }
  26847. /**
  26848. * TSL object that represents the velocity of a render pass.
  26849. *
  26850. * @tsl
  26851. * @type {VelocityNode}
  26852. */
  26853. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  26854. /**
  26855. * Computes a grayscale value for the given RGB color value.
  26856. *
  26857. * @tsl
  26858. * @function
  26859. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  26860. * @return {Node<vec3>} The grayscale color.
  26861. */
  26862. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  26863. return luminance( color.rgb );
  26864. } );
  26865. /**
  26866. * Super-saturates or desaturates the given RGB color.
  26867. *
  26868. * @tsl
  26869. * @function
  26870. * @param {Node<vec3>} color - The input color.
  26871. * @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.
  26872. * @return {Node<vec3>} The saturated color.
  26873. */
  26874. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  26875. return adjustment.mix( luminance( color.rgb ), color.rgb );
  26876. } );
  26877. /**
  26878. * Selectively enhance the intensity of less saturated RGB colors. Can result
  26879. * in a more natural and visually appealing image with enhanced color depth
  26880. * compared to {@link ColorAdjustment#saturation}.
  26881. *
  26882. * @tsl
  26883. * @function
  26884. * @param {Node<vec3>} color - The input color.
  26885. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  26886. * @return {Node<vec3>} The updated color.
  26887. */
  26888. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  26889. const average = add( color.r, color.g, color.b ).div( 3.0 );
  26890. const mx = color.r.max( color.g.max( color.b ) );
  26891. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  26892. return mix( color.rgb, mx, amt );
  26893. } );
  26894. /**
  26895. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  26896. *
  26897. * @tsl
  26898. * @function
  26899. * @param {Node<vec3>} color - The input color.
  26900. * @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.
  26901. * @return {Node<vec3>} The updated color.
  26902. */
  26903. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  26904. const k = vec3( 0.57735, 0.57735, 0.57735 );
  26905. const cosAngle = adjustment.cos();
  26906. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  26907. } );
  26908. /**
  26909. * Computes the luminance for the given RGB color value.
  26910. *
  26911. * @tsl
  26912. * @function
  26913. * @param {Node<vec3>} color - The color value to compute the luminance for.
  26914. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  26915. * @return {Node<float>} The luminance.
  26916. */
  26917. const luminance = (
  26918. color,
  26919. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  26920. ) => dot( color, luminanceCoefficients );
  26921. /**
  26922. * Color Decision List (CDL) v1.2
  26923. *
  26924. * Compact representation of color grading information, defined by slope, offset, power, and
  26925. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  26926. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  26927. *
  26928. * @tsl
  26929. * @function
  26930. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  26931. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  26932. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  26933. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  26934. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  26935. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  26936. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  26937. *
  26938. * References:
  26939. * - ASC CDL v1.2
  26940. * - {@link https://blender.stackexchange.com/a/55239/43930}
  26941. * - {@link https://docs.acescentral.com/specifications/acescc/}
  26942. */
  26943. const cdl = /*@__PURE__*/ Fn( ( [
  26944. color,
  26945. slope = vec3( 1 ),
  26946. offset = vec3( 0 ),
  26947. power = vec3( 1 ),
  26948. saturation = float( 1 ),
  26949. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  26950. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  26951. ] ) => {
  26952. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  26953. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  26954. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  26955. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  26956. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  26957. const pv = v.pow( power ).toVar();
  26958. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  26959. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  26960. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  26961. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  26962. return vec4( v.rgb, color.a );
  26963. } );
  26964. /**
  26965. * Represents a posterize effect which reduces the number of colors
  26966. * in an image, resulting in a more blocky and stylized appearance.
  26967. *
  26968. * @augments TempNode
  26969. */
  26970. class PosterizeNode extends TempNode {
  26971. static get type() {
  26972. return 'PosterizeNode';
  26973. }
  26974. /**
  26975. * Constructs a new posterize node.
  26976. *
  26977. * @param {Node} sourceNode - The input color.
  26978. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  26979. */
  26980. constructor( sourceNode, stepsNode ) {
  26981. super();
  26982. /**
  26983. * The input color.
  26984. *
  26985. * @type {Node}
  26986. */
  26987. this.sourceNode = sourceNode;
  26988. /**
  26989. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  26990. *
  26991. * @type {Node}
  26992. */
  26993. this.stepsNode = stepsNode;
  26994. }
  26995. setup() {
  26996. const { sourceNode, stepsNode } = this;
  26997. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  26998. }
  26999. }
  27000. /**
  27001. * TSL function for creating a posterize node.
  27002. *
  27003. * @tsl
  27004. * @function
  27005. * @param {Node} sourceNode - The input color.
  27006. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  27007. * @returns {PosterizeNode}
  27008. */
  27009. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ).setParameterLength( 2 );
  27010. const _size = /*@__PURE__*/ new Vector2();
  27011. /**
  27012. * Represents the texture of a pass node.
  27013. *
  27014. * @augments TextureNode
  27015. */
  27016. class PassTextureNode extends TextureNode {
  27017. static get type() {
  27018. return 'PassTextureNode';
  27019. }
  27020. /**
  27021. * Constructs a new pass texture node.
  27022. *
  27023. * @param {PassNode} passNode - The pass node.
  27024. * @param {Texture} texture - The output texture.
  27025. */
  27026. constructor( passNode, texture ) {
  27027. super( texture );
  27028. /**
  27029. * A reference to the pass node.
  27030. *
  27031. * @type {PassNode}
  27032. */
  27033. this.passNode = passNode;
  27034. this.setUpdateMatrix( false );
  27035. }
  27036. setup( builder ) {
  27037. this.passNode.build( builder );
  27038. return super.setup( builder );
  27039. }
  27040. clone() {
  27041. return new this.constructor( this.passNode, this.value );
  27042. }
  27043. }
  27044. /**
  27045. * An extension of `PassTextureNode` which allows to manage more than one
  27046. * internal texture. Relevant for the `getPreviousTexture()` related API.
  27047. *
  27048. * @augments PassTextureNode
  27049. */
  27050. class PassMultipleTextureNode extends PassTextureNode {
  27051. static get type() {
  27052. return 'PassMultipleTextureNode';
  27053. }
  27054. /**
  27055. * Constructs a new pass texture node.
  27056. *
  27057. * @param {PassNode} passNode - The pass node.
  27058. * @param {string} textureName - The output texture name.
  27059. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  27060. */
  27061. constructor( passNode, textureName, previousTexture = false ) {
  27062. // null is passed to the super call since this class does not
  27063. // use an external texture for rendering pass data into. Instead
  27064. // the texture is managed by the pass node itself
  27065. super( passNode, null );
  27066. /**
  27067. * The output texture name.
  27068. *
  27069. * @type {string}
  27070. */
  27071. this.textureName = textureName;
  27072. /**
  27073. * Whether previous frame data should be used or not.
  27074. *
  27075. * @type {boolean}
  27076. */
  27077. this.previousTexture = previousTexture;
  27078. }
  27079. /**
  27080. * Updates the texture reference of this node.
  27081. */
  27082. updateTexture() {
  27083. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  27084. }
  27085. setup( builder ) {
  27086. this.updateTexture();
  27087. return super.setup( builder );
  27088. }
  27089. clone() {
  27090. const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture );
  27091. newNode.uvNode = this.uvNode;
  27092. newNode.levelNode = this.levelNode;
  27093. newNode.biasNode = this.biasNode;
  27094. newNode.sampler = this.sampler;
  27095. newNode.depthNode = this.depthNode;
  27096. newNode.compareNode = this.compareNode;
  27097. newNode.gradNode = this.gradNode;
  27098. newNode.offsetNode = this.offsetNode;
  27099. return newNode;
  27100. }
  27101. }
  27102. /**
  27103. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  27104. * This pass produces a render for the given scene and camera and can provide multiple outputs
  27105. * via MRT for further processing.
  27106. *
  27107. * ```js
  27108. * const postProcessing = new PostProcessing( renderer );
  27109. *
  27110. * const scenePass = pass( scene, camera );
  27111. *
  27112. * postProcessing.outputNode = scenePass;
  27113. * ```
  27114. *
  27115. * @augments TempNode
  27116. */
  27117. class PassNode extends TempNode {
  27118. static get type() {
  27119. return 'PassNode';
  27120. }
  27121. /**
  27122. * Constructs a new pass node.
  27123. *
  27124. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  27125. * @param {Scene} scene - A reference to the scene.
  27126. * @param {Camera} camera - A reference to the camera.
  27127. * @param {Object} options - Options for the internal render target.
  27128. */
  27129. constructor( scope, scene, camera, options = {} ) {
  27130. super( 'vec4' );
  27131. /**
  27132. * The scope of the pass. The scope determines whether the node outputs color or depth.
  27133. *
  27134. * @type {('color'|'depth')}
  27135. */
  27136. this.scope = scope;
  27137. /**
  27138. * A reference to the scene.
  27139. *
  27140. * @type {Scene}
  27141. */
  27142. this.scene = scene;
  27143. /**
  27144. * A reference to the camera.
  27145. *
  27146. * @type {Camera}
  27147. */
  27148. this.camera = camera;
  27149. /**
  27150. * Options for the internal render target.
  27151. *
  27152. * @type {Object}
  27153. */
  27154. this.options = options;
  27155. /**
  27156. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  27157. *
  27158. * @private
  27159. * @type {number}
  27160. * @default 1
  27161. */
  27162. this._pixelRatio = 1;
  27163. /**
  27164. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  27165. * @private
  27166. * @type {number}
  27167. * @default 1
  27168. */
  27169. this._width = 1;
  27170. /**
  27171. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  27172. * @private
  27173. * @type {number}
  27174. * @default 1
  27175. */
  27176. this._height = 1;
  27177. const depthTexture = new DepthTexture();
  27178. depthTexture.isRenderTargetTexture = true;
  27179. //depthTexture.type = FloatType;
  27180. depthTexture.name = 'depth';
  27181. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  27182. renderTarget.texture.name = 'output';
  27183. renderTarget.depthTexture = depthTexture;
  27184. /**
  27185. * The pass's render target.
  27186. *
  27187. * @type {RenderTarget}
  27188. */
  27189. this.renderTarget = renderTarget;
  27190. /**
  27191. * An optional override material for the pass.
  27192. *
  27193. * @type {Material|null}
  27194. */
  27195. this.overrideMaterial = null;
  27196. /**
  27197. * Whether the pass is transparent.
  27198. *
  27199. * @type {boolean}
  27200. * @default false
  27201. */
  27202. this.transparent = true;
  27203. /**
  27204. * Whether the pass is opaque.
  27205. *
  27206. * @type {boolean}
  27207. * @default true
  27208. */
  27209. this.opaque = true;
  27210. /**
  27211. * An optional global context for the pass.
  27212. *
  27213. * @type {ContextNode|null}
  27214. */
  27215. this.contextNode = null;
  27216. /**
  27217. * A cache for the context node.
  27218. *
  27219. * @private
  27220. * @type {?Object}
  27221. * @default null
  27222. */
  27223. this._contextNodeCache = null;
  27224. /**
  27225. * A dictionary holding the internal result textures.
  27226. *
  27227. * @private
  27228. * @type {Object<string, Texture>}
  27229. */
  27230. this._textures = {
  27231. output: renderTarget.texture,
  27232. depth: depthTexture
  27233. };
  27234. /**
  27235. * A dictionary holding the internal texture nodes.
  27236. *
  27237. * @private
  27238. * @type {Object<string, TextureNode>}
  27239. */
  27240. this._textureNodes = {};
  27241. /**
  27242. * A dictionary holding the internal depth nodes.
  27243. *
  27244. * @private
  27245. * @type {Object}
  27246. */
  27247. this._linearDepthNodes = {};
  27248. /**
  27249. * A dictionary holding the internal viewZ nodes.
  27250. *
  27251. * @private
  27252. * @type {Object}
  27253. */
  27254. this._viewZNodes = {};
  27255. /**
  27256. * A dictionary holding the texture data of the previous frame.
  27257. * Used for computing velocity/motion vectors.
  27258. *
  27259. * @private
  27260. * @type {Object<string, Texture>}
  27261. */
  27262. this._previousTextures = {};
  27263. /**
  27264. * A dictionary holding the texture nodes of the previous frame.
  27265. * Used for computing velocity/motion vectors.
  27266. *
  27267. * @private
  27268. * @type {Object<string, TextureNode>}
  27269. */
  27270. this._previousTextureNodes = {};
  27271. /**
  27272. * The `near` property of the camera as a uniform.
  27273. *
  27274. * @private
  27275. * @type {UniformNode}
  27276. */
  27277. this._cameraNear = uniform( 0 );
  27278. /**
  27279. * The `far` property of the camera as a uniform.
  27280. *
  27281. * @private
  27282. * @type {UniformNode}
  27283. */
  27284. this._cameraFar = uniform( 0 );
  27285. /**
  27286. * A MRT node configuring the MRT settings.
  27287. *
  27288. * @private
  27289. * @type {?MRTNode}
  27290. * @default null
  27291. */
  27292. this._mrt = null;
  27293. /**
  27294. * Layer object for configuring the camera that is used
  27295. * to produce the pass.
  27296. *
  27297. * @private
  27298. * @type {?Layers}
  27299. * @default null
  27300. */
  27301. this._layers = null;
  27302. /**
  27303. * Scales the resolution of the internal render target.
  27304. *
  27305. * @private
  27306. * @type {number}
  27307. * @default 1
  27308. */
  27309. this._resolutionScale = 1;
  27310. /**
  27311. * Custom viewport definition.
  27312. *
  27313. * @private
  27314. * @type {?Vector4}
  27315. * @default null
  27316. */
  27317. this._viewport = null;
  27318. /**
  27319. * Custom scissor definition.
  27320. *
  27321. * @private
  27322. * @type {?Vector4}
  27323. * @default null
  27324. */
  27325. this._scissor = null;
  27326. /**
  27327. * This flag can be used for type testing.
  27328. *
  27329. * @type {boolean}
  27330. * @readonly
  27331. * @default true
  27332. */
  27333. this.isPassNode = true;
  27334. /**
  27335. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  27336. * scene once per frame in its {@link PassNode#updateBefore} method.
  27337. *
  27338. * @type {string}
  27339. * @default 'frame'
  27340. */
  27341. this.updateBeforeType = NodeUpdateType.FRAME;
  27342. /**
  27343. * This flag is used for global cache.
  27344. *
  27345. * @type {boolean}
  27346. * @default true
  27347. */
  27348. this.global = true;
  27349. }
  27350. /**
  27351. * Sets the resolution scale for the pass.
  27352. * The resolution scale is a factor that is multiplied with the renderer's width and height.
  27353. *
  27354. * @param {number} resolutionScale - The resolution scale to set. A value of `1` means full resolution.
  27355. * @return {PassNode} A reference to this pass.
  27356. */
  27357. setResolutionScale( resolutionScale ) {
  27358. this._resolutionScale = resolutionScale;
  27359. return this;
  27360. }
  27361. /**
  27362. * Gets the current resolution scale of the pass.
  27363. *
  27364. * @return {number} The current resolution scale. A value of `1` means full resolution.
  27365. */
  27366. getResolutionScale() {
  27367. return this._resolutionScale;
  27368. }
  27369. /**
  27370. * Sets the resolution for the pass.
  27371. * The resolution is a factor that is multiplied with the renderer's width and height.
  27372. *
  27373. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  27374. * @return {PassNode} A reference to this pass.
  27375. * @deprecated since r181. Use {@link PassNode#setResolutionScale `setResolutionScale()`} instead.
  27376. */
  27377. setResolution( resolution ) { // @deprecated, r181
  27378. warn( 'PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead.' );
  27379. return this.setResolutionScale( resolution );
  27380. }
  27381. /**
  27382. * Gets the current resolution of the pass.
  27383. *
  27384. * @return {number} The current resolution. A value of `1` means full resolution.
  27385. * @deprecated since r181. Use {@link PassNode#getResolutionScale `getResolutionScale()`} instead.
  27386. */
  27387. getResolution() { // @deprecated, r181
  27388. warn( 'PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead.' );
  27389. return this.getResolutionScale();
  27390. }
  27391. /**
  27392. * Sets the layer configuration that should be used when rendering the pass.
  27393. *
  27394. * @param {Layers} layers - The layers object to set.
  27395. * @return {PassNode} A reference to this pass.
  27396. */
  27397. setLayers( layers ) {
  27398. this._layers = layers;
  27399. return this;
  27400. }
  27401. /**
  27402. * Gets the current layer configuration of the pass.
  27403. *
  27404. * @return {?Layers} .
  27405. */
  27406. getLayers() {
  27407. return this._layers;
  27408. }
  27409. /**
  27410. * Sets the given MRT node to setup MRT for this pass.
  27411. *
  27412. * @param {MRTNode} mrt - The MRT object.
  27413. * @return {PassNode} A reference to this pass.
  27414. */
  27415. setMRT( mrt ) {
  27416. this._mrt = mrt;
  27417. return this;
  27418. }
  27419. /**
  27420. * Returns the current MRT node.
  27421. *
  27422. * @return {MRTNode} The current MRT node.
  27423. */
  27424. getMRT() {
  27425. return this._mrt;
  27426. }
  27427. /**
  27428. * Returns the texture for the given output name.
  27429. *
  27430. * @param {string} name - The output name to get the texture for.
  27431. * @return {Texture} The texture.
  27432. */
  27433. getTexture( name ) {
  27434. let texture = this._textures[ name ];
  27435. if ( texture === undefined ) {
  27436. const refTexture = this.renderTarget.texture;
  27437. texture = refTexture.clone();
  27438. texture.name = name;
  27439. this._textures[ name ] = texture;
  27440. this.renderTarget.textures.push( texture );
  27441. }
  27442. return texture;
  27443. }
  27444. /**
  27445. * Returns the texture holding the data of the previous frame for the given output name.
  27446. *
  27447. * @param {string} name - The output name to get the texture for.
  27448. * @return {Texture} The texture holding the data of the previous frame.
  27449. */
  27450. getPreviousTexture( name ) {
  27451. let texture = this._previousTextures[ name ];
  27452. if ( texture === undefined ) {
  27453. texture = this.getTexture( name ).clone();
  27454. this._previousTextures[ name ] = texture;
  27455. }
  27456. return texture;
  27457. }
  27458. /**
  27459. * Switches current and previous textures for the given output name.
  27460. *
  27461. * @param {string} name - The output name.
  27462. */
  27463. toggleTexture( name ) {
  27464. const prevTexture = this._previousTextures[ name ];
  27465. if ( prevTexture !== undefined ) {
  27466. const texture = this._textures[ name ];
  27467. const index = this.renderTarget.textures.indexOf( texture );
  27468. this.renderTarget.textures[ index ] = prevTexture;
  27469. this._textures[ name ] = prevTexture;
  27470. this._previousTextures[ name ] = texture;
  27471. this._textureNodes[ name ].updateTexture();
  27472. this._previousTextureNodes[ name ].updateTexture();
  27473. }
  27474. }
  27475. /**
  27476. * Returns the texture node for the given output name.
  27477. *
  27478. * @param {string} [name='output'] - The output name to get the texture node for.
  27479. * @return {TextureNode} The texture node.
  27480. */
  27481. getTextureNode( name = 'output' ) {
  27482. let textureNode = this._textureNodes[ name ];
  27483. if ( textureNode === undefined ) {
  27484. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  27485. textureNode.updateTexture();
  27486. this._textureNodes[ name ] = textureNode;
  27487. }
  27488. return textureNode;
  27489. }
  27490. /**
  27491. * Returns the previous texture node for the given output name.
  27492. *
  27493. * @param {string} [name='output'] - The output name to get the previous texture node for.
  27494. * @return {TextureNode} The previous texture node.
  27495. */
  27496. getPreviousTextureNode( name = 'output' ) {
  27497. let textureNode = this._previousTextureNodes[ name ];
  27498. if ( textureNode === undefined ) {
  27499. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  27500. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  27501. textureNode.updateTexture();
  27502. this._previousTextureNodes[ name ] = textureNode;
  27503. }
  27504. return textureNode;
  27505. }
  27506. /**
  27507. * Returns a viewZ node of this pass.
  27508. *
  27509. * @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.
  27510. * @return {Node} The viewZ node.
  27511. */
  27512. getViewZNode( name = 'depth' ) {
  27513. let viewZNode = this._viewZNodes[ name ];
  27514. if ( viewZNode === undefined ) {
  27515. const cameraNear = this._cameraNear;
  27516. const cameraFar = this._cameraFar;
  27517. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  27518. }
  27519. return viewZNode;
  27520. }
  27521. /**
  27522. * Returns a linear depth node of this pass.
  27523. *
  27524. * @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.
  27525. * @return {Node} The linear depth node.
  27526. */
  27527. getLinearDepthNode( name = 'depth' ) {
  27528. let linearDepthNode = this._linearDepthNodes[ name ];
  27529. if ( linearDepthNode === undefined ) {
  27530. const cameraNear = this._cameraNear;
  27531. const cameraFar = this._cameraFar;
  27532. const viewZNode = this.getViewZNode( name );
  27533. // TODO: just if ( builder.camera.isPerspectiveCamera )
  27534. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  27535. }
  27536. return linearDepthNode;
  27537. }
  27538. /**
  27539. * Precompiles the pass.
  27540. *
  27541. * Note that this method must be called after the pass configuration is complete.
  27542. * So calls like `setMRT()` and `getTextureNode()` must proceed the precompilation.
  27543. *
  27544. * @async
  27545. * @param {Renderer} renderer - The renderer.
  27546. * @return {Promise} A Promise that resolves when the compile has been finished.
  27547. * @see {@link Renderer#compileAsync}
  27548. */
  27549. async compileAsync( renderer ) {
  27550. const currentRenderTarget = renderer.getRenderTarget();
  27551. const currentMRT = renderer.getMRT();
  27552. renderer.setRenderTarget( this.renderTarget );
  27553. renderer.setMRT( this._mrt );
  27554. await renderer.compileAsync( this.scene, this.camera );
  27555. renderer.setRenderTarget( currentRenderTarget );
  27556. renderer.setMRT( currentMRT );
  27557. }
  27558. setup( { renderer } ) {
  27559. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  27560. this.renderTarget.texture.type = renderer.getColorBufferType();
  27561. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  27562. }
  27563. updateBefore( frame ) {
  27564. const { renderer } = frame;
  27565. const { scene } = this;
  27566. let camera;
  27567. let pixelRatio;
  27568. const outputRenderTarget = renderer.getOutputRenderTarget();
  27569. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  27570. pixelRatio = 1;
  27571. camera = renderer.xr.getCamera();
  27572. renderer.xr.updateCamera( camera );
  27573. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  27574. } else {
  27575. camera = this.camera;
  27576. pixelRatio = renderer.getPixelRatio();
  27577. renderer.getSize( _size );
  27578. }
  27579. this._pixelRatio = pixelRatio;
  27580. this.setSize( _size.width, _size.height );
  27581. const currentRenderTarget = renderer.getRenderTarget();
  27582. const currentMRT = renderer.getMRT();
  27583. const currentAutoClear = renderer.autoClear;
  27584. const currentTransparent = renderer.transparent;
  27585. const currentOpaque = renderer.opaque;
  27586. const currentMask = camera.layers.mask;
  27587. const currentContextNode = renderer.contextNode;
  27588. const currentOverrideMaterial = scene.overrideMaterial;
  27589. this._cameraNear.value = camera.near;
  27590. this._cameraFar.value = camera.far;
  27591. if ( this._layers !== null ) {
  27592. camera.layers.mask = this._layers.mask;
  27593. }
  27594. for ( const name in this._previousTextures ) {
  27595. this.toggleTexture( name );
  27596. }
  27597. if ( this.overrideMaterial !== null ) {
  27598. scene.overrideMaterial = this.overrideMaterial;
  27599. }
  27600. renderer.setRenderTarget( this.renderTarget );
  27601. renderer.setMRT( this._mrt );
  27602. renderer.autoClear = true;
  27603. renderer.transparent = this.transparent;
  27604. renderer.opaque = this.opaque;
  27605. if ( this.contextNode !== null ) {
  27606. if ( this._contextNodeCache === null || this._contextNodeCache.version !== this.version ) {
  27607. this._contextNodeCache = {
  27608. version: this.version,
  27609. context: context( { ...renderer.contextNode.getFlowContextData(), ...this.contextNode.getFlowContextData() } )
  27610. };
  27611. }
  27612. renderer.contextNode = this._contextNodeCache.context;
  27613. }
  27614. const currentSceneName = scene.name;
  27615. scene.name = this.name ? this.name : scene.name;
  27616. renderer.render( scene, camera );
  27617. scene.name = currentSceneName;
  27618. scene.overrideMaterial = currentOverrideMaterial;
  27619. renderer.setRenderTarget( currentRenderTarget );
  27620. renderer.setMRT( currentMRT );
  27621. renderer.autoClear = currentAutoClear;
  27622. renderer.transparent = currentTransparent;
  27623. renderer.opaque = currentOpaque;
  27624. renderer.contextNode = currentContextNode;
  27625. camera.layers.mask = currentMask;
  27626. }
  27627. /**
  27628. * Sets the size of the pass's render target. Honors the pixel ratio.
  27629. *
  27630. * @param {number} width - The width to set.
  27631. * @param {number} height - The height to set.
  27632. */
  27633. setSize( width, height ) {
  27634. this._width = width;
  27635. this._height = height;
  27636. const effectiveWidth = Math.floor( this._width * this._pixelRatio * this._resolutionScale );
  27637. const effectiveHeight = Math.floor( this._height * this._pixelRatio * this._resolutionScale );
  27638. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  27639. if ( this._scissor !== null ) this.renderTarget.scissor.copy( this._scissor );
  27640. if ( this._viewport !== null ) this.renderTarget.viewport.copy( this._viewport );
  27641. }
  27642. /**
  27643. * This method allows to define the pass's scissor rectangle. By default, the scissor rectangle is kept
  27644. * in sync with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  27645. * with `null` as the single argument.
  27646. *
  27647. * @param {?(number | Vector4)} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  27648. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  27649. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  27650. * @param {number} width - The width of the scissor box in logical pixel unit.
  27651. * @param {number} height - The height of the scissor box in logical pixel unit.
  27652. */
  27653. setScissor( x, y, width, height ) {
  27654. if ( x === null ) {
  27655. this._scissor = null;
  27656. } else {
  27657. if ( this._scissor === null ) this._scissor = new Vector4();
  27658. if ( x.isVector4 ) {
  27659. this._scissor.copy( x );
  27660. } else {
  27661. this._scissor.set( x, y, width, height );
  27662. }
  27663. this._scissor.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  27664. }
  27665. }
  27666. /**
  27667. * This method allows to define the pass's viewport. By default, the viewport is kept in sync
  27668. * with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  27669. * with `null` as the single argument.
  27670. *
  27671. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  27672. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  27673. * @param {number} width - The width of the viewport in logical pixel unit.
  27674. * @param {number} height - The height of the viewport in logical pixel unit.
  27675. */
  27676. setViewport( x, y, width, height ) {
  27677. if ( x === null ) {
  27678. this._viewport = null;
  27679. } else {
  27680. if ( this._viewport === null ) this._viewport = new Vector4();
  27681. if ( x.isVector4 ) {
  27682. this._viewport.copy( x );
  27683. } else {
  27684. this._viewport.set( x, y, width, height );
  27685. }
  27686. this._viewport.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  27687. }
  27688. }
  27689. /**
  27690. * Sets the pixel ratio the pass's render target and updates the size.
  27691. *
  27692. * @param {number} pixelRatio - The pixel ratio to set.
  27693. */
  27694. setPixelRatio( pixelRatio ) {
  27695. this._pixelRatio = pixelRatio;
  27696. this.setSize( this._width, this._height );
  27697. }
  27698. /**
  27699. * Frees internal resources. Should be called when the node is no longer in use.
  27700. */
  27701. dispose() {
  27702. this.renderTarget.dispose();
  27703. }
  27704. }
  27705. /**
  27706. * @static
  27707. * @type {'color'}
  27708. * @default 'color'
  27709. */
  27710. PassNode.COLOR = 'color';
  27711. /**
  27712. * @static
  27713. * @type {'depth'}
  27714. * @default 'depth'
  27715. */
  27716. PassNode.DEPTH = 'depth';
  27717. /**
  27718. * TSL function for creating a pass node.
  27719. *
  27720. * @tsl
  27721. * @function
  27722. * @param {Scene} scene - A reference to the scene.
  27723. * @param {Camera} camera - A reference to the camera.
  27724. * @param {Object} options - Options for the internal render target.
  27725. * @returns {PassNode}
  27726. */
  27727. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  27728. /**
  27729. * TSL function for creating a pass texture node.
  27730. *
  27731. * @tsl
  27732. * @function
  27733. * @param {PassNode} pass - The pass node.
  27734. * @param {Texture} texture - The output texture.
  27735. * @returns {PassTextureNode}
  27736. */
  27737. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  27738. /**
  27739. * TSL function for creating a depth pass node.
  27740. *
  27741. * @tsl
  27742. * @function
  27743. * @param {Scene} scene - A reference to the scene.
  27744. * @param {Camera} camera - A reference to the camera.
  27745. * @param {Object} options - Options for the internal render target.
  27746. * @returns {PassNode}
  27747. */
  27748. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  27749. /**
  27750. * Represents a render pass for producing a toon outline effect on compatible objects.
  27751. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  27752. * will receive the outline.
  27753. *
  27754. * ```js
  27755. * const postProcessing = new PostProcessing( renderer );
  27756. *
  27757. * const scenePass = toonOutlinePass( scene, camera );
  27758. *
  27759. * postProcessing.outputNode = scenePass;
  27760. * ```
  27761. * @augments PassNode
  27762. */
  27763. class ToonOutlinePassNode extends PassNode {
  27764. static get type() {
  27765. return 'ToonOutlinePassNode';
  27766. }
  27767. /**
  27768. * Constructs a new outline pass node.
  27769. *
  27770. * @param {Scene} scene - A reference to the scene.
  27771. * @param {Camera} camera - A reference to the camera.
  27772. * @param {Node} colorNode - Defines the outline's color.
  27773. * @param {Node} thicknessNode - Defines the outline's thickness.
  27774. * @param {Node} alphaNode - Defines the outline's alpha.
  27775. */
  27776. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  27777. super( PassNode.COLOR, scene, camera );
  27778. /**
  27779. * Defines the outline's color.
  27780. *
  27781. * @type {Node}
  27782. */
  27783. this.colorNode = colorNode;
  27784. /**
  27785. * Defines the outline's thickness.
  27786. *
  27787. * @type {Node}
  27788. */
  27789. this.thicknessNode = thicknessNode;
  27790. /**
  27791. * Defines the outline's alpha.
  27792. *
  27793. * @type {Node}
  27794. */
  27795. this.alphaNode = alphaNode;
  27796. /**
  27797. * An internal material cache.
  27798. *
  27799. * @private
  27800. * @type {WeakMap<Material, NodeMaterial>}
  27801. */
  27802. this._materialCache = new WeakMap();
  27803. /**
  27804. * The name of this pass.
  27805. *
  27806. * @type {string}
  27807. * @default 'Outline Pass'
  27808. */
  27809. this.name = 'Outline Pass';
  27810. }
  27811. updateBefore( frame ) {
  27812. const { renderer } = frame;
  27813. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  27814. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  27815. // only render outline for supported materials
  27816. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  27817. if ( material.wireframe === false ) {
  27818. const outlineMaterial = this._getOutlineMaterial( material );
  27819. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  27820. }
  27821. }
  27822. // default
  27823. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  27824. } );
  27825. super.updateBefore( frame );
  27826. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  27827. }
  27828. /**
  27829. * Creates the material used for outline rendering.
  27830. *
  27831. * @private
  27832. * @return {NodeMaterial} The outline material.
  27833. */
  27834. _createMaterial() {
  27835. const material = new NodeMaterial();
  27836. material.isMeshToonOutlineMaterial = true;
  27837. material.name = 'Toon_Outline';
  27838. material.side = BackSide;
  27839. // vertex node
  27840. const outlineNormal = normalLocal.negate();
  27841. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  27842. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  27843. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  27844. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  27845. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  27846. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  27847. // color node
  27848. material.colorNode = vec4( this.colorNode, this.alphaNode );
  27849. return material;
  27850. }
  27851. /**
  27852. * For the given toon material, this method returns a corresponding
  27853. * outline material.
  27854. *
  27855. * @private
  27856. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  27857. * @return {NodeMaterial} The outline material.
  27858. */
  27859. _getOutlineMaterial( originalMaterial ) {
  27860. let outlineMaterial = this._materialCache.get( originalMaterial );
  27861. if ( outlineMaterial === undefined ) {
  27862. outlineMaterial = this._createMaterial();
  27863. this._materialCache.set( originalMaterial, outlineMaterial );
  27864. }
  27865. return outlineMaterial;
  27866. }
  27867. }
  27868. /**
  27869. * TSL function for creating a toon outline pass node.
  27870. *
  27871. * @tsl
  27872. * @function
  27873. * @param {Scene} scene - A reference to the scene.
  27874. * @param {Camera} camera - A reference to the camera.
  27875. * @param {Color} color - Defines the outline's color.
  27876. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  27877. * @param {number} [alpha=1] - Defines the outline's alpha.
  27878. * @returns {ToonOutlinePassNode}
  27879. */
  27880. 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 ) ) );
  27881. /**
  27882. * Linear tone mapping, exposure only.
  27883. *
  27884. * @tsl
  27885. * @function
  27886. * @param {Node<vec3>} color - The color that should be tone mapped.
  27887. * @param {Node<float>} exposure - The exposure.
  27888. * @return {Node<vec3>} The tone mapped color.
  27889. */
  27890. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27891. return color.mul( exposure ).clamp();
  27892. } ).setLayout( {
  27893. name: 'linearToneMapping',
  27894. type: 'vec3',
  27895. inputs: [
  27896. { name: 'color', type: 'vec3' },
  27897. { name: 'exposure', type: 'float' }
  27898. ]
  27899. } );
  27900. /**
  27901. * Reinhard tone mapping.
  27902. *
  27903. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  27904. *
  27905. * @tsl
  27906. * @function
  27907. * @param {Node<vec3>} color - The color that should be tone mapped.
  27908. * @param {Node<float>} exposure - The exposure.
  27909. * @return {Node<vec3>} The tone mapped color.
  27910. */
  27911. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27912. color = color.mul( exposure );
  27913. return color.div( color.add( 1.0 ) ).clamp();
  27914. } ).setLayout( {
  27915. name: 'reinhardToneMapping',
  27916. type: 'vec3',
  27917. inputs: [
  27918. { name: 'color', type: 'vec3' },
  27919. { name: 'exposure', type: 'float' }
  27920. ]
  27921. } );
  27922. /**
  27923. * Cineon tone mapping.
  27924. *
  27925. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  27926. *
  27927. * @tsl
  27928. * @function
  27929. * @param {Node<vec3>} color - The color that should be tone mapped.
  27930. * @param {Node<float>} exposure - The exposure.
  27931. * @return {Node<vec3>} The tone mapped color.
  27932. */
  27933. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27934. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  27935. color = color.mul( exposure );
  27936. color = color.sub( 0.004 ).max( 0.0 );
  27937. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  27938. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  27939. return a.div( b ).pow( 2.2 );
  27940. } ).setLayout( {
  27941. name: 'cineonToneMapping',
  27942. type: 'vec3',
  27943. inputs: [
  27944. { name: 'color', type: 'vec3' },
  27945. { name: 'exposure', type: 'float' }
  27946. ]
  27947. } );
  27948. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  27949. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  27950. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  27951. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  27952. return a.div( b );
  27953. } );
  27954. /**
  27955. * ACESFilmic tone mapping.
  27956. *
  27957. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  27958. *
  27959. * @tsl
  27960. * @function
  27961. * @param {Node<vec3>} color - The color that should be tone mapped.
  27962. * @param {Node<float>} exposure - The exposure.
  27963. * @return {Node<vec3>} The tone mapped color.
  27964. */
  27965. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27966. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  27967. const ACESInputMat = mat3(
  27968. 0.59719, 0.35458, 0.04823,
  27969. 0.07600, 0.90834, 0.01566,
  27970. 0.02840, 0.13383, 0.83777
  27971. );
  27972. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  27973. const ACESOutputMat = mat3(
  27974. 1.60475, -0.53108, -0.07367,
  27975. -0.10208, 1.10813, -605e-5,
  27976. -327e-5, -0.07276, 1.07602
  27977. );
  27978. color = color.mul( exposure ).div( 0.6 );
  27979. color = ACESInputMat.mul( color );
  27980. // Apply RRT and ODT
  27981. color = RRTAndODTFit( color );
  27982. color = ACESOutputMat.mul( color );
  27983. // Clamp to [0, 1]
  27984. return color.clamp();
  27985. } ).setLayout( {
  27986. name: 'acesFilmicToneMapping',
  27987. type: 'vec3',
  27988. inputs: [
  27989. { name: 'color', type: 'vec3' },
  27990. { name: 'exposure', type: 'float' }
  27991. ]
  27992. } );
  27993. 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 ) );
  27994. 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 ) );
  27995. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  27996. const x = vec3( x_immutable ).toVar();
  27997. const x2 = vec3( x.mul( x ) ).toVar();
  27998. const x4 = vec3( x2.mul( x2 ) ).toVar();
  27999. 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 ) ) ) );
  28000. } );
  28001. /**
  28002. * AgX tone mapping.
  28003. *
  28004. * @tsl
  28005. * @function
  28006. * @param {Node<vec3>} color - The color that should be tone mapped.
  28007. * @param {Node<float>} exposure - The exposure.
  28008. * @return {Node<vec3>} The tone mapped color.
  28009. */
  28010. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28011. const colortone = vec3( color ).toVar();
  28012. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  28013. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  28014. const AgxMinEv = float( -12.47393 );
  28015. const AgxMaxEv = float( 4.026069 );
  28016. colortone.mulAssign( exposure );
  28017. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  28018. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  28019. colortone.assign( max$1( colortone, 1e-10 ) );
  28020. colortone.assign( log2( colortone ) );
  28021. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  28022. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  28023. colortone.assign( agxDefaultContrastApprox( colortone ) );
  28024. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  28025. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  28026. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  28027. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  28028. return colortone;
  28029. } ).setLayout( {
  28030. name: 'agxToneMapping',
  28031. type: 'vec3',
  28032. inputs: [
  28033. { name: 'color', type: 'vec3' },
  28034. { name: 'exposure', type: 'float' }
  28035. ]
  28036. } );
  28037. /**
  28038. * Neutral tone mapping.
  28039. *
  28040. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  28041. *
  28042. * @tsl
  28043. * @function
  28044. * @param {Node<vec3>} color - The color that should be tone mapped.
  28045. * @param {Node<float>} exposure - The exposure.
  28046. * @return {Node<vec3>} The tone mapped color.
  28047. */
  28048. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28049. const StartCompression = float( 0.8 - 0.04 );
  28050. const Desaturation = float( 0.15 );
  28051. color = color.mul( exposure );
  28052. const x = min$1( color.r, min$1( color.g, color.b ) );
  28053. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  28054. color.subAssign( offset );
  28055. const peak = max$1( color.r, max$1( color.g, color.b ) );
  28056. If( peak.lessThan( StartCompression ), () => {
  28057. return color;
  28058. } );
  28059. const d = sub( 1, StartCompression );
  28060. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  28061. color.mulAssign( newPeak.div( peak ) );
  28062. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  28063. return mix( color, vec3( newPeak ), g );
  28064. } ).setLayout( {
  28065. name: 'neutralToneMapping',
  28066. type: 'vec3',
  28067. inputs: [
  28068. { name: 'color', type: 'vec3' },
  28069. { name: 'exposure', type: 'float' }
  28070. ]
  28071. } );
  28072. /**
  28073. * This class represents native code sections. It is the base
  28074. * class for modules like {@link FunctionNode} which allows to implement
  28075. * functions with native shader languages.
  28076. *
  28077. * @augments Node
  28078. */
  28079. class CodeNode extends Node {
  28080. static get type() {
  28081. return 'CodeNode';
  28082. }
  28083. /**
  28084. * Constructs a new code node.
  28085. *
  28086. * @param {string} [code=''] - The native code.
  28087. * @param {Array<Node>} [includes=[]] - An array of includes.
  28088. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  28089. */
  28090. constructor( code = '', includes = [], language = '' ) {
  28091. super( 'code' );
  28092. /**
  28093. * This flag can be used for type testing.
  28094. *
  28095. * @type {boolean}
  28096. * @readonly
  28097. * @default true
  28098. */
  28099. this.isCodeNode = true;
  28100. /**
  28101. * This flag is used for global cache.
  28102. *
  28103. * @type {boolean}
  28104. * @default true
  28105. */
  28106. this.global = true;
  28107. /**
  28108. * The native code.
  28109. *
  28110. * @type {string}
  28111. * @default ''
  28112. */
  28113. this.code = code;
  28114. /**
  28115. * An array of includes
  28116. *
  28117. * @type {Array<Node>}
  28118. * @default []
  28119. */
  28120. this.includes = includes;
  28121. /**
  28122. * The used language.
  28123. *
  28124. * @type {('js'|'wgsl'|'glsl')}
  28125. * @default ''
  28126. */
  28127. this.language = language;
  28128. }
  28129. /**
  28130. * Sets the includes of this code node.
  28131. *
  28132. * @param {Array<Node>} includes - The includes to set.
  28133. * @return {CodeNode} A reference to this node.
  28134. */
  28135. setIncludes( includes ) {
  28136. this.includes = includes;
  28137. return this;
  28138. }
  28139. /**
  28140. * Returns the includes of this code node.
  28141. *
  28142. * @param {NodeBuilder} builder - The current node builder.
  28143. * @return {Array<Node>} The includes.
  28144. */
  28145. getIncludes( /*builder*/ ) {
  28146. return this.includes;
  28147. }
  28148. generate( builder ) {
  28149. const includes = this.getIncludes( builder );
  28150. for ( const include of includes ) {
  28151. include.build( builder );
  28152. }
  28153. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  28154. nodeCode.code = this.code;
  28155. return nodeCode.code;
  28156. }
  28157. serialize( data ) {
  28158. super.serialize( data );
  28159. data.code = this.code;
  28160. data.language = this.language;
  28161. }
  28162. deserialize( data ) {
  28163. super.deserialize( data );
  28164. this.code = data.code;
  28165. this.language = data.language;
  28166. }
  28167. }
  28168. /**
  28169. * TSL function for creating a code node.
  28170. *
  28171. * @tsl
  28172. * @function
  28173. * @param {string} [code] - The native code.
  28174. * @param {?Array<Node>} [includes=[]] - An array of includes.
  28175. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  28176. * @returns {CodeNode}
  28177. */
  28178. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  28179. /**
  28180. * TSL function for creating a JS code node.
  28181. *
  28182. * @tsl
  28183. * @function
  28184. * @param {string} src - The native code.
  28185. * @param {Array<Node>} includes - An array of includes.
  28186. * @returns {CodeNode}
  28187. */
  28188. const js = ( src, includes ) => code( src, includes, 'js' );
  28189. /**
  28190. * TSL function for creating a WGSL code node.
  28191. *
  28192. * @tsl
  28193. * @function
  28194. * @param {string} src - The native code.
  28195. * @param {Array<Node>} includes - An array of includes.
  28196. * @returns {CodeNode}
  28197. */
  28198. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  28199. /**
  28200. * TSL function for creating a GLSL code node.
  28201. *
  28202. * @tsl
  28203. * @function
  28204. * @param {string} src - The native code.
  28205. * @param {Array<Node>} includes - An array of includes.
  28206. * @returns {CodeNode}
  28207. */
  28208. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  28209. /**
  28210. * This class represents a native shader function. It can be used to implement
  28211. * certain aspects of a node material with native shader code. There are two predefined
  28212. * TSL functions for easier usage.
  28213. *
  28214. * - `wgslFn`: Creates a WGSL function node.
  28215. * - `glslFn`: Creates a GLSL function node.
  28216. *
  28217. * A basic example with one include looks like so:
  28218. *
  28219. * ```js
  28220. * const desaturateWGSLFn = wgslFn( `
  28221. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  28222. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  28223. * return vec3<f32>( dot( lum, color ) );
  28224. * }`
  28225. *);
  28226. * const someWGSLFn = wgslFn( `
  28227. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  28228. * return desaturate( color );
  28229. * }
  28230. * `, [ desaturateWGSLFn ] );
  28231. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  28232. *```
  28233. * @augments CodeNode
  28234. */
  28235. class FunctionNode extends CodeNode {
  28236. static get type() {
  28237. return 'FunctionNode';
  28238. }
  28239. /**
  28240. * Constructs a new function node.
  28241. *
  28242. * @param {string} [code=''] - The native code.
  28243. * @param {Array<Node>} [includes=[]] - An array of includes.
  28244. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  28245. */
  28246. constructor( code = '', includes = [], language = '' ) {
  28247. super( code, includes, language );
  28248. }
  28249. /**
  28250. * Returns the type of this function node.
  28251. *
  28252. * @param {NodeBuilder} builder - The current node builder.
  28253. * @return {string} The type.
  28254. */
  28255. getNodeType( builder ) {
  28256. return this.getNodeFunction( builder ).type;
  28257. }
  28258. /**
  28259. * Returns the type of a member of this function node.
  28260. *
  28261. * @param {NodeBuilder} builder - The current node builder.
  28262. * @param {string} name - The name of the member.
  28263. * @return {string} The type of the member.
  28264. */
  28265. getMemberType( builder, name ) {
  28266. const type = this.getNodeType( builder );
  28267. const structType = builder.getStructTypeNode( type );
  28268. return structType.getMemberType( builder, name );
  28269. }
  28270. /**
  28271. * Returns the inputs of this function node.
  28272. *
  28273. * @param {NodeBuilder} builder - The current node builder.
  28274. * @return {Array<NodeFunctionInput>} The inputs.
  28275. */
  28276. getInputs( builder ) {
  28277. return this.getNodeFunction( builder ).inputs;
  28278. }
  28279. /**
  28280. * Returns the node function for this function node.
  28281. *
  28282. * @param {NodeBuilder} builder - The current node builder.
  28283. * @return {NodeFunction} The node function.
  28284. */
  28285. getNodeFunction( builder ) {
  28286. const nodeData = builder.getDataFromNode( this );
  28287. let nodeFunction = nodeData.nodeFunction;
  28288. if ( nodeFunction === undefined ) {
  28289. nodeFunction = builder.parser.parseFunction( this.code );
  28290. nodeData.nodeFunction = nodeFunction;
  28291. }
  28292. return nodeFunction;
  28293. }
  28294. generate( builder, output ) {
  28295. super.generate( builder );
  28296. const nodeFunction = this.getNodeFunction( builder );
  28297. const name = nodeFunction.name;
  28298. const type = nodeFunction.type;
  28299. const nodeCode = builder.getCodeFromNode( this, type );
  28300. if ( name !== '' ) {
  28301. // use a custom property name
  28302. nodeCode.name = name;
  28303. }
  28304. const propertyName = builder.getPropertyName( nodeCode );
  28305. const code = this.getNodeFunction( builder ).getCode( propertyName );
  28306. nodeCode.code = code + '\n';
  28307. if ( output === 'property' ) {
  28308. return propertyName;
  28309. } else {
  28310. return builder.format( `${ propertyName }()`, type, output );
  28311. }
  28312. }
  28313. }
  28314. const nativeFn = ( code, includes = [], language = '' ) => {
  28315. for ( let i = 0; i < includes.length; i ++ ) {
  28316. const include = includes[ i ];
  28317. // TSL Function: glslFn, wgslFn
  28318. if ( typeof include === 'function' ) {
  28319. includes[ i ] = include.functionNode;
  28320. }
  28321. }
  28322. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  28323. const fn = ( ...params ) => functionNode.call( ...params );
  28324. fn.functionNode = functionNode;
  28325. return fn;
  28326. };
  28327. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  28328. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  28329. /**
  28330. * `ScriptableNode` uses this class to manage script inputs and outputs.
  28331. *
  28332. * @augments Node
  28333. */
  28334. class ScriptableValueNode extends Node {
  28335. static get type() {
  28336. return 'ScriptableValueNode';
  28337. }
  28338. /**
  28339. * Constructs a new scriptable node.
  28340. *
  28341. * @param {any} [value=null] - The value.
  28342. */
  28343. constructor( value = null ) {
  28344. super();
  28345. /**
  28346. * A reference to the value.
  28347. *
  28348. * @private
  28349. * @default null
  28350. */
  28351. this._value = value;
  28352. /**
  28353. * Depending on the type of `_value`, this property might cache parsed data.
  28354. *
  28355. * @private
  28356. * @default null
  28357. */
  28358. this._cache = null;
  28359. /**
  28360. * If this node represents an input, this property represents the input type.
  28361. *
  28362. * @type {?string}
  28363. * @default null
  28364. */
  28365. this.inputType = null;
  28366. /**
  28367. * If this node represents an output, this property represents the output type.
  28368. *
  28369. * @type {?string}
  28370. * @default null
  28371. */
  28372. this.outputType = null;
  28373. /**
  28374. * An event dispatcher for managing events.
  28375. *
  28376. * @type {EventDispatcher}
  28377. */
  28378. this.events = new EventDispatcher();
  28379. /**
  28380. * This flag can be used for type testing.
  28381. *
  28382. * @type {boolean}
  28383. * @readonly
  28384. * @default true
  28385. */
  28386. this.isScriptableValueNode = true;
  28387. }
  28388. /**
  28389. * Whether this node represents an output or not.
  28390. *
  28391. * @type {boolean}
  28392. * @readonly
  28393. * @default true
  28394. */
  28395. get isScriptableOutputNode() {
  28396. return this.outputType !== null;
  28397. }
  28398. set value( val ) {
  28399. if ( this._value === val ) return;
  28400. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  28401. URL.revokeObjectURL( this._cache );
  28402. this._cache = null;
  28403. }
  28404. this._value = val;
  28405. this.events.dispatchEvent( { type: 'change' } );
  28406. this.refresh();
  28407. }
  28408. /**
  28409. * The node's value.
  28410. *
  28411. * @type {any}
  28412. */
  28413. get value() {
  28414. return this._value;
  28415. }
  28416. /**
  28417. * Dispatches the `refresh` event.
  28418. */
  28419. refresh() {
  28420. this.events.dispatchEvent( { type: 'refresh' } );
  28421. }
  28422. /**
  28423. * The `value` property usually represents a node or even binary data in form of array buffers.
  28424. * In this case, this method tries to return the actual value behind the complex type.
  28425. *
  28426. * @return {any} The value.
  28427. */
  28428. getValue() {
  28429. const value = this.value;
  28430. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  28431. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  28432. } else if ( value && value.value !== null && value.value !== undefined && (
  28433. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  28434. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  28435. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  28436. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  28437. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  28438. ( this.inputType === 'Color' && value.value.isColor ) ||
  28439. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  28440. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  28441. ) ) {
  28442. return value.value;
  28443. }
  28444. return this._cache || value;
  28445. }
  28446. /**
  28447. * Overwritten since the node type is inferred from the value.
  28448. *
  28449. * @param {NodeBuilder} builder - The current node builder.
  28450. * @return {string} The node type.
  28451. */
  28452. getNodeType( builder ) {
  28453. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  28454. }
  28455. setup() {
  28456. return this.value && this.value.isNode ? this.value : float();
  28457. }
  28458. serialize( data ) {
  28459. super.serialize( data );
  28460. if ( this.value !== null ) {
  28461. if ( this.inputType === 'ArrayBuffer' ) {
  28462. data.value = arrayBufferToBase64( this.value );
  28463. } else {
  28464. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  28465. }
  28466. } else {
  28467. data.value = null;
  28468. }
  28469. data.inputType = this.inputType;
  28470. data.outputType = this.outputType;
  28471. }
  28472. deserialize( data ) {
  28473. super.deserialize( data );
  28474. let value = null;
  28475. if ( data.value !== null ) {
  28476. if ( data.inputType === 'ArrayBuffer' ) {
  28477. value = base64ToArrayBuffer( data.value );
  28478. } else if ( data.inputType === 'Texture' ) {
  28479. value = data.meta.textures[ data.value ];
  28480. } else {
  28481. value = data.meta.nodes[ data.value ] || null;
  28482. }
  28483. }
  28484. this.value = value;
  28485. this.inputType = data.inputType;
  28486. this.outputType = data.outputType;
  28487. }
  28488. }
  28489. /**
  28490. * TSL function for creating a scriptable value node.
  28491. *
  28492. * @tsl
  28493. * @function
  28494. * @param {any} [value] - The value.
  28495. * @returns {ScriptableValueNode}
  28496. */
  28497. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ).setParameterLength( 1 );
  28498. /**
  28499. * A Map-like data structure for managing resources of scriptable nodes.
  28500. *
  28501. * @augments Map
  28502. */
  28503. class Resources extends Map {
  28504. get( key, callback = null, ...params ) {
  28505. if ( this.has( key ) ) return super.get( key );
  28506. if ( callback !== null ) {
  28507. const value = callback( ...params );
  28508. this.set( key, value );
  28509. return value;
  28510. }
  28511. }
  28512. }
  28513. class Parameters {
  28514. constructor( scriptableNode ) {
  28515. this.scriptableNode = scriptableNode;
  28516. }
  28517. get parameters() {
  28518. return this.scriptableNode.parameters;
  28519. }
  28520. get layout() {
  28521. return this.scriptableNode.getLayout();
  28522. }
  28523. getInputLayout( id ) {
  28524. return this.scriptableNode.getInputLayout( id );
  28525. }
  28526. get( name ) {
  28527. const param = this.parameters[ name ];
  28528. const value = param ? param.getValue() : null;
  28529. return value;
  28530. }
  28531. }
  28532. /**
  28533. * Defines the resources (e.g. namespaces) of scriptable nodes.
  28534. *
  28535. * @type {Resources}
  28536. */
  28537. const ScriptableNodeResources = new Resources();
  28538. /**
  28539. * This type of node allows to implement nodes with custom scripts. The script
  28540. * section is represented as an instance of `CodeNode` written with JavaScript.
  28541. * The script itself must adhere to a specific structure.
  28542. *
  28543. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  28544. * - layout: The layout object defines the script's interface (inputs and outputs).
  28545. *
  28546. * ```js
  28547. * ScriptableNodeResources.set( 'TSL', TSL );
  28548. *
  28549. * const scriptableNode = scriptable( js( `
  28550. * layout = {
  28551. * outputType: 'node',
  28552. * elements: [
  28553. * { name: 'source', inputType: 'node' },
  28554. * ]
  28555. * };
  28556. *
  28557. * const { mul, oscSine } = TSL;
  28558. *
  28559. * function main() {
  28560. * const source = parameters.get( 'source' ) || float();
  28561. * return mul( source, oscSine() ) );
  28562. * }
  28563. *
  28564. * ` ) );
  28565. *
  28566. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  28567. *
  28568. * const material = new THREE.MeshBasicNodeMaterial();
  28569. * material.colorNode = scriptableNode;
  28570. * ```
  28571. *
  28572. * @augments Node
  28573. */
  28574. class ScriptableNode extends Node {
  28575. static get type() {
  28576. return 'ScriptableNode';
  28577. }
  28578. /**
  28579. * Constructs a new scriptable node.
  28580. *
  28581. * @param {?CodeNode} [codeNode=null] - The code node.
  28582. * @param {Object} [parameters={}] - The parameters definition.
  28583. */
  28584. constructor( codeNode = null, parameters = {} ) {
  28585. super();
  28586. /**
  28587. * The code node.
  28588. *
  28589. * @type {?CodeNode}
  28590. * @default null
  28591. */
  28592. this.codeNode = codeNode;
  28593. /**
  28594. * The parameters definition.
  28595. *
  28596. * @type {Object}
  28597. * @default {}
  28598. */
  28599. this.parameters = parameters;
  28600. this._local = new Resources();
  28601. this._output = scriptableValue( null );
  28602. this._outputs = {};
  28603. this._source = this.source;
  28604. this._method = null;
  28605. this._object = null;
  28606. this._value = null;
  28607. this._needsOutputUpdate = true;
  28608. this.onRefresh = this.onRefresh.bind( this );
  28609. /**
  28610. * This flag can be used for type testing.
  28611. *
  28612. * @type {boolean}
  28613. * @readonly
  28614. * @default true
  28615. */
  28616. this.isScriptableNode = true;
  28617. }
  28618. /**
  28619. * The source code of the scriptable node.
  28620. *
  28621. * @type {string}
  28622. */
  28623. get source() {
  28624. return this.codeNode ? this.codeNode.code : '';
  28625. }
  28626. /**
  28627. * Sets the reference of a local script variable.
  28628. *
  28629. * @param {string} name - The variable name.
  28630. * @param {Object} value - The reference to set.
  28631. * @return {Resources} The resource map
  28632. */
  28633. setLocal( name, value ) {
  28634. return this._local.set( name, value );
  28635. }
  28636. /**
  28637. * Gets the value of a local script variable.
  28638. *
  28639. * @param {string} name - The variable name.
  28640. * @return {Object} The value.
  28641. */
  28642. getLocal( name ) {
  28643. return this._local.get( name );
  28644. }
  28645. /**
  28646. * Event listener for the `refresh` event.
  28647. */
  28648. onRefresh() {
  28649. this._refresh();
  28650. }
  28651. /**
  28652. * Returns an input from the layout with the given id/name.
  28653. *
  28654. * @param {string} id - The id/name of the input.
  28655. * @return {Object} The element entry.
  28656. */
  28657. getInputLayout( id ) {
  28658. for ( const element of this.getLayout() ) {
  28659. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  28660. return element;
  28661. }
  28662. }
  28663. }
  28664. /**
  28665. * Returns an output from the layout with the given id/name.
  28666. *
  28667. * @param {string} id - The id/name of the output.
  28668. * @return {Object} The element entry.
  28669. */
  28670. getOutputLayout( id ) {
  28671. for ( const element of this.getLayout() ) {
  28672. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  28673. return element;
  28674. }
  28675. }
  28676. }
  28677. /**
  28678. * Defines a script output for the given name and value.
  28679. *
  28680. * @param {string} name - The name of the output.
  28681. * @param {Node} value - The node value.
  28682. * @return {ScriptableNode} A reference to this node.
  28683. */
  28684. setOutput( name, value ) {
  28685. const outputs = this._outputs;
  28686. if ( outputs[ name ] === undefined ) {
  28687. outputs[ name ] = scriptableValue( value );
  28688. } else {
  28689. outputs[ name ].value = value;
  28690. }
  28691. return this;
  28692. }
  28693. /**
  28694. * Returns a script output for the given name.
  28695. *
  28696. * @param {string} name - The name of the output.
  28697. * @return {ScriptableValueNode} The node value.
  28698. */
  28699. getOutput( name ) {
  28700. return this._outputs[ name ];
  28701. }
  28702. /**
  28703. * Returns a parameter for the given name
  28704. *
  28705. * @param {string} name - The name of the parameter.
  28706. * @return {ScriptableValueNode} The node value.
  28707. */
  28708. getParameter( name ) {
  28709. return this.parameters[ name ];
  28710. }
  28711. /**
  28712. * Sets a value for the given parameter name.
  28713. *
  28714. * @param {string} name - The parameter name.
  28715. * @param {any} value - The parameter value.
  28716. * @return {ScriptableNode} A reference to this node.
  28717. */
  28718. setParameter( name, value ) {
  28719. const parameters = this.parameters;
  28720. if ( value && value.isScriptableNode ) {
  28721. this.deleteParameter( name );
  28722. parameters[ name ] = value;
  28723. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  28724. } else if ( value && value.isScriptableValueNode ) {
  28725. this.deleteParameter( name );
  28726. parameters[ name ] = value;
  28727. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  28728. } else if ( parameters[ name ] === undefined ) {
  28729. parameters[ name ] = scriptableValue( value );
  28730. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  28731. } else {
  28732. parameters[ name ].value = value;
  28733. }
  28734. return this;
  28735. }
  28736. /**
  28737. * Returns the value of this node which is the value of
  28738. * the default output.
  28739. *
  28740. * @return {Node} The value.
  28741. */
  28742. getValue() {
  28743. return this.getDefaultOutput().getValue();
  28744. }
  28745. /**
  28746. * Deletes a parameter from the script.
  28747. *
  28748. * @param {string} name - The parameter to remove.
  28749. * @return {ScriptableNode} A reference to this node.
  28750. */
  28751. deleteParameter( name ) {
  28752. let valueNode = this.parameters[ name ];
  28753. if ( valueNode ) {
  28754. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  28755. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  28756. }
  28757. return this;
  28758. }
  28759. /**
  28760. * Deletes all parameters from the script.
  28761. *
  28762. * @return {ScriptableNode} A reference to this node.
  28763. */
  28764. clearParameters() {
  28765. for ( const name of Object.keys( this.parameters ) ) {
  28766. this.deleteParameter( name );
  28767. }
  28768. this.needsUpdate = true;
  28769. return this;
  28770. }
  28771. /**
  28772. * Calls a function from the script.
  28773. *
  28774. * @param {string} name - The function name.
  28775. * @param {...any} params - A list of parameters.
  28776. * @return {any} The result of the function call.
  28777. */
  28778. call( name, ...params ) {
  28779. const object = this.getObject();
  28780. const method = object[ name ];
  28781. if ( typeof method === 'function' ) {
  28782. return method( ...params );
  28783. }
  28784. }
  28785. /**
  28786. * Asynchronously calls a function from the script.
  28787. *
  28788. * @param {string} name - The function name.
  28789. * @param {...any} params - A list of parameters.
  28790. * @return {Promise<any>} The result of the function call.
  28791. */
  28792. async callAsync( name, ...params ) {
  28793. const object = this.getObject();
  28794. const method = object[ name ];
  28795. if ( typeof method === 'function' ) {
  28796. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  28797. }
  28798. }
  28799. /**
  28800. * Overwritten since the node types is inferred from the script's output.
  28801. *
  28802. * @param {NodeBuilder} builder - The current node builder
  28803. * @return {string} The node type.
  28804. */
  28805. getNodeType( builder ) {
  28806. return this.getDefaultOutputNode().getNodeType( builder );
  28807. }
  28808. /**
  28809. * Refreshes the script node.
  28810. *
  28811. * @param {?string} [output=null] - An optional output.
  28812. */
  28813. refresh( output = null ) {
  28814. if ( output !== null ) {
  28815. this.getOutput( output ).refresh();
  28816. } else {
  28817. this._refresh();
  28818. }
  28819. }
  28820. /**
  28821. * Returns an object representation of the script.
  28822. *
  28823. * @return {Object} The result object.
  28824. */
  28825. getObject() {
  28826. if ( this.needsUpdate ) this.dispose();
  28827. if ( this._object !== null ) return this._object;
  28828. //
  28829. const refresh = () => this.refresh();
  28830. const setOutput = ( id, value ) => this.setOutput( id, value );
  28831. const parameters = new Parameters( this );
  28832. const THREE = ScriptableNodeResources.get( 'THREE' );
  28833. const TSL = ScriptableNodeResources.get( 'TSL' );
  28834. const method = this.getMethod();
  28835. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  28836. this._object = method( ...params );
  28837. const layout = this._object.layout;
  28838. if ( layout ) {
  28839. if ( layout.cache === false ) {
  28840. this._local.clear();
  28841. }
  28842. // default output
  28843. this._output.outputType = layout.outputType || null;
  28844. if ( Array.isArray( layout.elements ) ) {
  28845. for ( const element of layout.elements ) {
  28846. const id = element.id || element.name;
  28847. if ( element.inputType ) {
  28848. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  28849. this.getParameter( id ).inputType = element.inputType;
  28850. }
  28851. if ( element.outputType ) {
  28852. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  28853. this.getOutput( id ).outputType = element.outputType;
  28854. }
  28855. }
  28856. }
  28857. }
  28858. return this._object;
  28859. }
  28860. deserialize( data ) {
  28861. super.deserialize( data );
  28862. for ( const name in this.parameters ) {
  28863. let valueNode = this.parameters[ name ];
  28864. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  28865. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  28866. }
  28867. }
  28868. /**
  28869. * Returns the layout of the script.
  28870. *
  28871. * @return {Object} The script's layout.
  28872. */
  28873. getLayout() {
  28874. return this.getObject().layout;
  28875. }
  28876. /**
  28877. * Returns default node output of the script.
  28878. *
  28879. * @return {Node} The default node output.
  28880. */
  28881. getDefaultOutputNode() {
  28882. const output = this.getDefaultOutput().value;
  28883. if ( output && output.isNode ) {
  28884. return output;
  28885. }
  28886. return float();
  28887. }
  28888. /**
  28889. * Returns default output of the script.
  28890. *
  28891. * @return {ScriptableValueNode} The default output.
  28892. */
  28893. getDefaultOutput() {
  28894. return this._exec()._output;
  28895. }
  28896. /**
  28897. * Returns a function created from the node's script.
  28898. *
  28899. * @return {Function} The function representing the node's code.
  28900. */
  28901. getMethod() {
  28902. if ( this.needsUpdate ) this.dispose();
  28903. if ( this._method !== null ) return this._method;
  28904. //
  28905. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  28906. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  28907. const properties = interfaceProps.join( ', ' );
  28908. const declarations = 'var ' + properties + '; var output = {};\n';
  28909. const returns = '\nreturn { ...output, ' + properties + ' };';
  28910. const code = declarations + this.codeNode.code + returns;
  28911. //
  28912. this._method = new Function( ...parametersProps, code );
  28913. return this._method;
  28914. }
  28915. /**
  28916. * Frees all internal resources.
  28917. */
  28918. dispose() {
  28919. if ( this._method === null ) return;
  28920. if ( this._object && typeof this._object.dispose === 'function' ) {
  28921. this._object.dispose();
  28922. }
  28923. this._method = null;
  28924. this._object = null;
  28925. this._source = null;
  28926. this._value = null;
  28927. this._needsOutputUpdate = true;
  28928. this._output.value = null;
  28929. this._outputs = {};
  28930. }
  28931. setup() {
  28932. return this.getDefaultOutputNode();
  28933. }
  28934. getCacheKey( force ) {
  28935. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  28936. for ( const param in this.parameters ) {
  28937. values.push( this.parameters[ param ].getCacheKey( force ) );
  28938. }
  28939. return hashArray( values );
  28940. }
  28941. set needsUpdate( value ) {
  28942. if ( value === true ) this.dispose();
  28943. }
  28944. get needsUpdate() {
  28945. return this.source !== this._source;
  28946. }
  28947. /**
  28948. * Executes the `main` function of the script.
  28949. *
  28950. * @private
  28951. * @return {ScriptableNode} A reference to this node.
  28952. */
  28953. _exec() {
  28954. if ( this.codeNode === null ) return this;
  28955. if ( this._needsOutputUpdate === true ) {
  28956. this._value = this.call( 'main' );
  28957. this._needsOutputUpdate = false;
  28958. }
  28959. this._output.value = this._value;
  28960. return this;
  28961. }
  28962. /**
  28963. * Executes the refresh.
  28964. *
  28965. * @private
  28966. */
  28967. _refresh() {
  28968. this.needsUpdate = true;
  28969. this._exec();
  28970. this._output.refresh();
  28971. }
  28972. }
  28973. /**
  28974. * TSL function for creating a scriptable node.
  28975. *
  28976. * @tsl
  28977. * @function
  28978. * @param {CodeNode} [codeNode] - The code node.
  28979. * @param {?Object} [parameters={}] - The parameters definition.
  28980. * @returns {ScriptableNode}
  28981. */
  28982. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ).setParameterLength( 1, 2 );
  28983. /**
  28984. * Returns a node that represents the `z` coordinate in view space
  28985. * for the current fragment. It's a different representation of the
  28986. * default depth value.
  28987. *
  28988. * This value can be part of a computation that defines how the fog
  28989. * density increases when moving away from the camera.
  28990. *
  28991. * @param {NodeBuilder} builder - The current node builder.
  28992. * @return {Node} The viewZ node.
  28993. */
  28994. function getViewZNode( builder ) {
  28995. let viewZ;
  28996. const getViewZ = builder.context.getViewZ;
  28997. if ( getViewZ !== undefined ) {
  28998. viewZ = getViewZ( this );
  28999. }
  29000. return ( viewZ || positionView.z ).negate();
  29001. }
  29002. /**
  29003. * Constructs a new range factor node.
  29004. *
  29005. * @tsl
  29006. * @function
  29007. * @param {Node} near - Defines the near value.
  29008. * @param {Node} far - Defines the far value.
  29009. */
  29010. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  29011. const viewZ = getViewZNode( builder );
  29012. return smoothstep( near, far, viewZ );
  29013. } );
  29014. /**
  29015. * Represents an exponential squared fog. This type of fog gives
  29016. * a clear view near the camera and a faster than exponentially
  29017. * densening fog farther from the camera.
  29018. *
  29019. * @tsl
  29020. * @function
  29021. * @param {Node} density - Defines the fog density.
  29022. */
  29023. const densityFogFactor = Fn( ( [ density ], builder ) => {
  29024. const viewZ = getViewZNode( builder );
  29025. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  29026. } );
  29027. /**
  29028. * This class can be used to configure a fog for the scene.
  29029. * Nodes of this type are assigned to `Scene.fogNode`.
  29030. *
  29031. * @tsl
  29032. * @function
  29033. * @param {Node} color - Defines the color of the fog.
  29034. * @param {Node} factor - Defines how the fog is factored in the scene.
  29035. */
  29036. const fog = Fn( ( [ color, factor ] ) => {
  29037. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  29038. } );
  29039. // Deprecated
  29040. /**
  29041. * @tsl
  29042. * @function
  29043. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  29044. *
  29045. * @param {Node} color
  29046. * @param {Node} near
  29047. * @param {Node} far
  29048. * @returns {Function}
  29049. */
  29050. function rangeFog( color, near, far ) { // @deprecated, r171
  29051. warn( 'TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  29052. return fog( color, rangeFogFactor( near, far ) );
  29053. }
  29054. /**
  29055. * @tsl
  29056. * @function
  29057. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  29058. *
  29059. * @param {Node} color
  29060. * @param {Node} density
  29061. * @returns {Function}
  29062. */
  29063. function densityFog( color, density ) { // @deprecated, r171
  29064. warn( 'TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  29065. return fog( color, densityFogFactor( density ) );
  29066. }
  29067. let min = null;
  29068. let max = null;
  29069. /**
  29070. * `RangeNode` generates random instanced attribute data in a defined range.
  29071. * An exemplary use case for this utility node is to generate random per-instance
  29072. * colors:
  29073. * ```js
  29074. * const material = new MeshBasicNodeMaterial();
  29075. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  29076. * const mesh = new InstancedMesh( geometry, material, count );
  29077. * ```
  29078. * @augments Node
  29079. */
  29080. class RangeNode extends Node {
  29081. static get type() {
  29082. return 'RangeNode';
  29083. }
  29084. /**
  29085. * Constructs a new range node.
  29086. *
  29087. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  29088. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  29089. */
  29090. constructor( minNode = float(), maxNode = float() ) {
  29091. super();
  29092. /**
  29093. * A node defining the lower bound of the range.
  29094. *
  29095. * @type {Node<any>}
  29096. * @default float()
  29097. */
  29098. this.minNode = minNode;
  29099. /**
  29100. * A node defining the upper bound of the range.
  29101. *
  29102. * @type {Node<any>}
  29103. * @default float()
  29104. */
  29105. this.maxNode = maxNode;
  29106. }
  29107. /**
  29108. * Returns the vector length which is computed based on the range definition.
  29109. *
  29110. * @param {NodeBuilder} builder - The current node builder.
  29111. * @return {number} The vector length.
  29112. */
  29113. getVectorLength( builder ) {
  29114. const minNode = this.getConstNode( this.minNode );
  29115. const maxNode = this.getConstNode( this.maxNode );
  29116. const minLength = builder.getTypeLength( getValueType( minNode.value ) );
  29117. const maxLength = builder.getTypeLength( getValueType( maxNode.value ) );
  29118. return minLength > maxLength ? minLength : maxLength;
  29119. }
  29120. /**
  29121. * This method is overwritten since the node type is inferred from range definition.
  29122. *
  29123. * @param {NodeBuilder} builder - The current node builder.
  29124. * @return {string} The node type.
  29125. */
  29126. getNodeType( builder ) {
  29127. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  29128. }
  29129. /**
  29130. * Returns a constant node from the given node by traversing it.
  29131. *
  29132. * @param {Node} node - The node to traverse.
  29133. * @returns {Node} The constant node, if found.
  29134. */
  29135. getConstNode( node ) {
  29136. let output = null;
  29137. node.traverse( n => {
  29138. if ( n.isConstNode === true ) {
  29139. output = n;
  29140. }
  29141. } );
  29142. if ( output === null ) {
  29143. throw new Error( 'THREE.TSL: No "ConstNode" found in node graph.' );
  29144. }
  29145. return output;
  29146. }
  29147. setup( builder ) {
  29148. const object = builder.object;
  29149. let output = null;
  29150. if ( object.count > 1 ) {
  29151. const minNode = this.getConstNode( this.minNode );
  29152. const maxNode = this.getConstNode( this.maxNode );
  29153. const minValue = minNode.value;
  29154. const maxValue = maxNode.value;
  29155. const minLength = builder.getTypeLength( getValueType( minValue ) );
  29156. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  29157. min = min || new Vector4();
  29158. max = max || new Vector4();
  29159. min.setScalar( 0 );
  29160. max.setScalar( 0 );
  29161. if ( minLength === 1 ) min.setScalar( minValue );
  29162. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  29163. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  29164. if ( maxLength === 1 ) max.setScalar( maxValue );
  29165. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  29166. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  29167. const stride = 4;
  29168. const length = stride * object.count;
  29169. const array = new Float32Array( length );
  29170. for ( let i = 0; i < length; i ++ ) {
  29171. const index = i % stride;
  29172. const minElementValue = min.getComponent( index );
  29173. const maxElementValue = max.getComponent( index );
  29174. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  29175. }
  29176. const nodeType = this.getNodeType( builder );
  29177. if ( object.count <= 4096 ) {
  29178. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  29179. } else {
  29180. // TODO: Improve anonymous buffer attribute creation removing this part
  29181. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  29182. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  29183. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  29184. }
  29185. } else {
  29186. output = float( 0 );
  29187. }
  29188. return output;
  29189. }
  29190. }
  29191. /**
  29192. * TSL function for creating a range node.
  29193. *
  29194. * @tsl
  29195. * @function
  29196. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  29197. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  29198. * @returns {RangeNode}
  29199. */
  29200. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  29201. /**
  29202. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  29203. * about the currently running dispatch and/or the device it is running on.
  29204. *
  29205. * This node can only be used with a WebGPU backend.
  29206. *
  29207. * @augments Node
  29208. */
  29209. class ComputeBuiltinNode extends Node {
  29210. static get type() {
  29211. return 'ComputeBuiltinNode';
  29212. }
  29213. /**
  29214. * Constructs a new compute builtin node.
  29215. *
  29216. * @param {string} builtinName - The built-in name.
  29217. * @param {string} nodeType - The node type.
  29218. */
  29219. constructor( builtinName, nodeType ) {
  29220. super( nodeType );
  29221. /**
  29222. * The built-in name.
  29223. *
  29224. * @private
  29225. * @type {string}
  29226. */
  29227. this._builtinName = builtinName;
  29228. }
  29229. /**
  29230. * This method is overwritten since hash is derived from the built-in name.
  29231. *
  29232. * @param {NodeBuilder} builder - The current node builder.
  29233. * @return {string} The hash.
  29234. */
  29235. getHash( builder ) {
  29236. return this.getBuiltinName( builder );
  29237. }
  29238. /**
  29239. * This method is overwritten since the node type is simply derived from `nodeType`..
  29240. *
  29241. * @param {NodeBuilder} builder - The current node builder.
  29242. * @return {string} The node type.
  29243. */
  29244. getNodeType( /*builder*/ ) {
  29245. return this.nodeType;
  29246. }
  29247. /**
  29248. * Sets the builtin name.
  29249. *
  29250. * @param {string} builtinName - The built-in name.
  29251. * @return {ComputeBuiltinNode} A reference to this node.
  29252. */
  29253. setBuiltinName( builtinName ) {
  29254. this._builtinName = builtinName;
  29255. return this;
  29256. }
  29257. /**
  29258. * Returns the builtin name.
  29259. *
  29260. * @param {NodeBuilder} builder - The current node builder.
  29261. * @return {string} The builtin name.
  29262. */
  29263. getBuiltinName( /*builder*/ ) {
  29264. return this._builtinName;
  29265. }
  29266. /**
  29267. * Whether the current node builder has the builtin or not.
  29268. *
  29269. * @param {NodeBuilder} builder - The current node builder.
  29270. * @return {boolean} Whether the builder has the builtin or not.
  29271. */
  29272. hasBuiltin( builder ) {
  29273. return builder.hasBuiltin( this._builtinName );
  29274. }
  29275. generate( builder, output ) {
  29276. const builtinName = this.getBuiltinName( builder );
  29277. const nodeType = this.getNodeType( builder );
  29278. if ( builder.shaderStage === 'compute' ) {
  29279. return builder.format( builtinName, nodeType, output );
  29280. } else {
  29281. warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  29282. return builder.generateConst( nodeType );
  29283. }
  29284. }
  29285. serialize( data ) {
  29286. super.serialize( data );
  29287. data.global = this.global;
  29288. data._builtinName = this._builtinName;
  29289. }
  29290. deserialize( data ) {
  29291. super.deserialize( data );
  29292. this.global = data.global;
  29293. this._builtinName = data._builtinName;
  29294. }
  29295. }
  29296. /**
  29297. * TSL function for creating a compute builtin node.
  29298. *
  29299. * @tsl
  29300. * @function
  29301. * @param {string} name - The built-in name.
  29302. * @param {string} nodeType - The node type.
  29303. * @returns {ComputeBuiltinNode}
  29304. */
  29305. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  29306. /**
  29307. * Represents the number of workgroups dispatched by the compute shader.
  29308. * ```js
  29309. * // Run 512 invocations/threads with a workgroup size of 128.
  29310. * const computeFn = Fn(() => {
  29311. *
  29312. * // numWorkgroups.x = 4
  29313. * storageBuffer.element(0).assign(numWorkgroups.x)
  29314. *
  29315. * })().compute(512, [128]);
  29316. *
  29317. * // Run 512 invocations/threads with the default workgroup size of 64.
  29318. * const computeFn = Fn(() => {
  29319. *
  29320. * // numWorkgroups.x = 8
  29321. * storageBuffer.element(0).assign(numWorkgroups.x)
  29322. *
  29323. * })().compute(512);
  29324. * ```
  29325. *
  29326. * @tsl
  29327. * @type {ComputeBuiltinNode<uvec3>}
  29328. */
  29329. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  29330. /**
  29331. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  29332. * ```js
  29333. * // Execute 12 compute threads with a workgroup size of 3.
  29334. * const computeFn = Fn( () => {
  29335. *
  29336. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  29337. *
  29338. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  29339. *
  29340. * } ).Else( () => {
  29341. *
  29342. * storageBuffer.element( instanceIndex ).assign( 0 );
  29343. *
  29344. * } );
  29345. *
  29346. * } )().compute( 12, [ 3 ] );
  29347. *
  29348. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  29349. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  29350. * ```
  29351. *
  29352. * @tsl
  29353. * @type {ComputeBuiltinNode<uvec3>}
  29354. */
  29355. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  29356. /**
  29357. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  29358. *
  29359. * @tsl
  29360. * @type {ComputeBuiltinNode<uvec3>}
  29361. */
  29362. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  29363. /**
  29364. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  29365. *
  29366. * @tsl
  29367. * @type {ComputeBuiltinNode<uvec3>}
  29368. */
  29369. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  29370. /**
  29371. * A device dependent variable that exposes the size of the current invocation's subgroup.
  29372. *
  29373. * @tsl
  29374. * @type {ComputeBuiltinNode<uint>}
  29375. */
  29376. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  29377. /**
  29378. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  29379. *
  29380. * This node can only be used with a WebGPU backend.
  29381. *
  29382. * @augments Node
  29383. */
  29384. class BarrierNode extends Node {
  29385. /**
  29386. * Constructs a new barrier node.
  29387. *
  29388. * @param {string} scope - The scope defines the behavior of the node.
  29389. */
  29390. constructor( scope ) {
  29391. super();
  29392. this.scope = scope;
  29393. }
  29394. generate( builder ) {
  29395. const { scope } = this;
  29396. const { renderer } = builder;
  29397. if ( renderer.backend.isWebGLBackend === true ) {
  29398. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  29399. } else {
  29400. builder.addLineFlowCode( `${scope}Barrier()`, this );
  29401. }
  29402. }
  29403. }
  29404. /**
  29405. * TSL function for creating a barrier node.
  29406. *
  29407. * @tsl
  29408. * @function
  29409. * @param {string} scope - The scope defines the behavior of the node..
  29410. * @returns {BarrierNode}
  29411. */
  29412. const barrier = nodeProxy( BarrierNode );
  29413. /**
  29414. * TSL function for creating a workgroup barrier. All compute shader
  29415. * invocations must wait for each invocation within a workgroup to
  29416. * complete before the barrier can be surpassed.
  29417. *
  29418. * @tsl
  29419. * @function
  29420. * @returns {BarrierNode}
  29421. */
  29422. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  29423. /**
  29424. * TSL function for creating a storage barrier. All invocations must
  29425. * wait for each access to variables within the 'storage' address space
  29426. * to complete before the barrier can be passed.
  29427. *
  29428. * @tsl
  29429. * @function
  29430. * @returns {BarrierNode}
  29431. */
  29432. const storageBarrier = () => barrier( 'storage' ).toStack();
  29433. /**
  29434. * TSL function for creating a texture barrier. All invocations must
  29435. * wait for each access to variables within the 'texture' address space
  29436. * to complete before the barrier can be passed.
  29437. *
  29438. * @tsl
  29439. * @function
  29440. * @returns {BarrierNode}
  29441. */
  29442. const textureBarrier = () => barrier( 'texture' ).toStack();
  29443. /**
  29444. * Represents an element of a 'workgroup' scoped buffer.
  29445. *
  29446. * @augments ArrayElementNode
  29447. */
  29448. class WorkgroupInfoElementNode extends ArrayElementNode {
  29449. /**
  29450. * Constructs a new workgroup info element node.
  29451. *
  29452. * @param {Node} workgroupInfoNode - The workgroup info node.
  29453. * @param {Node} indexNode - The index node that defines the element access.
  29454. */
  29455. constructor( workgroupInfoNode, indexNode ) {
  29456. super( workgroupInfoNode, indexNode );
  29457. /**
  29458. * This flag can be used for type testing.
  29459. *
  29460. * @type {boolean}
  29461. * @readonly
  29462. * @default true
  29463. */
  29464. this.isWorkgroupInfoElementNode = true;
  29465. }
  29466. generate( builder, output ) {
  29467. let snippet;
  29468. const isAssignContext = builder.context.assign;
  29469. snippet = super.generate( builder );
  29470. if ( isAssignContext !== true ) {
  29471. const type = this.getNodeType( builder );
  29472. snippet = builder.format( snippet, type, output );
  29473. }
  29474. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  29475. return snippet;
  29476. }
  29477. }
  29478. /**
  29479. * A node allowing the user to create a 'workgroup' scoped buffer within the
  29480. * context of a compute shader. Typically, workgroup scoped buffers are
  29481. * created to hold data that is transferred from a global storage scope into
  29482. * a local workgroup scope. For invocations within a workgroup, data
  29483. * access speeds on 'workgroup' scoped buffers can be significantly faster
  29484. * than similar access operations on globally accessible storage buffers.
  29485. *
  29486. * This node can only be used with a WebGPU backend.
  29487. *
  29488. * @augments Node
  29489. */
  29490. class WorkgroupInfoNode extends Node {
  29491. /**
  29492. * Constructs a new buffer scoped to type scope.
  29493. *
  29494. * @param {string} scope - TODO.
  29495. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  29496. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  29497. */
  29498. constructor( scope, bufferType, bufferCount = 0 ) {
  29499. super( bufferType );
  29500. /**
  29501. * The buffer type.
  29502. *
  29503. * @type {string}
  29504. */
  29505. this.bufferType = bufferType;
  29506. /**
  29507. * The buffer count.
  29508. *
  29509. * @type {number}
  29510. * @default 0
  29511. */
  29512. this.bufferCount = bufferCount;
  29513. /**
  29514. * This flag can be used for type testing.
  29515. *
  29516. * @type {boolean}
  29517. * @readonly
  29518. * @default true
  29519. */
  29520. this.isWorkgroupInfoNode = true;
  29521. /**
  29522. * The data type of the array buffer.
  29523. *
  29524. * @type {string}
  29525. */
  29526. this.elementType = bufferType;
  29527. /**
  29528. * TODO.
  29529. *
  29530. * @type {string}
  29531. */
  29532. this.scope = scope;
  29533. /**
  29534. * The name of the workgroup scoped buffer.
  29535. *
  29536. * @type {string}
  29537. * @default ''
  29538. */
  29539. this.name = '';
  29540. }
  29541. /**
  29542. * Sets the name of this node.
  29543. *
  29544. * @param {string} name - The name to set.
  29545. * @return {WorkgroupInfoNode} A reference to this node.
  29546. */
  29547. setName( name ) {
  29548. this.name = name;
  29549. return this;
  29550. }
  29551. /**
  29552. * Sets the name/label of this node.
  29553. *
  29554. * @deprecated
  29555. * @param {string} name - The name to set.
  29556. * @return {WorkgroupInfoNode} A reference to this node.
  29557. */
  29558. label( name ) {
  29559. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  29560. return this.setName( name );
  29561. }
  29562. /**
  29563. * Sets the scope of this node.
  29564. *
  29565. * @param {string} scope - The scope to set.
  29566. * @return {WorkgroupInfoNode} A reference to this node.
  29567. */
  29568. setScope( scope ) {
  29569. this.scope = scope;
  29570. return this;
  29571. }
  29572. /**
  29573. * The data type of the array buffer.
  29574. *
  29575. * @return {string} The element type.
  29576. */
  29577. getElementType() {
  29578. return this.elementType;
  29579. }
  29580. /**
  29581. * Overwrites the default implementation since the input type
  29582. * is inferred from the scope.
  29583. *
  29584. * @param {NodeBuilder} builder - The current node builder.
  29585. * @return {string} The input type.
  29586. */
  29587. getInputType( /*builder*/ ) {
  29588. return `${this.scope}Array`;
  29589. }
  29590. /**
  29591. * This method can be used to access elements via an index node.
  29592. *
  29593. * @param {IndexNode} indexNode - indexNode.
  29594. * @return {WorkgroupInfoElementNode} A reference to an element.
  29595. */
  29596. element( indexNode ) {
  29597. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  29598. }
  29599. generate( builder ) {
  29600. const name = ( this.name !== '' ) ? this.name : `${this.scope}Array_${this.id}`;
  29601. return builder.getScopedArray( name, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  29602. }
  29603. }
  29604. /**
  29605. * TSL function for creating a workgroup info node.
  29606. * Creates a new 'workgroup' scoped array buffer.
  29607. *
  29608. * @tsl
  29609. * @function
  29610. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  29611. * @param {number} [count=0] - The number of elements in the buffer.
  29612. * @returns {WorkgroupInfoNode}
  29613. */
  29614. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  29615. /**
  29616. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  29617. * within a shader. In an atomic function, any modification to an atomic variable will
  29618. * occur as an indivisible step with a defined order relative to other modifications.
  29619. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  29620. * atomic operations will not interfere with each other.
  29621. *
  29622. * This node can only be used with a WebGPU backend.
  29623. *
  29624. * @augments Node
  29625. */
  29626. class AtomicFunctionNode extends Node {
  29627. static get type() {
  29628. return 'AtomicFunctionNode';
  29629. }
  29630. /**
  29631. * Constructs a new atomic function node.
  29632. *
  29633. * @param {string} method - The signature of the atomic function to construct.
  29634. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29635. * @param {Node} valueNode - The value that mutates the atomic variable.
  29636. */
  29637. constructor( method, pointerNode, valueNode ) {
  29638. super( 'uint' );
  29639. /**
  29640. * The signature of the atomic function to construct.
  29641. *
  29642. * @type {string}
  29643. */
  29644. this.method = method;
  29645. /**
  29646. * An atomic variable or element of an atomic buffer.
  29647. *
  29648. * @type {Node}
  29649. */
  29650. this.pointerNode = pointerNode;
  29651. /**
  29652. * A value that modifies the atomic variable.
  29653. *
  29654. * @type {Node}
  29655. */
  29656. this.valueNode = valueNode;
  29657. /**
  29658. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  29659. *
  29660. * @type {boolean}
  29661. * @default true
  29662. */
  29663. this.parents = true;
  29664. }
  29665. /**
  29666. * Overwrites the default implementation to return the type of
  29667. * the pointer node.
  29668. *
  29669. * @param {NodeBuilder} builder - The current node builder.
  29670. * @return {string} The input type.
  29671. */
  29672. getInputType( builder ) {
  29673. return this.pointerNode.getNodeType( builder );
  29674. }
  29675. /**
  29676. * Overwritten since the node type is inferred from the input type.
  29677. *
  29678. * @param {NodeBuilder} builder - The current node builder.
  29679. * @return {string} The node type.
  29680. */
  29681. getNodeType( builder ) {
  29682. return this.getInputType( builder );
  29683. }
  29684. generate( builder ) {
  29685. const properties = builder.getNodeProperties( this );
  29686. const parents = properties.parents;
  29687. const method = this.method;
  29688. const type = this.getNodeType( builder );
  29689. const inputType = this.getInputType( builder );
  29690. const a = this.pointerNode;
  29691. const b = this.valueNode;
  29692. const params = [];
  29693. params.push( `&${ a.build( builder, inputType ) }` );
  29694. if ( b !== null ) {
  29695. params.push( b.build( builder, inputType ) );
  29696. }
  29697. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  29698. const isVoid = parents ? ( parents.length === 1 && parents[ 0 ].isStackNode === true ) : false;
  29699. if ( isVoid ) {
  29700. builder.addLineFlowCode( methodSnippet, this );
  29701. } else {
  29702. if ( properties.constNode === undefined ) {
  29703. properties.constNode = expression( methodSnippet, type ).toConst();
  29704. }
  29705. return properties.constNode.build( builder );
  29706. }
  29707. }
  29708. }
  29709. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  29710. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  29711. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  29712. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  29713. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  29714. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  29715. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  29716. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  29717. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  29718. /**
  29719. * TSL function for creating an atomic function node.
  29720. *
  29721. * @tsl
  29722. * @function
  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. * @returns {AtomicFunctionNode}
  29727. */
  29728. const atomicNode = nodeProxy( AtomicFunctionNode );
  29729. /**
  29730. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  29731. *
  29732. * @tsl
  29733. * @function
  29734. * @param {string} method - The signature of the atomic function to construct.
  29735. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29736. * @param {Node} valueNode - The value that mutates the atomic variable.
  29737. * @returns {AtomicFunctionNode}
  29738. */
  29739. const atomicFunc = ( method, pointerNode, valueNode ) => {
  29740. return atomicNode( method, pointerNode, valueNode ).toStack();
  29741. };
  29742. /**
  29743. * Loads the value stored in the atomic variable.
  29744. *
  29745. * @tsl
  29746. * @function
  29747. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29748. * @returns {AtomicFunctionNode}
  29749. */
  29750. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  29751. /**
  29752. * Stores a value in the atomic variable.
  29753. *
  29754. * @tsl
  29755. * @function
  29756. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29757. * @param {Node} valueNode - The value that mutates the atomic variable.
  29758. * @returns {AtomicFunctionNode}
  29759. */
  29760. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  29761. /**
  29762. * Increments the value stored in the atomic variable.
  29763. *
  29764. * @tsl
  29765. * @function
  29766. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29767. * @param {Node} valueNode - The value that mutates the atomic variable.
  29768. * @returns {AtomicFunctionNode}
  29769. */
  29770. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  29771. /**
  29772. * Decrements the value stored in the atomic variable.
  29773. *
  29774. * @tsl
  29775. * @function
  29776. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29777. * @param {Node} valueNode - The value that mutates the atomic variable.
  29778. * @returns {AtomicFunctionNode}
  29779. */
  29780. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  29781. /**
  29782. * Stores in an atomic variable the maximum between its current value and a parameter.
  29783. *
  29784. * @tsl
  29785. * @function
  29786. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29787. * @param {Node} valueNode - The value that mutates the atomic variable.
  29788. * @returns {AtomicFunctionNode}
  29789. */
  29790. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  29791. /**
  29792. * Stores in an atomic variable the minimum between its current value and a parameter.
  29793. *
  29794. * @tsl
  29795. * @function
  29796. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29797. * @param {Node} valueNode - The value that mutates the atomic variable.
  29798. * @returns {AtomicFunctionNode}
  29799. */
  29800. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  29801. /**
  29802. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  29803. *
  29804. * @tsl
  29805. * @function
  29806. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29807. * @param {Node} valueNode - The value that mutates the atomic variable.
  29808. * @returns {AtomicFunctionNode}
  29809. */
  29810. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  29811. /**
  29812. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  29813. *
  29814. * @tsl
  29815. * @function
  29816. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29817. * @param {Node} valueNode - The value that mutates the atomic variable.
  29818. * @returns {AtomicFunctionNode}
  29819. */
  29820. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  29821. /**
  29822. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  29823. *
  29824. * @tsl
  29825. * @function
  29826. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29827. * @param {Node} valueNode - The value that mutates the atomic variable.
  29828. * @returns {AtomicFunctionNode}
  29829. */
  29830. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  29831. /**
  29832. * This class represents a set of built in WGSL shader functions that sync
  29833. * synchronously execute an operation across a subgroup, or 'warp', of compute
  29834. * or fragment shader invocations within a workgroup. Typically, these functions
  29835. * will synchronously execute an operation using data from all active invocations
  29836. * within the subgroup, then broadcast that result to all active invocations. In
  29837. * other graphics APIs, subgroup functions are also referred to as wave intrinsics
  29838. * (DirectX/HLSL) or warp intrinsics (CUDA).
  29839. *
  29840. * @augments TempNode
  29841. */
  29842. class SubgroupFunctionNode extends TempNode {
  29843. static get type() {
  29844. return 'SubgroupFunctionNode';
  29845. }
  29846. /**
  29847. * Constructs a new function node.
  29848. *
  29849. * @param {string} method - The subgroup/wave intrinsic method to construct.
  29850. * @param {Node} [aNode=null] - The method's first argument.
  29851. * @param {Node} [bNode=null] - The method's second argument.
  29852. */
  29853. constructor( method, aNode = null, bNode = null ) {
  29854. super();
  29855. /**
  29856. * The subgroup/wave intrinsic method to construct.
  29857. *
  29858. * @type {String}
  29859. */
  29860. this.method = method;
  29861. /**
  29862. * The method's first argument.
  29863. *
  29864. * @type {Node}
  29865. */
  29866. this.aNode = aNode;
  29867. /**
  29868. * The method's second argument.
  29869. *
  29870. * @type {Node}
  29871. */
  29872. this.bNode = bNode;
  29873. }
  29874. getInputType( builder ) {
  29875. const aType = this.aNode ? this.aNode.getNodeType( builder ) : null;
  29876. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  29877. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  29878. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  29879. if ( aLen > bLen ) {
  29880. return aType;
  29881. } else {
  29882. return bType;
  29883. }
  29884. }
  29885. getNodeType( builder ) {
  29886. const method = this.method;
  29887. if ( method === SubgroupFunctionNode.SUBGROUP_ELECT ) {
  29888. return 'bool';
  29889. } else if ( method === SubgroupFunctionNode.SUBGROUP_BALLOT ) {
  29890. return 'uvec4';
  29891. } else {
  29892. return this.getInputType( builder );
  29893. }
  29894. }
  29895. generate( builder, output ) {
  29896. const method = this.method;
  29897. const type = this.getNodeType( builder );
  29898. const inputType = this.getInputType( builder );
  29899. const a = this.aNode;
  29900. const b = this.bNode;
  29901. const params = [];
  29902. if (
  29903. method === SubgroupFunctionNode.SUBGROUP_BROADCAST ||
  29904. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE ||
  29905. method === SubgroupFunctionNode.QUAD_BROADCAST
  29906. ) {
  29907. const bType = b.getNodeType( builder );
  29908. params.push(
  29909. a.build( builder, type ),
  29910. b.build( builder, bType === 'float' ? 'int' : type )
  29911. );
  29912. } else if (
  29913. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ||
  29914. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ||
  29915. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP
  29916. ) {
  29917. params.push(
  29918. a.build( builder, type ),
  29919. b.build( builder, 'uint' )
  29920. );
  29921. } else {
  29922. if ( a !== null ) params.push( a.build( builder, inputType ) );
  29923. if ( b !== null ) params.push( b.build( builder, inputType ) );
  29924. }
  29925. const paramsString = params.length === 0 ? '()' : `( ${params.join( ', ' )} )`;
  29926. return builder.format( `${ builder.getMethod( method, type ) }${paramsString}`, type, output );
  29927. }
  29928. serialize( data ) {
  29929. super.serialize( data );
  29930. data.method = this.method;
  29931. }
  29932. deserialize( data ) {
  29933. super.deserialize( data );
  29934. this.method = data.method;
  29935. }
  29936. }
  29937. // 0 inputs
  29938. SubgroupFunctionNode.SUBGROUP_ELECT = 'subgroupElect';
  29939. // 1 input
  29940. SubgroupFunctionNode.SUBGROUP_BALLOT = 'subgroupBallot';
  29941. SubgroupFunctionNode.SUBGROUP_ADD = 'subgroupAdd';
  29942. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD = 'subgroupInclusiveAdd';
  29943. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND = 'subgroupExclusiveAdd';
  29944. SubgroupFunctionNode.SUBGROUP_MUL = 'subgroupMul';
  29945. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL = 'subgroupInclusiveMul';
  29946. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL = 'subgroupExclusiveMul';
  29947. SubgroupFunctionNode.SUBGROUP_AND = 'subgroupAnd';
  29948. SubgroupFunctionNode.SUBGROUP_OR = 'subgroupOr';
  29949. SubgroupFunctionNode.SUBGROUP_XOR = 'subgroupXor';
  29950. SubgroupFunctionNode.SUBGROUP_MIN = 'subgroupMin';
  29951. SubgroupFunctionNode.SUBGROUP_MAX = 'subgroupMax';
  29952. SubgroupFunctionNode.SUBGROUP_ALL = 'subgroupAll';
  29953. SubgroupFunctionNode.SUBGROUP_ANY = 'subgroupAny';
  29954. SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST = 'subgroupBroadcastFirst';
  29955. SubgroupFunctionNode.QUAD_SWAP_X = 'quadSwapX';
  29956. SubgroupFunctionNode.QUAD_SWAP_Y = 'quadSwapY';
  29957. SubgroupFunctionNode.QUAD_SWAP_DIAGONAL = 'quadSwapDiagonal';
  29958. // 2 inputs
  29959. SubgroupFunctionNode.SUBGROUP_BROADCAST = 'subgroupBroadcast';
  29960. SubgroupFunctionNode.SUBGROUP_SHUFFLE = 'subgroupShuffle';
  29961. SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR = 'subgroupShuffleXor';
  29962. SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP = 'subgroupShuffleUp';
  29963. SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN = 'subgroupShuffleDown';
  29964. SubgroupFunctionNode.QUAD_BROADCAST = 'quadBroadcast';
  29965. /**
  29966. * Returns true if this invocation has the lowest subgroup_invocation_id
  29967. * among active invocations in the subgroup.
  29968. *
  29969. * @tsl
  29970. * @method
  29971. * @return {bool} The result of the computation.
  29972. */
  29973. const subgroupElect = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ELECT ).setParameterLength( 0 );
  29974. /**
  29975. * Returns a set of bitfields where the bit corresponding to subgroup_invocation_id
  29976. * is 1 if pred is true for that active invocation and 0 otherwise.
  29977. *
  29978. * @tsl
  29979. * @method
  29980. * @param {bool} pred - A boolean that sets the bit corresponding to the invocations subgroup invocation id.
  29981. * @return {vec4<u32>}- A bitfield corresponding to the pred value of each subgroup invocation.
  29982. */
  29983. const subgroupBallot = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BALLOT ).setParameterLength( 1 );
  29984. /**
  29985. * A reduction that adds e among all active invocations and returns that result.
  29986. *
  29987. * @tsl
  29988. * @method
  29989. * @param {number} e - The value provided to the reduction by the current invocation.
  29990. * @return {number} The accumulated result of the reduction operation.
  29991. */
  29992. const subgroupAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ADD ).setParameterLength( 1 );
  29993. /**
  29994. * An inclusive scan returning the sum of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  29995. *
  29996. * @tsl
  29997. * @method
  29998. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  29999. * @return {number} The accumulated result of the inclusive scan operation.
  30000. */
  30001. const subgroupInclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD ).setParameterLength( 1 );
  30002. /**
  30003. * An exclusive scan that returns the sum of e for all active invocations with subgroup_invocation_id less than this invocation.
  30004. *
  30005. * @tsl
  30006. * @method
  30007. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  30008. * @return {number} The accumulated result of the exclusive scan operation.
  30009. */
  30010. const subgroupExclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND ).setParameterLength( 1 );
  30011. /**
  30012. * A reduction that multiplies e among all active invocations and returns that result.
  30013. *
  30014. * @tsl
  30015. * @method
  30016. * @param {number} e - The value provided to the reduction by the current invocation.
  30017. * @return {number} The accumulated result of the reduction operation.
  30018. */
  30019. const subgroupMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MUL ).setParameterLength( 1 );
  30020. /**
  30021. * An inclusive scan returning the product of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  30022. *
  30023. * @tsl
  30024. * @method
  30025. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  30026. * @return {number} The accumulated result of the inclusive scan operation.
  30027. */
  30028. const subgroupInclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL ).setParameterLength( 1 );
  30029. /**
  30030. * An exclusive scan that returns the product of e for all active invocations with subgroup_invocation_id less than this invocation.
  30031. *
  30032. * @tsl
  30033. * @method
  30034. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  30035. * @return {number} The accumulated result of the exclusive scan operation.
  30036. */
  30037. const subgroupExclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL ).setParameterLength( 1 );
  30038. /**
  30039. * A reduction that performs a bitwise and of e among all active invocations and returns that result.
  30040. *
  30041. * @tsl
  30042. * @method
  30043. * @param {number} e - The value provided to the reduction by the current invocation.
  30044. * @return {number} The result of the reduction operation.
  30045. */
  30046. const subgroupAnd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_AND ).setParameterLength( 1 );
  30047. /**
  30048. * A reduction that performs a bitwise or of e among all active invocations and returns that result.
  30049. *
  30050. * @tsl
  30051. * @method
  30052. * @param {number} e - The value provided to the reduction by the current invocation.
  30053. * @return {number} The result of the reduction operation.
  30054. */
  30055. const subgroupOr = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_OR ).setParameterLength( 1 );
  30056. /**
  30057. * A reduction that performs a bitwise xor of e among all active invocations and returns that result.
  30058. *
  30059. * @tsl
  30060. * @method
  30061. * @param {number} e - The value provided to the reduction by the current invocation.
  30062. * @return {number} The result of the reduction operation.
  30063. */
  30064. const subgroupXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_XOR ).setParameterLength( 1 );
  30065. /**
  30066. * A reduction that performs a min of e among all active invocations and returns that result.
  30067. *
  30068. * @tsl
  30069. * @method
  30070. * @param {number} e - The value provided to the reduction by the current invocation.
  30071. * @return {number} The result of the reduction operation.
  30072. */
  30073. const subgroupMin = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MIN ).setParameterLength( 1 );
  30074. /**
  30075. * A reduction that performs a max of 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 result of the reduction operation.
  30081. */
  30082. const subgroupMax = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MAX ).setParameterLength( 1 );
  30083. /**
  30084. * Returns true if e is true for all active invocations in the subgroup.
  30085. *
  30086. * @tsl
  30087. * @method
  30088. * @return {bool} The result of the computation.
  30089. */
  30090. const subgroupAll = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ALL ).setParameterLength( 0 );
  30091. /**
  30092. * Returns true if e is true for any active invocation in the subgroup
  30093. *
  30094. * @tsl
  30095. * @method
  30096. * @return {bool} The result of the computation.
  30097. */
  30098. const subgroupAny = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ANY ).setParameterLength( 0 );
  30099. /**
  30100. * Broadcasts e from the active invocation with the lowest subgroup_invocation_id in the subgroup to all other active invocations.
  30101. *
  30102. * @tsl
  30103. * @method
  30104. * @param {number} e - The value to broadcast from the lowest subgroup invocation.
  30105. * @param {number} id - The subgroup invocation to broadcast from.
  30106. * @return {number} The broadcast value.
  30107. */
  30108. const subgroupBroadcastFirst = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST ).setParameterLength( 2 );
  30109. /**
  30110. * Swaps e between invocations in the quad in the X direction.
  30111. *
  30112. * @tsl
  30113. * @method
  30114. * @param {number} e - The value to swap from the current invocation.
  30115. * @return {number} The value received from the swap operation.
  30116. */
  30117. const quadSwapX = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_X ).setParameterLength( 1 );
  30118. /**
  30119. * Swaps e between invocations in the quad in the Y direction.
  30120. *
  30121. * @tsl
  30122. * @method
  30123. * @param {number} e - The value to swap from the current invocation.
  30124. * @return {number} The value received from the swap operation.
  30125. */
  30126. const quadSwapY = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_Y ).setParameterLength( 1 );
  30127. /**
  30128. * Swaps e between invocations in the quad diagonally.
  30129. *
  30130. * @tsl
  30131. * @method
  30132. * @param {number} e - The value to swap from the current invocation.
  30133. * @return {number} The value received from the swap operation.
  30134. */
  30135. const quadSwapDiagonal = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_DIAGONAL ).setParameterLength( 1 );
  30136. /**
  30137. * Broadcasts e from the invocation whose subgroup_invocation_id matches id, to all active invocations.
  30138. *
  30139. * @tsl
  30140. * @method
  30141. * @param {number} e - The value to broadcast from subgroup invocation 'id'.
  30142. * @param {number} id - The subgroup invocation to broadcast from.
  30143. * @return {number} The broadcast value.
  30144. */
  30145. const subgroupBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST ).setParameterLength( 2 );
  30146. /**
  30147. * Returns v from the active invocation whose subgroup_invocation_id matches id
  30148. *
  30149. * @tsl
  30150. * @method
  30151. * @param {number} v - The value to return from subgroup invocation id^mask.
  30152. * @param {number} id - The subgroup invocation which returns the value v.
  30153. * @return {number} The broadcast value.
  30154. */
  30155. const subgroupShuffle = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE ).setParameterLength( 2 );
  30156. /**
  30157. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id ^ mask.
  30158. *
  30159. * @tsl
  30160. * @method
  30161. * @param {number} v - The value to return from subgroup invocation id^mask.
  30162. * @param {number} mask - A bitmask that determines the target invocation via a XOR operation.
  30163. * @return {number} The broadcast value.
  30164. */
  30165. const subgroupShuffleXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ).setParameterLength( 2 );
  30166. /**
  30167. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id - delta
  30168. *
  30169. * @tsl
  30170. * @method
  30171. * @param {number} v - The value to return from subgroup invocation id^mask.
  30172. * @param {number} delta - A value that offsets the current in.
  30173. * @return {number} The broadcast value.
  30174. */
  30175. const subgroupShuffleUp = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP ).setParameterLength( 2 );
  30176. /**
  30177. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id + delta
  30178. *
  30179. * @tsl
  30180. * @method
  30181. * @param {number} v - The value to return from subgroup invocation id^mask.
  30182. * @param {number} delta - A value that offsets the current subgroup invocation.
  30183. * @return {number} The broadcast value.
  30184. */
  30185. const subgroupShuffleDown = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ).setParameterLength( 2 );
  30186. /**
  30187. * Broadcasts e from the quad invocation with id equal to id.
  30188. *
  30189. * @tsl
  30190. * @method
  30191. * @param {number} e - The value to broadcast.
  30192. * @return {number} The broadcast value.
  30193. */
  30194. const quadBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_BROADCAST ).setParameterLength( 1 );
  30195. let uniformsLib;
  30196. function getLightData( light ) {
  30197. uniformsLib = uniformsLib || new WeakMap();
  30198. let uniforms = uniformsLib.get( light );
  30199. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  30200. return uniforms;
  30201. }
  30202. /**
  30203. * TSL function for getting a shadow matrix uniform node for the given light.
  30204. *
  30205. * @tsl
  30206. * @function
  30207. * @param {Light} light -The light source.
  30208. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  30209. */
  30210. function lightShadowMatrix( light ) {
  30211. const data = getLightData( light );
  30212. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  30213. // normally, shadow matrices are updated in ShadowNode. However, if the shadow matrix is used outside
  30214. // of shadow rendering (like in ProjectorLightNode), the shadow matrix still requires an update
  30215. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  30216. if ( light.shadow.camera.coordinateSystem !== frame.camera.coordinateSystem ) {
  30217. light.shadow.camera.coordinateSystem = frame.camera.coordinateSystem;
  30218. light.shadow.camera.updateProjectionMatrix();
  30219. }
  30220. light.shadow.updateMatrices( light );
  30221. }
  30222. return light.shadow.matrix;
  30223. } ) );
  30224. }
  30225. /**
  30226. * TSL function for getting projected uv coordinates for the given light.
  30227. * Relevant when using maps with spot lights.
  30228. *
  30229. * @tsl
  30230. * @function
  30231. * @param {Light} light -The light source.
  30232. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  30233. * @returns {Node<vec3>} The projected uvs.
  30234. */
  30235. function lightProjectionUV( light, position = positionWorld ) {
  30236. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  30237. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  30238. return projectionUV;
  30239. }
  30240. /**
  30241. * TSL function for getting the position in world space for the given light.
  30242. *
  30243. * @tsl
  30244. * @function
  30245. * @param {Light} light -The light source.
  30246. * @returns {UniformNode<vec3>} The light's position in world space.
  30247. */
  30248. function lightPosition( light ) {
  30249. const data = getLightData( light );
  30250. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  30251. }
  30252. /**
  30253. * TSL function for getting the light target position in world space for the given light.
  30254. *
  30255. * @tsl
  30256. * @function
  30257. * @param {Light} light -The light source.
  30258. * @returns {UniformNode<vec3>} The light target position in world space.
  30259. */
  30260. function lightTargetPosition( light ) {
  30261. const data = getLightData( light );
  30262. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  30263. }
  30264. /**
  30265. * TSL function for getting the position in view space for the given light.
  30266. *
  30267. * @tsl
  30268. * @function
  30269. * @param {Light} light - The light source.
  30270. * @returns {UniformNode<vec3>} The light's position in view space.
  30271. */
  30272. function lightViewPosition( light ) {
  30273. const data = getLightData( light );
  30274. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  30275. self.value = self.value || new Vector3();
  30276. self.value.setFromMatrixPosition( light.matrixWorld );
  30277. self.value.applyMatrix4( camera.matrixWorldInverse );
  30278. } ) );
  30279. }
  30280. /**
  30281. * TSL function for getting the light target direction for the given light.
  30282. *
  30283. * @tsl
  30284. * @function
  30285. * @param {Light} light -The light source.
  30286. * @returns {Node<vec3>} The light's target direction.
  30287. */
  30288. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  30289. const sortLights = ( lights ) => {
  30290. return lights.sort( ( a, b ) => a.id - b.id );
  30291. };
  30292. const getLightNodeById = ( id, lightNodes ) => {
  30293. for ( const lightNode of lightNodes ) {
  30294. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  30295. return lightNode;
  30296. }
  30297. }
  30298. return null;
  30299. };
  30300. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  30301. const _hashData = [];
  30302. /**
  30303. * This node represents the scene's lighting and manages the lighting model's life cycle
  30304. * for the current build 3D object. It is responsible for computing the total outgoing
  30305. * light in a given lighting context.
  30306. *
  30307. * @augments Node
  30308. */
  30309. class LightsNode extends Node {
  30310. static get type() {
  30311. return 'LightsNode';
  30312. }
  30313. /**
  30314. * Constructs a new lights node.
  30315. */
  30316. constructor() {
  30317. super( 'vec3' );
  30318. /**
  30319. * A node representing the total diffuse light.
  30320. *
  30321. * @type {Node<vec3>}
  30322. */
  30323. this.totalDiffuseNode = property( 'vec3', 'totalDiffuse' );
  30324. /**
  30325. * A node representing the total specular light.
  30326. *
  30327. * @type {Node<vec3>}
  30328. */
  30329. this.totalSpecularNode = property( 'vec3', 'totalSpecular' );
  30330. /**
  30331. * A node representing the outgoing light.
  30332. *
  30333. * @type {Node<vec3>}
  30334. */
  30335. this.outgoingLightNode = property( 'vec3', 'outgoingLight' );
  30336. /**
  30337. * An array representing the lights in the scene.
  30338. *
  30339. * @private
  30340. * @type {Array<Light>}
  30341. */
  30342. this._lights = [];
  30343. /**
  30344. * For each light in the scene, this node will create a
  30345. * corresponding light node.
  30346. *
  30347. * @private
  30348. * @type {?Array<LightingNode>}
  30349. * @default null
  30350. */
  30351. this._lightNodes = null;
  30352. /**
  30353. * A hash for identifying the current light nodes setup.
  30354. *
  30355. * @private
  30356. * @type {?string}
  30357. * @default null
  30358. */
  30359. this._lightNodesHash = null;
  30360. /**
  30361. * `LightsNode` sets this property to `true` by default.
  30362. *
  30363. * @type {boolean}
  30364. * @default true
  30365. */
  30366. this.global = true;
  30367. }
  30368. /**
  30369. * Overwrites the default {@link Node#customCacheKey} implementation by including
  30370. * light data into the cache key.
  30371. *
  30372. * @return {number} The custom cache key.
  30373. */
  30374. customCacheKey() {
  30375. const lights = this._lights;
  30376. for ( let i = 0; i < lights.length; i ++ ) {
  30377. const light = lights[ i ];
  30378. _hashData.push( light.id );
  30379. _hashData.push( light.castShadow ? 1 : 0 );
  30380. if ( light.isSpotLight === true ) {
  30381. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  30382. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  30383. _hashData.push( hashMap, hashColorNode );
  30384. }
  30385. }
  30386. const cacheKey = hashArray( _hashData );
  30387. _hashData.length = 0;
  30388. return cacheKey;
  30389. }
  30390. /**
  30391. * Computes a hash value for identifying the current light nodes setup.
  30392. *
  30393. * @param {NodeBuilder} builder - A reference to the current node builder.
  30394. * @return {string} The computed hash.
  30395. */
  30396. getHash( builder ) {
  30397. if ( this._lightNodesHash === null ) {
  30398. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  30399. const hash = [];
  30400. for ( const lightNode of this._lightNodes ) {
  30401. hash.push( lightNode.getHash() );
  30402. }
  30403. this._lightNodesHash = 'lights-' + hash.join( ',' );
  30404. }
  30405. return this._lightNodesHash;
  30406. }
  30407. analyze( builder ) {
  30408. const properties = builder.getNodeProperties( this );
  30409. for ( const node of properties.nodes ) {
  30410. node.build( builder );
  30411. }
  30412. properties.outputNode.build( builder );
  30413. }
  30414. /**
  30415. * Creates lighting nodes for each scene light. This makes it possible to further
  30416. * process lights in the node system.
  30417. *
  30418. * @param {NodeBuilder} builder - A reference to the current node builder.
  30419. */
  30420. setupLightsNode( builder ) {
  30421. const lightNodes = [];
  30422. const previousLightNodes = this._lightNodes;
  30423. const lights = sortLights( this._lights );
  30424. const nodeLibrary = builder.renderer.library;
  30425. for ( const light of lights ) {
  30426. if ( light.isNode ) {
  30427. lightNodes.push( nodeObject( light ) );
  30428. } else {
  30429. let lightNode = null;
  30430. if ( previousLightNodes !== null ) {
  30431. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  30432. }
  30433. if ( lightNode === null ) {
  30434. // find the corresponding node type for a given light
  30435. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  30436. if ( lightNodeClass === null ) {
  30437. warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  30438. continue;
  30439. }
  30440. let lightNode = null;
  30441. if ( ! _lightsNodeRef.has( light ) ) {
  30442. lightNode = nodeObject( new lightNodeClass( light ) );
  30443. _lightsNodeRef.set( light, lightNode );
  30444. } else {
  30445. lightNode = _lightsNodeRef.get( light );
  30446. }
  30447. lightNodes.push( lightNode );
  30448. }
  30449. }
  30450. }
  30451. this._lightNodes = lightNodes;
  30452. }
  30453. /**
  30454. * Sets up a direct light in the lighting model.
  30455. *
  30456. * @param {Object} builder - The builder object containing the context and stack.
  30457. * @param {Object} lightNode - The light node.
  30458. * @param {Object} lightData - The light object containing color and direction properties.
  30459. */
  30460. setupDirectLight( builder, lightNode, lightData ) {
  30461. const { lightingModel, reflectedLight } = builder.context;
  30462. lightingModel.direct( {
  30463. ...lightData,
  30464. lightNode,
  30465. reflectedLight
  30466. }, builder );
  30467. }
  30468. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  30469. const { lightingModel, reflectedLight } = builder.context;
  30470. lightingModel.directRectArea( {
  30471. ...lightData,
  30472. lightNode,
  30473. reflectedLight
  30474. }, builder );
  30475. }
  30476. /**
  30477. * Setups the internal lights by building all respective
  30478. * light nodes.
  30479. *
  30480. * @param {NodeBuilder} builder - A reference to the current node builder.
  30481. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  30482. */
  30483. setupLights( builder, lightNodes ) {
  30484. for ( const lightNode of lightNodes ) {
  30485. lightNode.build( builder );
  30486. }
  30487. }
  30488. getLightNodes( builder ) {
  30489. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  30490. return this._lightNodes;
  30491. }
  30492. /**
  30493. * The implementation makes sure that for each light in the scene
  30494. * there is a corresponding light node. By building the light nodes
  30495. * and evaluating the lighting model the outgoing light is computed.
  30496. *
  30497. * @param {NodeBuilder} builder - A reference to the current node builder.
  30498. * @return {Node<vec3>} A node representing the outgoing light.
  30499. */
  30500. setup( builder ) {
  30501. const currentLightsNode = builder.lightsNode;
  30502. builder.lightsNode = this;
  30503. //
  30504. let outgoingLightNode = this.outgoingLightNode;
  30505. const context = builder.context;
  30506. const lightingModel = context.lightingModel;
  30507. const properties = builder.getNodeProperties( this );
  30508. if ( lightingModel ) {
  30509. const { totalDiffuseNode, totalSpecularNode } = this;
  30510. context.outgoingLight = outgoingLightNode;
  30511. const stack = builder.addStack();
  30512. //
  30513. properties.nodes = stack.nodes;
  30514. //
  30515. lightingModel.start( builder );
  30516. //
  30517. const { backdrop, backdropAlpha } = context;
  30518. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  30519. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  30520. if ( backdrop !== null ) {
  30521. if ( backdropAlpha !== null ) {
  30522. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  30523. } else {
  30524. totalDiffuse = vec3( backdrop );
  30525. }
  30526. }
  30527. totalDiffuseNode.assign( totalDiffuse );
  30528. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  30529. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  30530. //
  30531. lightingModel.finish( builder );
  30532. //
  30533. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  30534. } else {
  30535. properties.nodes = [];
  30536. }
  30537. //
  30538. builder.lightsNode = currentLightsNode;
  30539. return outgoingLightNode;
  30540. }
  30541. /**
  30542. * Configures this node with an array of lights.
  30543. *
  30544. * @param {Array<Light>} lights - An array of lights.
  30545. * @return {LightsNode} A reference to this node.
  30546. */
  30547. setLights( lights ) {
  30548. this._lights = lights;
  30549. this._lightNodes = null;
  30550. this._lightNodesHash = null;
  30551. return this;
  30552. }
  30553. /**
  30554. * Returns an array of the scene's lights.
  30555. *
  30556. * @return {Array<Light>} The scene's lights.
  30557. */
  30558. getLights() {
  30559. return this._lights;
  30560. }
  30561. /**
  30562. * Whether the scene has lights or not.
  30563. *
  30564. * @type {boolean}
  30565. */
  30566. get hasLights() {
  30567. return this._lights.length > 0;
  30568. }
  30569. }
  30570. /**
  30571. * TSL function for creating an instance of `LightsNode` and configuring
  30572. * it with the given array of lights.
  30573. *
  30574. * @tsl
  30575. * @function
  30576. * @param {Array<Light>} lights - An array of lights.
  30577. * @return {LightsNode} The created lights node.
  30578. */
  30579. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  30580. /**
  30581. * Base class for all shadow nodes.
  30582. *
  30583. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  30584. * Lighting nodes might share the same shadow node type or use specific ones depending on
  30585. * their requirements.
  30586. *
  30587. * @augments Node
  30588. */
  30589. class ShadowBaseNode extends Node {
  30590. static get type() {
  30591. return 'ShadowBaseNode';
  30592. }
  30593. /**
  30594. * Constructs a new shadow base node.
  30595. *
  30596. * @param {Light} light - The shadow casting light.
  30597. */
  30598. constructor( light ) {
  30599. super();
  30600. /**
  30601. * The shadow casting light.
  30602. *
  30603. * @type {Light}
  30604. */
  30605. this.light = light;
  30606. /**
  30607. * Overwritten since shadows are updated by default per render.
  30608. *
  30609. * @type {string}
  30610. * @default 'render'
  30611. */
  30612. this.updateBeforeType = NodeUpdateType.RENDER;
  30613. /**
  30614. * This flag can be used for type testing.
  30615. *
  30616. * @type {boolean}
  30617. * @readonly
  30618. * @default true
  30619. */
  30620. this.isShadowBaseNode = true;
  30621. }
  30622. /**
  30623. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  30624. *
  30625. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  30626. */
  30627. setupShadowPosition( { context, material } ) {
  30628. // Use assign inside an Fn()
  30629. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  30630. }
  30631. }
  30632. /**
  30633. * TSL object that represents the vertex position in world space during the shadow pass.
  30634. *
  30635. * @tsl
  30636. * @type {Node<vec3>}
  30637. */
  30638. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  30639. /**
  30640. * Saves the state of the given renderer and stores it into the given state object.
  30641. *
  30642. * If not state object is provided, the function creates one.
  30643. *
  30644. * @private
  30645. * @function
  30646. * @param {Renderer} renderer - The renderer.
  30647. * @param {Object} [state={}] - The state.
  30648. * @return {Object} The state.
  30649. */
  30650. function saveRendererState( renderer, state = {} ) {
  30651. state.toneMapping = renderer.toneMapping;
  30652. state.toneMappingExposure = renderer.toneMappingExposure;
  30653. state.outputColorSpace = renderer.outputColorSpace;
  30654. state.renderTarget = renderer.getRenderTarget();
  30655. state.activeCubeFace = renderer.getActiveCubeFace();
  30656. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  30657. state.renderObjectFunction = renderer.getRenderObjectFunction();
  30658. state.pixelRatio = renderer.getPixelRatio();
  30659. state.mrt = renderer.getMRT();
  30660. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  30661. state.clearAlpha = renderer.getClearAlpha();
  30662. state.autoClear = renderer.autoClear;
  30663. state.scissorTest = renderer.getScissorTest();
  30664. return state;
  30665. }
  30666. /**
  30667. * Saves the state of the given renderer and stores it into the given state object.
  30668. * Besides, the function also resets the state of the renderer to its default values.
  30669. *
  30670. * If not state object is provided, the function creates one.
  30671. *
  30672. * @private
  30673. * @function
  30674. * @param {Renderer} renderer - The renderer.
  30675. * @param {Object} [state={}] - The state.
  30676. * @return {Object} The state.
  30677. */
  30678. function resetRendererState( renderer, state ) {
  30679. state = saveRendererState( renderer, state );
  30680. renderer.setMRT( null );
  30681. renderer.setRenderObjectFunction( null );
  30682. renderer.setClearColor( 0x000000, 1 );
  30683. renderer.autoClear = true;
  30684. return state;
  30685. }
  30686. /**
  30687. * Restores the state of the given renderer from the given state object.
  30688. *
  30689. * @private
  30690. * @function
  30691. * @param {Renderer} renderer - The renderer.
  30692. * @param {Object} state - The state to restore.
  30693. */
  30694. function restoreRendererState( renderer, state ) {
  30695. renderer.toneMapping = state.toneMapping;
  30696. renderer.toneMappingExposure = state.toneMappingExposure;
  30697. renderer.outputColorSpace = state.outputColorSpace;
  30698. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  30699. renderer.setRenderObjectFunction( state.renderObjectFunction );
  30700. renderer.setPixelRatio( state.pixelRatio );
  30701. renderer.setMRT( state.mrt );
  30702. renderer.setClearColor( state.clearColor, state.clearAlpha );
  30703. renderer.autoClear = state.autoClear;
  30704. renderer.setScissorTest( state.scissorTest );
  30705. }
  30706. /**
  30707. * Saves the state of the given scene and stores it into the given state object.
  30708. *
  30709. * If not state object is provided, the function creates one.
  30710. *
  30711. * @private
  30712. * @function
  30713. * @param {Scene} scene - The scene.
  30714. * @param {Object} [state={}] - The state.
  30715. * @return {Object} The state.
  30716. */
  30717. function saveSceneState( scene, state = {} ) {
  30718. state.background = scene.background;
  30719. state.backgroundNode = scene.backgroundNode;
  30720. state.overrideMaterial = scene.overrideMaterial;
  30721. return state;
  30722. }
  30723. /**
  30724. * Saves the state of the given scene and stores it into the given state object.
  30725. * Besides, the function also resets the state of the scene to its default values.
  30726. *
  30727. * If not state object is provided, the function creates one.
  30728. *
  30729. * @private
  30730. * @function
  30731. * @param {Scene} scene - The scene.
  30732. * @param {Object} [state={}] - The state.
  30733. * @return {Object} The state.
  30734. */
  30735. function resetSceneState( scene, state ) {
  30736. state = saveSceneState( scene, state );
  30737. scene.background = null;
  30738. scene.backgroundNode = null;
  30739. scene.overrideMaterial = null;
  30740. return state;
  30741. }
  30742. /**
  30743. * Restores the state of the given scene from the given state object.
  30744. *
  30745. * @private
  30746. * @function
  30747. * @param {Scene} scene - The scene.
  30748. * @param {Object} state - The state to restore.
  30749. */
  30750. function restoreSceneState( scene, state ) {
  30751. scene.background = state.background;
  30752. scene.backgroundNode = state.backgroundNode;
  30753. scene.overrideMaterial = state.overrideMaterial;
  30754. }
  30755. /**
  30756. * Saves the state of the given renderer and scene and stores it into the given state object.
  30757. *
  30758. * If not state object is provided, the function creates one.
  30759. *
  30760. * @private
  30761. * @function
  30762. * @param {Renderer} renderer - The renderer.
  30763. * @param {Scene} scene - The scene.
  30764. * @param {Object} [state={}] - The state.
  30765. * @return {Object} The state.
  30766. */
  30767. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  30768. state = saveRendererState( renderer, state );
  30769. state = saveSceneState( scene, state );
  30770. return state;
  30771. }
  30772. /**
  30773. * Saves the state of the given renderer and scene and stores it into the given state object.
  30774. * Besides, the function also resets the state of the renderer and scene to its default values.
  30775. *
  30776. * If not state object is provided, the function creates one.
  30777. *
  30778. * @private
  30779. * @function
  30780. * @param {Renderer} renderer - The renderer.
  30781. * @param {Scene} scene - The scene.
  30782. * @param {Object} [state={}] - The state.
  30783. * @return {Object} The state.
  30784. */
  30785. function resetRendererAndSceneState( renderer, scene, state ) {
  30786. state = resetRendererState( renderer, state );
  30787. state = resetSceneState( scene, state );
  30788. return state;
  30789. }
  30790. /**
  30791. * Restores the state of the given renderer and scene from the given state object.
  30792. *
  30793. * @private
  30794. * @function
  30795. * @param {Renderer} renderer - The renderer.
  30796. * @param {Scene} scene - The scene.
  30797. * @param {Object} state - The state to restore.
  30798. */
  30799. function restoreRendererAndSceneState( renderer, scene, state ) {
  30800. restoreRendererState( renderer, state );
  30801. restoreSceneState( scene, state );
  30802. }
  30803. var RendererUtils = /*#__PURE__*/Object.freeze({
  30804. __proto__: null,
  30805. resetRendererAndSceneState: resetRendererAndSceneState,
  30806. resetRendererState: resetRendererState,
  30807. resetSceneState: resetSceneState,
  30808. restoreRendererAndSceneState: restoreRendererAndSceneState,
  30809. restoreRendererState: restoreRendererState,
  30810. restoreSceneState: restoreSceneState,
  30811. saveRendererAndSceneState: saveRendererAndSceneState,
  30812. saveRendererState: saveRendererState,
  30813. saveSceneState: saveSceneState
  30814. });
  30815. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  30816. /**
  30817. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  30818. * with a binary `[0,1]` result.
  30819. *
  30820. * @method
  30821. * @param {Object} inputs - The input parameter object.
  30822. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30823. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30824. * @return {Node<float>} The filtering result.
  30825. */
  30826. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  30827. let basic = texture( depthTexture, shadowCoord.xy ).setName( 't_basic' );
  30828. if ( depthTexture.isArrayTexture ) {
  30829. basic = basic.depth( depthLayer );
  30830. }
  30831. return basic.compare( shadowCoord.z );
  30832. } );
  30833. /**
  30834. * A shadow filtering function performing PCF filtering with Vogel disk sampling and IGN.
  30835. *
  30836. * Uses 5 samples distributed via Vogel disk pattern, rotated per-pixel using Interleaved
  30837. * Gradient Noise (IGN) to break up banding artifacts. Combined with hardware PCF (4-tap
  30838. * filtering per sample), this effectively provides 20 filtered taps with better distribution.
  30839. *
  30840. * @method
  30841. * @param {Object} inputs - The input parameter object.
  30842. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30843. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30844. * @param {LightShadow} inputs.shadow - The light shadow.
  30845. * @return {Node<float>} The filtering result.
  30846. */
  30847. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  30848. const depthCompare = ( uv, compare ) => {
  30849. let depth = texture( depthTexture, uv );
  30850. if ( depthTexture.isArrayTexture ) {
  30851. depth = depth.depth( depthLayer );
  30852. }
  30853. return depth.compare( compare );
  30854. };
  30855. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  30856. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  30857. const texelSize = vec2( 1 ).div( mapSize );
  30858. const radiusScaled = radius.mul( texelSize.x );
  30859. // Use IGN to rotate sampling pattern per pixel (phi = IGN * 2π)
  30860. const phi = interleavedGradientNoise( screenCoordinate.xy ).mul( 6.28318530718 );
  30861. // 5 samples using Vogel disk distribution
  30862. return add(
  30863. depthCompare( shadowCoord.xy.add( vogelDiskSample( 0, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  30864. depthCompare( shadowCoord.xy.add( vogelDiskSample( 1, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  30865. depthCompare( shadowCoord.xy.add( vogelDiskSample( 2, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  30866. depthCompare( shadowCoord.xy.add( vogelDiskSample( 3, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  30867. depthCompare( shadowCoord.xy.add( vogelDiskSample( 4, 5, phi ).mul( radiusScaled ) ), shadowCoord.z )
  30868. ).mul( 1 / 5 );
  30869. } );
  30870. /**
  30871. * A shadow filtering function performing PCF soft filtering.
  30872. *
  30873. * @method
  30874. * @param {Object} inputs - The input parameter object.
  30875. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30876. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30877. * @param {LightShadow} inputs.shadow - The light shadow.
  30878. * @return {Node<float>} The filtering result.
  30879. */
  30880. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  30881. const depthCompare = ( uv, compare ) => {
  30882. let depth = texture( depthTexture, uv );
  30883. if ( depthTexture.isArrayTexture ) {
  30884. depth = depth.depth( depthLayer );
  30885. }
  30886. return depth.compare( compare );
  30887. };
  30888. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  30889. const texelSize = vec2( 1 ).div( mapSize );
  30890. const dx = texelSize.x;
  30891. const dy = texelSize.y;
  30892. const uv = shadowCoord.xy;
  30893. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  30894. uv.subAssign( f.mul( texelSize ) );
  30895. return add(
  30896. depthCompare( uv, shadowCoord.z ),
  30897. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  30898. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  30899. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  30900. mix(
  30901. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  30902. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  30903. f.x
  30904. ),
  30905. mix(
  30906. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  30907. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  30908. f.x
  30909. ),
  30910. mix(
  30911. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  30912. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  30913. f.y
  30914. ),
  30915. mix(
  30916. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  30917. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  30918. f.y
  30919. ),
  30920. mix(
  30921. mix(
  30922. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  30923. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  30924. f.x
  30925. ),
  30926. mix(
  30927. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  30928. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  30929. f.x
  30930. ),
  30931. f.y
  30932. )
  30933. ).mul( 1 / 9 );
  30934. } );
  30935. /**
  30936. * A shadow filtering function performing VSM filtering.
  30937. *
  30938. * @method
  30939. * @param {Object} inputs - The input parameter object.
  30940. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30941. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30942. * @return {Node<float>} The filtering result.
  30943. */
  30944. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  30945. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  30946. if ( depthTexture.isArrayTexture ) {
  30947. distribution = distribution.depth( depthLayer );
  30948. }
  30949. distribution = distribution.rg;
  30950. const mean = distribution.x;
  30951. const variance = max$1( 0.0000001, distribution.y.mul( distribution.y ) );
  30952. const hardShadow = step( shadowCoord.z, mean );
  30953. // Early return if fully lit
  30954. If( hardShadow.equal( 1.0 ), () => {
  30955. return float( 1.0 );
  30956. } );
  30957. // Distance from mean
  30958. const d = shadowCoord.z.sub( mean );
  30959. // Chebyshev's inequality for upper bound on probability
  30960. let p_max = variance.div( variance.add( d.mul( d ) ) );
  30961. // Reduce light bleeding by remapping [amount, 1] to [0, 1]
  30962. p_max = clamp( sub( p_max, 0.3 ).div( 0.65 ) );
  30963. return max$1( hardShadow, p_max );
  30964. } );
  30965. //
  30966. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  30967. let dist = positionWorld.sub( position ).length();
  30968. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  30969. dist = dist.saturate(); // clamp to [ 0, 1 ]
  30970. return dist;
  30971. } );
  30972. const linearShadowDistance = ( light ) => {
  30973. const camera = light.shadow.camera;
  30974. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  30975. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  30976. const referencePosition = objectPosition( light );
  30977. return linearDistance( referencePosition, nearDistance, farDistance );
  30978. };
  30979. /**
  30980. * Retrieves or creates a shadow material for the given light source.
  30981. *
  30982. * This function checks if a shadow material already exists for the provided light.
  30983. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  30984. * in the `shadowMaterialLib` for future use.
  30985. *
  30986. * @tsl
  30987. * @function
  30988. * @param {Light} light - The light source for which the shadow material is needed.
  30989. * If the light is a point light, a depth node is calculated
  30990. * using the linear shadow distance.
  30991. * @returns {NodeMaterial} The shadow material associated with the given light.
  30992. */
  30993. const getShadowMaterial = ( light ) => {
  30994. let material = shadowMaterialLib.get( light );
  30995. if ( material === undefined ) {
  30996. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  30997. material = new NodeMaterial();
  30998. material.colorNode = vec4( 0, 0, 0, 1 );
  30999. material.depthNode = depthNode;
  31000. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  31001. material.name = 'ShadowMaterial';
  31002. material.fog = false;
  31003. shadowMaterialLib.set( light, material );
  31004. }
  31005. return material;
  31006. };
  31007. //
  31008. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  31009. const _shadowRenderObjectKeys = [];
  31010. /**
  31011. * Creates a function to render shadow objects in a scene.
  31012. *
  31013. * @tsl
  31014. * @function
  31015. * @param {Renderer} renderer - The renderer.
  31016. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  31017. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  31018. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  31019. * @return {shadowRenderObjectFunction} A function that renders shadow objects.
  31020. */
  31021. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  31022. _shadowRenderObjectKeys[ 0 ] = renderer;
  31023. _shadowRenderObjectKeys[ 1 ] = shadow;
  31024. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  31025. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  31026. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  31027. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  31028. if ( useVelocity ) {
  31029. getDataFromObject( object ).useVelocity = true;
  31030. }
  31031. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  31032. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  31033. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  31034. }
  31035. };
  31036. renderObjectFunction.shadowType = shadowType;
  31037. renderObjectFunction.useVelocity = useVelocity;
  31038. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  31039. }
  31040. _shadowRenderObjectKeys[ 0 ] = null;
  31041. _shadowRenderObjectKeys[ 1 ] = null;
  31042. return renderObjectFunction;
  31043. };
  31044. /**
  31045. * Represents the shader code for the first VSM render pass.
  31046. *
  31047. * @private
  31048. * @method
  31049. * @param {Object} inputs - The input parameter object.
  31050. * @param {Node<float>} inputs.samples - The number of samples
  31051. * @param {Node<float>} inputs.radius - The radius.
  31052. * @param {Node<float>} inputs.size - The size.
  31053. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  31054. * @return {Node<vec2>} The VSM output.
  31055. */
  31056. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  31057. const mean = float( 0 ).toVar( 'meanVertical' );
  31058. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  31059. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  31060. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  31061. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  31062. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  31063. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  31064. if ( shadowPass.value.isArrayTexture ) {
  31065. depth = depth.depth( depthLayer );
  31066. }
  31067. depth = depth.x;
  31068. mean.addAssign( depth );
  31069. squaredMean.addAssign( depth.mul( depth ) );
  31070. } );
  31071. mean.divAssign( samples );
  31072. squaredMean.divAssign( samples );
  31073. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ).max( 0 ) );
  31074. return vec2( mean, std_dev );
  31075. } );
  31076. /**
  31077. * Represents the shader code for the second VSM render pass.
  31078. *
  31079. * @private
  31080. * @method
  31081. * @param {Object} inputs - The input parameter object.
  31082. * @param {Node<float>} inputs.samples - The number of samples
  31083. * @param {Node<float>} inputs.radius - The radius.
  31084. * @param {Node<float>} inputs.size - The size.
  31085. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  31086. * @return {Node<vec2>} The VSM output.
  31087. */
  31088. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  31089. const mean = float( 0 ).toVar( 'meanHorizontal' );
  31090. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  31091. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  31092. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  31093. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  31094. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  31095. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  31096. if ( shadowPass.value.isArrayTexture ) {
  31097. distribution = distribution.depth( depthLayer );
  31098. }
  31099. mean.addAssign( distribution.x );
  31100. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  31101. } );
  31102. mean.divAssign( samples );
  31103. squaredMean.divAssign( samples );
  31104. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ).max( 0 ) );
  31105. return vec2( mean, std_dev );
  31106. } );
  31107. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  31108. //
  31109. let _rendererState;
  31110. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  31111. /**
  31112. * Represents the default shadow implementation for lighting nodes.
  31113. *
  31114. * @augments ShadowBaseNode
  31115. */
  31116. class ShadowNode extends ShadowBaseNode {
  31117. static get type() {
  31118. return 'ShadowNode';
  31119. }
  31120. /**
  31121. * Constructs a new shadow node.
  31122. *
  31123. * @param {Light} light - The shadow casting light.
  31124. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  31125. */
  31126. constructor( light, shadow = null ) {
  31127. super( light );
  31128. /**
  31129. * The light shadow which defines the properties light's
  31130. * shadow.
  31131. *
  31132. * @type {?LightShadow}
  31133. * @default null
  31134. */
  31135. this.shadow = shadow || light.shadow;
  31136. /**
  31137. * A reference to the shadow map which is a render target.
  31138. *
  31139. * @type {?RenderTarget}
  31140. * @default null
  31141. */
  31142. this.shadowMap = null;
  31143. /**
  31144. * Only relevant for VSM shadows. Render target for the
  31145. * first VSM render pass.
  31146. *
  31147. * @type {?RenderTarget}
  31148. * @default null
  31149. */
  31150. this.vsmShadowMapVertical = null;
  31151. /**
  31152. * Only relevant for VSM shadows. Render target for the
  31153. * second VSM render pass.
  31154. *
  31155. * @type {?RenderTarget}
  31156. * @default null
  31157. */
  31158. this.vsmShadowMapHorizontal = null;
  31159. /**
  31160. * Only relevant for VSM shadows. Node material which
  31161. * is used to render the first VSM pass.
  31162. *
  31163. * @type {?NodeMaterial}
  31164. * @default null
  31165. */
  31166. this.vsmMaterialVertical = null;
  31167. /**
  31168. * Only relevant for VSM shadows. Node material which
  31169. * is used to render the second VSM pass.
  31170. *
  31171. * @type {?NodeMaterial}
  31172. * @default null
  31173. */
  31174. this.vsmMaterialHorizontal = null;
  31175. /**
  31176. * A reference to the output node which defines the
  31177. * final result of this shadow node.
  31178. *
  31179. * @type {?Node}
  31180. * @private
  31181. * @default null
  31182. */
  31183. this._node = null;
  31184. /**
  31185. * The current shadow map type of this shadow node.
  31186. *
  31187. * @type {?number}
  31188. * @private
  31189. * @default null
  31190. */
  31191. this._currentShadowType = null;
  31192. /**
  31193. * A Weak Map holding the current frame ID per camera. Used
  31194. * to control the update of shadow maps.
  31195. *
  31196. * @type {WeakMap<Camera,number>}
  31197. * @private
  31198. */
  31199. this._cameraFrameId = new WeakMap();
  31200. /**
  31201. * This flag can be used for type testing.
  31202. *
  31203. * @type {boolean}
  31204. * @readonly
  31205. * @default true
  31206. */
  31207. this.isShadowNode = true;
  31208. /**
  31209. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  31210. *
  31211. * @type {number}
  31212. * @readonly
  31213. * @default true
  31214. */
  31215. this.depthLayer = 0;
  31216. }
  31217. /**
  31218. * Setups the shadow filtering.
  31219. *
  31220. * @param {NodeBuilder} builder - A reference to the current node builder.
  31221. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  31222. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  31223. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31224. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  31225. * @param {LightShadow} inputs.shadow - The light shadow.
  31226. * @return {Node<float>} The result node of the shadow filtering.
  31227. */
  31228. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  31229. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  31230. .and( shadowCoord.x.lessThanEqual( 1 ) )
  31231. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  31232. .and( shadowCoord.y.lessThanEqual( 1 ) )
  31233. .and( shadowCoord.z.lessThanEqual( 1 ) );
  31234. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  31235. return frustumTest.select( shadowNode, float( 1 ) );
  31236. }
  31237. /**
  31238. * Setups the shadow coordinates.
  31239. *
  31240. * @param {NodeBuilder} builder - A reference to the current node builder.
  31241. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  31242. * @return {Node<vec3>} The shadow coordinates.
  31243. */
  31244. setupShadowCoord( builder, shadowPosition ) {
  31245. const { shadow } = this;
  31246. const { renderer } = builder;
  31247. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  31248. let shadowCoord = shadowPosition;
  31249. let coordZ;
  31250. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  31251. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  31252. coordZ = shadowCoord.z;
  31253. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  31254. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  31255. }
  31256. } else {
  31257. const w = shadowCoord.w;
  31258. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  31259. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  31260. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  31261. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  31262. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  31263. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  31264. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  31265. }
  31266. shadowCoord = vec3(
  31267. shadowCoord.x,
  31268. shadowCoord.y.oneMinus(), // follow webgpu standards
  31269. coordZ.add( bias )
  31270. );
  31271. return shadowCoord;
  31272. }
  31273. /**
  31274. * Returns the shadow filtering function for the given shadow type.
  31275. *
  31276. * @param {number} type - The shadow type.
  31277. * @return {Function} The filtering function.
  31278. */
  31279. getShadowFilterFn( type ) {
  31280. return _shadowFilterLib[ type ];
  31281. }
  31282. setupRenderTarget( shadow, builder ) {
  31283. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  31284. depthTexture.name = 'ShadowDepthTexture';
  31285. depthTexture.compareFunction = LessCompare;
  31286. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  31287. shadowMap.texture.name = 'ShadowMap';
  31288. shadowMap.texture.type = shadow.mapType;
  31289. shadowMap.depthTexture = depthTexture;
  31290. return { shadowMap, depthTexture };
  31291. }
  31292. /**
  31293. * Setups the shadow output node.
  31294. *
  31295. * @param {NodeBuilder} builder - A reference to the current node builder.
  31296. * @return {Node<vec3>} The shadow output node.
  31297. */
  31298. setupShadow( builder ) {
  31299. const { renderer, camera } = builder;
  31300. const { light, shadow } = this;
  31301. const shadowMapType = renderer.shadowMap.type;
  31302. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  31303. shadow.camera.coordinateSystem = camera.coordinateSystem;
  31304. shadow.camera.updateProjectionMatrix();
  31305. // VSM
  31306. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  31307. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  31308. if ( shadowMap.depth > 1 ) {
  31309. if ( ! shadowMap._vsmShadowMapVertical ) {
  31310. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  31311. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  31312. }
  31313. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  31314. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  31315. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  31316. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  31317. }
  31318. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  31319. } else {
  31320. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  31321. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  31322. }
  31323. let shadowPassVertical = texture( depthTexture );
  31324. if ( depthTexture.isArrayTexture ) {
  31325. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  31326. }
  31327. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  31328. if ( depthTexture.isArrayTexture ) {
  31329. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  31330. }
  31331. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  31332. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  31333. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  31334. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  31335. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  31336. material.name = 'VSMVertical';
  31337. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  31338. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  31339. material.name = 'VSMHorizontal';
  31340. }
  31341. //
  31342. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  31343. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  31344. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( normalWorld.mul( normalBias ) ) );
  31345. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  31346. //
  31347. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  31348. if ( filterFn === null ) {
  31349. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  31350. }
  31351. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  31352. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  31353. let shadowColor;
  31354. if ( shadowMap.texture.isCubeTexture ) {
  31355. // For cube shadow maps (point lights), use cubeTexture with vec3 coordinates
  31356. shadowColor = cubeTexture( shadowMap.texture, shadowCoord.xyz );
  31357. } else {
  31358. shadowColor = texture( shadowMap.texture, shadowCoord );
  31359. if ( depthTexture.isArrayTexture ) {
  31360. shadowColor = shadowColor.depth( this.depthLayer );
  31361. }
  31362. }
  31363. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  31364. this.shadowMap = shadowMap;
  31365. this.shadow.map = shadowMap;
  31366. // Shadow Output + Inspector
  31367. const inspectName = `${ this.light.type } Shadow [ ${ this.light.name || 'ID: ' + this.light.id } ]`;
  31368. return shadowOutput.toInspector( `${ inspectName } / Color`, () => {
  31369. if ( this.shadowMap.texture.isCubeTexture ) {
  31370. return cubeTexture( this.shadowMap.texture );
  31371. }
  31372. return texture( this.shadowMap.texture );
  31373. } ).toInspector( `${ inspectName } / Depth`, () => {
  31374. return textureLoad( this.shadowMap.depthTexture, uv$1().mul( textureSize( texture( this.shadowMap.depthTexture ) ) ) ).x.oneMinus();
  31375. } );
  31376. }
  31377. /**
  31378. * The implementation performs the setup of the output node. An output is only
  31379. * produces if shadow mapping is globally enabled in the renderer.
  31380. *
  31381. * @param {NodeBuilder} builder - A reference to the current node builder.
  31382. * @return {ShaderCallNodeInternal} The output node.
  31383. */
  31384. setup( builder ) {
  31385. if ( builder.renderer.shadowMap.enabled === false ) return;
  31386. return Fn( () => {
  31387. const currentShadowType = builder.renderer.shadowMap.type;
  31388. if ( this._currentShadowType !== currentShadowType ) {
  31389. this._reset();
  31390. this._node = null;
  31391. }
  31392. let node = this._node;
  31393. this.setupShadowPosition( builder );
  31394. if ( node === null ) {
  31395. this._node = node = this.setupShadow( builder );
  31396. this._currentShadowType = currentShadowType;
  31397. }
  31398. if ( builder.material.shadowNode ) { // @deprecated, r171
  31399. warn( 'NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  31400. }
  31401. if ( builder.material.receivedShadowNode ) {
  31402. node = builder.material.receivedShadowNode( node );
  31403. }
  31404. return node;
  31405. } )();
  31406. }
  31407. /**
  31408. * Renders the shadow. The logic of this function could be included
  31409. * into {@link ShadowNode#updateShadow} however more specialized shadow
  31410. * nodes might require a custom shadow map rendering. By having a
  31411. * dedicated method, it's easier to overwrite the default behavior.
  31412. *
  31413. * @param {NodeFrame} frame - A reference to the current node frame.
  31414. */
  31415. renderShadow( frame ) {
  31416. const { shadow, shadowMap, light } = this;
  31417. const { renderer, scene } = frame;
  31418. shadow.updateMatrices( light );
  31419. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  31420. const currentSceneName = scene.name;
  31421. scene.name = `Shadow Map [ ${ light.name || 'ID: ' + light.id } ]`;
  31422. renderer.render( scene, shadow.camera );
  31423. scene.name = currentSceneName;
  31424. }
  31425. /**
  31426. * Updates the shadow.
  31427. *
  31428. * @param {NodeFrame} frame - A reference to the current node frame.
  31429. */
  31430. updateShadow( frame ) {
  31431. const { shadowMap, light, shadow } = this;
  31432. const { renderer, scene, camera } = frame;
  31433. const shadowType = renderer.shadowMap.type;
  31434. const depthVersion = shadowMap.depthTexture.version;
  31435. this._depthVersionCached = depthVersion;
  31436. const _shadowCameraLayer = shadow.camera.layers.mask;
  31437. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  31438. shadow.camera.layers.mask = camera.layers.mask;
  31439. }
  31440. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  31441. const currentMRT = renderer.getMRT();
  31442. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  31443. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  31444. scene.overrideMaterial = getShadowMaterial( light );
  31445. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  31446. renderer.setClearColor( 0x000000, 0 );
  31447. renderer.setRenderTarget( shadowMap );
  31448. this.renderShadow( frame );
  31449. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  31450. // vsm blur pass
  31451. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  31452. this.vsmPass( renderer );
  31453. }
  31454. shadow.camera.layers.mask = _shadowCameraLayer;
  31455. restoreRendererAndSceneState( renderer, scene, _rendererState );
  31456. }
  31457. /**
  31458. * For VSM additional render passes are required.
  31459. *
  31460. * @param {Renderer} renderer - A reference to the current renderer.
  31461. */
  31462. vsmPass( renderer ) {
  31463. const { shadow } = this;
  31464. const depth = this.shadowMap.depth;
  31465. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  31466. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  31467. renderer.setRenderTarget( this.vsmShadowMapVertical );
  31468. _quadMesh.material = this.vsmMaterialVertical;
  31469. _quadMesh.render( renderer );
  31470. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  31471. _quadMesh.material = this.vsmMaterialHorizontal;
  31472. _quadMesh.render( renderer );
  31473. }
  31474. /**
  31475. * Frees the internal resources of this shadow node.
  31476. */
  31477. dispose() {
  31478. this._reset();
  31479. super.dispose();
  31480. }
  31481. /**
  31482. * Resets the resouce state of this shadow node.
  31483. *
  31484. * @private
  31485. */
  31486. _reset() {
  31487. this._currentShadowType = null;
  31488. if ( this.shadowMap ) {
  31489. this.shadowMap.dispose();
  31490. this.shadowMap = null;
  31491. }
  31492. if ( this.vsmShadowMapVertical !== null ) {
  31493. this.vsmShadowMapVertical.dispose();
  31494. this.vsmShadowMapVertical = null;
  31495. this.vsmMaterialVertical.dispose();
  31496. this.vsmMaterialVertical = null;
  31497. }
  31498. if ( this.vsmShadowMapHorizontal !== null ) {
  31499. this.vsmShadowMapHorizontal.dispose();
  31500. this.vsmShadowMapHorizontal = null;
  31501. this.vsmMaterialHorizontal.dispose();
  31502. this.vsmMaterialHorizontal = null;
  31503. }
  31504. }
  31505. /**
  31506. * The implementation performs the update of the shadow map if necessary.
  31507. *
  31508. * @param {NodeFrame} frame - A reference to the current node frame.
  31509. */
  31510. updateBefore( frame ) {
  31511. const { shadow } = this;
  31512. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  31513. if ( needsUpdate ) {
  31514. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  31515. needsUpdate = false;
  31516. }
  31517. this._cameraFrameId[ frame.camera ] = frame.frameId;
  31518. }
  31519. if ( needsUpdate ) {
  31520. this.updateShadow( frame );
  31521. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  31522. shadow.needsUpdate = false;
  31523. }
  31524. }
  31525. }
  31526. }
  31527. /**
  31528. * Shadow Render Object Function.
  31529. *
  31530. * @function shadowRenderObjectFunction
  31531. * @param {Object3D} object - The 3D object to render.
  31532. * @param {Scene} scene - The scene containing the object.
  31533. * @param {Camera} _camera - The camera used for rendering.
  31534. * @param {BufferGeometry} geometry - The geometry of the object.
  31535. * @param {Material} material - The material of the object.
  31536. * @param {Group} group - The group the object belongs to.
  31537. * @param {...any} params - Additional parameters for rendering.
  31538. */
  31539. /**
  31540. * TSL function for creating an instance of `ShadowNode`.
  31541. *
  31542. * @tsl
  31543. * @function
  31544. * @param {Light} light - The shadow casting light.
  31545. * @param {?LightShadow} [shadow] - The light shadow.
  31546. * @return {ShadowNode} The created shadow node.
  31547. */
  31548. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  31549. const _clearColor$1 = /*@__PURE__*/ new Color();
  31550. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  31551. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  31552. const _lookTarget = /*@__PURE__*/ new Vector3();
  31553. // Cube map face directions and up vectors for point light shadows
  31554. // Face order: +X, -X, +Y, -Y, +Z, -Z
  31555. // WebGPU coordinate system - Y faces swapped to match texture sampling convention
  31556. const _cubeDirectionsWebGPU = [
  31557. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ),
  31558. /*@__PURE__*/ new Vector3( 0, 1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  31559. ];
  31560. const _cubeUpsWebGPU = [
  31561. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, -1 ),
  31562. /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  31563. ];
  31564. // WebGL coordinate system - standard OpenGL convention
  31565. const _cubeDirectionsWebGL = [
  31566. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, 1, 0 ),
  31567. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  31568. ];
  31569. const _cubeUpsWebGL = [
  31570. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ),
  31571. /*@__PURE__*/ new Vector3( 0, 0, -1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  31572. ];
  31573. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp } ) => {
  31574. return cubeTexture( depthTexture, bd3D ).compare( dp );
  31575. } );
  31576. /**
  31577. * A shadow filtering function for point lights using Vogel disk sampling and IGN.
  31578. *
  31579. * Uses 5 samples distributed via Vogel disk pattern in tangent space around the
  31580. * sample direction, rotated per-pixel using Interleaved Gradient Noise (IGN).
  31581. *
  31582. * @method
  31583. * @param {Object} inputs - The input parameter object.
  31584. * @param {CubeDepthTexture} inputs.depthTexture - A reference to the shadow cube map.
  31585. * @param {Node<vec3>} inputs.bd3D - The normalized direction from light to fragment.
  31586. * @param {Node<float>} inputs.dp - The depth value to compare against.
  31587. * @param {LightShadow} inputs.shadow - The light shadow.
  31588. * @return {Node<float>} The filtering result.
  31589. */
  31590. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, shadow } ) => {
  31591. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  31592. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  31593. const texelSize = radius.div( mapSize.x );
  31594. // Build a tangent-space coordinate system for applying offsets
  31595. const absDir = abs( bd3D );
  31596. const tangent = normalize( cross( bd3D, absDir.x.greaterThan( absDir.z ).select( vec3( 0, 1, 0 ), vec3( 1, 0, 0 ) ) ) );
  31597. const bitangent = cross( bd3D, tangent );
  31598. // Use IGN to rotate sampling pattern per pixel (phi = IGN * 2π)
  31599. const phi = interleavedGradientNoise( screenCoordinate.xy ).mul( 6.28318530718 );
  31600. // 5 samples using Vogel disk distribution in tangent space
  31601. const sample0 = vogelDiskSample( 0, 5, phi );
  31602. const sample1 = vogelDiskSample( 1, 5, phi );
  31603. const sample2 = vogelDiskSample( 2, 5, phi );
  31604. const sample3 = vogelDiskSample( 3, 5, phi );
  31605. const sample4 = vogelDiskSample( 4, 5, phi );
  31606. return cubeTexture( depthTexture, bd3D.add( tangent.mul( sample0.x ).add( bitangent.mul( sample0.y ) ).mul( texelSize ) ) ).compare( dp )
  31607. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample1.x ).add( bitangent.mul( sample1.y ) ).mul( texelSize ) ) ).compare( dp ) )
  31608. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample2.x ).add( bitangent.mul( sample2.y ) ).mul( texelSize ) ) ).compare( dp ) )
  31609. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample3.x ).add( bitangent.mul( sample3.y ) ).mul( texelSize ) ) ).compare( dp ) )
  31610. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample4.x ).add( bitangent.mul( sample4.y ) ).mul( texelSize ) ) ).compare( dp ) )
  31611. .mul( 1.0 / 5.0 );
  31612. } );
  31613. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  31614. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  31615. // the vector from the light to the world-space position of the fragment.
  31616. const lightToPosition = shadowCoord.xyz.toVar();
  31617. const lightToPositionLength = lightToPosition.length();
  31618. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  31619. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  31620. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  31621. const result = float( 1.0 ).toVar();
  31622. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  31623. // dp = normalized distance from light to fragment position
  31624. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  31625. dp.addAssign( bias );
  31626. // bd3D = base direction 3D (direction from light to fragment)
  31627. const bd3D = lightToPosition.normalize();
  31628. // percentage-closer filtering using cube texture sampling
  31629. result.assign( filterFn( { depthTexture, bd3D, dp, shadow } ) );
  31630. } );
  31631. return result;
  31632. } );
  31633. /**
  31634. * Represents the shadow implementation for point light nodes.
  31635. *
  31636. * @augments ShadowNode
  31637. */
  31638. class PointShadowNode extends ShadowNode {
  31639. static get type() {
  31640. return 'PointShadowNode';
  31641. }
  31642. /**
  31643. * Constructs a new point shadow node.
  31644. *
  31645. * @param {PointLight} light - The shadow casting point light.
  31646. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  31647. */
  31648. constructor( light, shadow = null ) {
  31649. super( light, shadow );
  31650. }
  31651. /**
  31652. * Overwrites the default implementation to return point light shadow specific
  31653. * filtering functions.
  31654. *
  31655. * @param {number} type - The shadow type.
  31656. * @return {Function} The filtering function.
  31657. */
  31658. getShadowFilterFn( type ) {
  31659. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  31660. }
  31661. /**
  31662. * Overwrites the default implementation so the unaltered shadow position is used.
  31663. *
  31664. * @param {NodeBuilder} builder - A reference to the current node builder.
  31665. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  31666. * @return {Node<vec3>} The shadow coordinates.
  31667. */
  31668. setupShadowCoord( builder, shadowPosition ) {
  31669. return shadowPosition;
  31670. }
  31671. /**
  31672. * Overwrites the default implementation to only use point light specific
  31673. * shadow filter functions.
  31674. *
  31675. * @param {NodeBuilder} builder - A reference to the current node builder.
  31676. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  31677. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  31678. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's depth texture.
  31679. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  31680. * @param {LightShadow} inputs.shadow - The light shadow.
  31681. * @return {Node<float>} The result node of the shadow filtering.
  31682. */
  31683. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  31684. return pointShadowFilter( { filterFn, depthTexture, shadowCoord, shadow } );
  31685. }
  31686. /**
  31687. * Overwrites the default implementation to create a CubeRenderTarget with CubeDepthTexture.
  31688. *
  31689. * @param {LightShadow} shadow - The light shadow object.
  31690. * @param {NodeBuilder} builder - A reference to the current node builder.
  31691. * @return {Object} An object containing the shadow map and depth texture.
  31692. */
  31693. setupRenderTarget( shadow, builder ) {
  31694. const depthTexture = new CubeDepthTexture( shadow.mapSize.width );
  31695. depthTexture.name = 'PointShadowDepthTexture';
  31696. depthTexture.compareFunction = LessCompare;
  31697. const shadowMap = builder.createCubeRenderTarget( shadow.mapSize.width );
  31698. shadowMap.texture.name = 'PointShadowMap';
  31699. shadowMap.depthTexture = depthTexture;
  31700. return { shadowMap, depthTexture };
  31701. }
  31702. /**
  31703. * Overwrites the default implementation with point light specific
  31704. * rendering code.
  31705. *
  31706. * @param {NodeFrame} frame - A reference to the current node frame.
  31707. */
  31708. renderShadow( frame ) {
  31709. const { shadow, shadowMap, light } = this;
  31710. const { renderer, scene } = frame;
  31711. const camera = shadow.camera;
  31712. const shadowMatrix = shadow.matrix;
  31713. // Select cube directions/ups based on coordinate system
  31714. const isWebGPU = renderer.coordinateSystem === WebGPUCoordinateSystem;
  31715. const cubeDirections = isWebGPU ? _cubeDirectionsWebGPU : _cubeDirectionsWebGL;
  31716. const cubeUps = isWebGPU ? _cubeUpsWebGPU : _cubeUpsWebGL;
  31717. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.width );
  31718. //
  31719. const previousAutoClear = renderer.autoClear;
  31720. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  31721. const previousClearAlpha = renderer.getClearAlpha();
  31722. renderer.autoClear = false;
  31723. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  31724. // Render each cube face
  31725. for ( let face = 0; face < 6; face ++ ) {
  31726. // Set render target to the specific cube face
  31727. renderer.setRenderTarget( shadowMap, face );
  31728. renderer.clear();
  31729. // Update shadow camera matrices for this face
  31730. const far = light.distance || camera.far;
  31731. if ( far !== camera.far ) {
  31732. camera.far = far;
  31733. camera.updateProjectionMatrix();
  31734. }
  31735. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  31736. camera.position.copy( _lightPositionWorld );
  31737. _lookTarget.copy( camera.position );
  31738. _lookTarget.add( cubeDirections[ face ] );
  31739. camera.up.copy( cubeUps[ face ] );
  31740. camera.lookAt( _lookTarget );
  31741. camera.updateMatrixWorld();
  31742. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  31743. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  31744. shadow._frustum.setFromProjectionMatrix( _projScreenMatrix$1, camera.coordinateSystem, camera.reversedDepth );
  31745. //
  31746. const currentSceneName = scene.name;
  31747. scene.name = `Point Light Shadow [ ${ light.name || 'ID: ' + light.id } ] - Face ${ face + 1 }`;
  31748. renderer.render( scene, camera );
  31749. scene.name = currentSceneName;
  31750. }
  31751. //
  31752. renderer.autoClear = previousAutoClear;
  31753. renderer.setClearColor( previousClearColor, previousClearAlpha );
  31754. }
  31755. }
  31756. /**
  31757. * TSL function for creating an instance of `PointShadowNode`.
  31758. *
  31759. * @tsl
  31760. * @function
  31761. * @param {PointLight} light - The shadow casting point light.
  31762. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  31763. * @return {PointShadowNode} The created point shadow node.
  31764. */
  31765. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  31766. /**
  31767. * Base class for analytic light nodes.
  31768. *
  31769. * @augments LightingNode
  31770. */
  31771. class AnalyticLightNode extends LightingNode {
  31772. static get type() {
  31773. return 'AnalyticLightNode';
  31774. }
  31775. /**
  31776. * Constructs a new analytic light node.
  31777. *
  31778. * @param {?Light} [light=null] - The light source.
  31779. */
  31780. constructor( light = null ) {
  31781. super();
  31782. /**
  31783. * The light source.
  31784. *
  31785. * @type {?Light}
  31786. * @default null
  31787. */
  31788. this.light = light;
  31789. /**
  31790. * The light's color value.
  31791. *
  31792. * @type {Color}
  31793. */
  31794. this.color = new Color();
  31795. /**
  31796. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  31797. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  31798. *
  31799. * @type {Node}
  31800. */
  31801. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  31802. /**
  31803. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  31804. * The final color node is represented by a different node when using shadows.
  31805. *
  31806. * @type {?Node}
  31807. * @default null
  31808. */
  31809. this.baseColorNode = null;
  31810. /**
  31811. * Represents the light's shadow.
  31812. *
  31813. * @type {?ShadowNode}
  31814. * @default null
  31815. */
  31816. this.shadowNode = null;
  31817. /**
  31818. * Represents the light's shadow color.
  31819. *
  31820. * @type {?Node}
  31821. * @default null
  31822. */
  31823. this.shadowColorNode = null;
  31824. /**
  31825. * This flag can be used for type testing.
  31826. *
  31827. * @type {boolean}
  31828. * @readonly
  31829. * @default true
  31830. */
  31831. this.isAnalyticLightNode = true;
  31832. /**
  31833. * Overwritten since analytic light nodes are updated
  31834. * once per frame.
  31835. *
  31836. * @type {string}
  31837. * @default 'frame'
  31838. */
  31839. this.updateType = NodeUpdateType.FRAME;
  31840. }
  31841. getHash() {
  31842. return this.light.uuid;
  31843. }
  31844. /**
  31845. * Returns a node representing a direction vector which points from the current
  31846. * position in view space to the light's position in view space.
  31847. *
  31848. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  31849. * @return {Node<vec3>} The light vector node.
  31850. */
  31851. getLightVector( builder ) {
  31852. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  31853. }
  31854. /**
  31855. * Sets up the direct lighting for the analytic light node.
  31856. *
  31857. * @abstract
  31858. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  31859. * @return {Object|undefined} The direct light data (color and direction).
  31860. */
  31861. setupDirect( /*builder*/ ) { }
  31862. /**
  31863. * Sets up the direct rect area lighting for the analytic light node.
  31864. *
  31865. * @abstract
  31866. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  31867. * @return {Object|undefined} The direct rect area light data.
  31868. */
  31869. setupDirectRectArea( /*builder*/ ) { }
  31870. /**
  31871. * Setups the shadow node for this light. The method exists so concrete light classes
  31872. * can setup different types of shadow nodes.
  31873. *
  31874. * @return {ShadowNode} The created shadow node.
  31875. */
  31876. setupShadowNode() {
  31877. return shadow( this.light );
  31878. }
  31879. /**
  31880. * Setups the shadow for this light. This method is only executed if the light
  31881. * cast shadows and the current build object receives shadows. It incorporates
  31882. * shadows into the lighting computation.
  31883. *
  31884. * @param {NodeBuilder} builder - The current node builder.
  31885. */
  31886. setupShadow( builder ) {
  31887. const { renderer } = builder;
  31888. if ( renderer.shadowMap.enabled === false ) return;
  31889. let shadowColorNode = this.shadowColorNode;
  31890. if ( shadowColorNode === null ) {
  31891. const customShadowNode = this.light.shadow.shadowNode;
  31892. let shadowNode;
  31893. if ( customShadowNode !== undefined ) {
  31894. shadowNode = nodeObject( customShadowNode );
  31895. } else {
  31896. shadowNode = this.setupShadowNode();
  31897. }
  31898. this.shadowNode = shadowNode;
  31899. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  31900. this.baseColorNode = this.colorNode;
  31901. }
  31902. //
  31903. if ( builder.context.getShadow ) {
  31904. shadowColorNode = builder.context.getShadow( this, builder );
  31905. }
  31906. this.colorNode = shadowColorNode;
  31907. }
  31908. /**
  31909. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  31910. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  31911. * invocate the respective interface methods.
  31912. *
  31913. * @param {NodeBuilder} builder - The current node builder.
  31914. */
  31915. setup( builder ) {
  31916. this.colorNode = this.baseColorNode || this.colorNode;
  31917. if ( this.light.castShadow ) {
  31918. if ( builder.object.receiveShadow ) {
  31919. this.setupShadow( builder );
  31920. }
  31921. } else if ( this.shadowNode !== null ) {
  31922. this.shadowNode.dispose();
  31923. this.shadowNode = null;
  31924. this.shadowColorNode = null;
  31925. }
  31926. const directLightData = this.setupDirect( builder );
  31927. const directRectAreaLightData = this.setupDirectRectArea( builder );
  31928. if ( directLightData ) {
  31929. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  31930. }
  31931. if ( directRectAreaLightData ) {
  31932. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  31933. }
  31934. }
  31935. /**
  31936. * The update method is used to update light uniforms per frame.
  31937. * Potentially overwritten in concrete light nodes to update light
  31938. * specific uniforms.
  31939. *
  31940. * @param {NodeFrame} frame - A reference to the current node frame.
  31941. */
  31942. update( /*frame*/ ) {
  31943. const { light } = this;
  31944. this.color.copy( light.color ).multiplyScalar( light.intensity );
  31945. }
  31946. }
  31947. /**
  31948. * Represents a `discard` shader operation in TSL.
  31949. *
  31950. * @method
  31951. * @param {Object} inputs - The input parameter object.
  31952. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  31953. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  31954. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  31955. * @return {Node<float>} The distance falloff.
  31956. */
  31957. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  31958. // based upon Frostbite 3 Moving to Physically-based Rendering
  31959. // page 32, equation 26: E[window1]
  31960. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  31961. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  31962. return cutoffDistance.greaterThan( 0 ).select(
  31963. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  31964. distanceFalloff
  31965. );
  31966. } ); // validated
  31967. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  31968. const lightDirection = lightVector.normalize();
  31969. const lightDistance = lightVector.length();
  31970. const attenuation = getDistanceAttenuation( {
  31971. lightDistance,
  31972. cutoffDistance,
  31973. decayExponent
  31974. } );
  31975. const lightColor = color.mul( attenuation );
  31976. return { lightDirection, lightColor };
  31977. };
  31978. /**
  31979. * Module for representing point lights as nodes.
  31980. *
  31981. * @augments AnalyticLightNode
  31982. */
  31983. class PointLightNode extends AnalyticLightNode {
  31984. static get type() {
  31985. return 'PointLightNode';
  31986. }
  31987. /**
  31988. * Constructs a new point light node.
  31989. *
  31990. * @param {?PointLight} [light=null] - The point light source.
  31991. */
  31992. constructor( light = null ) {
  31993. super( light );
  31994. /**
  31995. * Uniform node representing the cutoff distance.
  31996. *
  31997. * @type {UniformNode<float>}
  31998. */
  31999. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  32000. /**
  32001. * Uniform node representing the decay exponent.
  32002. *
  32003. * @type {UniformNode<float>}
  32004. */
  32005. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  32006. }
  32007. /**
  32008. * Overwritten to updated point light specific uniforms.
  32009. *
  32010. * @param {NodeFrame} frame - A reference to the current node frame.
  32011. */
  32012. update( frame ) {
  32013. const { light } = this;
  32014. super.update( frame );
  32015. this.cutoffDistanceNode.value = light.distance;
  32016. this.decayExponentNode.value = light.decay;
  32017. }
  32018. /**
  32019. * Overwritten to setup point light specific shadow.
  32020. *
  32021. * @return {PointShadowNode}
  32022. */
  32023. setupShadowNode() {
  32024. return pointShadow( this.light );
  32025. }
  32026. setupDirect( builder ) {
  32027. return directPointLight( {
  32028. color: this.colorNode,
  32029. lightVector: this.getLightVector( builder ),
  32030. cutoffDistance: this.cutoffDistanceNode,
  32031. decayExponent: this.decayExponentNode
  32032. } );
  32033. }
  32034. }
  32035. /**
  32036. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  32037. *
  32038. * @tsl
  32039. * @function
  32040. * @param {Node<vec2>} coord - The uv coordinates.
  32041. * @return {Node<float>} The result data.
  32042. */
  32043. const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => {
  32044. const uv = coord.mul( 2.0 );
  32045. const cx = uv.x.floor();
  32046. const cy = uv.y.floor();
  32047. const result = cx.add( cy ).mod( 2.0 );
  32048. return result.sign();
  32049. } );
  32050. /**
  32051. * Generates a circle based on the uv coordinates.
  32052. *
  32053. * @tsl
  32054. * @function
  32055. * @param {Node<vec2>} coord - The uv to generate the circle.
  32056. * @return {Node<float>} The circle shape.
  32057. */
  32058. const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => {
  32059. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  32060. let alpha;
  32061. if ( material.alphaToCoverage && renderer.currentSamples > 0 ) {
  32062. const dlen = float( len2.fwidth() ).toVar();
  32063. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  32064. } else {
  32065. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  32066. }
  32067. return alpha;
  32068. } );
  32069. // Three.js Transpiler
  32070. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  32071. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  32072. const f = float( f_immutable ).toVar();
  32073. const t = float( t_immutable ).toVar();
  32074. const b = bool( b_immutable ).toVar();
  32075. return select( b, t, f );
  32076. } ).setLayout( {
  32077. name: 'mx_select',
  32078. type: 'float',
  32079. inputs: [
  32080. { name: 'b', type: 'bool' },
  32081. { name: 't', type: 'float' },
  32082. { name: 'f', type: 'float' }
  32083. ]
  32084. } );
  32085. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  32086. const b = bool( b_immutable ).toVar();
  32087. const val = float( val_immutable ).toVar();
  32088. return select( b, val.negate(), val );
  32089. } ).setLayout( {
  32090. name: 'mx_negate_if',
  32091. type: 'float',
  32092. inputs: [
  32093. { name: 'val', type: 'float' },
  32094. { name: 'b', type: 'bool' }
  32095. ]
  32096. } );
  32097. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  32098. const x = float( x_immutable ).toVar();
  32099. return int( floor( x ) );
  32100. } ).setLayout( {
  32101. name: 'mx_floor',
  32102. type: 'int',
  32103. inputs: [
  32104. { name: 'x', type: 'float' }
  32105. ]
  32106. } );
  32107. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  32108. const x = float( x_immutable ).toVar();
  32109. i.assign( mx_floor( x ) );
  32110. return x.sub( float( i ) );
  32111. } );
  32112. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  32113. const t = float( t_immutable ).toVar();
  32114. const s = float( s_immutable ).toVar();
  32115. const v3 = float( v3_immutable ).toVar();
  32116. const v2 = float( v2_immutable ).toVar();
  32117. const v1 = float( v1_immutable ).toVar();
  32118. const v0 = float( v0_immutable ).toVar();
  32119. const s1 = float( sub( 1.0, s ) ).toVar();
  32120. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  32121. } ).setLayout( {
  32122. name: 'mx_bilerp_0',
  32123. type: 'float',
  32124. inputs: [
  32125. { name: 'v0', type: 'float' },
  32126. { name: 'v1', type: 'float' },
  32127. { name: 'v2', type: 'float' },
  32128. { name: 'v3', type: 'float' },
  32129. { name: 's', type: 'float' },
  32130. { name: 't', type: 'float' }
  32131. ]
  32132. } );
  32133. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  32134. const t = float( t_immutable ).toVar();
  32135. const s = float( s_immutable ).toVar();
  32136. const v3 = vec3( v3_immutable ).toVar();
  32137. const v2 = vec3( v2_immutable ).toVar();
  32138. const v1 = vec3( v1_immutable ).toVar();
  32139. const v0 = vec3( v0_immutable ).toVar();
  32140. const s1 = float( sub( 1.0, s ) ).toVar();
  32141. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  32142. } ).setLayout( {
  32143. name: 'mx_bilerp_1',
  32144. type: 'vec3',
  32145. inputs: [
  32146. { name: 'v0', type: 'vec3' },
  32147. { name: 'v1', type: 'vec3' },
  32148. { name: 'v2', type: 'vec3' },
  32149. { name: 'v3', type: 'vec3' },
  32150. { name: 's', type: 'float' },
  32151. { name: 't', type: 'float' }
  32152. ]
  32153. } );
  32154. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  32155. 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 ] ) => {
  32156. const r = float( r_immutable ).toVar();
  32157. const t = float( t_immutable ).toVar();
  32158. const s = float( s_immutable ).toVar();
  32159. const v7 = float( v7_immutable ).toVar();
  32160. const v6 = float( v6_immutable ).toVar();
  32161. const v5 = float( v5_immutable ).toVar();
  32162. const v4 = float( v4_immutable ).toVar();
  32163. const v3 = float( v3_immutable ).toVar();
  32164. const v2 = float( v2_immutable ).toVar();
  32165. const v1 = float( v1_immutable ).toVar();
  32166. const v0 = float( v0_immutable ).toVar();
  32167. const s1 = float( sub( 1.0, s ) ).toVar();
  32168. const t1 = float( sub( 1.0, t ) ).toVar();
  32169. const r1 = float( sub( 1.0, r ) ).toVar();
  32170. 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 ) ) ) ) ) );
  32171. } ).setLayout( {
  32172. name: 'mx_trilerp_0',
  32173. type: 'float',
  32174. inputs: [
  32175. { name: 'v0', type: 'float' },
  32176. { name: 'v1', type: 'float' },
  32177. { name: 'v2', type: 'float' },
  32178. { name: 'v3', type: 'float' },
  32179. { name: 'v4', type: 'float' },
  32180. { name: 'v5', type: 'float' },
  32181. { name: 'v6', type: 'float' },
  32182. { name: 'v7', type: 'float' },
  32183. { name: 's', type: 'float' },
  32184. { name: 't', type: 'float' },
  32185. { name: 'r', type: 'float' }
  32186. ]
  32187. } );
  32188. 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 ] ) => {
  32189. const r = float( r_immutable ).toVar();
  32190. const t = float( t_immutable ).toVar();
  32191. const s = float( s_immutable ).toVar();
  32192. const v7 = vec3( v7_immutable ).toVar();
  32193. const v6 = vec3( v6_immutable ).toVar();
  32194. const v5 = vec3( v5_immutable ).toVar();
  32195. const v4 = vec3( v4_immutable ).toVar();
  32196. const v3 = vec3( v3_immutable ).toVar();
  32197. const v2 = vec3( v2_immutable ).toVar();
  32198. const v1 = vec3( v1_immutable ).toVar();
  32199. const v0 = vec3( v0_immutable ).toVar();
  32200. const s1 = float( sub( 1.0, s ) ).toVar();
  32201. const t1 = float( sub( 1.0, t ) ).toVar();
  32202. const r1 = float( sub( 1.0, r ) ).toVar();
  32203. 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 ) ) ) ) ) );
  32204. } ).setLayout( {
  32205. name: 'mx_trilerp_1',
  32206. type: 'vec3',
  32207. inputs: [
  32208. { name: 'v0', type: 'vec3' },
  32209. { name: 'v1', type: 'vec3' },
  32210. { name: 'v2', type: 'vec3' },
  32211. { name: 'v3', type: 'vec3' },
  32212. { name: 'v4', type: 'vec3' },
  32213. { name: 'v5', type: 'vec3' },
  32214. { name: 'v6', type: 'vec3' },
  32215. { name: 'v7', type: 'vec3' },
  32216. { name: 's', type: 'float' },
  32217. { name: 't', type: 'float' },
  32218. { name: 'r', type: 'float' }
  32219. ]
  32220. } );
  32221. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  32222. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  32223. const y = float( y_immutable ).toVar();
  32224. const x = float( x_immutable ).toVar();
  32225. const hash = uint( hash_immutable ).toVar();
  32226. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  32227. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  32228. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  32229. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  32230. } ).setLayout( {
  32231. name: 'mx_gradient_float_0',
  32232. type: 'float',
  32233. inputs: [
  32234. { name: 'hash', type: 'uint' },
  32235. { name: 'x', type: 'float' },
  32236. { name: 'y', type: 'float' }
  32237. ]
  32238. } );
  32239. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  32240. const z = float( z_immutable ).toVar();
  32241. const y = float( y_immutable ).toVar();
  32242. const x = float( x_immutable ).toVar();
  32243. const hash = uint( hash_immutable ).toVar();
  32244. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  32245. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  32246. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  32247. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  32248. } ).setLayout( {
  32249. name: 'mx_gradient_float_1',
  32250. type: 'float',
  32251. inputs: [
  32252. { name: 'hash', type: 'uint' },
  32253. { name: 'x', type: 'float' },
  32254. { name: 'y', type: 'float' },
  32255. { name: 'z', type: 'float' }
  32256. ]
  32257. } );
  32258. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  32259. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  32260. const y = float( y_immutable ).toVar();
  32261. const x = float( x_immutable ).toVar();
  32262. const hash = uvec3( hash_immutable ).toVar();
  32263. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  32264. } ).setLayout( {
  32265. name: 'mx_gradient_vec3_0',
  32266. type: 'vec3',
  32267. inputs: [
  32268. { name: 'hash', type: 'uvec3' },
  32269. { name: 'x', type: 'float' },
  32270. { name: 'y', type: 'float' }
  32271. ]
  32272. } );
  32273. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  32274. const z = float( z_immutable ).toVar();
  32275. const y = float( y_immutable ).toVar();
  32276. const x = float( x_immutable ).toVar();
  32277. const hash = uvec3( hash_immutable ).toVar();
  32278. 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 ) );
  32279. } ).setLayout( {
  32280. name: 'mx_gradient_vec3_1',
  32281. type: 'vec3',
  32282. inputs: [
  32283. { name: 'hash', type: 'uvec3' },
  32284. { name: 'x', type: 'float' },
  32285. { name: 'y', type: 'float' },
  32286. { name: 'z', type: 'float' }
  32287. ]
  32288. } );
  32289. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  32290. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32291. const v = float( v_immutable ).toVar();
  32292. return mul( 0.6616, v );
  32293. } ).setLayout( {
  32294. name: 'mx_gradient_scale2d_0',
  32295. type: 'float',
  32296. inputs: [
  32297. { name: 'v', type: 'float' }
  32298. ]
  32299. } );
  32300. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32301. const v = float( v_immutable ).toVar();
  32302. return mul( 0.9820, v );
  32303. } ).setLayout( {
  32304. name: 'mx_gradient_scale3d_0',
  32305. type: 'float',
  32306. inputs: [
  32307. { name: 'v', type: 'float' }
  32308. ]
  32309. } );
  32310. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32311. const v = vec3( v_immutable ).toVar();
  32312. return mul( 0.6616, v );
  32313. } ).setLayout( {
  32314. name: 'mx_gradient_scale2d_1',
  32315. type: 'vec3',
  32316. inputs: [
  32317. { name: 'v', type: 'vec3' }
  32318. ]
  32319. } );
  32320. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  32321. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32322. const v = vec3( v_immutable ).toVar();
  32323. return mul( 0.9820, v );
  32324. } ).setLayout( {
  32325. name: 'mx_gradient_scale3d_1',
  32326. type: 'vec3',
  32327. inputs: [
  32328. { name: 'v', type: 'vec3' }
  32329. ]
  32330. } );
  32331. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  32332. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  32333. const k = int( k_immutable ).toVar();
  32334. const x = uint( x_immutable ).toVar();
  32335. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  32336. } ).setLayout( {
  32337. name: 'mx_rotl32',
  32338. type: 'uint',
  32339. inputs: [
  32340. { name: 'x', type: 'uint' },
  32341. { name: 'k', type: 'int' }
  32342. ]
  32343. } );
  32344. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  32345. a.subAssign( c );
  32346. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  32347. c.addAssign( b );
  32348. b.subAssign( a );
  32349. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  32350. a.addAssign( c );
  32351. c.subAssign( b );
  32352. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  32353. b.addAssign( a );
  32354. a.subAssign( c );
  32355. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  32356. c.addAssign( b );
  32357. b.subAssign( a );
  32358. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  32359. a.addAssign( c );
  32360. c.subAssign( b );
  32361. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  32362. b.addAssign( a );
  32363. } );
  32364. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  32365. const c = uint( c_immutable ).toVar();
  32366. const b = uint( b_immutable ).toVar();
  32367. const a = uint( a_immutable ).toVar();
  32368. c.bitXorAssign( b );
  32369. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  32370. a.bitXorAssign( c );
  32371. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  32372. b.bitXorAssign( a );
  32373. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  32374. c.bitXorAssign( b );
  32375. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  32376. a.bitXorAssign( c );
  32377. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  32378. b.bitXorAssign( a );
  32379. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  32380. c.bitXorAssign( b );
  32381. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  32382. return c;
  32383. } ).setLayout( {
  32384. name: 'mx_bjfinal',
  32385. type: 'uint',
  32386. inputs: [
  32387. { name: 'a', type: 'uint' },
  32388. { name: 'b', type: 'uint' },
  32389. { name: 'c', type: 'uint' }
  32390. ]
  32391. } );
  32392. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  32393. const bits = uint( bits_immutable ).toVar();
  32394. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  32395. } ).setLayout( {
  32396. name: 'mx_bits_to_01',
  32397. type: 'float',
  32398. inputs: [
  32399. { name: 'bits', type: 'uint' }
  32400. ]
  32401. } );
  32402. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  32403. const t = float( t_immutable ).toVar();
  32404. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  32405. } ).setLayout( {
  32406. name: 'mx_fade',
  32407. type: 'float',
  32408. inputs: [
  32409. { name: 't', type: 'float' }
  32410. ]
  32411. } );
  32412. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  32413. const x = int( x_immutable ).toVar();
  32414. const len = uint( uint( 1 ) ).toVar();
  32415. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  32416. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  32417. } ).setLayout( {
  32418. name: 'mx_hash_int_0',
  32419. type: 'uint',
  32420. inputs: [
  32421. { name: 'x', type: 'int' }
  32422. ]
  32423. } );
  32424. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  32425. const y = int( y_immutable ).toVar();
  32426. const x = int( x_immutable ).toVar();
  32427. const len = uint( uint( 2 ) ).toVar();
  32428. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32429. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32430. a.addAssign( uint( x ) );
  32431. b.addAssign( uint( y ) );
  32432. return mx_bjfinal( a, b, c );
  32433. } ).setLayout( {
  32434. name: 'mx_hash_int_1',
  32435. type: 'uint',
  32436. inputs: [
  32437. { name: 'x', type: 'int' },
  32438. { name: 'y', type: 'int' }
  32439. ]
  32440. } );
  32441. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  32442. const z = int( z_immutable ).toVar();
  32443. const y = int( y_immutable ).toVar();
  32444. const x = int( x_immutable ).toVar();
  32445. const len = uint( uint( 3 ) ).toVar();
  32446. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32447. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32448. a.addAssign( uint( x ) );
  32449. b.addAssign( uint( y ) );
  32450. c.addAssign( uint( z ) );
  32451. return mx_bjfinal( a, b, c );
  32452. } ).setLayout( {
  32453. name: 'mx_hash_int_2',
  32454. type: 'uint',
  32455. inputs: [
  32456. { name: 'x', type: 'int' },
  32457. { name: 'y', type: 'int' },
  32458. { name: 'z', type: 'int' }
  32459. ]
  32460. } );
  32461. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  32462. const xx = int( xx_immutable ).toVar();
  32463. const z = int( z_immutable ).toVar();
  32464. const y = int( y_immutable ).toVar();
  32465. const x = int( x_immutable ).toVar();
  32466. const len = uint( uint( 4 ) ).toVar();
  32467. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32468. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32469. a.addAssign( uint( x ) );
  32470. b.addAssign( uint( y ) );
  32471. c.addAssign( uint( z ) );
  32472. mx_bjmix( a, b, c );
  32473. a.addAssign( uint( xx ) );
  32474. return mx_bjfinal( a, b, c );
  32475. } ).setLayout( {
  32476. name: 'mx_hash_int_3',
  32477. type: 'uint',
  32478. inputs: [
  32479. { name: 'x', type: 'int' },
  32480. { name: 'y', type: 'int' },
  32481. { name: 'z', type: 'int' },
  32482. { name: 'xx', type: 'int' }
  32483. ]
  32484. } );
  32485. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  32486. const yy = int( yy_immutable ).toVar();
  32487. const xx = int( xx_immutable ).toVar();
  32488. const z = int( z_immutable ).toVar();
  32489. const y = int( y_immutable ).toVar();
  32490. const x = int( x_immutable ).toVar();
  32491. const len = uint( uint( 5 ) ).toVar();
  32492. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32493. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32494. a.addAssign( uint( x ) );
  32495. b.addAssign( uint( y ) );
  32496. c.addAssign( uint( z ) );
  32497. mx_bjmix( a, b, c );
  32498. a.addAssign( uint( xx ) );
  32499. b.addAssign( uint( yy ) );
  32500. return mx_bjfinal( a, b, c );
  32501. } ).setLayout( {
  32502. name: 'mx_hash_int_4',
  32503. type: 'uint',
  32504. inputs: [
  32505. { name: 'x', type: 'int' },
  32506. { name: 'y', type: 'int' },
  32507. { name: 'z', type: 'int' },
  32508. { name: 'xx', type: 'int' },
  32509. { name: 'yy', type: 'int' }
  32510. ]
  32511. } );
  32512. 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 ] );
  32513. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  32514. const y = int( y_immutable ).toVar();
  32515. const x = int( x_immutable ).toVar();
  32516. const h = uint( mx_hash_int( x, y ) ).toVar();
  32517. const result = uvec3().toVar();
  32518. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  32519. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  32520. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  32521. return result;
  32522. } ).setLayout( {
  32523. name: 'mx_hash_vec3_0',
  32524. type: 'uvec3',
  32525. inputs: [
  32526. { name: 'x', type: 'int' },
  32527. { name: 'y', type: 'int' }
  32528. ]
  32529. } );
  32530. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  32531. const z = int( z_immutable ).toVar();
  32532. const y = int( y_immutable ).toVar();
  32533. const x = int( x_immutable ).toVar();
  32534. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  32535. const result = uvec3().toVar();
  32536. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  32537. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  32538. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  32539. return result;
  32540. } ).setLayout( {
  32541. name: 'mx_hash_vec3_1',
  32542. type: 'uvec3',
  32543. inputs: [
  32544. { name: 'x', type: 'int' },
  32545. { name: 'y', type: 'int' },
  32546. { name: 'z', type: 'int' }
  32547. ]
  32548. } );
  32549. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  32550. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32551. const p = vec2( p_immutable ).toVar();
  32552. const X = int().toVar(), Y = int().toVar();
  32553. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32554. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32555. const u = float( mx_fade( fx ) ).toVar();
  32556. const v = float( mx_fade( fy ) ).toVar();
  32557. 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();
  32558. return mx_gradient_scale2d( result );
  32559. } ).setLayout( {
  32560. name: 'mx_perlin_noise_float_0',
  32561. type: 'float',
  32562. inputs: [
  32563. { name: 'p', type: 'vec2' }
  32564. ]
  32565. } );
  32566. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32567. const p = vec3( p_immutable ).toVar();
  32568. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32569. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32570. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32571. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  32572. const u = float( mx_fade( fx ) ).toVar();
  32573. const v = float( mx_fade( fy ) ).toVar();
  32574. const w = float( mx_fade( fz ) ).toVar();
  32575. 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();
  32576. return mx_gradient_scale3d( result );
  32577. } ).setLayout( {
  32578. name: 'mx_perlin_noise_float_1',
  32579. type: 'float',
  32580. inputs: [
  32581. { name: 'p', type: 'vec3' }
  32582. ]
  32583. } );
  32584. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  32585. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32586. const p = vec2( p_immutable ).toVar();
  32587. const X = int().toVar(), Y = int().toVar();
  32588. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32589. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32590. const u = float( mx_fade( fx ) ).toVar();
  32591. const v = float( mx_fade( fy ) ).toVar();
  32592. 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();
  32593. return mx_gradient_scale2d( result );
  32594. } ).setLayout( {
  32595. name: 'mx_perlin_noise_vec3_0',
  32596. type: 'vec3',
  32597. inputs: [
  32598. { name: 'p', type: 'vec2' }
  32599. ]
  32600. } );
  32601. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32602. const p = vec3( p_immutable ).toVar();
  32603. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32604. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32605. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32606. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  32607. const u = float( mx_fade( fx ) ).toVar();
  32608. const v = float( mx_fade( fy ) ).toVar();
  32609. const w = float( mx_fade( fz ) ).toVar();
  32610. 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();
  32611. return mx_gradient_scale3d( result );
  32612. } ).setLayout( {
  32613. name: 'mx_perlin_noise_vec3_1',
  32614. type: 'vec3',
  32615. inputs: [
  32616. { name: 'p', type: 'vec3' }
  32617. ]
  32618. } );
  32619. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  32620. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32621. const p = float( p_immutable ).toVar();
  32622. const ix = int( mx_floor( p ) ).toVar();
  32623. return mx_bits_to_01( mx_hash_int( ix ) );
  32624. } ).setLayout( {
  32625. name: 'mx_cell_noise_float_0',
  32626. type: 'float',
  32627. inputs: [
  32628. { name: 'p', type: 'float' }
  32629. ]
  32630. } );
  32631. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32632. const p = vec2( p_immutable ).toVar();
  32633. const ix = int( mx_floor( p.x ) ).toVar();
  32634. const iy = int( mx_floor( p.y ) ).toVar();
  32635. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  32636. } ).setLayout( {
  32637. name: 'mx_cell_noise_float_1',
  32638. type: 'float',
  32639. inputs: [
  32640. { name: 'p', type: 'vec2' }
  32641. ]
  32642. } );
  32643. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32644. const p = vec3( p_immutable ).toVar();
  32645. const ix = int( mx_floor( p.x ) ).toVar();
  32646. const iy = int( mx_floor( p.y ) ).toVar();
  32647. const iz = int( mx_floor( p.z ) ).toVar();
  32648. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  32649. } ).setLayout( {
  32650. name: 'mx_cell_noise_float_2',
  32651. type: 'float',
  32652. inputs: [
  32653. { name: 'p', type: 'vec3' }
  32654. ]
  32655. } );
  32656. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32657. const p = vec4( p_immutable ).toVar();
  32658. const ix = int( mx_floor( p.x ) ).toVar();
  32659. const iy = int( mx_floor( p.y ) ).toVar();
  32660. const iz = int( mx_floor( p.z ) ).toVar();
  32661. const iw = int( mx_floor( p.w ) ).toVar();
  32662. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  32663. } ).setLayout( {
  32664. name: 'mx_cell_noise_float_3',
  32665. type: 'float',
  32666. inputs: [
  32667. { name: 'p', type: 'vec4' }
  32668. ]
  32669. } );
  32670. 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 ] );
  32671. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32672. const p = float( p_immutable ).toVar();
  32673. const ix = int( mx_floor( p ) ).toVar();
  32674. 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 ) ) ) );
  32675. } ).setLayout( {
  32676. name: 'mx_cell_noise_vec3_0',
  32677. type: 'vec3',
  32678. inputs: [
  32679. { name: 'p', type: 'float' }
  32680. ]
  32681. } );
  32682. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32683. const p = vec2( p_immutable ).toVar();
  32684. const ix = int( mx_floor( p.x ) ).toVar();
  32685. const iy = int( mx_floor( p.y ) ).toVar();
  32686. 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 ) ) ) );
  32687. } ).setLayout( {
  32688. name: 'mx_cell_noise_vec3_1',
  32689. type: 'vec3',
  32690. inputs: [
  32691. { name: 'p', type: 'vec2' }
  32692. ]
  32693. } );
  32694. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32695. const p = vec3( p_immutable ).toVar();
  32696. const ix = int( mx_floor( p.x ) ).toVar();
  32697. const iy = int( mx_floor( p.y ) ).toVar();
  32698. const iz = int( mx_floor( p.z ) ).toVar();
  32699. 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 ) ) ) );
  32700. } ).setLayout( {
  32701. name: 'mx_cell_noise_vec3_2',
  32702. type: 'vec3',
  32703. inputs: [
  32704. { name: 'p', type: 'vec3' }
  32705. ]
  32706. } );
  32707. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32708. const p = vec4( p_immutable ).toVar();
  32709. const ix = int( mx_floor( p.x ) ).toVar();
  32710. const iy = int( mx_floor( p.y ) ).toVar();
  32711. const iz = int( mx_floor( p.z ) ).toVar();
  32712. const iw = int( mx_floor( p.w ) ).toVar();
  32713. 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 ) ) ) );
  32714. } ).setLayout( {
  32715. name: 'mx_cell_noise_vec3_3',
  32716. type: 'vec3',
  32717. inputs: [
  32718. { name: 'p', type: 'vec4' }
  32719. ]
  32720. } );
  32721. 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 ] );
  32722. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32723. const diminish = float( diminish_immutable ).toVar();
  32724. const lacunarity = float( lacunarity_immutable ).toVar();
  32725. const octaves = int( octaves_immutable ).toVar();
  32726. const p = vec3( p_immutable ).toVar();
  32727. const result = float( 0.0 ).toVar();
  32728. const amplitude = float( 1.0 ).toVar();
  32729. Loop( octaves, () => {
  32730. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  32731. amplitude.mulAssign( diminish );
  32732. p.mulAssign( lacunarity );
  32733. } );
  32734. return result;
  32735. } ).setLayout( {
  32736. name: 'mx_fractal_noise_float',
  32737. type: 'float',
  32738. inputs: [
  32739. { name: 'p', type: 'vec3' },
  32740. { name: 'octaves', type: 'int' },
  32741. { name: 'lacunarity', type: 'float' },
  32742. { name: 'diminish', type: 'float' }
  32743. ]
  32744. } );
  32745. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32746. const diminish = float( diminish_immutable ).toVar();
  32747. const lacunarity = float( lacunarity_immutable ).toVar();
  32748. const octaves = int( octaves_immutable ).toVar();
  32749. const p = vec3( p_immutable ).toVar();
  32750. const result = vec3( 0.0 ).toVar();
  32751. const amplitude = float( 1.0 ).toVar();
  32752. Loop( octaves, () => {
  32753. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  32754. amplitude.mulAssign( diminish );
  32755. p.mulAssign( lacunarity );
  32756. } );
  32757. return result;
  32758. } ).setLayout( {
  32759. name: 'mx_fractal_noise_vec3',
  32760. type: 'vec3',
  32761. inputs: [
  32762. { name: 'p', type: 'vec3' },
  32763. { name: 'octaves', type: 'int' },
  32764. { name: 'lacunarity', type: 'float' },
  32765. { name: 'diminish', type: 'float' }
  32766. ]
  32767. } );
  32768. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32769. const diminish = float( diminish_immutable ).toVar();
  32770. const lacunarity = float( lacunarity_immutable ).toVar();
  32771. const octaves = int( octaves_immutable ).toVar();
  32772. const p = vec3( p_immutable ).toVar();
  32773. 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 ) );
  32774. } ).setLayout( {
  32775. name: 'mx_fractal_noise_vec2',
  32776. type: 'vec2',
  32777. inputs: [
  32778. { name: 'p', type: 'vec3' },
  32779. { name: 'octaves', type: 'int' },
  32780. { name: 'lacunarity', type: 'float' },
  32781. { name: 'diminish', type: 'float' }
  32782. ]
  32783. } );
  32784. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32785. const diminish = float( diminish_immutable ).toVar();
  32786. const lacunarity = float( lacunarity_immutable ).toVar();
  32787. const octaves = int( octaves_immutable ).toVar();
  32788. const p = vec3( p_immutable ).toVar();
  32789. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  32790. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  32791. return vec4( c, f );
  32792. } ).setLayout( {
  32793. name: 'mx_fractal_noise_vec4',
  32794. type: 'vec4',
  32795. inputs: [
  32796. { name: 'p', type: 'vec3' },
  32797. { name: 'octaves', type: 'int' },
  32798. { name: 'lacunarity', type: 'float' },
  32799. { name: 'diminish', type: 'float' }
  32800. ]
  32801. } );
  32802. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  32803. const metric = int( metric_immutable ).toVar();
  32804. const jitter = float( jitter_immutable ).toVar();
  32805. const yoff = int( yoff_immutable ).toVar();
  32806. const xoff = int( xoff_immutable ).toVar();
  32807. const y = int( y_immutable ).toVar();
  32808. const x = int( x_immutable ).toVar();
  32809. const p = vec2( p_immutable ).toVar();
  32810. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  32811. const off = vec2( tmp.x, tmp.y ).toVar();
  32812. off.subAssign( 0.5 );
  32813. off.mulAssign( jitter );
  32814. off.addAssign( 0.5 );
  32815. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  32816. const diff = vec2( cellpos.sub( p ) ).toVar();
  32817. If( metric.equal( int( 2 ) ), () => {
  32818. return abs( diff.x ).add( abs( diff.y ) );
  32819. } );
  32820. If( metric.equal( int( 3 ) ), () => {
  32821. return max$1( abs( diff.x ), abs( diff.y ) );
  32822. } );
  32823. return dot( diff, diff );
  32824. } ).setLayout( {
  32825. name: 'mx_worley_distance_0',
  32826. type: 'float',
  32827. inputs: [
  32828. { name: 'p', type: 'vec2' },
  32829. { name: 'x', type: 'int' },
  32830. { name: 'y', type: 'int' },
  32831. { name: 'xoff', type: 'int' },
  32832. { name: 'yoff', type: 'int' },
  32833. { name: 'jitter', type: 'float' },
  32834. { name: 'metric', type: 'int' }
  32835. ]
  32836. } );
  32837. 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 ] ) => {
  32838. const metric = int( metric_immutable ).toVar();
  32839. const jitter = float( jitter_immutable ).toVar();
  32840. const zoff = int( zoff_immutable ).toVar();
  32841. const yoff = int( yoff_immutable ).toVar();
  32842. const xoff = int( xoff_immutable ).toVar();
  32843. const z = int( z_immutable ).toVar();
  32844. const y = int( y_immutable ).toVar();
  32845. const x = int( x_immutable ).toVar();
  32846. const p = vec3( p_immutable ).toVar();
  32847. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  32848. off.subAssign( 0.5 );
  32849. off.mulAssign( jitter );
  32850. off.addAssign( 0.5 );
  32851. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  32852. const diff = vec3( cellpos.sub( p ) ).toVar();
  32853. If( metric.equal( int( 2 ) ), () => {
  32854. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  32855. } );
  32856. If( metric.equal( int( 3 ) ), () => {
  32857. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  32858. } );
  32859. return dot( diff, diff );
  32860. } ).setLayout( {
  32861. name: 'mx_worley_distance_1',
  32862. type: 'float',
  32863. inputs: [
  32864. { name: 'p', type: 'vec3' },
  32865. { name: 'x', type: 'int' },
  32866. { name: 'y', type: 'int' },
  32867. { name: 'z', type: 'int' },
  32868. { name: 'xoff', type: 'int' },
  32869. { name: 'yoff', type: 'int' },
  32870. { name: 'zoff', type: 'int' },
  32871. { name: 'jitter', type: 'float' },
  32872. { name: 'metric', type: 'int' }
  32873. ]
  32874. } );
  32875. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  32876. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32877. const metric = int( metric_immutable ).toVar();
  32878. const jitter = float( jitter_immutable ).toVar();
  32879. const p = vec2( p_immutable ).toVar();
  32880. const X = int().toVar(), Y = int().toVar();
  32881. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  32882. const sqdist = float( 1e6 ).toVar();
  32883. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32884. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32885. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  32886. sqdist.assign( min$1( sqdist, dist ) );
  32887. } );
  32888. } );
  32889. If( metric.equal( int( 0 ) ), () => {
  32890. sqdist.assign( sqrt( sqdist ) );
  32891. } );
  32892. return sqdist;
  32893. } ).setLayout( {
  32894. name: 'mx_worley_noise_float_0',
  32895. type: 'float',
  32896. inputs: [
  32897. { name: 'p', type: 'vec2' },
  32898. { name: 'jitter', type: 'float' },
  32899. { name: 'metric', type: 'int' }
  32900. ]
  32901. } );
  32902. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32903. const metric = int( metric_immutable ).toVar();
  32904. const jitter = float( jitter_immutable ).toVar();
  32905. const p = vec2( p_immutable ).toVar();
  32906. const X = int().toVar(), Y = int().toVar();
  32907. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  32908. const sqdist = vec2( 1e6, 1e6 ).toVar();
  32909. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32910. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32911. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  32912. If( dist.lessThan( sqdist.x ), () => {
  32913. sqdist.y.assign( sqdist.x );
  32914. sqdist.x.assign( dist );
  32915. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  32916. sqdist.y.assign( dist );
  32917. } );
  32918. } );
  32919. } );
  32920. If( metric.equal( int( 0 ) ), () => {
  32921. sqdist.assign( sqrt( sqdist ) );
  32922. } );
  32923. return sqdist;
  32924. } ).setLayout( {
  32925. name: 'mx_worley_noise_vec2_0',
  32926. type: 'vec2',
  32927. inputs: [
  32928. { name: 'p', type: 'vec2' },
  32929. { name: 'jitter', type: 'float' },
  32930. { name: 'metric', type: 'int' }
  32931. ]
  32932. } );
  32933. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32934. const metric = int( metric_immutable ).toVar();
  32935. const jitter = float( jitter_immutable ).toVar();
  32936. const p = vec2( p_immutable ).toVar();
  32937. const X = int().toVar(), Y = int().toVar();
  32938. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  32939. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  32940. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32941. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32942. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  32943. If( dist.lessThan( sqdist.x ), () => {
  32944. sqdist.z.assign( sqdist.y );
  32945. sqdist.y.assign( sqdist.x );
  32946. sqdist.x.assign( dist );
  32947. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  32948. sqdist.z.assign( sqdist.y );
  32949. sqdist.y.assign( dist );
  32950. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  32951. sqdist.z.assign( dist );
  32952. } );
  32953. } );
  32954. } );
  32955. If( metric.equal( int( 0 ) ), () => {
  32956. sqdist.assign( sqrt( sqdist ) );
  32957. } );
  32958. return sqdist;
  32959. } ).setLayout( {
  32960. name: 'mx_worley_noise_vec3_0',
  32961. type: 'vec3',
  32962. inputs: [
  32963. { name: 'p', type: 'vec2' },
  32964. { name: 'jitter', type: 'float' },
  32965. { name: 'metric', type: 'int' }
  32966. ]
  32967. } );
  32968. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32969. const metric = int( metric_immutable ).toVar();
  32970. const jitter = float( jitter_immutable ).toVar();
  32971. const p = vec3( p_immutable ).toVar();
  32972. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32973. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  32974. const sqdist = float( 1e6 ).toVar();
  32975. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32976. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32977. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  32978. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  32979. sqdist.assign( min$1( sqdist, dist ) );
  32980. } );
  32981. } );
  32982. } );
  32983. If( metric.equal( int( 0 ) ), () => {
  32984. sqdist.assign( sqrt( sqdist ) );
  32985. } );
  32986. return sqdist;
  32987. } ).setLayout( {
  32988. name: 'mx_worley_noise_float_1',
  32989. type: 'float',
  32990. inputs: [
  32991. { name: 'p', type: 'vec3' },
  32992. { name: 'jitter', type: 'float' },
  32993. { name: 'metric', type: 'int' }
  32994. ]
  32995. } );
  32996. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  32997. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32998. const metric = int( metric_immutable ).toVar();
  32999. const jitter = float( jitter_immutable ).toVar();
  33000. const p = vec3( p_immutable ).toVar();
  33001. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33002. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  33003. const sqdist = vec2( 1e6, 1e6 ).toVar();
  33004. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33005. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33006. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  33007. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  33008. If( dist.lessThan( sqdist.x ), () => {
  33009. sqdist.y.assign( sqdist.x );
  33010. sqdist.x.assign( dist );
  33011. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33012. sqdist.y.assign( dist );
  33013. } );
  33014. } );
  33015. } );
  33016. } );
  33017. If( metric.equal( int( 0 ) ), () => {
  33018. sqdist.assign( sqrt( sqdist ) );
  33019. } );
  33020. return sqdist;
  33021. } ).setLayout( {
  33022. name: 'mx_worley_noise_vec2_1',
  33023. type: 'vec2',
  33024. inputs: [
  33025. { name: 'p', type: 'vec3' },
  33026. { name: 'jitter', type: 'float' },
  33027. { name: 'metric', type: 'int' }
  33028. ]
  33029. } );
  33030. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  33031. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33032. const metric = int( metric_immutable ).toVar();
  33033. const jitter = float( jitter_immutable ).toVar();
  33034. const p = vec3( p_immutable ).toVar();
  33035. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33036. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  33037. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  33038. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33039. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33040. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  33041. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  33042. If( dist.lessThan( sqdist.x ), () => {
  33043. sqdist.z.assign( sqdist.y );
  33044. sqdist.y.assign( sqdist.x );
  33045. sqdist.x.assign( dist );
  33046. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33047. sqdist.z.assign( sqdist.y );
  33048. sqdist.y.assign( dist );
  33049. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  33050. sqdist.z.assign( dist );
  33051. } );
  33052. } );
  33053. } );
  33054. } );
  33055. If( metric.equal( int( 0 ) ), () => {
  33056. sqdist.assign( sqrt( sqdist ) );
  33057. } );
  33058. return sqdist;
  33059. } ).setLayout( {
  33060. name: 'mx_worley_noise_vec3_1',
  33061. type: 'vec3',
  33062. inputs: [
  33063. { name: 'p', type: 'vec3' },
  33064. { name: 'jitter', type: 'float' },
  33065. { name: 'metric', type: 'int' }
  33066. ]
  33067. } );
  33068. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  33069. // Unified Noise 2D
  33070. const mx_unifiednoise2d$1 = /*@__PURE__*/ Fn( ( [
  33071. noiseType_immutable, texcoord_immutable, freq_immutable, offset_immutable,
  33072. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  33073. octaves_immutable, lacunarity_immutable, diminish_immutable
  33074. ] ) => {
  33075. const noiseType = int( noiseType_immutable ).toVar();
  33076. const texcoord = vec2( texcoord_immutable ).toVar();
  33077. const freq = vec2( freq_immutable ).toVar();
  33078. const offset = vec2( offset_immutable ).toVar();
  33079. const jitter = float( jitter_immutable ).toVar();
  33080. const outmin = float( outmin_immutable ).toVar();
  33081. const outmax = float( outmax_immutable ).toVar();
  33082. const clampoutput = bool( clampoutput_immutable ).toVar();
  33083. const octaves = int( octaves_immutable ).toVar();
  33084. const lacunarity = float( lacunarity_immutable ).toVar();
  33085. const diminish = float( diminish_immutable ).toVar();
  33086. // Compute input position
  33087. const p = texcoord.mul( freq ).add( offset );
  33088. const result = float( 0.0 ).toVar();
  33089. // Perlin
  33090. If( noiseType.equal( int( 0 ) ), () => {
  33091. result.assign( mx_perlin_noise_vec3( p ) );
  33092. } );
  33093. // Cell
  33094. If( noiseType.equal( int( 1 ) ), () => {
  33095. result.assign( mx_cell_noise_vec3( p ) );
  33096. } );
  33097. // Worley (metric=0 = euclidean)
  33098. If( noiseType.equal( int( 2 ) ), () => {
  33099. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  33100. } );
  33101. // Fractal (use vec3(p, 0.0) for 2D input)
  33102. If( noiseType.equal( int( 3 ) ), () => {
  33103. result.assign( mx_fractal_noise_vec3$1( vec3( p, 0.0 ), octaves, lacunarity, diminish ) );
  33104. } );
  33105. // Remap output to [outmin, outmax]
  33106. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  33107. // Clamp if requested
  33108. If( clampoutput, () => {
  33109. result.assign( clamp( result, outmin, outmax ) );
  33110. } );
  33111. return result;
  33112. } ).setLayout( {
  33113. name: 'mx_unifiednoise2d',
  33114. type: 'float',
  33115. inputs: [
  33116. { name: 'noiseType', type: 'int' },
  33117. { name: 'texcoord', type: 'vec2' },
  33118. { name: 'freq', type: 'vec2' },
  33119. { name: 'offset', type: 'vec2' },
  33120. { name: 'jitter', type: 'float' },
  33121. { name: 'outmin', type: 'float' },
  33122. { name: 'outmax', type: 'float' },
  33123. { name: 'clampoutput', type: 'bool' },
  33124. { name: 'octaves', type: 'int' },
  33125. { name: 'lacunarity', type: 'float' },
  33126. { name: 'diminish', type: 'float' }
  33127. ]
  33128. } );
  33129. // Unified Noise 3D
  33130. const mx_unifiednoise3d$1 = /*@__PURE__*/ Fn( ( [
  33131. noiseType_immutable, position_immutable, freq_immutable, offset_immutable,
  33132. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  33133. octaves_immutable, lacunarity_immutable, diminish_immutable
  33134. ] ) => {
  33135. const noiseType = int( noiseType_immutable ).toVar();
  33136. const position = vec3( position_immutable ).toVar();
  33137. const freq = vec3( freq_immutable ).toVar();
  33138. const offset = vec3( offset_immutable ).toVar();
  33139. const jitter = float( jitter_immutable ).toVar();
  33140. const outmin = float( outmin_immutable ).toVar();
  33141. const outmax = float( outmax_immutable ).toVar();
  33142. const clampoutput = bool( clampoutput_immutable ).toVar();
  33143. const octaves = int( octaves_immutable ).toVar();
  33144. const lacunarity = float( lacunarity_immutable ).toVar();
  33145. const diminish = float( diminish_immutable ).toVar();
  33146. // Compute input position
  33147. const p = position.mul( freq ).add( offset );
  33148. const result = float( 0.0 ).toVar();
  33149. // Perlin
  33150. If( noiseType.equal( int( 0 ) ), () => {
  33151. result.assign( mx_perlin_noise_vec3( p ) );
  33152. } );
  33153. // Cell
  33154. If( noiseType.equal( int( 1 ) ), () => {
  33155. result.assign( mx_cell_noise_vec3( p ) );
  33156. } );
  33157. // Worley (metric=0 = euclidean)
  33158. If( noiseType.equal( int( 2 ) ), () => {
  33159. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  33160. } );
  33161. // Fractal
  33162. If( noiseType.equal( int( 3 ) ), () => {
  33163. result.assign( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) );
  33164. } );
  33165. // Remap output to [outmin, outmax]
  33166. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  33167. // Clamp if requested
  33168. If( clampoutput, () => {
  33169. result.assign( clamp( result, outmin, outmax ) );
  33170. } );
  33171. return result;
  33172. } ).setLayout( {
  33173. name: 'mx_unifiednoise3d',
  33174. type: 'float',
  33175. inputs: [
  33176. { name: 'noiseType', type: 'int' },
  33177. { name: 'position', type: 'vec3' },
  33178. { name: 'freq', type: 'vec3' },
  33179. { name: 'offset', type: 'vec3' },
  33180. { name: 'jitter', type: 'float' },
  33181. { name: 'outmin', type: 'float' },
  33182. { name: 'outmax', type: 'float' },
  33183. { name: 'clampoutput', type: 'bool' },
  33184. { name: 'octaves', type: 'int' },
  33185. { name: 'lacunarity', type: 'float' },
  33186. { name: 'diminish', type: 'float' }
  33187. ]
  33188. } );
  33189. // Three.js Transpiler
  33190. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  33191. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  33192. const s = hsv.y;
  33193. const v = hsv.z;
  33194. const result = vec3().toVar();
  33195. If( s.lessThan( 0.0001 ), () => {
  33196. result.assign( vec3( v, v, v ) );
  33197. } ).Else( () => {
  33198. let h = hsv.x;
  33199. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  33200. const hi = int( trunc( h ) );
  33201. const f = h.sub( float( hi ) );
  33202. const p = v.mul( s.oneMinus() );
  33203. const q = v.mul( s.mul( f ).oneMinus() );
  33204. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  33205. If( hi.equal( int( 0 ) ), () => {
  33206. result.assign( vec3( v, t, p ) );
  33207. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  33208. result.assign( vec3( q, v, p ) );
  33209. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  33210. result.assign( vec3( p, v, t ) );
  33211. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  33212. result.assign( vec3( p, q, v ) );
  33213. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  33214. result.assign( vec3( t, p, v ) );
  33215. } ).Else( () => {
  33216. result.assign( vec3( v, p, q ) );
  33217. } );
  33218. } );
  33219. return result;
  33220. } ).setLayout( {
  33221. name: 'mx_hsvtorgb',
  33222. type: 'vec3',
  33223. inputs: [
  33224. { name: 'hsv', type: 'vec3' }
  33225. ]
  33226. } );
  33227. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  33228. const c = vec3( c_immutable ).toVar();
  33229. const r = float( c.x ).toVar();
  33230. const g = float( c.y ).toVar();
  33231. const b = float( c.z ).toVar();
  33232. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  33233. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  33234. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  33235. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  33236. v.assign( maxcomp );
  33237. If( maxcomp.greaterThan( 0.0 ), () => {
  33238. s.assign( delta.div( maxcomp ) );
  33239. } ).Else( () => {
  33240. s.assign( 0.0 );
  33241. } );
  33242. If( s.lessThanEqual( 0.0 ), () => {
  33243. h.assign( 0.0 );
  33244. } ).Else( () => {
  33245. If( r.greaterThanEqual( maxcomp ), () => {
  33246. h.assign( g.sub( b ).div( delta ) );
  33247. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  33248. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  33249. } ).Else( () => {
  33250. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  33251. } );
  33252. h.mulAssign( 1.0 / 6.0 );
  33253. If( h.lessThan( 0.0 ), () => {
  33254. h.addAssign( 1.0 );
  33255. } );
  33256. } );
  33257. return vec3( h, s, v );
  33258. } ).setLayout( {
  33259. name: 'mx_rgbtohsv',
  33260. type: 'vec3',
  33261. inputs: [
  33262. { name: 'c', type: 'vec3' }
  33263. ]
  33264. } );
  33265. // Three.js Transpiler
  33266. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  33267. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  33268. const color = vec3( color_immutable ).toVar();
  33269. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  33270. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  33271. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  33272. return mix( linSeg, powSeg, isAbove );
  33273. } ).setLayout( {
  33274. name: 'mx_srgb_texture_to_lin_rec709',
  33275. type: 'vec3',
  33276. inputs: [
  33277. { name: 'color', type: 'vec3' }
  33278. ]
  33279. } );
  33280. const mx_aastep = ( threshold, value ) => {
  33281. threshold = float( threshold );
  33282. value = float( value );
  33283. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  33284. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  33285. };
  33286. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  33287. const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' );
  33288. const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' );
  33289. // Bilinear ramp: interpolate between four corners (tl, tr, bl, br) using texcoord.x and texcoord.y
  33290. const mx_ramp4 = (
  33291. valuetl, valuetr, valuebl, valuebr, texcoord = uv$1()
  33292. ) => {
  33293. const u = texcoord.x.clamp();
  33294. const v = texcoord.y.clamp();
  33295. const top = mix( valuetl, valuetr, u );
  33296. const bottom = mix( valuebl, valuebr, u );
  33297. return mix( top, bottom, v );
  33298. };
  33299. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  33300. const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' );
  33301. const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' );
  33302. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  33303. const mx_safepower = ( in1, in2 = 1 ) => {
  33304. in1 = float( in1 );
  33305. return in1.abs().pow( in2 ).mul( in1.sign() );
  33306. };
  33307. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  33308. const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33309. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33310. const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33311. const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => {
  33312. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  33313. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  33314. return noise_vec4.mul( amplitude ).add( pivot );
  33315. };
  33316. 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 );
  33317. 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 );
  33318. const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33319. const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33320. const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33321. const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  33322. 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 );
  33323. 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 );
  33324. 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 );
  33325. 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 );
  33326. // === Moved from MaterialXLoader.js ===
  33327. // Math ops
  33328. const mx_add = ( in1, in2 = float( 0 ) ) => add( in1, in2 );
  33329. const mx_subtract = ( in1, in2 = float( 0 ) ) => sub( in1, in2 );
  33330. const mx_multiply = ( in1, in2 = float( 1 ) ) => mul( in1, in2 );
  33331. const mx_divide = ( in1, in2 = float( 1 ) ) => div( in1, in2 );
  33332. const mx_modulo = ( in1, in2 = float( 1 ) ) => mod( in1, in2 );
  33333. const mx_power = ( in1, in2 = float( 1 ) ) => pow( in1, in2 );
  33334. const mx_atan2 = ( in1 = float( 0 ), in2 = float( 1 ) ) => atan( in1, in2 );
  33335. const mx_timer = () => time;
  33336. const mx_frame = () => frameId;
  33337. const mx_invert = ( in1, amount = float( 1 ) ) => sub( amount, in1 );
  33338. const mx_ifgreater = ( value1, value2, in1, in2 ) => value1.greaterThan( value2 ).mix( in1, in2 );
  33339. const mx_ifgreatereq = ( value1, value2, in1, in2 ) => value1.greaterThanEqual( value2 ).mix( in1, in2 );
  33340. const mx_ifequal = ( value1, value2, in1, in2 ) => value1.equal( value2 ).mix( in1, in2 );
  33341. // Enhanced separate node to support multi-output referencing (outx, outy, outz, outw)
  33342. const mx_separate = ( in1, channelOrOut = null ) => {
  33343. if ( typeof channelOrOut === 'string' ) {
  33344. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  33345. const c = channelOrOut.replace( /^out/, '' ).toLowerCase();
  33346. if ( map[ c ] !== undefined ) return in1.element( map[ c ] );
  33347. }
  33348. if ( typeof channelOrOut === 'number' ) {
  33349. return in1.element( channelOrOut );
  33350. }
  33351. if ( typeof channelOrOut === 'string' && channelOrOut.length === 1 ) {
  33352. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  33353. if ( map[ channelOrOut ] !== undefined ) return in1.element( map[ channelOrOut ] );
  33354. }
  33355. return in1;
  33356. };
  33357. const mx_place2d = (
  33358. texcoord, pivot = vec2( 0.5, 0.5 ), scale = vec2( 1, 1 ), rotate = float( 0 ), offset = vec2( 0, 0 )/*, operationorder = int( 0 )*/
  33359. ) => {
  33360. let uv = texcoord;
  33361. if ( pivot ) uv = uv.sub( pivot );
  33362. if ( scale ) uv = uv.mul( scale );
  33363. if ( rotate ) {
  33364. const rad = rotate.mul( Math.PI / 180.0 );
  33365. const cosR = rad.cos();
  33366. const sinR = rad.sin();
  33367. uv = vec2(
  33368. uv.x.mul( cosR ).sub( uv.y.mul( sinR ) ),
  33369. uv.x.mul( sinR ).add( uv.y.mul( cosR ) )
  33370. );
  33371. }
  33372. if ( pivot ) uv = uv.add( pivot );
  33373. if ( offset ) uv = uv.add( offset );
  33374. return uv;
  33375. };
  33376. const mx_rotate2d = ( input, amount ) => {
  33377. input = vec2( input );
  33378. amount = float( amount );
  33379. const radians = amount.mul( Math.PI / 180.0 );
  33380. return rotate( input, radians );
  33381. };
  33382. const mx_rotate3d = ( input, amount, axis ) => {
  33383. input = vec3( input );
  33384. amount = float( amount );
  33385. axis = vec3( axis );
  33386. const radians = amount.mul( Math.PI / 180.0 );
  33387. const nAxis = axis.normalize();
  33388. const cosA = radians.cos();
  33389. const sinA = radians.sin();
  33390. const oneMinusCosA = float( 1 ).sub( cosA );
  33391. const rot =
  33392. input.mul( cosA )
  33393. .add( nAxis.cross( input ).mul( sinA ) )
  33394. .add( nAxis.mul( nAxis.dot( input ) ).mul( oneMinusCosA ) );
  33395. return rot;
  33396. };
  33397. const mx_heighttonormal = ( input, scale/*, texcoord*/ ) => {
  33398. input = vec3( input );
  33399. scale = float( scale );
  33400. return bumpMap( input, scale );
  33401. };
  33402. /**
  33403. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  33404. *
  33405. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  33406. *
  33407. * ```js
  33408. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  33409. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  33410. * ```
  33411. *
  33412. * @tsl
  33413. * @function
  33414. * @param {Node<vec3>} normal - The normal to correct.
  33415. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  33416. * @param {Node<vec3>} cubePos - The cube position.
  33417. * @return {Node<vec3>} The parallax corrected normal.
  33418. */
  33419. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  33420. const nDir = normalize( normal ).toVar();
  33421. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  33422. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  33423. const rbminmax = vec3().toVar();
  33424. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  33425. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  33426. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  33427. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  33428. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  33429. return boxIntersection.sub( cubePos );
  33430. } );
  33431. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  33432. // normal is assumed to have unit length
  33433. const x = normal.x, y = normal.y, z = normal.z;
  33434. // band 0
  33435. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  33436. // band 1
  33437. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  33438. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  33439. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  33440. // band 2
  33441. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  33442. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  33443. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  33444. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  33445. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  33446. return result;
  33447. } );
  33448. // constants
  33449. var TSL = /*#__PURE__*/Object.freeze({
  33450. __proto__: null,
  33451. BRDF_GGX: BRDF_GGX,
  33452. BRDF_Lambert: BRDF_Lambert,
  33453. BasicPointShadowFilter: BasicPointShadowFilter,
  33454. BasicShadowFilter: BasicShadowFilter,
  33455. Break: Break,
  33456. Const: Const,
  33457. Continue: Continue,
  33458. DFGApprox: DFGApprox,
  33459. D_GGX: D_GGX,
  33460. Discard: Discard,
  33461. EPSILON: EPSILON,
  33462. F_Schlick: F_Schlick,
  33463. Fn: Fn,
  33464. HALF_PI: HALF_PI,
  33465. INFINITY: INFINITY,
  33466. If: If,
  33467. Loop: Loop,
  33468. NodeAccess: NodeAccess,
  33469. NodeShaderStage: NodeShaderStage,
  33470. NodeType: NodeType,
  33471. NodeUpdateType: NodeUpdateType,
  33472. OnBeforeMaterialUpdate: OnBeforeMaterialUpdate,
  33473. OnBeforeObjectUpdate: OnBeforeObjectUpdate,
  33474. OnMaterialUpdate: OnMaterialUpdate,
  33475. OnObjectUpdate: OnObjectUpdate,
  33476. PCFShadowFilter: PCFShadowFilter,
  33477. PCFSoftShadowFilter: PCFSoftShadowFilter,
  33478. PI: PI,
  33479. PI2: PI2,
  33480. PointShadowFilter: PointShadowFilter,
  33481. Return: Return,
  33482. Schlick_to_F0: Schlick_to_F0,
  33483. ScriptableNodeResources: ScriptableNodeResources,
  33484. ShaderNode: ShaderNode,
  33485. Stack: Stack,
  33486. Switch: Switch,
  33487. TBNViewMatrix: TBNViewMatrix,
  33488. TWO_PI: TWO_PI,
  33489. VSMShadowFilter: VSMShadowFilter,
  33490. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  33491. Var: Var,
  33492. VarIntent: VarIntent,
  33493. abs: abs,
  33494. acesFilmicToneMapping: acesFilmicToneMapping,
  33495. acos: acos,
  33496. add: add,
  33497. addMethodChaining: addMethodChaining,
  33498. addNodeElement: addNodeElement,
  33499. agxToneMapping: agxToneMapping,
  33500. all: all,
  33501. alphaT: alphaT,
  33502. and: and,
  33503. anisotropy: anisotropy,
  33504. anisotropyB: anisotropyB,
  33505. anisotropyT: anisotropyT,
  33506. any: any,
  33507. append: append,
  33508. array: array,
  33509. arrayBuffer: arrayBuffer,
  33510. asin: asin,
  33511. assign: assign,
  33512. atan: atan,
  33513. atan2: atan2,
  33514. atomicAdd: atomicAdd,
  33515. atomicAnd: atomicAnd,
  33516. atomicFunc: atomicFunc,
  33517. atomicLoad: atomicLoad,
  33518. atomicMax: atomicMax,
  33519. atomicMin: atomicMin,
  33520. atomicOr: atomicOr,
  33521. atomicStore: atomicStore,
  33522. atomicSub: atomicSub,
  33523. atomicXor: atomicXor,
  33524. attenuationColor: attenuationColor,
  33525. attenuationDistance: attenuationDistance,
  33526. attribute: attribute,
  33527. attributeArray: attributeArray,
  33528. backgroundBlurriness: backgroundBlurriness,
  33529. backgroundIntensity: backgroundIntensity,
  33530. backgroundRotation: backgroundRotation,
  33531. batch: batch,
  33532. bentNormalView: bentNormalView,
  33533. billboarding: billboarding,
  33534. bitAnd: bitAnd,
  33535. bitNot: bitNot,
  33536. bitOr: bitOr,
  33537. bitXor: bitXor,
  33538. bitangentGeometry: bitangentGeometry,
  33539. bitangentLocal: bitangentLocal,
  33540. bitangentView: bitangentView,
  33541. bitangentWorld: bitangentWorld,
  33542. bitcast: bitcast,
  33543. blendBurn: blendBurn,
  33544. blendColor: blendColor,
  33545. blendDodge: blendDodge,
  33546. blendOverlay: blendOverlay,
  33547. blendScreen: blendScreen,
  33548. blur: blur,
  33549. bool: bool,
  33550. buffer: buffer,
  33551. bufferAttribute: bufferAttribute,
  33552. builtin: builtin,
  33553. builtinAOContext: builtinAOContext,
  33554. builtinShadowContext: builtinShadowContext,
  33555. bumpMap: bumpMap,
  33556. burn: burn,
  33557. bvec2: bvec2,
  33558. bvec3: bvec3,
  33559. bvec4: bvec4,
  33560. bypass: bypass,
  33561. cache: cache,
  33562. call: call,
  33563. cameraFar: cameraFar,
  33564. cameraIndex: cameraIndex,
  33565. cameraNear: cameraNear,
  33566. cameraNormalMatrix: cameraNormalMatrix,
  33567. cameraPosition: cameraPosition,
  33568. cameraProjectionMatrix: cameraProjectionMatrix,
  33569. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  33570. cameraViewMatrix: cameraViewMatrix,
  33571. cameraViewport: cameraViewport,
  33572. cameraWorldMatrix: cameraWorldMatrix,
  33573. cbrt: cbrt,
  33574. cdl: cdl,
  33575. ceil: ceil,
  33576. checker: checker,
  33577. cineonToneMapping: cineonToneMapping,
  33578. clamp: clamp,
  33579. clearcoat: clearcoat,
  33580. clearcoatNormalView: clearcoatNormalView,
  33581. clearcoatRoughness: clearcoatRoughness,
  33582. code: code,
  33583. color: color,
  33584. colorSpaceToWorking: colorSpaceToWorking,
  33585. colorToDirection: colorToDirection,
  33586. compute: compute,
  33587. computeKernel: computeKernel,
  33588. computeSkinning: computeSkinning,
  33589. context: context,
  33590. convert: convert,
  33591. convertColorSpace: convertColorSpace,
  33592. convertToTexture: convertToTexture,
  33593. cos: cos,
  33594. countLeadingZeros: countLeadingZeros,
  33595. countOneBits: countOneBits,
  33596. countTrailingZeros: countTrailingZeros,
  33597. cross: cross,
  33598. cubeTexture: cubeTexture,
  33599. cubeTextureBase: cubeTextureBase,
  33600. dFdx: dFdx,
  33601. dFdy: dFdy,
  33602. dashSize: dashSize,
  33603. debug: debug,
  33604. decrement: decrement,
  33605. decrementBefore: decrementBefore,
  33606. defaultBuildStages: defaultBuildStages,
  33607. defaultShaderStages: defaultShaderStages,
  33608. defined: defined,
  33609. degrees: degrees,
  33610. deltaTime: deltaTime,
  33611. densityFog: densityFog,
  33612. densityFogFactor: densityFogFactor,
  33613. depth: depth,
  33614. depthPass: depthPass,
  33615. determinant: determinant,
  33616. difference: difference,
  33617. diffuseColor: diffuseColor,
  33618. diffuseContribution: diffuseContribution,
  33619. directPointLight: directPointLight,
  33620. directionToColor: directionToColor,
  33621. directionToFaceDirection: directionToFaceDirection,
  33622. dispersion: dispersion,
  33623. distance: distance,
  33624. div: div,
  33625. dodge: dodge,
  33626. dot: dot,
  33627. drawIndex: drawIndex,
  33628. dynamicBufferAttribute: dynamicBufferAttribute,
  33629. element: element,
  33630. emissive: emissive,
  33631. equal: equal,
  33632. equals: equals,
  33633. equirectUV: equirectUV,
  33634. exp: exp,
  33635. exp2: exp2,
  33636. expression: expression,
  33637. faceDirection: faceDirection,
  33638. faceForward: faceForward,
  33639. faceforward: faceforward,
  33640. float: float,
  33641. floatBitsToInt: floatBitsToInt,
  33642. floatBitsToUint: floatBitsToUint,
  33643. floor: floor,
  33644. fog: fog,
  33645. fract: fract,
  33646. frameGroup: frameGroup,
  33647. frameId: frameId,
  33648. frontFacing: frontFacing,
  33649. fwidth: fwidth,
  33650. gain: gain,
  33651. gapSize: gapSize,
  33652. getConstNodeType: getConstNodeType,
  33653. getCurrentStack: getCurrentStack,
  33654. getDirection: getDirection,
  33655. getDistanceAttenuation: getDistanceAttenuation,
  33656. getGeometryRoughness: getGeometryRoughness,
  33657. getNormalFromDepth: getNormalFromDepth,
  33658. getParallaxCorrectNormal: getParallaxCorrectNormal,
  33659. getRoughness: getRoughness,
  33660. getScreenPosition: getScreenPosition,
  33661. getShIrradianceAt: getShIrradianceAt,
  33662. getShadowMaterial: getShadowMaterial,
  33663. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  33664. getTextureIndex: getTextureIndex,
  33665. getViewPosition: getViewPosition,
  33666. ggxConvolution: ggxConvolution,
  33667. globalId: globalId,
  33668. glsl: glsl,
  33669. glslFn: glslFn,
  33670. grayscale: grayscale,
  33671. greaterThan: greaterThan,
  33672. greaterThanEqual: greaterThanEqual,
  33673. hash: hash,
  33674. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  33675. highpModelViewMatrix: highpModelViewMatrix,
  33676. hue: hue,
  33677. increment: increment,
  33678. incrementBefore: incrementBefore,
  33679. inspector: inspector,
  33680. instance: instance,
  33681. instanceIndex: instanceIndex,
  33682. instancedArray: instancedArray,
  33683. instancedBufferAttribute: instancedBufferAttribute,
  33684. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  33685. instancedMesh: instancedMesh,
  33686. int: int,
  33687. intBitsToFloat: intBitsToFloat,
  33688. interleavedGradientNoise: interleavedGradientNoise,
  33689. inverse: inverse,
  33690. inverseSqrt: inverseSqrt,
  33691. inversesqrt: inversesqrt,
  33692. invocationLocalIndex: invocationLocalIndex,
  33693. invocationSubgroupIndex: invocationSubgroupIndex,
  33694. ior: ior,
  33695. iridescence: iridescence,
  33696. iridescenceIOR: iridescenceIOR,
  33697. iridescenceThickness: iridescenceThickness,
  33698. isolate: isolate,
  33699. ivec2: ivec2,
  33700. ivec3: ivec3,
  33701. ivec4: ivec4,
  33702. js: js,
  33703. label: label,
  33704. length: length,
  33705. lengthSq: lengthSq,
  33706. lessThan: lessThan,
  33707. lessThanEqual: lessThanEqual,
  33708. lightPosition: lightPosition,
  33709. lightProjectionUV: lightProjectionUV,
  33710. lightShadowMatrix: lightShadowMatrix,
  33711. lightTargetDirection: lightTargetDirection,
  33712. lightTargetPosition: lightTargetPosition,
  33713. lightViewPosition: lightViewPosition,
  33714. lightingContext: lightingContext,
  33715. lights: lights,
  33716. linearDepth: linearDepth,
  33717. linearToneMapping: linearToneMapping,
  33718. localId: localId,
  33719. log: log,
  33720. log2: log2,
  33721. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  33722. luminance: luminance,
  33723. mat2: mat2,
  33724. mat3: mat3,
  33725. mat4: mat4,
  33726. matcapUV: matcapUV,
  33727. materialAO: materialAO,
  33728. materialAlphaTest: materialAlphaTest,
  33729. materialAnisotropy: materialAnisotropy,
  33730. materialAnisotropyVector: materialAnisotropyVector,
  33731. materialAttenuationColor: materialAttenuationColor,
  33732. materialAttenuationDistance: materialAttenuationDistance,
  33733. materialClearcoat: materialClearcoat,
  33734. materialClearcoatNormal: materialClearcoatNormal,
  33735. materialClearcoatRoughness: materialClearcoatRoughness,
  33736. materialColor: materialColor,
  33737. materialDispersion: materialDispersion,
  33738. materialEmissive: materialEmissive,
  33739. materialEnvIntensity: materialEnvIntensity,
  33740. materialEnvRotation: materialEnvRotation,
  33741. materialIOR: materialIOR,
  33742. materialIridescence: materialIridescence,
  33743. materialIridescenceIOR: materialIridescenceIOR,
  33744. materialIridescenceThickness: materialIridescenceThickness,
  33745. materialLightMap: materialLightMap,
  33746. materialLineDashOffset: materialLineDashOffset,
  33747. materialLineDashSize: materialLineDashSize,
  33748. materialLineGapSize: materialLineGapSize,
  33749. materialLineScale: materialLineScale,
  33750. materialLineWidth: materialLineWidth,
  33751. materialMetalness: materialMetalness,
  33752. materialNormal: materialNormal,
  33753. materialOpacity: materialOpacity,
  33754. materialPointSize: materialPointSize,
  33755. materialReference: materialReference,
  33756. materialReflectivity: materialReflectivity,
  33757. materialRefractionRatio: materialRefractionRatio,
  33758. materialRotation: materialRotation,
  33759. materialRoughness: materialRoughness,
  33760. materialSheen: materialSheen,
  33761. materialSheenRoughness: materialSheenRoughness,
  33762. materialShininess: materialShininess,
  33763. materialSpecular: materialSpecular,
  33764. materialSpecularColor: materialSpecularColor,
  33765. materialSpecularIntensity: materialSpecularIntensity,
  33766. materialSpecularStrength: materialSpecularStrength,
  33767. materialThickness: materialThickness,
  33768. materialTransmission: materialTransmission,
  33769. max: max$1,
  33770. maxMipLevel: maxMipLevel,
  33771. mediumpModelViewMatrix: mediumpModelViewMatrix,
  33772. metalness: metalness,
  33773. min: min$1,
  33774. mix: mix,
  33775. mixElement: mixElement,
  33776. mod: mod,
  33777. modInt: modInt,
  33778. modelDirection: modelDirection,
  33779. modelNormalMatrix: modelNormalMatrix,
  33780. modelPosition: modelPosition,
  33781. modelRadius: modelRadius,
  33782. modelScale: modelScale,
  33783. modelViewMatrix: modelViewMatrix,
  33784. modelViewPosition: modelViewPosition,
  33785. modelViewProjection: modelViewProjection,
  33786. modelWorldMatrix: modelWorldMatrix,
  33787. modelWorldMatrixInverse: modelWorldMatrixInverse,
  33788. morphReference: morphReference,
  33789. mrt: mrt,
  33790. mul: mul,
  33791. mx_aastep: mx_aastep,
  33792. mx_add: mx_add,
  33793. mx_atan2: mx_atan2,
  33794. mx_cell_noise_float: mx_cell_noise_float,
  33795. mx_contrast: mx_contrast,
  33796. mx_divide: mx_divide,
  33797. mx_fractal_noise_float: mx_fractal_noise_float,
  33798. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  33799. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  33800. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  33801. mx_frame: mx_frame,
  33802. mx_heighttonormal: mx_heighttonormal,
  33803. mx_hsvtorgb: mx_hsvtorgb,
  33804. mx_ifequal: mx_ifequal,
  33805. mx_ifgreater: mx_ifgreater,
  33806. mx_ifgreatereq: mx_ifgreatereq,
  33807. mx_invert: mx_invert,
  33808. mx_modulo: mx_modulo,
  33809. mx_multiply: mx_multiply,
  33810. mx_noise_float: mx_noise_float,
  33811. mx_noise_vec3: mx_noise_vec3,
  33812. mx_noise_vec4: mx_noise_vec4,
  33813. mx_place2d: mx_place2d,
  33814. mx_power: mx_power,
  33815. mx_ramp4: mx_ramp4,
  33816. mx_ramplr: mx_ramplr,
  33817. mx_ramptb: mx_ramptb,
  33818. mx_rgbtohsv: mx_rgbtohsv,
  33819. mx_rotate2d: mx_rotate2d,
  33820. mx_rotate3d: mx_rotate3d,
  33821. mx_safepower: mx_safepower,
  33822. mx_separate: mx_separate,
  33823. mx_splitlr: mx_splitlr,
  33824. mx_splittb: mx_splittb,
  33825. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  33826. mx_subtract: mx_subtract,
  33827. mx_timer: mx_timer,
  33828. mx_transform_uv: mx_transform_uv,
  33829. mx_unifiednoise2d: mx_unifiednoise2d,
  33830. mx_unifiednoise3d: mx_unifiednoise3d,
  33831. mx_worley_noise_float: mx_worley_noise_float,
  33832. mx_worley_noise_vec2: mx_worley_noise_vec2,
  33833. mx_worley_noise_vec3: mx_worley_noise_vec3,
  33834. negate: negate,
  33835. neutralToneMapping: neutralToneMapping,
  33836. nodeArray: nodeArray,
  33837. nodeImmutable: nodeImmutable,
  33838. nodeObject: nodeObject,
  33839. nodeObjectIntent: nodeObjectIntent,
  33840. nodeObjects: nodeObjects,
  33841. nodeProxy: nodeProxy,
  33842. nodeProxyIntent: nodeProxyIntent,
  33843. normalFlat: normalFlat,
  33844. normalGeometry: normalGeometry,
  33845. normalLocal: normalLocal,
  33846. normalMap: normalMap,
  33847. normalView: normalView,
  33848. normalViewGeometry: normalViewGeometry,
  33849. normalWorld: normalWorld,
  33850. normalWorldGeometry: normalWorldGeometry,
  33851. normalize: normalize,
  33852. not: not,
  33853. notEqual: notEqual,
  33854. numWorkgroups: numWorkgroups,
  33855. objectDirection: objectDirection,
  33856. objectGroup: objectGroup,
  33857. objectPosition: objectPosition,
  33858. objectRadius: objectRadius,
  33859. objectScale: objectScale,
  33860. objectViewPosition: objectViewPosition,
  33861. objectWorldMatrix: objectWorldMatrix,
  33862. oneMinus: oneMinus,
  33863. or: or,
  33864. orthographicDepthToViewZ: orthographicDepthToViewZ,
  33865. oscSawtooth: oscSawtooth,
  33866. oscSine: oscSine,
  33867. oscSquare: oscSquare,
  33868. oscTriangle: oscTriangle,
  33869. output: output,
  33870. outputStruct: outputStruct,
  33871. overlay: overlay,
  33872. overloadingFn: overloadingFn,
  33873. packHalf2x16: packHalf2x16,
  33874. packSnorm2x16: packSnorm2x16,
  33875. packUnorm2x16: packUnorm2x16,
  33876. parabola: parabola,
  33877. parallaxDirection: parallaxDirection,
  33878. parallaxUV: parallaxUV,
  33879. parameter: parameter,
  33880. pass: pass,
  33881. passTexture: passTexture,
  33882. pcurve: pcurve,
  33883. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  33884. pmremTexture: pmremTexture,
  33885. pointShadow: pointShadow,
  33886. pointUV: pointUV,
  33887. pointWidth: pointWidth,
  33888. positionGeometry: positionGeometry,
  33889. positionLocal: positionLocal,
  33890. positionPrevious: positionPrevious,
  33891. positionView: positionView,
  33892. positionViewDirection: positionViewDirection,
  33893. positionWorld: positionWorld,
  33894. positionWorldDirection: positionWorldDirection,
  33895. posterize: posterize,
  33896. pow: pow,
  33897. pow2: pow2,
  33898. pow3: pow3,
  33899. pow4: pow4,
  33900. premultiplyAlpha: premultiplyAlpha,
  33901. property: property,
  33902. quadBroadcast: quadBroadcast,
  33903. quadSwapDiagonal: quadSwapDiagonal,
  33904. quadSwapX: quadSwapX,
  33905. quadSwapY: quadSwapY,
  33906. radians: radians,
  33907. rand: rand,
  33908. range: range,
  33909. rangeFog: rangeFog,
  33910. rangeFogFactor: rangeFogFactor,
  33911. reciprocal: reciprocal,
  33912. reference: reference,
  33913. referenceBuffer: referenceBuffer,
  33914. reflect: reflect,
  33915. reflectVector: reflectVector,
  33916. reflectView: reflectView,
  33917. reflector: reflector,
  33918. refract: refract,
  33919. refractVector: refractVector,
  33920. refractView: refractView,
  33921. reinhardToneMapping: reinhardToneMapping,
  33922. remap: remap,
  33923. remapClamp: remapClamp,
  33924. renderGroup: renderGroup,
  33925. renderOutput: renderOutput,
  33926. rendererReference: rendererReference,
  33927. replaceDefaultUV: replaceDefaultUV,
  33928. rotate: rotate,
  33929. rotateUV: rotateUV,
  33930. roughness: roughness,
  33931. round: round,
  33932. rtt: rtt,
  33933. sRGBTransferEOTF: sRGBTransferEOTF,
  33934. sRGBTransferOETF: sRGBTransferOETF,
  33935. sample: sample,
  33936. sampler: sampler,
  33937. samplerComparison: samplerComparison,
  33938. saturate: saturate,
  33939. saturation: saturation,
  33940. screen: screen,
  33941. screenCoordinate: screenCoordinate,
  33942. screenDPR: screenDPR,
  33943. screenSize: screenSize,
  33944. screenUV: screenUV,
  33945. scriptable: scriptable,
  33946. scriptableValue: scriptableValue,
  33947. select: select,
  33948. setCurrentStack: setCurrentStack,
  33949. setName: setName,
  33950. shaderStages: shaderStages,
  33951. shadow: shadow,
  33952. shadowPositionWorld: shadowPositionWorld,
  33953. shapeCircle: shapeCircle,
  33954. sharedUniformGroup: sharedUniformGroup,
  33955. sheen: sheen,
  33956. sheenRoughness: sheenRoughness,
  33957. shiftLeft: shiftLeft,
  33958. shiftRight: shiftRight,
  33959. shininess: shininess,
  33960. sign: sign,
  33961. sin: sin,
  33962. sinc: sinc,
  33963. skinning: skinning,
  33964. smoothstep: smoothstep,
  33965. smoothstepElement: smoothstepElement,
  33966. specularColor: specularColor,
  33967. specularColorBlended: specularColorBlended,
  33968. specularF90: specularF90,
  33969. spherizeUV: spherizeUV,
  33970. split: split,
  33971. spritesheetUV: spritesheetUV,
  33972. sqrt: sqrt,
  33973. stack: stack,
  33974. step: step,
  33975. stepElement: stepElement,
  33976. storage: storage,
  33977. storageBarrier: storageBarrier,
  33978. storageObject: storageObject,
  33979. storageTexture: storageTexture,
  33980. string: string,
  33981. struct: struct,
  33982. sub: sub,
  33983. subBuild: subBuild,
  33984. subgroupAdd: subgroupAdd,
  33985. subgroupAll: subgroupAll,
  33986. subgroupAnd: subgroupAnd,
  33987. subgroupAny: subgroupAny,
  33988. subgroupBallot: subgroupBallot,
  33989. subgroupBroadcast: subgroupBroadcast,
  33990. subgroupBroadcastFirst: subgroupBroadcastFirst,
  33991. subgroupElect: subgroupElect,
  33992. subgroupExclusiveAdd: subgroupExclusiveAdd,
  33993. subgroupExclusiveMul: subgroupExclusiveMul,
  33994. subgroupInclusiveAdd: subgroupInclusiveAdd,
  33995. subgroupInclusiveMul: subgroupInclusiveMul,
  33996. subgroupIndex: subgroupIndex,
  33997. subgroupMax: subgroupMax,
  33998. subgroupMin: subgroupMin,
  33999. subgroupMul: subgroupMul,
  34000. subgroupOr: subgroupOr,
  34001. subgroupShuffle: subgroupShuffle,
  34002. subgroupShuffleDown: subgroupShuffleDown,
  34003. subgroupShuffleUp: subgroupShuffleUp,
  34004. subgroupShuffleXor: subgroupShuffleXor,
  34005. subgroupSize: subgroupSize,
  34006. subgroupXor: subgroupXor,
  34007. tan: tan,
  34008. tangentGeometry: tangentGeometry,
  34009. tangentLocal: tangentLocal,
  34010. tangentView: tangentView,
  34011. tangentWorld: tangentWorld,
  34012. texture: texture,
  34013. texture3D: texture3D,
  34014. texture3DLevel: texture3DLevel,
  34015. texture3DLoad: texture3DLoad,
  34016. textureBarrier: textureBarrier,
  34017. textureBicubic: textureBicubic,
  34018. textureBicubicLevel: textureBicubicLevel,
  34019. textureCubeUV: textureCubeUV,
  34020. textureLevel: textureLevel,
  34021. textureLoad: textureLoad,
  34022. textureSize: textureSize,
  34023. textureStore: textureStore,
  34024. thickness: thickness,
  34025. time: time,
  34026. toneMapping: toneMapping,
  34027. toneMappingExposure: toneMappingExposure,
  34028. toonOutlinePass: toonOutlinePass,
  34029. transformDirection: transformDirection,
  34030. transformNormal: transformNormal,
  34031. transformNormalToView: transformNormalToView,
  34032. transformedClearcoatNormalView: transformedClearcoatNormalView,
  34033. transformedNormalView: transformedNormalView,
  34034. transformedNormalWorld: transformedNormalWorld,
  34035. transmission: transmission,
  34036. transpose: transpose,
  34037. triNoise3D: triNoise3D,
  34038. triplanarTexture: triplanarTexture,
  34039. triplanarTextures: triplanarTextures,
  34040. trunc: trunc,
  34041. uint: uint,
  34042. uintBitsToFloat: uintBitsToFloat,
  34043. uniform: uniform,
  34044. uniformArray: uniformArray,
  34045. uniformCubeTexture: uniformCubeTexture,
  34046. uniformFlow: uniformFlow,
  34047. uniformGroup: uniformGroup,
  34048. uniformTexture: uniformTexture,
  34049. unpackHalf2x16: unpackHalf2x16,
  34050. unpackNormal: unpackNormal,
  34051. unpackSnorm2x16: unpackSnorm2x16,
  34052. unpackUnorm2x16: unpackUnorm2x16,
  34053. unpremultiplyAlpha: unpremultiplyAlpha,
  34054. userData: userData,
  34055. uv: uv$1,
  34056. uvec2: uvec2,
  34057. uvec3: uvec3,
  34058. uvec4: uvec4,
  34059. varying: varying,
  34060. varyingProperty: varyingProperty,
  34061. vec2: vec2,
  34062. vec3: vec3,
  34063. vec4: vec4,
  34064. vectorComponents: vectorComponents,
  34065. velocity: velocity,
  34066. vertexColor: vertexColor,
  34067. vertexIndex: vertexIndex,
  34068. vertexStage: vertexStage,
  34069. vibrance: vibrance,
  34070. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  34071. viewZToOrthographicDepth: viewZToOrthographicDepth,
  34072. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  34073. viewport: viewport,
  34074. viewportCoordinate: viewportCoordinate,
  34075. viewportDepthTexture: viewportDepthTexture,
  34076. viewportLinearDepth: viewportLinearDepth,
  34077. viewportMipTexture: viewportMipTexture,
  34078. viewportResolution: viewportResolution,
  34079. viewportSafeUV: viewportSafeUV,
  34080. viewportSharedTexture: viewportSharedTexture,
  34081. viewportSize: viewportSize,
  34082. viewportTexture: viewportTexture,
  34083. viewportUV: viewportUV,
  34084. vogelDiskSample: vogelDiskSample,
  34085. wgsl: wgsl,
  34086. wgslFn: wgslFn,
  34087. workgroupArray: workgroupArray,
  34088. workgroupBarrier: workgroupBarrier,
  34089. workgroupId: workgroupId,
  34090. workingToColorSpace: workingToColorSpace,
  34091. xor: xor
  34092. });
  34093. const _clearColor = /*@__PURE__*/ new Color4();
  34094. /**
  34095. * This renderer module manages the background.
  34096. *
  34097. * @private
  34098. * @augments DataMap
  34099. */
  34100. class Background extends DataMap {
  34101. /**
  34102. * Constructs a new background management component.
  34103. *
  34104. * @param {Renderer} renderer - The renderer.
  34105. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  34106. */
  34107. constructor( renderer, nodes ) {
  34108. super();
  34109. /**
  34110. * The renderer.
  34111. *
  34112. * @type {Renderer}
  34113. */
  34114. this.renderer = renderer;
  34115. /**
  34116. * Renderer component for managing nodes related logic.
  34117. *
  34118. * @type {Nodes}
  34119. */
  34120. this.nodes = nodes;
  34121. }
  34122. /**
  34123. * Updates the background for the given scene. Depending on how `Scene.background`
  34124. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  34125. * or add a mesh to the render list for rendering the background as a textured plane
  34126. * or skybox.
  34127. *
  34128. * @param {Scene} scene - The scene.
  34129. * @param {RenderList} renderList - The current render list.
  34130. * @param {RenderContext} renderContext - The current render context.
  34131. */
  34132. update( scene, renderList, renderContext ) {
  34133. const renderer = this.renderer;
  34134. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  34135. let forceClear = false;
  34136. if ( background === null ) {
  34137. // no background settings, use clear color configuration from the renderer
  34138. renderer._clearColor.getRGB( _clearColor );
  34139. _clearColor.a = renderer._clearColor.a;
  34140. } else if ( background.isColor === true ) {
  34141. // background is an opaque color
  34142. background.getRGB( _clearColor );
  34143. _clearColor.a = 1;
  34144. forceClear = true;
  34145. } else if ( background.isNode === true ) {
  34146. const sceneData = this.get( scene );
  34147. const backgroundNode = background;
  34148. _clearColor.copy( renderer._clearColor );
  34149. let backgroundMesh = sceneData.backgroundMesh;
  34150. if ( backgroundMesh === undefined ) {
  34151. const backgroundMeshNode = vec4( backgroundNode ).mul( backgroundIntensity ).context( {
  34152. // @TODO: Add Texture2D support using node context
  34153. getUV: () => backgroundRotation.mul( normalWorldGeometry ),
  34154. getTextureLevel: () => backgroundBlurriness
  34155. } );
  34156. // when using orthographic cameras, we must scale the skybox sphere
  34157. // up to exceed the dimensions of the camera's viewing box.
  34158. const isOrtho = cameraProjectionMatrix.element( 3 ).element( 3 ).equal( 1.0 );
  34159. // calculate the orthographic scale
  34160. // projectionMatrix[1][1] is (1 / top). Invert it to get the height and multiply by 3.0
  34161. // (an arbitrary safety factor) to ensure the skybox is large enough to cover the corners
  34162. // of the rectangular screen
  34163. const orthoScale = div( 1.0, cameraProjectionMatrix.element( 1 ).element( 1 ) ).mul( 3.0 );
  34164. // compute vertex position
  34165. const modifiedPosition = isOrtho.select( positionLocal.mul( orthoScale ), positionLocal );
  34166. let viewProj = cameraProjectionMatrix.mul( modelViewMatrix.mul( vec4( modifiedPosition, 1.0 ) ) );
  34167. // force background to far plane so it does not occlude objects
  34168. viewProj = viewProj.setZ( viewProj.w );
  34169. const nodeMaterial = new NodeMaterial();
  34170. nodeMaterial.name = 'Background.material';
  34171. nodeMaterial.side = BackSide;
  34172. nodeMaterial.depthTest = false;
  34173. nodeMaterial.depthWrite = false;
  34174. nodeMaterial.allowOverride = false;
  34175. nodeMaterial.fog = false;
  34176. nodeMaterial.lights = false;
  34177. nodeMaterial.vertexNode = viewProj;
  34178. nodeMaterial.colorNode = backgroundMeshNode;
  34179. sceneData.backgroundMeshNode = backgroundMeshNode;
  34180. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  34181. backgroundMesh.frustumCulled = false;
  34182. backgroundMesh.name = 'Background.mesh';
  34183. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  34184. this.matrixWorld.copyPosition( camera.matrixWorld );
  34185. };
  34186. function onBackgroundDispose() {
  34187. background.removeEventListener( 'dispose', onBackgroundDispose );
  34188. backgroundMesh.material.dispose();
  34189. backgroundMesh.geometry.dispose();
  34190. }
  34191. background.addEventListener( 'dispose', onBackgroundDispose );
  34192. }
  34193. const backgroundCacheKey = backgroundNode.getCacheKey();
  34194. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  34195. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  34196. sceneData.backgroundMeshNode.needsUpdate = true;
  34197. backgroundMesh.material.needsUpdate = true;
  34198. sceneData.backgroundCacheKey = backgroundCacheKey;
  34199. }
  34200. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  34201. } else {
  34202. error( 'Renderer: Unsupported background configuration.', background );
  34203. }
  34204. //
  34205. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  34206. if ( environmentBlendMode === 'additive' ) {
  34207. _clearColor.set( 0, 0, 0, 1 );
  34208. } else if ( environmentBlendMode === 'alpha-blend' ) {
  34209. _clearColor.set( 0, 0, 0, 0 );
  34210. }
  34211. //
  34212. if ( renderer.autoClear === true || forceClear === true ) {
  34213. const clearColorValue = renderContext.clearColorValue;
  34214. clearColorValue.r = _clearColor.r;
  34215. clearColorValue.g = _clearColor.g;
  34216. clearColorValue.b = _clearColor.b;
  34217. clearColorValue.a = _clearColor.a;
  34218. // premultiply alpha
  34219. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  34220. clearColorValue.r *= clearColorValue.a;
  34221. clearColorValue.g *= clearColorValue.a;
  34222. clearColorValue.b *= clearColorValue.a;
  34223. }
  34224. //
  34225. renderContext.depthClearValue = renderer._clearDepth;
  34226. renderContext.stencilClearValue = renderer._clearStencil;
  34227. renderContext.clearColor = renderer.autoClearColor === true;
  34228. renderContext.clearDepth = renderer.autoClearDepth === true;
  34229. renderContext.clearStencil = renderer.autoClearStencil === true;
  34230. } else {
  34231. renderContext.clearColor = false;
  34232. renderContext.clearDepth = false;
  34233. renderContext.clearStencil = false;
  34234. }
  34235. }
  34236. }
  34237. let _id$7 = 0;
  34238. /**
  34239. * A bind group represents a collection of bindings and thus a collection
  34240. * or resources. Bind groups are assigned to pipelines to provide them
  34241. * with the required resources (like uniform buffers or textures).
  34242. *
  34243. * @private
  34244. */
  34245. class BindGroup {
  34246. /**
  34247. * Constructs a new bind group.
  34248. *
  34249. * @param {string} name - The bind group's name.
  34250. * @param {Array<Binding>} bindings - An array of bindings.
  34251. * @param {number} index - The group index.
  34252. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  34253. */
  34254. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  34255. /**
  34256. * The bind group's name.
  34257. *
  34258. * @type {string}
  34259. */
  34260. this.name = name;
  34261. /**
  34262. * An array of bindings.
  34263. *
  34264. * @type {Array<Binding>}
  34265. */
  34266. this.bindings = bindings;
  34267. /**
  34268. * The group index.
  34269. *
  34270. * @type {number}
  34271. */
  34272. this.index = index;
  34273. /**
  34274. * An array of reference bindings.
  34275. *
  34276. * @type {Array<Binding>}
  34277. */
  34278. this.bindingsReference = bindingsReference;
  34279. /**
  34280. * The group's ID.
  34281. *
  34282. * @type {number}
  34283. */
  34284. this.id = _id$7 ++;
  34285. }
  34286. }
  34287. /**
  34288. * This module represents the state of a node builder after it was
  34289. * used to build the nodes for a render object. The state holds the
  34290. * results of the build for further processing in the renderer.
  34291. *
  34292. * Render objects with identical cache keys share the same node builder state.
  34293. *
  34294. * @private
  34295. */
  34296. class NodeBuilderState {
  34297. /**
  34298. * Constructs a new node builder state.
  34299. *
  34300. * @param {string} vertexShader - The native vertex shader code.
  34301. * @param {string} fragmentShader - The native fragment shader code.
  34302. * @param {string} computeShader - The native compute shader code.
  34303. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  34304. * @param {Array<BindGroup>} bindings - An array of bind groups.
  34305. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  34306. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  34307. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  34308. * @param {NodeMaterialObserver} observer - A node material observer.
  34309. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  34310. */
  34311. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  34312. /**
  34313. * The native vertex shader code.
  34314. *
  34315. * @type {string}
  34316. */
  34317. this.vertexShader = vertexShader;
  34318. /**
  34319. * The native fragment shader code.
  34320. *
  34321. * @type {string}
  34322. */
  34323. this.fragmentShader = fragmentShader;
  34324. /**
  34325. * The native compute shader code.
  34326. *
  34327. * @type {string}
  34328. */
  34329. this.computeShader = computeShader;
  34330. /**
  34331. * An array with transform attribute objects.
  34332. * Only relevant when using compute shaders with WebGL 2.
  34333. *
  34334. * @type {Array<Object>}
  34335. */
  34336. this.transforms = transforms;
  34337. /**
  34338. * An array of node attributes representing
  34339. * the attributes of the shaders.
  34340. *
  34341. * @type {Array<NodeAttribute>}
  34342. */
  34343. this.nodeAttributes = nodeAttributes;
  34344. /**
  34345. * An array of bind groups representing the uniform or storage
  34346. * buffers, texture or samplers of the shader.
  34347. *
  34348. * @type {Array<BindGroup>}
  34349. */
  34350. this.bindings = bindings;
  34351. /**
  34352. * An array of nodes that implement their `update()` method.
  34353. *
  34354. * @type {Array<Node>}
  34355. */
  34356. this.updateNodes = updateNodes;
  34357. /**
  34358. * An array of nodes that implement their `updateBefore()` method.
  34359. *
  34360. * @type {Array<Node>}
  34361. */
  34362. this.updateBeforeNodes = updateBeforeNodes;
  34363. /**
  34364. * An array of nodes that implement their `updateAfter()` method.
  34365. *
  34366. * @type {Array<Node>}
  34367. */
  34368. this.updateAfterNodes = updateAfterNodes;
  34369. /**
  34370. * A node material observer.
  34371. *
  34372. * @type {NodeMaterialObserver}
  34373. */
  34374. this.observer = observer;
  34375. /**
  34376. * How often this state is used by render objects.
  34377. *
  34378. * @type {number}
  34379. */
  34380. this.usedTimes = 0;
  34381. }
  34382. /**
  34383. * This method is used to create a array of bind groups based
  34384. * on the existing bind groups of this state. Shared groups are
  34385. * not cloned.
  34386. *
  34387. * @return {Array<BindGroup>} A array of bind groups.
  34388. */
  34389. createBindings() {
  34390. const bindings = [];
  34391. for ( const instanceGroup of this.bindings ) {
  34392. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  34393. if ( shared !== true ) {
  34394. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup.bindingsReference );
  34395. bindings.push( bindingsGroup );
  34396. for ( const instanceBinding of instanceGroup.bindings ) {
  34397. bindingsGroup.bindings.push( instanceBinding.clone() );
  34398. }
  34399. } else {
  34400. bindings.push( instanceGroup );
  34401. }
  34402. }
  34403. return bindings;
  34404. }
  34405. }
  34406. /**
  34407. * {@link NodeBuilder} is going to create instances of this class during the build process
  34408. * of nodes. They represent the final shader attributes that are going to be generated
  34409. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  34410. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  34411. */
  34412. class NodeAttribute {
  34413. /**
  34414. * Constructs a new node attribute.
  34415. *
  34416. * @param {string} name - The name of the attribute.
  34417. * @param {string} type - The type of the attribute.
  34418. * @param {?Node} node - An optional reference to the node.
  34419. */
  34420. constructor( name, type, node = null ) {
  34421. /**
  34422. * This flag can be used for type testing.
  34423. *
  34424. * @type {boolean}
  34425. * @readonly
  34426. * @default true
  34427. */
  34428. this.isNodeAttribute = true;
  34429. /**
  34430. * The name of the attribute.
  34431. *
  34432. * @type {string}
  34433. */
  34434. this.name = name;
  34435. /**
  34436. * The type of the attribute.
  34437. *
  34438. * @type {string}
  34439. */
  34440. this.type = type;
  34441. /**
  34442. * An optional reference to the node.
  34443. *
  34444. * @type {?Node}
  34445. * @default null
  34446. */
  34447. this.node = node;
  34448. }
  34449. }
  34450. /**
  34451. * {@link NodeBuilder} is going to create instances of this class during the build process
  34452. * of nodes. They represent the final shader uniforms that are going to be generated
  34453. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  34454. * for this purpose.
  34455. */
  34456. class NodeUniform {
  34457. /**
  34458. * Constructs a new node uniform.
  34459. *
  34460. * @param {string} name - The name of the uniform.
  34461. * @param {string} type - The type of the uniform.
  34462. * @param {UniformNode} node - An reference to the node.
  34463. */
  34464. constructor( name, type, node ) {
  34465. /**
  34466. * This flag can be used for type testing.
  34467. *
  34468. * @type {boolean}
  34469. * @readonly
  34470. * @default true
  34471. */
  34472. this.isNodeUniform = true;
  34473. /**
  34474. * The name of the uniform.
  34475. *
  34476. * @type {string}
  34477. */
  34478. this.name = name;
  34479. /**
  34480. * The type of the uniform.
  34481. *
  34482. * @type {string}
  34483. */
  34484. this.type = type;
  34485. /**
  34486. * An reference to the node.
  34487. *
  34488. * @type {UniformNode}
  34489. */
  34490. this.node = node;
  34491. }
  34492. /**
  34493. * The value of the uniform node.
  34494. *
  34495. * @type {any}
  34496. */
  34497. get value() {
  34498. return this.node.value;
  34499. }
  34500. set value( val ) {
  34501. this.node.value = val;
  34502. }
  34503. /**
  34504. * The id of the uniform node.
  34505. *
  34506. * @type {number}
  34507. */
  34508. get id() {
  34509. return this.node.id;
  34510. }
  34511. /**
  34512. * The uniform node's group.
  34513. *
  34514. * @type {UniformGroupNode}
  34515. */
  34516. get groupNode() {
  34517. return this.node.groupNode;
  34518. }
  34519. }
  34520. /**
  34521. * {@link NodeBuilder} is going to create instances of this class during the build process
  34522. * of nodes. They represent the final shader variables that are going to be generated
  34523. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  34524. * this purpose.
  34525. */
  34526. class NodeVar {
  34527. /**
  34528. * Constructs a new node variable.
  34529. *
  34530. * @param {string} name - The name of the variable.
  34531. * @param {string} type - The type of the variable.
  34532. * @param {boolean} [readOnly=false] - The read-only flag.
  34533. * @param {?number} [count=null] - The size.
  34534. */
  34535. constructor( name, type, readOnly = false, count = null ) {
  34536. /**
  34537. * This flag can be used for type testing.
  34538. *
  34539. * @type {boolean}
  34540. * @readonly
  34541. * @default true
  34542. */
  34543. this.isNodeVar = true;
  34544. /**
  34545. * The name of the variable.
  34546. *
  34547. * @type {string}
  34548. */
  34549. this.name = name;
  34550. /**
  34551. * The type of the variable.
  34552. *
  34553. * @type {string}
  34554. */
  34555. this.type = type;
  34556. /**
  34557. * The read-only flag.
  34558. *
  34559. * @type {boolean}
  34560. */
  34561. this.readOnly = readOnly;
  34562. /**
  34563. * The size.
  34564. *
  34565. * @type {?number}
  34566. */
  34567. this.count = count;
  34568. }
  34569. }
  34570. /**
  34571. * {@link NodeBuilder} is going to create instances of this class during the build process
  34572. * of nodes. They represent the final shader varyings that are going to be generated
  34573. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  34574. * this purpose.
  34575. *
  34576. * @augments NodeVar
  34577. */
  34578. class NodeVarying extends NodeVar {
  34579. /**
  34580. * Constructs a new node varying.
  34581. *
  34582. * @param {string} name - The name of the varying.
  34583. * @param {string} type - The type of the varying.
  34584. * @param {?string} interpolationType - The interpolation type of the varying.
  34585. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  34586. */
  34587. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  34588. super( name, type );
  34589. /**
  34590. * Whether this varying requires interpolation or not. This property can be used
  34591. * to check if the varying can be optimized for a variable.
  34592. *
  34593. * @type {boolean}
  34594. * @default false
  34595. */
  34596. this.needsInterpolation = false;
  34597. /**
  34598. * This flag can be used for type testing.
  34599. *
  34600. * @type {boolean}
  34601. * @readonly
  34602. * @default true
  34603. */
  34604. this.isNodeVarying = true;
  34605. /**
  34606. * The interpolation type of the varying data.
  34607. *
  34608. * @type {?string}
  34609. * @default null
  34610. */
  34611. this.interpolationType = interpolationType;
  34612. /**
  34613. * The interpolation sampling type of varying data.
  34614. *
  34615. * @type {?string}
  34616. * @default null
  34617. */
  34618. this.interpolationSampling = interpolationSampling;
  34619. }
  34620. }
  34621. /**
  34622. * {@link NodeBuilder} is going to create instances of this class during the build process
  34623. * of nodes. They represent user-defined, native shader code portions that are going to be
  34624. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  34625. * for this purpose.
  34626. */
  34627. class NodeCode {
  34628. /**
  34629. * Constructs a new code node.
  34630. *
  34631. * @param {string} name - The name of the code.
  34632. * @param {string} type - The node type.
  34633. * @param {string} [code=''] - The native shader code.
  34634. */
  34635. constructor( name, type, code = '' ) {
  34636. /**
  34637. * The name of the code.
  34638. *
  34639. * @type {string}
  34640. */
  34641. this.name = name;
  34642. /**
  34643. * The node type.
  34644. *
  34645. * @type {string}
  34646. */
  34647. this.type = type;
  34648. /**
  34649. * The native shader code.
  34650. *
  34651. * @type {string}
  34652. * @default ''
  34653. */
  34654. this.code = code;
  34655. Object.defineProperty( this, 'isNodeCode', { value: true } );
  34656. }
  34657. }
  34658. let _id$6 = 0;
  34659. /**
  34660. * This utility class is used in {@link NodeBuilder} as an internal
  34661. * cache data structure for node data.
  34662. */
  34663. class NodeCache {
  34664. /**
  34665. * Constructs a new node cache.
  34666. *
  34667. * @param {?NodeCache} parent - A reference to a parent cache.
  34668. */
  34669. constructor( parent = null ) {
  34670. /**
  34671. * The id of the cache.
  34672. *
  34673. * @type {number}
  34674. * @readonly
  34675. */
  34676. this.id = _id$6 ++;
  34677. /**
  34678. * A weak map for managing node data.
  34679. *
  34680. * @type {WeakMap<Node, Object>}
  34681. */
  34682. this.nodesData = new WeakMap();
  34683. /**
  34684. * Reference to a parent node cache.
  34685. *
  34686. * @type {?NodeCache}
  34687. * @default null
  34688. */
  34689. this.parent = parent;
  34690. }
  34691. /**
  34692. * Returns the data for the given node.
  34693. *
  34694. * @param {Node} node - The node.
  34695. * @return {?Object} The data for the node.
  34696. */
  34697. getData( node ) {
  34698. let data = this.nodesData.get( node );
  34699. if ( data === undefined && this.parent !== null ) {
  34700. data = this.parent.getData( node );
  34701. }
  34702. return data;
  34703. }
  34704. /**
  34705. * Sets the data for a given node.
  34706. *
  34707. * @param {Node} node - The node.
  34708. * @param {Object} data - The data that should be cached.
  34709. */
  34710. setData( node, data ) {
  34711. this.nodesData.set( node, data );
  34712. }
  34713. }
  34714. class StructType {
  34715. constructor( name, members ) {
  34716. this.name = name;
  34717. this.members = members;
  34718. this.output = false;
  34719. }
  34720. }
  34721. /**
  34722. * Abstract base class for uniforms.
  34723. *
  34724. * @abstract
  34725. * @private
  34726. */
  34727. class Uniform {
  34728. /**
  34729. * Constructs a new uniform.
  34730. *
  34731. * @param {string} name - The uniform's name.
  34732. * @param {any} value - The uniform's value.
  34733. */
  34734. constructor( name, value ) {
  34735. /**
  34736. * The uniform's name.
  34737. *
  34738. * @type {string}
  34739. */
  34740. this.name = name;
  34741. /**
  34742. * The uniform's value.
  34743. *
  34744. * @type {any}
  34745. */
  34746. this.value = value;
  34747. /**
  34748. * Used to build the uniform buffer according to the STD140 layout.
  34749. * Derived uniforms will set this property to a data type specific
  34750. * value.
  34751. *
  34752. * @type {number}
  34753. */
  34754. this.boundary = 0;
  34755. /**
  34756. * The item size. Derived uniforms will set this property to a data
  34757. * type specific value.
  34758. *
  34759. * @type {number}
  34760. */
  34761. this.itemSize = 0;
  34762. /**
  34763. * This property is set by {@link UniformsGroup} and marks
  34764. * the start position in the uniform buffer.
  34765. *
  34766. * @type {number}
  34767. */
  34768. this.offset = 0;
  34769. }
  34770. /**
  34771. * Sets the uniform's value.
  34772. *
  34773. * @param {any} value - The value to set.
  34774. */
  34775. setValue( value ) {
  34776. this.value = value;
  34777. }
  34778. /**
  34779. * Returns the uniform's value.
  34780. *
  34781. * @return {any} The value.
  34782. */
  34783. getValue() {
  34784. return this.value;
  34785. }
  34786. }
  34787. /**
  34788. * Represents a Number uniform.
  34789. *
  34790. * @private
  34791. * @augments Uniform
  34792. */
  34793. class NumberUniform extends Uniform {
  34794. /**
  34795. * Constructs a new Number uniform.
  34796. *
  34797. * @param {string} name - The uniform's name.
  34798. * @param {number} value - The uniform's value.
  34799. */
  34800. constructor( name, value = 0 ) {
  34801. super( name, value );
  34802. /**
  34803. * This flag can be used for type testing.
  34804. *
  34805. * @type {boolean}
  34806. * @readonly
  34807. * @default true
  34808. */
  34809. this.isNumberUniform = true;
  34810. this.boundary = 4;
  34811. this.itemSize = 1;
  34812. }
  34813. }
  34814. /**
  34815. * Represents a Vector2 uniform.
  34816. *
  34817. * @private
  34818. * @augments Uniform
  34819. */
  34820. class Vector2Uniform extends Uniform {
  34821. /**
  34822. * Constructs a new Number uniform.
  34823. *
  34824. * @param {string} name - The uniform's name.
  34825. * @param {Vector2} value - The uniform's value.
  34826. */
  34827. constructor( name, value = new Vector2() ) {
  34828. super( name, value );
  34829. /**
  34830. * This flag can be used for type testing.
  34831. *
  34832. * @type {boolean}
  34833. * @readonly
  34834. * @default true
  34835. */
  34836. this.isVector2Uniform = true;
  34837. this.boundary = 8;
  34838. this.itemSize = 2;
  34839. }
  34840. }
  34841. /**
  34842. * Represents a Vector3 uniform.
  34843. *
  34844. * @private
  34845. * @augments Uniform
  34846. */
  34847. class Vector3Uniform extends Uniform {
  34848. /**
  34849. * Constructs a new Number uniform.
  34850. *
  34851. * @param {string} name - The uniform's name.
  34852. * @param {Vector3} value - The uniform's value.
  34853. */
  34854. constructor( name, value = new Vector3() ) {
  34855. super( name, value );
  34856. /**
  34857. * This flag can be used for type testing.
  34858. *
  34859. * @type {boolean}
  34860. * @readonly
  34861. * @default true
  34862. */
  34863. this.isVector3Uniform = true;
  34864. this.boundary = 16;
  34865. this.itemSize = 3;
  34866. }
  34867. }
  34868. /**
  34869. * Represents a Vector4 uniform.
  34870. *
  34871. * @private
  34872. * @augments Uniform
  34873. */
  34874. class Vector4Uniform extends Uniform {
  34875. /**
  34876. * Constructs a new Number uniform.
  34877. *
  34878. * @param {string} name - The uniform's name.
  34879. * @param {Vector4} value - The uniform's value.
  34880. */
  34881. constructor( name, value = new Vector4() ) {
  34882. super( name, value );
  34883. /**
  34884. * This flag can be used for type testing.
  34885. *
  34886. * @type {boolean}
  34887. * @readonly
  34888. * @default true
  34889. */
  34890. this.isVector4Uniform = true;
  34891. this.boundary = 16;
  34892. this.itemSize = 4;
  34893. }
  34894. }
  34895. /**
  34896. * Represents a Color uniform.
  34897. *
  34898. * @private
  34899. * @augments Uniform
  34900. */
  34901. class ColorUniform extends Uniform {
  34902. /**
  34903. * Constructs a new Number uniform.
  34904. *
  34905. * @param {string} name - The uniform's name.
  34906. * @param {Color} value - The uniform's value.
  34907. */
  34908. constructor( name, value = new Color() ) {
  34909. super( name, value );
  34910. /**
  34911. * This flag can be used for type testing.
  34912. *
  34913. * @type {boolean}
  34914. * @readonly
  34915. * @default true
  34916. */
  34917. this.isColorUniform = true;
  34918. this.boundary = 16;
  34919. this.itemSize = 3;
  34920. }
  34921. }
  34922. /**
  34923. * Represents a Matrix2 uniform.
  34924. *
  34925. * @private
  34926. * @augments Uniform
  34927. */
  34928. class Matrix2Uniform extends Uniform {
  34929. /**
  34930. * Constructs a new Number uniform.
  34931. *
  34932. * @param {string} name - The uniform's name.
  34933. * @param {Matrix2} value - The uniform's value.
  34934. */
  34935. constructor( name, value = new Matrix2() ) {
  34936. super( name, value );
  34937. /**
  34938. * This flag can be used for type testing.
  34939. *
  34940. * @type {boolean}
  34941. * @readonly
  34942. * @default true
  34943. */
  34944. this.isMatrix2Uniform = true;
  34945. this.boundary = 8;
  34946. this.itemSize = 4;
  34947. }
  34948. }
  34949. /**
  34950. * Represents a Matrix3 uniform.
  34951. *
  34952. * @private
  34953. * @augments Uniform
  34954. */
  34955. class Matrix3Uniform extends Uniform {
  34956. /**
  34957. * Constructs a new Number uniform.
  34958. *
  34959. * @param {string} name - The uniform's name.
  34960. * @param {Matrix3} value - The uniform's value.
  34961. */
  34962. constructor( name, value = new Matrix3() ) {
  34963. super( name, value );
  34964. /**
  34965. * This flag can be used for type testing.
  34966. *
  34967. * @type {boolean}
  34968. * @readonly
  34969. * @default true
  34970. */
  34971. this.isMatrix3Uniform = true;
  34972. this.boundary = 48;
  34973. this.itemSize = 12;
  34974. }
  34975. }
  34976. /**
  34977. * Represents a Matrix4 uniform.
  34978. *
  34979. * @private
  34980. * @augments Uniform
  34981. */
  34982. class Matrix4Uniform extends Uniform {
  34983. /**
  34984. * Constructs a new Number uniform.
  34985. *
  34986. * @param {string} name - The uniform's name.
  34987. * @param {Matrix4} value - The uniform's value.
  34988. */
  34989. constructor( name, value = new Matrix4() ) {
  34990. super( name, value );
  34991. /**
  34992. * This flag can be used for type testing.
  34993. *
  34994. * @type {boolean}
  34995. * @readonly
  34996. * @default true
  34997. */
  34998. this.isMatrix4Uniform = true;
  34999. this.boundary = 64;
  35000. this.itemSize = 16;
  35001. }
  35002. }
  35003. /**
  35004. * A special form of Number uniform binding type.
  35005. * It's value is managed by a node object.
  35006. *
  35007. * @private
  35008. * @augments NumberUniform
  35009. */
  35010. class NumberNodeUniform extends NumberUniform {
  35011. /**
  35012. * Constructs a new node-based Number uniform.
  35013. *
  35014. * @param {NodeUniform} nodeUniform - The node uniform.
  35015. */
  35016. constructor( nodeUniform ) {
  35017. super( nodeUniform.name, nodeUniform.value );
  35018. /**
  35019. * The node uniform.
  35020. *
  35021. * @type {NodeUniform}
  35022. */
  35023. this.nodeUniform = nodeUniform;
  35024. }
  35025. /**
  35026. * Overwritten to return the value of the node uniform.
  35027. *
  35028. * @return {number} The value.
  35029. */
  35030. getValue() {
  35031. return this.nodeUniform.value;
  35032. }
  35033. /**
  35034. * Returns the node uniform data type.
  35035. *
  35036. * @return {string} The data type.
  35037. */
  35038. getType() {
  35039. return this.nodeUniform.type;
  35040. }
  35041. }
  35042. /**
  35043. * A special form of Vector2 uniform binding type.
  35044. * It's value is managed by a node object.
  35045. *
  35046. * @private
  35047. * @augments Vector2Uniform
  35048. */
  35049. class Vector2NodeUniform extends Vector2Uniform {
  35050. /**
  35051. * Constructs a new node-based Vector2 uniform.
  35052. *
  35053. * @param {NodeUniform} nodeUniform - The node uniform.
  35054. */
  35055. constructor( nodeUniform ) {
  35056. super( nodeUniform.name, nodeUniform.value );
  35057. /**
  35058. * The node uniform.
  35059. *
  35060. * @type {NodeUniform}
  35061. */
  35062. this.nodeUniform = nodeUniform;
  35063. }
  35064. /**
  35065. * Overwritten to return the value of the node uniform.
  35066. *
  35067. * @return {Vector2} The value.
  35068. */
  35069. getValue() {
  35070. return this.nodeUniform.value;
  35071. }
  35072. /**
  35073. * Returns the node uniform data type.
  35074. *
  35075. * @return {string} The data type.
  35076. */
  35077. getType() {
  35078. return this.nodeUniform.type;
  35079. }
  35080. }
  35081. /**
  35082. * A special form of Vector3 uniform binding type.
  35083. * It's value is managed by a node object.
  35084. *
  35085. * @private
  35086. * @augments Vector3Uniform
  35087. */
  35088. class Vector3NodeUniform extends Vector3Uniform {
  35089. /**
  35090. * Constructs a new node-based Vector3 uniform.
  35091. *
  35092. * @param {NodeUniform} nodeUniform - The node uniform.
  35093. */
  35094. constructor( nodeUniform ) {
  35095. super( nodeUniform.name, nodeUniform.value );
  35096. /**
  35097. * The node uniform.
  35098. *
  35099. * @type {NodeUniform}
  35100. */
  35101. this.nodeUniform = nodeUniform;
  35102. }
  35103. /**
  35104. * Overwritten to return the value of the node uniform.
  35105. *
  35106. * @return {Vector3} The value.
  35107. */
  35108. getValue() {
  35109. return this.nodeUniform.value;
  35110. }
  35111. /**
  35112. * Returns the node uniform data type.
  35113. *
  35114. * @return {string} The data type.
  35115. */
  35116. getType() {
  35117. return this.nodeUniform.type;
  35118. }
  35119. }
  35120. /**
  35121. * A special form of Vector4 uniform binding type.
  35122. * It's value is managed by a node object.
  35123. *
  35124. * @private
  35125. * @augments Vector4Uniform
  35126. */
  35127. class Vector4NodeUniform extends Vector4Uniform {
  35128. /**
  35129. * Constructs a new node-based Vector4 uniform.
  35130. *
  35131. * @param {NodeUniform} nodeUniform - The node uniform.
  35132. */
  35133. constructor( nodeUniform ) {
  35134. super( nodeUniform.name, nodeUniform.value );
  35135. /**
  35136. * The node uniform.
  35137. *
  35138. * @type {NodeUniform}
  35139. */
  35140. this.nodeUniform = nodeUniform;
  35141. }
  35142. /**
  35143. * Overwritten to return the value of the node uniform.
  35144. *
  35145. * @return {Vector4} The value.
  35146. */
  35147. getValue() {
  35148. return this.nodeUniform.value;
  35149. }
  35150. /**
  35151. * Returns the node uniform data type.
  35152. *
  35153. * @return {string} The data type.
  35154. */
  35155. getType() {
  35156. return this.nodeUniform.type;
  35157. }
  35158. }
  35159. /**
  35160. * A special form of Color uniform binding type.
  35161. * It's value is managed by a node object.
  35162. *
  35163. * @private
  35164. * @augments ColorUniform
  35165. */
  35166. class ColorNodeUniform extends ColorUniform {
  35167. /**
  35168. * Constructs a new node-based Color uniform.
  35169. *
  35170. * @param {NodeUniform} nodeUniform - The node uniform.
  35171. */
  35172. constructor( nodeUniform ) {
  35173. super( nodeUniform.name, nodeUniform.value );
  35174. /**
  35175. * The node uniform.
  35176. *
  35177. * @type {NodeUniform}
  35178. */
  35179. this.nodeUniform = nodeUniform;
  35180. }
  35181. /**
  35182. * Overwritten to return the value of the node uniform.
  35183. *
  35184. * @return {Color} The value.
  35185. */
  35186. getValue() {
  35187. return this.nodeUniform.value;
  35188. }
  35189. /**
  35190. * Returns the node uniform data type.
  35191. *
  35192. * @return {string} The data type.
  35193. */
  35194. getType() {
  35195. return this.nodeUniform.type;
  35196. }
  35197. }
  35198. /**
  35199. * A special form of Matrix2 uniform binding type.
  35200. * It's value is managed by a node object.
  35201. *
  35202. * @private
  35203. * @augments Matrix2Uniform
  35204. */
  35205. class Matrix2NodeUniform extends Matrix2Uniform {
  35206. /**
  35207. * Constructs a new node-based Matrix2 uniform.
  35208. *
  35209. * @param {NodeUniform} nodeUniform - The node uniform.
  35210. */
  35211. constructor( nodeUniform ) {
  35212. super( nodeUniform.name, nodeUniform.value );
  35213. /**
  35214. * The node uniform.
  35215. *
  35216. * @type {NodeUniform}
  35217. */
  35218. this.nodeUniform = nodeUniform;
  35219. }
  35220. /**
  35221. * Overwritten to return the value of the node uniform.
  35222. *
  35223. * @return {Matrix2} The value.
  35224. */
  35225. getValue() {
  35226. return this.nodeUniform.value;
  35227. }
  35228. /**
  35229. * Returns the node uniform data type.
  35230. *
  35231. * @return {string} The data type.
  35232. */
  35233. getType() {
  35234. return this.nodeUniform.type;
  35235. }
  35236. }
  35237. /**
  35238. * A special form of Matrix3 uniform binding type.
  35239. * It's value is managed by a node object.
  35240. *
  35241. * @private
  35242. * @augments Matrix3Uniform
  35243. */
  35244. class Matrix3NodeUniform extends Matrix3Uniform {
  35245. /**
  35246. * Constructs a new node-based Matrix3 uniform.
  35247. *
  35248. * @param {NodeUniform} nodeUniform - The node uniform.
  35249. */
  35250. constructor( nodeUniform ) {
  35251. super( nodeUniform.name, nodeUniform.value );
  35252. /**
  35253. * The node uniform.
  35254. *
  35255. * @type {NodeUniform}
  35256. */
  35257. this.nodeUniform = nodeUniform;
  35258. }
  35259. /**
  35260. * Overwritten to return the value of the node uniform.
  35261. *
  35262. * @return {Matrix3} The value.
  35263. */
  35264. getValue() {
  35265. return this.nodeUniform.value;
  35266. }
  35267. /**
  35268. * Returns the node uniform data type.
  35269. *
  35270. * @return {string} The data type.
  35271. */
  35272. getType() {
  35273. return this.nodeUniform.type;
  35274. }
  35275. }
  35276. /**
  35277. * A special form of Matrix4 uniform binding type.
  35278. * It's value is managed by a node object.
  35279. *
  35280. * @private
  35281. * @augments Matrix4Uniform
  35282. */
  35283. class Matrix4NodeUniform extends Matrix4Uniform {
  35284. /**
  35285. * Constructs a new node-based Matrix4 uniform.
  35286. *
  35287. * @param {NodeUniform} nodeUniform - The node uniform.
  35288. */
  35289. constructor( nodeUniform ) {
  35290. super( nodeUniform.name, nodeUniform.value );
  35291. /**
  35292. * The node uniform.
  35293. *
  35294. * @type {NodeUniform}
  35295. */
  35296. this.nodeUniform = nodeUniform;
  35297. }
  35298. /**
  35299. * Overwritten to return the value of the node uniform.
  35300. *
  35301. * @return {Matrix4} The value.
  35302. */
  35303. getValue() {
  35304. return this.nodeUniform.value;
  35305. }
  35306. /**
  35307. * Returns the node uniform data type.
  35308. *
  35309. * @return {string} The data type.
  35310. */
  35311. getType() {
  35312. return this.nodeUniform.type;
  35313. }
  35314. }
  35315. let _id$5 = 0;
  35316. const sharedNodeData = new WeakMap();
  35317. const rendererCache = new WeakMap();
  35318. const typeFromArray = new Map( [
  35319. [ Int8Array, 'int' ],
  35320. [ Int16Array, 'int' ],
  35321. [ Int32Array, 'int' ],
  35322. [ Uint8Array, 'uint' ],
  35323. [ Uint16Array, 'uint' ],
  35324. [ Uint32Array, 'uint' ],
  35325. [ Float32Array, 'float' ]
  35326. ] );
  35327. const toFloat = ( value ) => {
  35328. if ( /e/g.test( value ) ) {
  35329. return String( value ).replace( /\+/g, '' );
  35330. } else {
  35331. value = Number( value );
  35332. return value + ( value % 1 ? '' : '.0' );
  35333. }
  35334. };
  35335. /**
  35336. * Base class for builders which generate a shader program based
  35337. * on a 3D object and its node material definition.
  35338. */
  35339. class NodeBuilder {
  35340. /**
  35341. * Constructs a new node builder.
  35342. *
  35343. * @param {Object3D} object - The 3D object.
  35344. * @param {Renderer} renderer - The current renderer.
  35345. * @param {NodeParser} parser - A reference to a node parser.
  35346. */
  35347. constructor( object, renderer, parser ) {
  35348. /**
  35349. * The 3D object.
  35350. *
  35351. * @type {Object3D}
  35352. */
  35353. this.object = object;
  35354. /**
  35355. * The material of the 3D object.
  35356. *
  35357. * @type {?Material}
  35358. */
  35359. this.material = ( object && object.material ) || null;
  35360. /**
  35361. * The geometry of the 3D object.
  35362. *
  35363. * @type {?BufferGeometry}
  35364. */
  35365. this.geometry = ( object && object.geometry ) || null;
  35366. /**
  35367. * The current renderer.
  35368. *
  35369. * @type {Renderer}
  35370. */
  35371. this.renderer = renderer;
  35372. /**
  35373. * A reference to a node parser.
  35374. *
  35375. * @type {NodeParser}
  35376. */
  35377. this.parser = parser;
  35378. /**
  35379. * The scene the 3D object belongs to.
  35380. *
  35381. * @type {?Scene}
  35382. * @default null
  35383. */
  35384. this.scene = null;
  35385. /**
  35386. * The camera the 3D object is rendered with.
  35387. *
  35388. * @type {?Camera}
  35389. * @default null
  35390. */
  35391. this.camera = null;
  35392. /**
  35393. * A list of all nodes the builder is processing
  35394. * for this 3D object.
  35395. *
  35396. * @type {Array<Node>}
  35397. */
  35398. this.nodes = [];
  35399. /**
  35400. * A list of all sequential nodes.
  35401. *
  35402. * @type {Array<Node>}
  35403. */
  35404. this.sequentialNodes = [];
  35405. /**
  35406. * A list of all nodes which {@link Node#update} method should be executed.
  35407. *
  35408. * @type {Array<Node>}
  35409. */
  35410. this.updateNodes = [];
  35411. /**
  35412. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  35413. *
  35414. * @type {Array<Node>}
  35415. */
  35416. this.updateBeforeNodes = [];
  35417. /**
  35418. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  35419. *
  35420. * @type {Array<Node>}
  35421. */
  35422. this.updateAfterNodes = [];
  35423. /**
  35424. * A dictionary that assigns each node to a unique hash.
  35425. *
  35426. * @type {Object<number,Node>}
  35427. */
  35428. this.hashNodes = {};
  35429. /**
  35430. * A reference to a node material observer.
  35431. *
  35432. * @type {?NodeMaterialObserver}
  35433. * @default null
  35434. */
  35435. this.observer = null;
  35436. /**
  35437. * A reference to the current lights node.
  35438. *
  35439. * @type {?LightsNode}
  35440. * @default null
  35441. */
  35442. this.lightsNode = null;
  35443. /**
  35444. * A reference to the current environment node.
  35445. *
  35446. * @type {?Node}
  35447. * @default null
  35448. */
  35449. this.environmentNode = null;
  35450. /**
  35451. * A reference to the current fog node.
  35452. *
  35453. * @type {?Node}
  35454. * @default null
  35455. */
  35456. this.fogNode = null;
  35457. /**
  35458. * The current clipping context.
  35459. *
  35460. * @type {?ClippingContext}
  35461. */
  35462. this.clippingContext = null;
  35463. /**
  35464. * The generated vertex shader.
  35465. *
  35466. * @type {?string}
  35467. */
  35468. this.vertexShader = null;
  35469. /**
  35470. * The generated fragment shader.
  35471. *
  35472. * @type {?string}
  35473. */
  35474. this.fragmentShader = null;
  35475. /**
  35476. * The generated compute shader.
  35477. *
  35478. * @type {?string}
  35479. */
  35480. this.computeShader = null;
  35481. /**
  35482. * Nodes used in the primary flow of code generation.
  35483. *
  35484. * @type {Object<string,Array<Node>>}
  35485. */
  35486. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  35487. /**
  35488. * Nodes code from `.flowNodes`.
  35489. *
  35490. * @type {Object<string,string>}
  35491. */
  35492. this.flowCode = { vertex: '', fragment: '', compute: '' };
  35493. /**
  35494. * This dictionary holds the node uniforms of the builder.
  35495. * The uniforms are maintained in an array for each shader stage.
  35496. *
  35497. * @type {Object}
  35498. */
  35499. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  35500. /**
  35501. * This dictionary holds the output structs of the builder.
  35502. * The structs are maintained in an array for each shader stage.
  35503. *
  35504. * @type {Object}
  35505. */
  35506. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  35507. /**
  35508. * This dictionary holds the types of the builder.
  35509. *
  35510. * @type {Object}
  35511. */
  35512. this.types = { vertex: [], fragment: [], compute: [], index: 0 };
  35513. /**
  35514. * This dictionary holds the bindings for each shader stage.
  35515. *
  35516. * @type {Object}
  35517. */
  35518. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  35519. /**
  35520. * This dictionary maintains the binding indices per bind group.
  35521. *
  35522. * @type {Object}
  35523. */
  35524. this.bindingsIndexes = {};
  35525. /**
  35526. * Reference to the array of bind groups.
  35527. *
  35528. * @type {?Array<BindGroup>}
  35529. */
  35530. this.bindGroups = null;
  35531. /**
  35532. * This array holds the node attributes of this builder
  35533. * created via {@link AttributeNode}.
  35534. *
  35535. * @type {Array<NodeAttribute>}
  35536. */
  35537. this.attributes = [];
  35538. /**
  35539. * This array holds the node attributes of this builder
  35540. * created via {@link BufferAttributeNode}.
  35541. *
  35542. * @type {Array<NodeAttribute>}
  35543. */
  35544. this.bufferAttributes = [];
  35545. /**
  35546. * This array holds the node varyings of this builder.
  35547. *
  35548. * @type {Array<NodeVarying>}
  35549. */
  35550. this.varyings = [];
  35551. /**
  35552. * This dictionary holds the (native) node codes of this builder.
  35553. * The codes are maintained in an array for each shader stage.
  35554. *
  35555. * @type {Object<string,Array<NodeCode>>}
  35556. */
  35557. this.codes = {};
  35558. /**
  35559. * This dictionary holds the node variables of this builder.
  35560. * The variables are maintained in an array for each shader stage.
  35561. * This dictionary is also used to count the number of variables
  35562. * according to their type (const, vars).
  35563. *
  35564. * @type {Object<string,Array<NodeVar>|number>}
  35565. */
  35566. this.vars = {};
  35567. /**
  35568. * This dictionary holds the declarations for each shader stage.
  35569. *
  35570. * @type {Object}
  35571. */
  35572. this.declarations = {};
  35573. /**
  35574. * Current code flow.
  35575. * All code generated in this stack will be stored in `.flow`.
  35576. *
  35577. * @type {{code: string}}
  35578. */
  35579. this.flow = { code: '' };
  35580. /**
  35581. * A chain of nodes.
  35582. * Used to check recursive calls in node-graph.
  35583. *
  35584. * @type {Array<Node>}
  35585. */
  35586. this.chaining = [];
  35587. /**
  35588. * The current stack.
  35589. * This reflects the current process in the code block hierarchy,
  35590. * it is useful to know if the current process is inside a conditional for example.
  35591. *
  35592. * @type {StackNode}
  35593. */
  35594. this.stack = stack();
  35595. /**
  35596. * List of stack nodes.
  35597. * The current stack hierarchy is stored in an array.
  35598. *
  35599. * @type {Array<StackNode>}
  35600. */
  35601. this.stacks = [];
  35602. /**
  35603. * A tab value. Used for shader string generation.
  35604. *
  35605. * @type {string}
  35606. * @default '\t'
  35607. */
  35608. this.tab = '\t';
  35609. /**
  35610. * Reference to the current function node.
  35611. *
  35612. * @type {?FunctionNode}
  35613. * @default null
  35614. */
  35615. this.currentFunctionNode = null;
  35616. /**
  35617. * The builder's context.
  35618. *
  35619. * @type {Object}
  35620. */
  35621. this.context = {
  35622. material: this.material
  35623. };
  35624. /**
  35625. * The builder's cache.
  35626. *
  35627. * @type {NodeCache}
  35628. */
  35629. this.cache = new NodeCache();
  35630. /**
  35631. * Since the {@link NodeBuilder#cache} might be temporarily
  35632. * overwritten by other caches, this member retains the reference
  35633. * to the builder's own cache.
  35634. *
  35635. * @type {NodeCache}
  35636. * @default this.cache
  35637. */
  35638. this.globalCache = this.cache;
  35639. this.flowsData = new WeakMap();
  35640. /**
  35641. * The current shader stage.
  35642. *
  35643. * @type {?('vertex'|'fragment'|'compute'|'any')}
  35644. */
  35645. this.shaderStage = null;
  35646. /**
  35647. * The current build stage.
  35648. *
  35649. * @type {?('setup'|'analyze'|'generate')}
  35650. */
  35651. this.buildStage = null;
  35652. /**
  35653. * The sub-build layers.
  35654. *
  35655. * @type {Array<SubBuildNode>}
  35656. * @default []
  35657. */
  35658. this.subBuildLayers = [];
  35659. /**
  35660. * The active stack nodes.
  35661. *
  35662. * @type {Array<StackNode>}
  35663. */
  35664. this.activeStacks = [];
  35665. /**
  35666. * The current sub-build TSL function(Fn).
  35667. *
  35668. * @type {?string}
  35669. * @default null
  35670. */
  35671. this.subBuildFn = null;
  35672. /**
  35673. * The current TSL function(Fn) call node.
  35674. *
  35675. * @type {?Node}
  35676. * @default null
  35677. */
  35678. this.fnCall = null;
  35679. Object.defineProperty( this, 'id', { value: _id$5 ++ } );
  35680. }
  35681. /**
  35682. * Whether the material is opaque or not.
  35683. *
  35684. * @return {boolean} Whether the material is opaque or not.
  35685. */
  35686. isOpaque() {
  35687. const material = this.material;
  35688. return material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false;
  35689. }
  35690. /**
  35691. * Returns the bind groups of the current renderer.
  35692. *
  35693. * @return {ChainMap} The cache.
  35694. */
  35695. getBindGroupsCache() {
  35696. let bindGroupsCache = rendererCache.get( this.renderer );
  35697. if ( bindGroupsCache === undefined ) {
  35698. bindGroupsCache = new ChainMap();
  35699. rendererCache.set( this.renderer, bindGroupsCache );
  35700. }
  35701. return bindGroupsCache;
  35702. }
  35703. /**
  35704. * Factory method for creating an instance of {@link RenderTarget} with the given
  35705. * dimensions and options.
  35706. *
  35707. * @param {number} width - The width of the render target.
  35708. * @param {number} height - The height of the render target.
  35709. * @param {Object} options - The options of the render target.
  35710. * @return {RenderTarget} The render target.
  35711. */
  35712. createRenderTarget( width, height, options ) {
  35713. return new RenderTarget( width, height, options );
  35714. }
  35715. /**
  35716. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  35717. * dimensions and options.
  35718. *
  35719. * @param {number} size - The size of the cube render target.
  35720. * @param {Object} options - The options of the cube render target.
  35721. * @return {CubeRenderTarget} The cube render target.
  35722. */
  35723. createCubeRenderTarget( size, options ) {
  35724. return new CubeRenderTarget( size, options );
  35725. }
  35726. /**
  35727. * Whether the given node is included in the internal array of nodes or not.
  35728. *
  35729. * @param {Node} node - The node to test.
  35730. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  35731. */
  35732. includes( node ) {
  35733. return this.nodes.includes( node );
  35734. }
  35735. /**
  35736. * Returns the output struct name which is required by
  35737. * {@link OutputStructNode}.
  35738. *
  35739. * @abstract
  35740. * @return {string} The name of the output struct.
  35741. */
  35742. getOutputStructName() {}
  35743. /**
  35744. * Returns a bind group for the given group name and binding.
  35745. *
  35746. * @private
  35747. * @param {string} groupName - The group name.
  35748. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  35749. * @return {BindGroup} The bind group
  35750. */
  35751. _getBindGroup( groupName, bindings ) {
  35752. const bindGroupsCache = this.getBindGroupsCache();
  35753. //
  35754. const bindingsArray = [];
  35755. let sharedGroup = true;
  35756. for ( const binding of bindings ) {
  35757. bindingsArray.push( binding );
  35758. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  35759. }
  35760. //
  35761. let bindGroup;
  35762. if ( sharedGroup ) {
  35763. bindGroup = bindGroupsCache.get( bindingsArray );
  35764. if ( bindGroup === undefined ) {
  35765. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  35766. bindGroupsCache.set( bindingsArray, bindGroup );
  35767. }
  35768. } else {
  35769. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  35770. }
  35771. return bindGroup;
  35772. }
  35773. /**
  35774. * Returns an array of node uniform groups for the given group name and shader stage.
  35775. *
  35776. * @param {string} groupName - The group name.
  35777. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35778. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  35779. */
  35780. getBindGroupArray( groupName, shaderStage ) {
  35781. const bindings = this.bindings[ shaderStage ];
  35782. let bindGroup = bindings[ groupName ];
  35783. if ( bindGroup === undefined ) {
  35784. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  35785. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  35786. }
  35787. bindings[ groupName ] = bindGroup = [];
  35788. }
  35789. return bindGroup;
  35790. }
  35791. /**
  35792. * Returns a list bindings of all shader stages separated by groups.
  35793. *
  35794. * @return {Array<BindGroup>} The list of bindings.
  35795. */
  35796. getBindings() {
  35797. let bindingsGroups = this.bindGroups;
  35798. if ( bindingsGroups === null ) {
  35799. const groups = {};
  35800. const bindings = this.bindings;
  35801. for ( const shaderStage of shaderStages ) {
  35802. for ( const groupName in bindings[ shaderStage ] ) {
  35803. const uniforms = bindings[ shaderStage ][ groupName ];
  35804. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  35805. groupUniforms.push( ...uniforms );
  35806. }
  35807. }
  35808. bindingsGroups = [];
  35809. for ( const groupName in groups ) {
  35810. const group = groups[ groupName ];
  35811. const bindingsGroup = this._getBindGroup( groupName, group );
  35812. bindingsGroups.push( bindingsGroup );
  35813. }
  35814. this.bindGroups = bindingsGroups;
  35815. }
  35816. return bindingsGroups;
  35817. }
  35818. /**
  35819. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  35820. */
  35821. sortBindingGroups() {
  35822. const bindingsGroups = this.getBindings();
  35823. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  35824. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  35825. const bindingGroup = bindingsGroups[ i ];
  35826. this.bindingsIndexes[ bindingGroup.name ].group = i;
  35827. bindingGroup.index = i;
  35828. }
  35829. }
  35830. /**
  35831. * The builder maintains each node in a hash-based dictionary.
  35832. * This method sets the given node (value) with the given hash (key) into this dictionary.
  35833. *
  35834. * @param {Node} node - The node to add.
  35835. * @param {number} hash - The hash of the node.
  35836. */
  35837. setHashNode( node, hash ) {
  35838. this.hashNodes[ hash ] = node;
  35839. }
  35840. /**
  35841. * Adds a node to this builder.
  35842. *
  35843. * @param {Node} node - The node to add.
  35844. */
  35845. addNode( node ) {
  35846. if ( this.nodes.includes( node ) === false ) {
  35847. this.nodes.push( node );
  35848. this.setHashNode( node, node.getHash( this ) );
  35849. }
  35850. }
  35851. /**
  35852. * It is used to add Nodes that will be used as FRAME and RENDER events,
  35853. * and need to follow a certain sequence in the calls to work correctly.
  35854. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  35855. *
  35856. * @param {Node} node - The node to add.
  35857. */
  35858. addSequentialNode( node ) {
  35859. if ( this.sequentialNodes.includes( node ) === false ) {
  35860. this.sequentialNodes.push( node );
  35861. }
  35862. }
  35863. /**
  35864. * Checks the update types of nodes
  35865. */
  35866. buildUpdateNodes() {
  35867. for ( const node of this.nodes ) {
  35868. const updateType = node.getUpdateType();
  35869. if ( updateType !== NodeUpdateType.NONE ) {
  35870. this.updateNodes.push( node );
  35871. }
  35872. }
  35873. for ( const node of this.sequentialNodes ) {
  35874. const updateBeforeType = node.getUpdateBeforeType();
  35875. const updateAfterType = node.getUpdateAfterType();
  35876. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  35877. this.updateBeforeNodes.push( node );
  35878. }
  35879. if ( updateAfterType !== NodeUpdateType.NONE ) {
  35880. this.updateAfterNodes.push( node );
  35881. }
  35882. }
  35883. }
  35884. /**
  35885. * A reference the current node which is the
  35886. * last node in the chain of nodes.
  35887. *
  35888. * @type {Node}
  35889. */
  35890. get currentNode() {
  35891. return this.chaining[ this.chaining.length - 1 ];
  35892. }
  35893. /**
  35894. * Whether the given texture is filtered or not.
  35895. *
  35896. * @param {Texture} texture - The texture to check.
  35897. * @return {boolean} Whether the given texture is filtered or not.
  35898. */
  35899. isFilteredTexture( texture ) {
  35900. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  35901. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  35902. }
  35903. /**
  35904. * Adds the given node to the internal node chain.
  35905. * This is used to check recursive calls in node-graph.
  35906. *
  35907. * @param {Node} node - The node to add.
  35908. */
  35909. addChain( node ) {
  35910. /*
  35911. if ( this.chaining.indexOf( node ) !== - 1 ) {
  35912. warn( 'Recursive node: ', node );
  35913. }
  35914. */
  35915. this.chaining.push( node );
  35916. }
  35917. /**
  35918. * Removes the given node from the internal node chain.
  35919. *
  35920. * @param {Node} node - The node to remove.
  35921. */
  35922. removeChain( node ) {
  35923. const lastChain = this.chaining.pop();
  35924. if ( lastChain !== node ) {
  35925. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  35926. }
  35927. }
  35928. /**
  35929. * Returns the native shader method name for a given generic name. E.g.
  35930. * the method name `textureDimensions` matches the WGSL name but must be
  35931. * resolved to `textureSize` in GLSL.
  35932. *
  35933. * @abstract
  35934. * @param {string} method - The method name to resolve.
  35935. * @return {string} The resolved method name.
  35936. */
  35937. getMethod( method ) {
  35938. return method;
  35939. }
  35940. /**
  35941. * Returns the native snippet for a ternary operation. E.g. GLSL would output
  35942. * a ternary op as `cond ? x : y` whereas WGSL would output it as `select(y, x, cond)`
  35943. *
  35944. * @abstract
  35945. * @param {string} condSnippet - The condition determining which expression gets resolved.
  35946. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  35947. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  35948. * @return {string} The resolved method name.
  35949. */
  35950. getTernary( /* condSnippet, ifSnippet, elseSnippet*/ ) {
  35951. return null;
  35952. }
  35953. /**
  35954. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  35955. *
  35956. * @param {number} hash - The hash of the node.
  35957. * @return {Node} The found node.
  35958. */
  35959. getNodeFromHash( hash ) {
  35960. return this.hashNodes[ hash ];
  35961. }
  35962. /**
  35963. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  35964. *
  35965. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  35966. * @param {Node} node - The node to add.
  35967. * @return {Node} The node.
  35968. */
  35969. addFlow( shaderStage, node ) {
  35970. this.flowNodes[ shaderStage ].push( node );
  35971. return node;
  35972. }
  35973. /**
  35974. * Sets builder's context.
  35975. *
  35976. * @param {Object} context - The context to set.
  35977. */
  35978. setContext( context ) {
  35979. this.context = context;
  35980. }
  35981. /**
  35982. * Returns the builder's current context.
  35983. *
  35984. * @return {Object} The builder's current context.
  35985. */
  35986. getContext() {
  35987. return this.context;
  35988. }
  35989. /**
  35990. * Adds context data to the builder's current context.
  35991. *
  35992. * @param {Object} context - The context to add.
  35993. * @return {Object} The previous context.
  35994. */
  35995. addContext( context ) {
  35996. const previousContext = this.getContext();
  35997. this.setContext( { ...this.context, ...context } );
  35998. return previousContext;
  35999. }
  36000. /**
  36001. * Gets a context used in shader construction that can be shared across different materials.
  36002. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  36003. *
  36004. * @return {Object} The builder's current context without material.
  36005. */
  36006. getSharedContext() {
  36007. ({ ...this.context });
  36008. return this.context;
  36009. }
  36010. /**
  36011. * Sets builder's cache.
  36012. *
  36013. * @param {NodeCache} cache - The cache to set.
  36014. */
  36015. setCache( cache ) {
  36016. this.cache = cache;
  36017. }
  36018. /**
  36019. * Returns the builder's current cache.
  36020. *
  36021. * @return {NodeCache} The builder's current cache.
  36022. */
  36023. getCache() {
  36024. return this.cache;
  36025. }
  36026. /**
  36027. * Returns a cache for the given node.
  36028. *
  36029. * @param {Node} node - The node.
  36030. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  36031. * @return {NodeCache} The cache.
  36032. */
  36033. getCacheFromNode( node, parent = true ) {
  36034. const data = this.getDataFromNode( node );
  36035. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  36036. return data.cache;
  36037. }
  36038. /**
  36039. * Whether the requested feature is available or not.
  36040. *
  36041. * @abstract
  36042. * @param {string} name - The requested feature.
  36043. * @return {boolean} Whether the requested feature is supported or not.
  36044. */
  36045. isAvailable( /*name*/ ) {
  36046. return false;
  36047. }
  36048. /**
  36049. * Returns the vertexIndex input variable as a native shader string.
  36050. *
  36051. * @abstract
  36052. * @return {string} The instanceIndex shader string.
  36053. */
  36054. getVertexIndex() {
  36055. warn( 'Abstract function.' );
  36056. }
  36057. /**
  36058. * Contextually returns either the vertex stage instance index builtin
  36059. * or the linearized index of an compute invocation within a grid of workgroups.
  36060. *
  36061. * @abstract
  36062. * @return {string} The instanceIndex shader string.
  36063. */
  36064. getInstanceIndex() {
  36065. warn( 'Abstract function.' );
  36066. }
  36067. /**
  36068. * Returns the drawIndex input variable as a native shader string.
  36069. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  36070. *
  36071. * @abstract
  36072. * @return {?string} The drawIndex shader string.
  36073. */
  36074. getDrawIndex() {
  36075. warn( 'Abstract function.' );
  36076. }
  36077. /**
  36078. * Returns the frontFacing input variable as a native shader string.
  36079. *
  36080. * @abstract
  36081. * @return {string} The frontFacing shader string.
  36082. */
  36083. getFrontFacing() {
  36084. warn( 'Abstract function.' );
  36085. }
  36086. /**
  36087. * Returns the fragCoord input variable as a native shader string.
  36088. *
  36089. * @abstract
  36090. * @return {string} The fragCoord shader string.
  36091. */
  36092. getFragCoord() {
  36093. warn( 'Abstract function.' );
  36094. }
  36095. /**
  36096. * Whether to flip texture data along its vertical axis or not. WebGL needs
  36097. * this method evaluate to `true`, WebGPU to `false`.
  36098. *
  36099. * @abstract
  36100. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  36101. */
  36102. isFlipY() {
  36103. return false;
  36104. }
  36105. /**
  36106. * Calling this method increases the usage count for the given node by one.
  36107. *
  36108. * @param {Node} node - The node to increase the usage count for.
  36109. * @return {number} The updated usage count.
  36110. */
  36111. increaseUsage( node ) {
  36112. const nodeData = this.getDataFromNode( node );
  36113. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  36114. return nodeData.usageCount;
  36115. }
  36116. /**
  36117. * Generates a texture sample shader string for the given texture data.
  36118. *
  36119. * @abstract
  36120. * @param {Texture} texture - The texture.
  36121. * @param {string} textureProperty - The texture property name.
  36122. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  36123. * @return {string} The generated shader string.
  36124. */
  36125. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  36126. warn( 'Abstract function.' );
  36127. }
  36128. /**
  36129. * Generates a texture LOD shader string for the given texture data.
  36130. *
  36131. * @abstract
  36132. * @param {Texture} texture - The texture.
  36133. * @param {string} textureProperty - The texture property name.
  36134. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  36135. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  36136. * @param {string} levelSnippet - Snippet defining the mip level.
  36137. * @return {string} The generated shader string.
  36138. */
  36139. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  36140. warn( 'Abstract function.' );
  36141. }
  36142. /**
  36143. * Generates the array declaration string.
  36144. *
  36145. * @param {string} type - The type.
  36146. * @param {?number} [count] - The count.
  36147. * @return {string} The generated value as a shader string.
  36148. */
  36149. generateArrayDeclaration( type, count ) {
  36150. return this.getType( type ) + '[ ' + count + ' ]';
  36151. }
  36152. /**
  36153. * Generates the array shader string for the given type and value.
  36154. *
  36155. * @param {string} type - The type.
  36156. * @param {?number} [count] - The count.
  36157. * @param {?Array<Node>} [values=null] - The default values.
  36158. * @return {string} The generated value as a shader string.
  36159. */
  36160. generateArray( type, count, values = null ) {
  36161. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  36162. for ( let i = 0; i < count; i ++ ) {
  36163. const value = values ? values[ i ] : null;
  36164. if ( value !== null ) {
  36165. snippet += value.build( this, type );
  36166. } else {
  36167. snippet += this.generateConst( type );
  36168. }
  36169. if ( i < count - 1 ) snippet += ', ';
  36170. }
  36171. snippet += ' )';
  36172. return snippet;
  36173. }
  36174. /**
  36175. * Generates the struct shader string.
  36176. *
  36177. * @param {string} type - The type.
  36178. * @param {Array<Object>} [membersLayout] - The count.
  36179. * @param {?Array<Node>} [values=null] - The default values.
  36180. * @return {string} The generated value as a shader string.
  36181. */
  36182. generateStruct( type, membersLayout, values = null ) {
  36183. const snippets = [];
  36184. for ( const member of membersLayout ) {
  36185. const { name, type } = member;
  36186. if ( values && values[ name ] && values[ name ].isNode ) {
  36187. snippets.push( values[ name ].build( this, type ) );
  36188. } else {
  36189. snippets.push( this.generateConst( type ) );
  36190. }
  36191. }
  36192. return type + '( ' + snippets.join( ', ' ) + ' )';
  36193. }
  36194. /**
  36195. * Generates the shader string for the given type and value.
  36196. *
  36197. * @param {string} type - The type.
  36198. * @param {?any} [value=null] - The value.
  36199. * @return {string} The generated value as a shader string.
  36200. */
  36201. generateConst( type, value = null ) {
  36202. if ( value === null ) {
  36203. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  36204. else if ( type === 'bool' ) value = false;
  36205. else if ( type === 'color' ) value = new Color();
  36206. else if ( type === 'vec2' || type === 'uvec2' || type === 'ivec2' ) value = new Vector2();
  36207. else if ( type === 'vec3' || type === 'uvec3' || type === 'ivec3' ) value = new Vector3();
  36208. else if ( type === 'vec4' || type === 'uvec4' || type === 'ivec4' ) value = new Vector4();
  36209. }
  36210. if ( type === 'float' ) return toFloat( value );
  36211. if ( type === 'int' ) return `${ Math.round( value ) }`;
  36212. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  36213. if ( type === 'bool' ) return value ? 'true' : 'false';
  36214. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  36215. const typeLength = this.getTypeLength( type );
  36216. const componentType = this.getComponentType( type );
  36217. const generateConst = value => this.generateConst( componentType, value );
  36218. if ( typeLength === 2 ) {
  36219. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  36220. } else if ( typeLength === 3 ) {
  36221. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  36222. } else if ( typeLength === 4 && type !== 'mat2' ) {
  36223. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  36224. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  36225. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  36226. } else if ( typeLength > 4 ) {
  36227. return `${ this.getType( type ) }()`;
  36228. }
  36229. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  36230. }
  36231. /**
  36232. * It might be necessary to convert certain data types to different ones
  36233. * so this method can be used to hide the conversion.
  36234. *
  36235. * @param {string} type - The type.
  36236. * @return {string} The updated type.
  36237. */
  36238. getType( type ) {
  36239. if ( type === 'color' ) return 'vec3';
  36240. return type;
  36241. }
  36242. /**
  36243. * Whether the given attribute name is defined in the geometry or not.
  36244. *
  36245. * @param {string} name - The attribute name.
  36246. * @return {boolean} Whether the given attribute name is defined in the geometry.
  36247. */
  36248. hasGeometryAttribute( name ) {
  36249. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  36250. }
  36251. /**
  36252. * Returns a node attribute for the given name and type.
  36253. *
  36254. * @param {string} name - The attribute's name.
  36255. * @param {string} type - The attribute's type.
  36256. * @return {NodeAttribute} The node attribute.
  36257. */
  36258. getAttribute( name, type ) {
  36259. const attributes = this.attributes;
  36260. // find attribute
  36261. for ( const attribute of attributes ) {
  36262. if ( attribute.name === name ) {
  36263. return attribute;
  36264. }
  36265. }
  36266. // create a new if no exist
  36267. const attribute = new NodeAttribute( name, type );
  36268. this.registerDeclaration( attribute );
  36269. attributes.push( attribute );
  36270. return attribute;
  36271. }
  36272. /**
  36273. * Returns for the given node and shader stage the property name for the shader.
  36274. *
  36275. * @param {Node} node - The node.
  36276. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36277. * @return {string} The property name.
  36278. */
  36279. getPropertyName( node/*, shaderStage*/ ) {
  36280. return node.name;
  36281. }
  36282. /**
  36283. * Whether the given type is a vector type or not.
  36284. *
  36285. * @param {string} type - The type to check.
  36286. * @return {boolean} Whether the given type is a vector type or not.
  36287. */
  36288. isVector( type ) {
  36289. return /vec\d/.test( type );
  36290. }
  36291. /**
  36292. * Whether the given type is a matrix type or not.
  36293. *
  36294. * @param {string} type - The type to check.
  36295. * @return {boolean} Whether the given type is a matrix type or not.
  36296. */
  36297. isMatrix( type ) {
  36298. return /mat\d/.test( type );
  36299. }
  36300. /**
  36301. * Whether the given type is a reference type or not.
  36302. *
  36303. * @param {string} type - The type to check.
  36304. * @return {boolean} Whether the given type is a reference type or not.
  36305. */
  36306. isReference( type ) {
  36307. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  36308. }
  36309. /**
  36310. * Checks if the given texture requires a manual conversion to the working color space.
  36311. *
  36312. * @abstract
  36313. * @param {Texture} texture - The texture to check.
  36314. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  36315. */
  36316. needsToWorkingColorSpace( /*texture*/ ) {
  36317. return false;
  36318. }
  36319. /**
  36320. * Returns the component type of a given texture.
  36321. *
  36322. * @param {Texture} texture - The texture.
  36323. * @return {string} The component type.
  36324. */
  36325. getComponentTypeFromTexture( texture ) {
  36326. const type = texture.type;
  36327. if ( texture.isDataTexture ) {
  36328. if ( type === IntType ) return 'int';
  36329. if ( type === UnsignedIntType ) return 'uint';
  36330. }
  36331. return 'float';
  36332. }
  36333. /**
  36334. * Returns the element type for a given type.
  36335. *
  36336. * @param {string} type - The type.
  36337. * @return {string} The element type.
  36338. */
  36339. getElementType( type ) {
  36340. if ( type === 'mat2' ) return 'vec2';
  36341. if ( type === 'mat3' ) return 'vec3';
  36342. if ( type === 'mat4' ) return 'vec4';
  36343. return this.getComponentType( type );
  36344. }
  36345. /**
  36346. * Returns the component type for a given type.
  36347. *
  36348. * @param {string} type - The type.
  36349. * @return {string} The component type.
  36350. */
  36351. getComponentType( type ) {
  36352. type = this.getVectorType( type );
  36353. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  36354. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  36355. if ( componentType === null ) return null;
  36356. if ( componentType[ 1 ] === 'b' ) return 'bool';
  36357. if ( componentType[ 1 ] === 'i' ) return 'int';
  36358. if ( componentType[ 1 ] === 'u' ) return 'uint';
  36359. return 'float';
  36360. }
  36361. /**
  36362. * Returns the vector type for a given type.
  36363. *
  36364. * @param {string} type - The type.
  36365. * @return {string} The vector type.
  36366. */
  36367. getVectorType( type ) {
  36368. if ( type === 'color' ) return 'vec3';
  36369. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  36370. return type;
  36371. }
  36372. /**
  36373. * Returns the data type for the given the length and component type.
  36374. *
  36375. * @param {number} length - The length.
  36376. * @param {string} [componentType='float'] - The component type.
  36377. * @return {string} The type.
  36378. */
  36379. getTypeFromLength( length, componentType = 'float' ) {
  36380. if ( length === 1 ) return componentType;
  36381. let baseType = getTypeFromLength( length );
  36382. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  36383. // fix edge case for mat2x2 being same size as vec4
  36384. if ( /mat2/.test( componentType ) === true ) {
  36385. baseType = baseType.replace( 'vec', 'mat' );
  36386. }
  36387. return prefix + baseType;
  36388. }
  36389. /**
  36390. * Returns the type for a given typed array.
  36391. *
  36392. * @param {TypedArray} array - The typed array.
  36393. * @return {string} The type.
  36394. */
  36395. getTypeFromArray( array ) {
  36396. return typeFromArray.get( array.constructor );
  36397. }
  36398. /**
  36399. * Returns the type is an integer type.
  36400. *
  36401. * @param {string} type - The type.
  36402. * @return {boolean} Whether the type is an integer type or not.
  36403. */
  36404. isInteger( type ) {
  36405. return /int|uint|(i|u)vec/.test( type );
  36406. }
  36407. /**
  36408. * Returns the type for a given buffer attribute.
  36409. *
  36410. * @param {BufferAttribute} attribute - The buffer attribute.
  36411. * @return {string} The type.
  36412. */
  36413. getTypeFromAttribute( attribute ) {
  36414. let dataAttribute = attribute;
  36415. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  36416. const array = dataAttribute.array;
  36417. const itemSize = attribute.itemSize;
  36418. const normalized = attribute.normalized;
  36419. let arrayType;
  36420. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  36421. arrayType = this.getTypeFromArray( array );
  36422. }
  36423. return this.getTypeFromLength( itemSize, arrayType );
  36424. }
  36425. /**
  36426. * Returns the length for the given data type.
  36427. *
  36428. * @param {string} type - The data type.
  36429. * @return {number} The length.
  36430. */
  36431. getTypeLength( type ) {
  36432. const vecType = this.getVectorType( type );
  36433. const vecNum = /vec([2-4])/.exec( vecType );
  36434. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  36435. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  36436. if ( /mat2/.test( type ) === true ) return 4;
  36437. if ( /mat3/.test( type ) === true ) return 9;
  36438. if ( /mat4/.test( type ) === true ) return 16;
  36439. return 0;
  36440. }
  36441. /**
  36442. * Returns the vector type for a given matrix type.
  36443. *
  36444. * @param {string} type - The matrix type.
  36445. * @return {string} The vector type.
  36446. */
  36447. getVectorFromMatrix( type ) {
  36448. return type.replace( 'mat', 'vec' );
  36449. }
  36450. /**
  36451. * For a given type this method changes the component type to the
  36452. * given value. E.g. `vec4` should be changed to the new component type
  36453. * `uint` which results in `uvec4`.
  36454. *
  36455. * @param {string} type - The type.
  36456. * @param {string} newComponentType - The new component type.
  36457. * @return {string} The new type.
  36458. */
  36459. changeComponentType( type, newComponentType ) {
  36460. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  36461. }
  36462. /**
  36463. * Returns the integer type pendant for the given type.
  36464. *
  36465. * @param {string} type - The type.
  36466. * @return {string} The integer type.
  36467. */
  36468. getIntegerType( type ) {
  36469. const componentType = this.getComponentType( type );
  36470. if ( componentType === 'int' || componentType === 'uint' ) return type;
  36471. return this.changeComponentType( type, 'int' );
  36472. }
  36473. /**
  36474. * Adds an active stack to the internal stack.
  36475. *
  36476. * @param {StackNode} stack - The stack node to add.
  36477. */
  36478. setActiveStack( stack ) {
  36479. this.activeStacks.push( stack );
  36480. }
  36481. /**
  36482. * Removes the active stack from the internal stack.
  36483. *
  36484. * @param {StackNode} stack - The stack node to remove.
  36485. */
  36486. removeActiveStack( stack ) {
  36487. if ( this.activeStacks[ this.activeStacks.length - 1 ] === stack ) {
  36488. this.activeStacks.pop();
  36489. } else {
  36490. throw new Error( 'NodeBuilder: Invalid active stack removal.' );
  36491. }
  36492. }
  36493. /**
  36494. * Returns the active stack.
  36495. *
  36496. * @return {StackNode} The active stack.
  36497. */
  36498. getActiveStack() {
  36499. return this.activeStacks[ this.activeStacks.length - 1 ];
  36500. }
  36501. /**
  36502. * Returns the base stack.
  36503. *
  36504. * @return {StackNode} The base stack.
  36505. */
  36506. getBaseStack() {
  36507. return this.activeStacks[ 0 ];
  36508. }
  36509. /**
  36510. * Adds a stack node to the internal stack.
  36511. *
  36512. * @return {StackNode} The added stack node.
  36513. */
  36514. addStack() {
  36515. this.stack = stack( this.stack );
  36516. const previousStack = getCurrentStack();
  36517. this.stacks.push( previousStack );
  36518. setCurrentStack( this.stack );
  36519. return this.stack;
  36520. }
  36521. /**
  36522. * Removes the last stack node from the internal stack.
  36523. *
  36524. * @return {StackNode} The removed stack node.
  36525. */
  36526. removeStack() {
  36527. const lastStack = this.stack;
  36528. for ( const node of lastStack.nodes ) {
  36529. const nodeData = this.getDataFromNode( node );
  36530. nodeData.stack = lastStack;
  36531. }
  36532. this.stack = lastStack.parent;
  36533. setCurrentStack( this.stacks.pop() );
  36534. return lastStack;
  36535. }
  36536. /**
  36537. * The builder maintains (cached) data for each node during the building process. This method
  36538. * can be used to get these data for a specific shader stage and cache.
  36539. *
  36540. * @param {Node} node - The node to get the data for.
  36541. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36542. * @param {?NodeCache} cache - An optional cache.
  36543. * @return {Object} The node data.
  36544. */
  36545. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  36546. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  36547. let nodeData = cache.getData( node );
  36548. if ( nodeData === undefined ) {
  36549. nodeData = {};
  36550. cache.setData( node, nodeData );
  36551. }
  36552. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  36553. //
  36554. let data = nodeData[ shaderStage ];
  36555. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  36556. const subBuild = this.getClosestSubBuild( subBuilds );
  36557. if ( subBuild ) {
  36558. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  36559. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  36560. data.subBuilds = subBuilds;
  36561. }
  36562. return data;
  36563. }
  36564. /**
  36565. * Returns the properties for the given node and shader stage.
  36566. *
  36567. * Properties are typically used within a build stage to reference a node's
  36568. * child node or nodes manually assigned to the properties in a separate build stage.
  36569. * A typical usage pattern for defining nodes manually would be assigning dependency nodes
  36570. * to the current node's properties in the setup stage and building those properties in the generate stage.
  36571. *
  36572. * @param {Node} node - The node to get the properties for.
  36573. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  36574. * @return {Object} The node properties.
  36575. */
  36576. getNodeProperties( node, shaderStage = 'any' ) {
  36577. const nodeData = this.getDataFromNode( node, shaderStage );
  36578. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  36579. }
  36580. /**
  36581. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  36582. *
  36583. * @param {BufferAttributeNode} node - The buffer attribute node.
  36584. * @param {string} type - The node type.
  36585. * @return {NodeAttribute} The node attribute.
  36586. */
  36587. getBufferAttributeFromNode( node, type ) {
  36588. const nodeData = this.getDataFromNode( node, 'vertex' );
  36589. let bufferAttribute = nodeData.bufferAttribute;
  36590. if ( bufferAttribute === undefined ) {
  36591. const index = this.uniforms.index ++;
  36592. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  36593. this.bufferAttributes.push( bufferAttribute );
  36594. nodeData.bufferAttribute = bufferAttribute;
  36595. }
  36596. return bufferAttribute;
  36597. }
  36598. /**
  36599. * Returns an instance of {@link StructType} for the given struct name and shader stage
  36600. * or null if not found.
  36601. *
  36602. * @param {string} name - The name of the struct.
  36603. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36604. * @return {?StructType} The struct type or null if not found.
  36605. */
  36606. getStructTypeNode( name, shaderStage = this.shaderStage ) {
  36607. return this.types[ shaderStage ][ name ] || null;
  36608. }
  36609. /**
  36610. * Returns an instance of {@link StructType} for the given output struct node.
  36611. *
  36612. * @param {OutputStructNode} node - The output struct node.
  36613. * @param {Array<Object>} membersLayout - The output struct types.
  36614. * @param {?string} [name=null] - The name of the struct.
  36615. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36616. * @return {StructType} The struct type attribute.
  36617. */
  36618. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  36619. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  36620. let structType = nodeData.structType;
  36621. if ( structType === undefined ) {
  36622. const index = this.structs.index ++;
  36623. if ( name === null ) name = 'StructType' + index;
  36624. structType = new StructType( name, membersLayout );
  36625. this.structs[ shaderStage ].push( structType );
  36626. this.types[ shaderStage ][ name ] = node;
  36627. nodeData.structType = structType;
  36628. }
  36629. return structType;
  36630. }
  36631. /**
  36632. * Returns an instance of {@link StructType} for the given output struct node.
  36633. *
  36634. * @param {OutputStructNode} node - The output struct node.
  36635. * @param {Array<Object>} membersLayout - The output struct types.
  36636. * @return {StructType} The struct type attribute.
  36637. */
  36638. getOutputStructTypeFromNode( node, membersLayout ) {
  36639. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  36640. structType.output = true;
  36641. return structType;
  36642. }
  36643. /**
  36644. * Returns an instance of {@link NodeUniform} for the given uniform node.
  36645. *
  36646. * @param {UniformNode} node - The uniform node.
  36647. * @param {string} type - The uniform type.
  36648. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36649. * @param {?string} name - The name of the uniform.
  36650. * @return {NodeUniform} The node uniform.
  36651. */
  36652. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  36653. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  36654. let nodeUniform = nodeData.uniform;
  36655. if ( nodeUniform === undefined ) {
  36656. const index = this.uniforms.index ++;
  36657. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  36658. this.uniforms[ shaderStage ].push( nodeUniform );
  36659. this.registerDeclaration( nodeUniform );
  36660. nodeData.uniform = nodeUniform;
  36661. }
  36662. return nodeUniform;
  36663. }
  36664. /**
  36665. * Returns an instance of {@link NodeVar} for the given variable node.
  36666. *
  36667. * @param {VarNode} node - The variable node.
  36668. * @param {?string} name - The variable's name.
  36669. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  36670. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36671. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  36672. *
  36673. * @return {NodeVar} The node variable.
  36674. */
  36675. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  36676. const nodeData = this.getDataFromNode( node, shaderStage );
  36677. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  36678. let nodeVar = nodeData[ subBuildVariable ];
  36679. if ( nodeVar === undefined ) {
  36680. const idNS = readOnly ? '_const' : '_var';
  36681. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  36682. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  36683. if ( name === null ) {
  36684. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  36685. this.vars[ idNS ] ++;
  36686. }
  36687. //
  36688. if ( subBuildVariable !== 'variable' ) {
  36689. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  36690. }
  36691. //
  36692. const count = node.getArrayCount( this );
  36693. nodeVar = new NodeVar( name, type, readOnly, count );
  36694. if ( ! readOnly ) {
  36695. vars.push( nodeVar );
  36696. }
  36697. this.registerDeclaration( nodeVar );
  36698. nodeData[ subBuildVariable ] = nodeVar;
  36699. }
  36700. return nodeVar;
  36701. }
  36702. /**
  36703. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  36704. *
  36705. * @param {Node} node - The varying node.
  36706. * @return {boolean} Returns true if deterministic.
  36707. */
  36708. isDeterministic( node ) {
  36709. if ( node.isMathNode ) {
  36710. return this.isDeterministic( node.aNode ) &&
  36711. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  36712. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  36713. } else if ( node.isOperatorNode ) {
  36714. return this.isDeterministic( node.aNode ) &&
  36715. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  36716. } else if ( node.isArrayNode ) {
  36717. if ( node.values !== null ) {
  36718. for ( const n of node.values ) {
  36719. if ( ! this.isDeterministic( n ) ) {
  36720. return false;
  36721. }
  36722. }
  36723. }
  36724. return true;
  36725. } else if ( node.isConstNode ) {
  36726. return true;
  36727. }
  36728. return false;
  36729. }
  36730. /**
  36731. * Returns an instance of {@link NodeVarying} for the given varying node.
  36732. *
  36733. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  36734. * @param {?string} name - The varying's name.
  36735. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  36736. * @param {?string} interpolationType - The interpolation type of the varying.
  36737. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  36738. * @return {NodeVar} The node varying.
  36739. */
  36740. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  36741. const nodeData = this.getDataFromNode( node, 'any' );
  36742. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  36743. let nodeVarying = nodeData[ subBuildVarying ];
  36744. if ( nodeVarying === undefined ) {
  36745. const varyings = this.varyings;
  36746. const index = varyings.length;
  36747. if ( name === null ) name = 'nodeVarying' + index;
  36748. //
  36749. if ( subBuildVarying !== 'varying' ) {
  36750. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  36751. }
  36752. //
  36753. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  36754. varyings.push( nodeVarying );
  36755. this.registerDeclaration( nodeVarying );
  36756. nodeData[ subBuildVarying ] = nodeVarying;
  36757. }
  36758. return nodeVarying;
  36759. }
  36760. /**
  36761. * Registers a node declaration in the current shader stage.
  36762. *
  36763. * @param {Object} node - The node to be registered.
  36764. */
  36765. registerDeclaration( node ) {
  36766. const shaderStage = this.shaderStage;
  36767. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  36768. const property = this.getPropertyName( node );
  36769. let index = 1;
  36770. let name = property;
  36771. // Automatically renames the property if the name is already in use.
  36772. while ( declarations[ name ] !== undefined ) {
  36773. name = property + '_' + index ++;
  36774. }
  36775. if ( index > 1 ) {
  36776. node.name = name;
  36777. warn( `TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  36778. }
  36779. declarations[ name ] = node;
  36780. }
  36781. /**
  36782. * Returns an instance of {@link NodeCode} for the given code node.
  36783. *
  36784. * @param {CodeNode} node - The code node.
  36785. * @param {string} type - The node type.
  36786. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36787. * @return {NodeCode} The node code.
  36788. */
  36789. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  36790. const nodeData = this.getDataFromNode( node );
  36791. let nodeCode = nodeData.code;
  36792. if ( nodeCode === undefined ) {
  36793. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  36794. const index = codes.length;
  36795. nodeCode = new NodeCode( 'nodeCode' + index, type );
  36796. codes.push( nodeCode );
  36797. nodeData.code = nodeCode;
  36798. }
  36799. return nodeCode;
  36800. }
  36801. /**
  36802. * Adds a code flow based on the code-block hierarchy.
  36803. * This is used so that code-blocks like If,Else create their variables locally if the Node
  36804. * is only used inside one of these conditionals in the current shader stage.
  36805. *
  36806. * @param {Node} node - The node to add.
  36807. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  36808. */
  36809. addFlowCodeHierarchy( node, nodeBlock ) {
  36810. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  36811. let needsFlowCode = true;
  36812. let nodeBlockHierarchy = nodeBlock;
  36813. while ( nodeBlockHierarchy ) {
  36814. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  36815. needsFlowCode = false;
  36816. break;
  36817. }
  36818. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  36819. }
  36820. if ( needsFlowCode ) {
  36821. for ( const flowCode of flowCodes ) {
  36822. this.addLineFlowCode( flowCode );
  36823. }
  36824. }
  36825. }
  36826. /**
  36827. * Add a inline-code to the current flow code-block.
  36828. *
  36829. * @param {Node} node - The node to add.
  36830. * @param {string} code - The code to add.
  36831. * @param {Node} nodeBlock - Current ConditionalNode
  36832. */
  36833. addLineFlowCodeBlock( node, code, nodeBlock ) {
  36834. const nodeData = this.getDataFromNode( node );
  36835. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  36836. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  36837. flowCodes.push( code );
  36838. codeBlock.set( nodeBlock, true );
  36839. }
  36840. /**
  36841. * Add a inline-code to the current flow.
  36842. *
  36843. * @param {string} code - The code to add.
  36844. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  36845. * @return {NodeBuilder} A reference to this node builder.
  36846. */
  36847. addLineFlowCode( code, node = null ) {
  36848. if ( code === '' ) return this;
  36849. if ( node !== null && this.context.nodeBlock ) {
  36850. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  36851. }
  36852. code = this.tab + code;
  36853. if ( ! /;\s*$/.test( code ) ) {
  36854. code = code + ';\n';
  36855. }
  36856. this.flow.code += code;
  36857. return this;
  36858. }
  36859. /**
  36860. * Adds a code to the current code flow.
  36861. *
  36862. * @param {string} code - Shader code.
  36863. * @return {NodeBuilder} A reference to this node builder.
  36864. */
  36865. addFlowCode( code ) {
  36866. this.flow.code += code;
  36867. return this;
  36868. }
  36869. /**
  36870. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  36871. * Typically used in codes with If,Else.
  36872. *
  36873. * @return {NodeBuilder} A reference to this node builder.
  36874. */
  36875. addFlowTab() {
  36876. this.tab += '\t';
  36877. return this;
  36878. }
  36879. /**
  36880. * Removes a tab.
  36881. *
  36882. * @return {NodeBuilder} A reference to this node builder.
  36883. */
  36884. removeFlowTab() {
  36885. this.tab = this.tab.slice( 0, -1 );
  36886. return this;
  36887. }
  36888. /**
  36889. * Gets the current flow data based on a Node.
  36890. *
  36891. * @param {Node} node - Node that the flow was started.
  36892. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36893. * @return {Object} The flow data.
  36894. */
  36895. getFlowData( node/*, shaderStage*/ ) {
  36896. return this.flowsData.get( node );
  36897. }
  36898. /**
  36899. * Executes the node flow based on a root node to generate the final shader code.
  36900. *
  36901. * @param {Node} node - The node to execute.
  36902. * @return {Object} The code flow.
  36903. */
  36904. flowNode( node ) {
  36905. const output = node.getNodeType( this );
  36906. const flowData = this.flowChildNode( node, output );
  36907. this.flowsData.set( node, flowData );
  36908. return flowData;
  36909. }
  36910. /**
  36911. * Includes a node in the current function node.
  36912. *
  36913. * @param {Node} node - The node to include.
  36914. * @returns {void}
  36915. */
  36916. addInclude( node ) {
  36917. if ( this.currentFunctionNode !== null ) {
  36918. this.currentFunctionNode.includes.push( node );
  36919. }
  36920. }
  36921. /**
  36922. * Returns the native shader operator name for a given generic name.
  36923. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  36924. *
  36925. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  36926. * @return {FunctionNode} The build function node.
  36927. */
  36928. buildFunctionNode( shaderNode ) {
  36929. const fn = new FunctionNode();
  36930. const previous = this.currentFunctionNode;
  36931. this.currentFunctionNode = fn;
  36932. fn.code = this.buildFunctionCode( shaderNode );
  36933. this.currentFunctionNode = previous;
  36934. return fn;
  36935. }
  36936. /**
  36937. * Generates a code flow based on a TSL function: Fn().
  36938. *
  36939. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  36940. * @return {Object}
  36941. */
  36942. flowShaderNode( shaderNode ) {
  36943. const layout = shaderNode.layout;
  36944. const inputs = {
  36945. [ Symbol.iterator ]() {
  36946. let index = 0;
  36947. const values = Object.values( this );
  36948. return {
  36949. next: () => ( {
  36950. value: values[ index ],
  36951. done: index ++ >= values.length
  36952. } )
  36953. };
  36954. }
  36955. };
  36956. for ( const input of layout.inputs ) {
  36957. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  36958. }
  36959. //
  36960. shaderNode.layout = null;
  36961. const callNode = shaderNode.call( inputs );
  36962. const flowData = this.flowStagesNode( callNode, layout.type );
  36963. shaderNode.layout = layout;
  36964. return flowData;
  36965. }
  36966. /**
  36967. * Executes the node in a specific build stage.
  36968. *
  36969. * This function can be used to arbitrarily execute the specified build stage
  36970. * outside of the standard build process. For instance, if a node's type depends
  36971. * on properties created by the 'setup' stage, then flowBuildStage(node, 'setup')
  36972. * can be used to execute the setup build stage and access its generated nodes
  36973. * before the standard build process begins.
  36974. *
  36975. * @param {Node} node - The node to execute.
  36976. * @param {string} buildStage - The build stage to execute the node in.
  36977. * @param {?(Node|string)} [output=null] - Expected output type. For example 'vec3'.
  36978. * @return {?(Node|string)} The result of the node build.
  36979. */
  36980. flowBuildStage( node, buildStage, output = null ) {
  36981. const previousBuildStage = this.getBuildStage();
  36982. this.setBuildStage( buildStage );
  36983. const result = node.build( this, output );
  36984. this.setBuildStage( previousBuildStage );
  36985. return result;
  36986. }
  36987. /**
  36988. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  36989. *
  36990. * @param {Node} node - The node to execute.
  36991. * @param {?string} output - Expected output type. For example 'vec3'.
  36992. * @return {Object}
  36993. */
  36994. flowStagesNode( node, output = null ) {
  36995. const previousFlow = this.flow;
  36996. const previousVars = this.vars;
  36997. const previousDeclarations = this.declarations;
  36998. const previousCache = this.cache;
  36999. const previousBuildStage = this.buildStage;
  37000. const previousStack = this.stack;
  37001. const flow = {
  37002. code: ''
  37003. };
  37004. this.flow = flow;
  37005. this.vars = {};
  37006. this.declarations = {};
  37007. this.cache = new NodeCache();
  37008. this.stack = stack();
  37009. for ( const buildStage of defaultBuildStages ) {
  37010. this.setBuildStage( buildStage );
  37011. flow.result = node.build( this, output );
  37012. }
  37013. flow.vars = this.getVars( this.shaderStage );
  37014. this.flow = previousFlow;
  37015. this.vars = previousVars;
  37016. this.declarations = previousDeclarations;
  37017. this.cache = previousCache;
  37018. this.stack = previousStack;
  37019. this.setBuildStage( previousBuildStage );
  37020. return flow;
  37021. }
  37022. /**
  37023. * Returns the native shader operator name for a given generic name.
  37024. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  37025. *
  37026. * @abstract
  37027. * @param {string} op - The operator name to resolve.
  37028. * @return {?string} The resolved operator name.
  37029. */
  37030. getFunctionOperator( /* op */ ) {
  37031. return null;
  37032. }
  37033. /**
  37034. * Builds the given shader node.
  37035. *
  37036. * @abstract
  37037. * @param {ShaderNodeInternal} shaderNode - The shader node.
  37038. * @return {string} The function code.
  37039. */
  37040. buildFunctionCode( /* shaderNode */ ) {
  37041. warn( 'Abstract function.' );
  37042. }
  37043. /**
  37044. * Generates a code flow based on a child Node.
  37045. *
  37046. * @param {Node} node - The node to execute.
  37047. * @param {?string} output - Expected output type. For example 'vec3'.
  37048. * @return {Object} The code flow.
  37049. */
  37050. flowChildNode( node, output = null ) {
  37051. const previousFlow = this.flow;
  37052. const flow = {
  37053. code: ''
  37054. };
  37055. this.flow = flow;
  37056. flow.result = node.build( this, output );
  37057. this.flow = previousFlow;
  37058. return flow;
  37059. }
  37060. /**
  37061. * Executes a flow of code in a different stage.
  37062. *
  37063. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  37064. * return the value in fragment-stage even if it is being executed in an input fragment.
  37065. *
  37066. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37067. * @param {Node} node - The node to execute.
  37068. * @param {?string} output - Expected output type. For example 'vec3'.
  37069. * @param {?string} propertyName - The property name to assign the result.
  37070. * @return {?(Object|Node)} The code flow or node.build() result.
  37071. */
  37072. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  37073. const previousTab = this.tab;
  37074. const previousCache = this.cache;
  37075. const previousShaderStage = this.shaderStage;
  37076. const previousContext = this.context;
  37077. this.setShaderStage( shaderStage );
  37078. const context = { ...this.context };
  37079. delete context.nodeBlock;
  37080. this.cache = this.globalCache;
  37081. this.tab = '\t';
  37082. this.context = context;
  37083. let result = null;
  37084. if ( this.buildStage === 'generate' ) {
  37085. const flowData = this.flowChildNode( node, output );
  37086. if ( propertyName !== null ) {
  37087. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  37088. }
  37089. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  37090. result = flowData;
  37091. } else {
  37092. result = node.build( this );
  37093. }
  37094. this.setShaderStage( previousShaderStage );
  37095. this.cache = previousCache;
  37096. this.tab = previousTab;
  37097. this.context = previousContext;
  37098. return result;
  37099. }
  37100. /**
  37101. * Returns an array holding all node attributes of this node builder.
  37102. *
  37103. * @return {Array<NodeAttribute>} The node attributes of this builder.
  37104. */
  37105. getAttributesArray() {
  37106. return this.attributes.concat( this.bufferAttributes );
  37107. }
  37108. /**
  37109. * Returns the attribute definitions as a shader string for the given shader stage.
  37110. *
  37111. * @abstract
  37112. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37113. * @return {string} The attribute code section.
  37114. */
  37115. getAttributes( /*shaderStage*/ ) {
  37116. warn( 'Abstract function.' );
  37117. }
  37118. /**
  37119. * Returns the varying definitions as a shader string for the given shader stage.
  37120. *
  37121. * @abstract
  37122. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37123. * @return {string} The varying code section.
  37124. */
  37125. getVaryings( /*shaderStage*/ ) {
  37126. warn( 'Abstract function.' );
  37127. }
  37128. /**
  37129. * Returns a single variable definition as a shader string for the given variable type and name.
  37130. *
  37131. * @param {string} type - The variable's type.
  37132. * @param {string} name - The variable's name.
  37133. * @param {?number} [count=null] - The array length.
  37134. * @return {string} The shader string.
  37135. */
  37136. getVar( type, name, count = null ) {
  37137. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  37138. }
  37139. /**
  37140. * Returns the variable definitions as a shader string for the given shader stage.
  37141. *
  37142. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37143. * @return {string} The variable code section.
  37144. */
  37145. getVars( shaderStage ) {
  37146. let snippet = '';
  37147. const vars = this.vars[ shaderStage ];
  37148. if ( vars !== undefined ) {
  37149. for ( const variable of vars ) {
  37150. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  37151. }
  37152. }
  37153. return snippet;
  37154. }
  37155. /**
  37156. * Returns the uniform definitions as a shader string for the given shader stage.
  37157. *
  37158. * @abstract
  37159. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37160. * @return {string} The uniform code section.
  37161. */
  37162. getUniforms( /*shaderStage*/ ) {
  37163. warn( 'Abstract function.' );
  37164. }
  37165. /**
  37166. * Returns the native code definitions as a shader string for the given shader stage.
  37167. *
  37168. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37169. * @return {string} The native code section.
  37170. */
  37171. getCodes( shaderStage ) {
  37172. const codes = this.codes[ shaderStage ];
  37173. let code = '';
  37174. if ( codes !== undefined ) {
  37175. for ( const nodeCode of codes ) {
  37176. code += nodeCode.code + '\n';
  37177. }
  37178. }
  37179. return code;
  37180. }
  37181. /**
  37182. * Returns the hash of this node builder.
  37183. *
  37184. * @return {string} The hash.
  37185. */
  37186. getHash() {
  37187. return this.vertexShader + this.fragmentShader + this.computeShader;
  37188. }
  37189. /**
  37190. * Sets the current shader stage.
  37191. *
  37192. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  37193. */
  37194. setShaderStage( shaderStage ) {
  37195. this.shaderStage = shaderStage;
  37196. }
  37197. /**
  37198. * Returns the current shader stage.
  37199. *
  37200. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  37201. */
  37202. getShaderStage() {
  37203. return this.shaderStage;
  37204. }
  37205. /**
  37206. * Sets the current build stage.
  37207. *
  37208. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  37209. */
  37210. setBuildStage( buildStage ) {
  37211. this.buildStage = buildStage;
  37212. }
  37213. /**
  37214. * Returns the current build stage.
  37215. *
  37216. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  37217. */
  37218. getBuildStage() {
  37219. return this.buildStage;
  37220. }
  37221. /**
  37222. * Controls the code build of the shader stages.
  37223. *
  37224. * @abstract
  37225. */
  37226. buildCode() {
  37227. warn( 'Abstract function.' );
  37228. }
  37229. /**
  37230. * Returns the current sub-build layer.
  37231. *
  37232. * @return {SubBuildNode} The current sub-build layers.
  37233. */
  37234. get subBuild() {
  37235. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  37236. }
  37237. /**
  37238. * Adds a sub-build layer to the node builder.
  37239. *
  37240. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  37241. */
  37242. addSubBuild( subBuild ) {
  37243. this.subBuildLayers.push( subBuild );
  37244. }
  37245. /**
  37246. * Removes the last sub-build layer from the node builder.
  37247. *
  37248. * @return {SubBuildNode} The removed sub-build layer.
  37249. */
  37250. removeSubBuild() {
  37251. return this.subBuildLayers.pop();
  37252. }
  37253. /**
  37254. * Returns the closest sub-build layer for the given data.
  37255. *
  37256. * @param {Node|Set<string>|Array<string>} data - The data to get the closest sub-build layer from.
  37257. * @return {?string} The closest sub-build name or null if none found.
  37258. */
  37259. getClosestSubBuild( data ) {
  37260. let subBuilds;
  37261. if ( data && data.isNode ) {
  37262. if ( data.isShaderCallNodeInternal ) {
  37263. subBuilds = data.shaderNode.subBuilds;
  37264. } else if ( data.isStackNode ) {
  37265. subBuilds = [ data.subBuild ];
  37266. } else {
  37267. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  37268. }
  37269. } else if ( data instanceof Set ) {
  37270. subBuilds = [ ...data ];
  37271. } else {
  37272. subBuilds = data;
  37273. }
  37274. if ( ! subBuilds ) return null;
  37275. const subBuildLayers = this.subBuildLayers;
  37276. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  37277. const subBuild = subBuilds[ i ];
  37278. if ( subBuildLayers.includes( subBuild ) ) {
  37279. return subBuild;
  37280. }
  37281. }
  37282. return null;
  37283. }
  37284. /**
  37285. * Returns the output node of a sub-build layer.
  37286. *
  37287. * @param {Node} node - The node to get the output from.
  37288. * @return {string} The output node name.
  37289. */
  37290. getSubBuildOutput( node ) {
  37291. return this.getSubBuildProperty( 'outputNode', node );
  37292. }
  37293. /**
  37294. * Returns the sub-build property name for the given property and node.
  37295. *
  37296. * @param {string} [property=''] - The property name.
  37297. * @param {?Node} [node=null] - The node to get the sub-build from.
  37298. * @return {string} The sub-build property name.
  37299. */
  37300. getSubBuildProperty( property = '', node = null ) {
  37301. let subBuild;
  37302. if ( node !== null ) {
  37303. subBuild = this.getClosestSubBuild( node );
  37304. } else {
  37305. subBuild = this.subBuildFn;
  37306. }
  37307. let result;
  37308. if ( subBuild ) {
  37309. result = property ? ( subBuild + '_' + property ) : subBuild;
  37310. } else {
  37311. result = property;
  37312. }
  37313. return result;
  37314. }
  37315. /**
  37316. * Central build method which controls the build for the given object.
  37317. *
  37318. * @return {NodeBuilder} A reference to this node builder.
  37319. */
  37320. build() {
  37321. const { object, material, renderer } = this;
  37322. if ( material !== null ) {
  37323. let nodeMaterial = renderer.library.fromMaterial( material );
  37324. if ( nodeMaterial === null ) {
  37325. error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  37326. nodeMaterial = new NodeMaterial();
  37327. }
  37328. nodeMaterial.build( this );
  37329. } else {
  37330. this.addFlow( 'compute', object );
  37331. }
  37332. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  37333. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  37334. // generate() -> stage 3: generate shader
  37335. for ( const buildStage of defaultBuildStages ) {
  37336. this.setBuildStage( buildStage );
  37337. if ( this.context.vertex && this.context.vertex.isNode ) {
  37338. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  37339. }
  37340. for ( const shaderStage of shaderStages ) {
  37341. this.setShaderStage( shaderStage );
  37342. const flowNodes = this.flowNodes[ shaderStage ];
  37343. for ( const node of flowNodes ) {
  37344. if ( buildStage === 'generate' ) {
  37345. this.flowNode( node );
  37346. } else {
  37347. node.build( this );
  37348. }
  37349. }
  37350. }
  37351. }
  37352. this.setBuildStage( null );
  37353. this.setShaderStage( null );
  37354. // stage 4: build code for a specific output
  37355. this.buildCode();
  37356. this.buildUpdateNodes();
  37357. return this;
  37358. }
  37359. /**
  37360. * Returns shared data object for the given node.
  37361. *
  37362. * @param {Node} node - The node to get shared data from.
  37363. * @return {Object} The shared data.
  37364. */
  37365. getSharedDataFromNode( node ) {
  37366. let data = sharedNodeData.get( node );
  37367. if ( data === undefined ) {
  37368. data = {};
  37369. }
  37370. return data;
  37371. }
  37372. /**
  37373. * Returns a uniform representation which is later used for UBO generation and rendering.
  37374. *
  37375. * @param {NodeUniform} uniformNode - The uniform node.
  37376. * @param {string} type - The requested type.
  37377. * @return {Uniform} The uniform.
  37378. */
  37379. getNodeUniform( uniformNode, type ) {
  37380. const nodeData = this.getSharedDataFromNode( uniformNode );
  37381. let node = nodeData.cache;
  37382. if ( node === undefined ) {
  37383. if ( type === 'float' || type === 'int' || type === 'uint' ) node = new NumberNodeUniform( uniformNode );
  37384. else if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) node = new Vector2NodeUniform( uniformNode );
  37385. else if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) node = new Vector3NodeUniform( uniformNode );
  37386. else if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) node = new Vector4NodeUniform( uniformNode );
  37387. else if ( type === 'color' ) node = new ColorNodeUniform( uniformNode );
  37388. else if ( type === 'mat2' ) node = new Matrix2NodeUniform( uniformNode );
  37389. else if ( type === 'mat3' ) node = new Matrix3NodeUniform( uniformNode );
  37390. else if ( type === 'mat4' ) node = new Matrix4NodeUniform( uniformNode );
  37391. else {
  37392. throw new Error( `Uniform "${ type }" not implemented.` );
  37393. }
  37394. nodeData.cache = node;
  37395. }
  37396. return node;
  37397. }
  37398. /**
  37399. * Formats the given shader snippet from a given type into another one. E.g.
  37400. * this method might be used to convert a simple float string `"1.0"` into a
  37401. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  37402. *
  37403. * @param {string} snippet - The shader snippet.
  37404. * @param {string} fromType - The source type.
  37405. * @param {string} toType - The target type.
  37406. * @return {string} The updated shader string.
  37407. */
  37408. format( snippet, fromType, toType ) {
  37409. fromType = this.getVectorType( fromType );
  37410. toType = this.getVectorType( toType );
  37411. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  37412. return snippet;
  37413. }
  37414. const fromTypeLength = this.getTypeLength( fromType );
  37415. const toTypeLength = this.getTypeLength( toType );
  37416. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  37417. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  37418. }
  37419. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  37420. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  37421. }
  37422. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  37423. // @TODO: ignore for now
  37424. return snippet;
  37425. }
  37426. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  37427. // @TODO: ignore for now
  37428. return snippet;
  37429. }
  37430. if ( fromTypeLength === toTypeLength ) {
  37431. return `${ this.getType( toType ) }( ${ snippet } )`;
  37432. }
  37433. if ( fromTypeLength > toTypeLength ) {
  37434. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  37435. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  37436. }
  37437. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  37438. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  37439. }
  37440. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  37441. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  37442. }
  37443. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  37444. // convert a number value to vector type, e.g:
  37445. // vec3( 1u ) -> vec3( float( 1u ) )
  37446. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  37447. }
  37448. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  37449. }
  37450. /**
  37451. * Returns a signature with the engine's current revision.
  37452. *
  37453. * @return {string} The signature.
  37454. */
  37455. getSignature() {
  37456. return `// Three.js r${ REVISION } - Node System\n`;
  37457. }
  37458. }
  37459. /**
  37460. * Management class for updating nodes. The module tracks metrics like
  37461. * the elapsed time, delta time, the render and frame ID to correctly
  37462. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  37463. * and {@link Node#updateAfter} depending on the node's configuration.
  37464. */
  37465. class NodeFrame {
  37466. /**
  37467. * Constructs a new node fame.
  37468. */
  37469. constructor() {
  37470. /**
  37471. * The elapsed time in seconds.
  37472. *
  37473. * @type {number}
  37474. * @default 0
  37475. */
  37476. this.time = 0;
  37477. /**
  37478. * The delta time in seconds.
  37479. *
  37480. * @type {number}
  37481. * @default 0
  37482. */
  37483. this.deltaTime = 0;
  37484. /**
  37485. * The frame ID.
  37486. *
  37487. * @type {number}
  37488. * @default 0
  37489. */
  37490. this.frameId = 0;
  37491. /**
  37492. * The render ID.
  37493. *
  37494. * @type {number}
  37495. * @default 0
  37496. */
  37497. this.renderId = 0;
  37498. /**
  37499. * Used to control the {@link Node#update} call.
  37500. *
  37501. * @type {WeakMap<Node, Object>}
  37502. */
  37503. this.updateMap = new WeakMap();
  37504. /**
  37505. * Used to control the {@link Node#updateBefore} call.
  37506. *
  37507. * @type {WeakMap<Node, Object>}
  37508. */
  37509. this.updateBeforeMap = new WeakMap();
  37510. /**
  37511. * Used to control the {@link Node#updateAfter} call.
  37512. *
  37513. * @type {WeakMap<Node, Object>}
  37514. */
  37515. this.updateAfterMap = new WeakMap();
  37516. /**
  37517. * A reference to the current renderer.
  37518. *
  37519. * @type {?Renderer}
  37520. * @default null
  37521. */
  37522. this.renderer = null;
  37523. /**
  37524. * A reference to the current material.
  37525. *
  37526. * @type {?Material}
  37527. * @default null
  37528. */
  37529. this.material = null;
  37530. /**
  37531. * A reference to the current camera.
  37532. *
  37533. * @type {?Camera}
  37534. * @default null
  37535. */
  37536. this.camera = null;
  37537. /**
  37538. * A reference to the current 3D object.
  37539. *
  37540. * @type {?Object3D}
  37541. * @default null
  37542. */
  37543. this.object = null;
  37544. /**
  37545. * A reference to the current scene.
  37546. *
  37547. * @type {?Scene}
  37548. * @default null
  37549. */
  37550. this.scene = null;
  37551. }
  37552. /**
  37553. * Returns a dictionary for a given node and update map which
  37554. * is used to correctly call node update methods per frame or render.
  37555. *
  37556. * @private
  37557. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  37558. * @param {Node} nodeRef - The reference to the current node.
  37559. * @return {Object<string,WeakMap<Object, number>>} The dictionary.
  37560. */
  37561. _getMaps( referenceMap, nodeRef ) {
  37562. let maps = referenceMap.get( nodeRef );
  37563. if ( maps === undefined ) {
  37564. maps = {
  37565. renderId: 0,
  37566. frameId: 0,
  37567. };
  37568. referenceMap.set( nodeRef, maps );
  37569. }
  37570. return maps;
  37571. }
  37572. /**
  37573. * This method executes the {@link Node#updateBefore} for the given node.
  37574. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  37575. * is only executed once per frame, render or object depending on the update
  37576. * type.
  37577. *
  37578. * @param {Node} node - The node that should be updated.
  37579. */
  37580. updateBeforeNode( node ) {
  37581. const updateType = node.getUpdateBeforeType();
  37582. const reference = node.updateReference( this );
  37583. if ( updateType === NodeUpdateType.FRAME ) {
  37584. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  37585. if ( nodeUpdateBeforeMap.frameId !== this.frameId ) {
  37586. const previousFrameId = nodeUpdateBeforeMap.frameId;
  37587. nodeUpdateBeforeMap.frameId = this.frameId;
  37588. if ( node.updateBefore( this ) === false ) {
  37589. nodeUpdateBeforeMap.frameId = previousFrameId;
  37590. }
  37591. }
  37592. } else if ( updateType === NodeUpdateType.RENDER ) {
  37593. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  37594. if ( nodeUpdateBeforeMap.renderId !== this.renderId ) {
  37595. const previousRenderId = nodeUpdateBeforeMap.renderId;
  37596. nodeUpdateBeforeMap.renderId = this.renderId;
  37597. if ( node.updateBefore( this ) === false ) {
  37598. nodeUpdateBeforeMap.renderId = previousRenderId;
  37599. }
  37600. }
  37601. } else if ( updateType === NodeUpdateType.OBJECT ) {
  37602. node.updateBefore( this );
  37603. }
  37604. }
  37605. /**
  37606. * This method executes the {@link Node#updateAfter} for the given node.
  37607. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  37608. * is only executed once per frame, render or object depending on the update
  37609. * type.
  37610. *
  37611. * @param {Node} node - The node that should be updated.
  37612. */
  37613. updateAfterNode( node ) {
  37614. const updateType = node.getUpdateAfterType();
  37615. const reference = node.updateReference( this );
  37616. if ( updateType === NodeUpdateType.FRAME ) {
  37617. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  37618. if ( nodeUpdateAfterMap.frameId !== this.frameId ) {
  37619. if ( node.updateAfter( this ) !== false ) {
  37620. nodeUpdateAfterMap.frameId = this.frameId;
  37621. }
  37622. }
  37623. } else if ( updateType === NodeUpdateType.RENDER ) {
  37624. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  37625. if ( nodeUpdateAfterMap.renderId !== this.renderId ) {
  37626. if ( node.updateAfter( this ) !== false ) {
  37627. nodeUpdateAfterMap.renderId = this.renderId;
  37628. }
  37629. }
  37630. } else if ( updateType === NodeUpdateType.OBJECT ) {
  37631. node.updateAfter( this );
  37632. }
  37633. }
  37634. /**
  37635. * This method executes the {@link Node#update} for the given node.
  37636. * It makes sure {@link Node#updateType} is honored meaning the update
  37637. * is only executed once per frame, render or object depending on the update
  37638. * type.
  37639. *
  37640. * @param {Node} node - The node that should be updated.
  37641. */
  37642. updateNode( node ) {
  37643. const updateType = node.getUpdateType();
  37644. const reference = node.updateReference( this );
  37645. if ( updateType === NodeUpdateType.FRAME ) {
  37646. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  37647. if ( nodeUpdateMap.frameId !== this.frameId ) {
  37648. if ( node.update( this ) !== false ) {
  37649. nodeUpdateMap.frameId = this.frameId;
  37650. }
  37651. }
  37652. } else if ( updateType === NodeUpdateType.RENDER ) {
  37653. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  37654. if ( nodeUpdateMap.renderId !== this.renderId ) {
  37655. if ( node.update( this ) !== false ) {
  37656. nodeUpdateMap.renderId = this.renderId;
  37657. }
  37658. }
  37659. } else if ( updateType === NodeUpdateType.OBJECT ) {
  37660. node.update( this );
  37661. }
  37662. }
  37663. /**
  37664. * Updates the internal state of the node frame. This method is
  37665. * called by the renderer in its internal animation loop.
  37666. */
  37667. update() {
  37668. this.frameId ++;
  37669. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  37670. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  37671. this.lastTime = performance.now();
  37672. this.time += this.deltaTime;
  37673. }
  37674. }
  37675. /**
  37676. * Describes the input of a {@link NodeFunction}.
  37677. */
  37678. class NodeFunctionInput {
  37679. /**
  37680. * Constructs a new node function input.
  37681. *
  37682. * @param {string} type - The input type.
  37683. * @param {string} name - The input name.
  37684. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  37685. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  37686. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  37687. */
  37688. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  37689. /**
  37690. * The input type.
  37691. *
  37692. * @type {string}
  37693. */
  37694. this.type = type;
  37695. /**
  37696. * The input name.
  37697. *
  37698. * @type {string}
  37699. */
  37700. this.name = name;
  37701. /**
  37702. * If the input is an Array, count will be the length.
  37703. *
  37704. * @type {?number}
  37705. * @default null
  37706. */
  37707. this.count = count;
  37708. /**
  37709. *The parameter qualifier (only relevant for GLSL).
  37710. *
  37711. * @type {('in'|'out'|'inout')}
  37712. * @default ''
  37713. */
  37714. this.qualifier = qualifier;
  37715. /**
  37716. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  37717. *
  37718. * @type {boolean}
  37719. * @default false
  37720. */
  37721. this.isConst = isConst;
  37722. }
  37723. }
  37724. NodeFunctionInput.isNodeFunctionInput = true;
  37725. /**
  37726. * Module for representing directional lights as nodes.
  37727. *
  37728. * @augments AnalyticLightNode
  37729. */
  37730. class DirectionalLightNode extends AnalyticLightNode {
  37731. static get type() {
  37732. return 'DirectionalLightNode';
  37733. }
  37734. /**
  37735. * Constructs a new directional light node.
  37736. *
  37737. * @param {?DirectionalLight} [light=null] - The directional light source.
  37738. */
  37739. constructor( light = null ) {
  37740. super( light );
  37741. }
  37742. setupDirect() {
  37743. const lightColor = this.colorNode;
  37744. const lightDirection = lightTargetDirection( this.light );
  37745. return { lightDirection, lightColor };
  37746. }
  37747. }
  37748. const _matrix41 = /*@__PURE__*/ new Matrix4();
  37749. const _matrix42 = /*@__PURE__*/ new Matrix4();
  37750. let _ltcLib = null;
  37751. /**
  37752. * Module for representing rect area lights as nodes.
  37753. *
  37754. * @augments AnalyticLightNode
  37755. */
  37756. class RectAreaLightNode extends AnalyticLightNode {
  37757. static get type() {
  37758. return 'RectAreaLightNode';
  37759. }
  37760. /**
  37761. * Constructs a new rect area light node.
  37762. *
  37763. * @param {?RectAreaLight} [light=null] - The rect area light source.
  37764. */
  37765. constructor( light = null ) {
  37766. super( light );
  37767. /**
  37768. * Uniform node representing the half height of the are light.
  37769. *
  37770. * @type {UniformNode<vec3>}
  37771. */
  37772. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  37773. /**
  37774. * Uniform node representing the half width of the are light.
  37775. *
  37776. * @type {UniformNode<vec3>}
  37777. */
  37778. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  37779. /**
  37780. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  37781. * relies on `viewMatrix` which might vary per render call.
  37782. *
  37783. * @type {string}
  37784. * @default 'render'
  37785. */
  37786. this.updateType = NodeUpdateType.RENDER;
  37787. }
  37788. /**
  37789. * Overwritten to updated rect area light specific uniforms.
  37790. *
  37791. * @param {NodeFrame} frame - A reference to the current node frame.
  37792. */
  37793. update( frame ) {
  37794. super.update( frame );
  37795. const { light } = this;
  37796. const viewMatrix = frame.camera.matrixWorldInverse;
  37797. _matrix42.identity();
  37798. _matrix41.copy( light.matrixWorld );
  37799. _matrix41.premultiply( viewMatrix );
  37800. _matrix42.extractRotation( _matrix41 );
  37801. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  37802. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  37803. this.halfWidth.value.applyMatrix4( _matrix42 );
  37804. this.halfHeight.value.applyMatrix4( _matrix42 );
  37805. }
  37806. setupDirectRectArea( builder ) {
  37807. let ltc_1, ltc_2;
  37808. if ( builder.isAvailable( 'float32Filterable' ) ) {
  37809. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  37810. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  37811. } else {
  37812. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  37813. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  37814. }
  37815. const { colorNode, light } = this;
  37816. const lightPosition = lightViewPosition( light );
  37817. return {
  37818. lightColor: colorNode,
  37819. lightPosition,
  37820. halfWidth: this.halfWidth,
  37821. halfHeight: this.halfHeight,
  37822. ltc_1,
  37823. ltc_2
  37824. };
  37825. }
  37826. /**
  37827. * Used to configure the internal BRDF approximation texture data.
  37828. *
  37829. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  37830. */
  37831. static setLTC( ltc ) {
  37832. _ltcLib = ltc;
  37833. }
  37834. }
  37835. /**
  37836. * Module for representing spot lights as nodes.
  37837. *
  37838. * @augments AnalyticLightNode
  37839. */
  37840. class SpotLightNode extends AnalyticLightNode {
  37841. static get type() {
  37842. return 'SpotLightNode';
  37843. }
  37844. /**
  37845. * Constructs a new spot light node.
  37846. *
  37847. * @param {?SpotLight} [light=null] - The spot light source.
  37848. */
  37849. constructor( light = null ) {
  37850. super( light );
  37851. /**
  37852. * Uniform node representing the cone cosine.
  37853. *
  37854. * @type {UniformNode<float>}
  37855. */
  37856. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  37857. /**
  37858. * Uniform node representing the penumbra cosine.
  37859. *
  37860. * @type {UniformNode<float>}
  37861. */
  37862. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  37863. /**
  37864. * Uniform node representing the cutoff distance.
  37865. *
  37866. * @type {UniformNode<float>}
  37867. */
  37868. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  37869. /**
  37870. * Uniform node representing the decay exponent.
  37871. *
  37872. * @type {UniformNode<float>}
  37873. */
  37874. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  37875. /**
  37876. * Uniform node representing the light color.
  37877. *
  37878. * @type {UniformNode<Color>}
  37879. */
  37880. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  37881. }
  37882. /**
  37883. * Overwritten to updated spot light specific uniforms.
  37884. *
  37885. * @param {NodeFrame} frame - A reference to the current node frame.
  37886. */
  37887. update( frame ) {
  37888. super.update( frame );
  37889. const { light } = this;
  37890. this.coneCosNode.value = Math.cos( light.angle );
  37891. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  37892. this.cutoffDistanceNode.value = light.distance;
  37893. this.decayExponentNode.value = light.decay;
  37894. }
  37895. /**
  37896. * Computes the spot attenuation for the given angle.
  37897. *
  37898. * @param {NodeBuilder} builder - The node builder.
  37899. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  37900. * @return {Node<float>} The spot attenuation.
  37901. */
  37902. getSpotAttenuation( builder, angleCosine ) {
  37903. const { coneCosNode, penumbraCosNode } = this;
  37904. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  37905. }
  37906. getLightCoord( builder ) {
  37907. const properties = builder.getNodeProperties( this );
  37908. let projectionUV = properties.projectionUV;
  37909. if ( projectionUV === undefined ) {
  37910. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  37911. properties.projectionUV = projectionUV;
  37912. }
  37913. return projectionUV;
  37914. }
  37915. setupDirect( builder ) {
  37916. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  37917. const lightVector = this.getLightVector( builder );
  37918. const lightDirection = lightVector.normalize();
  37919. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  37920. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  37921. const lightDistance = lightVector.length();
  37922. const lightAttenuation = getDistanceAttenuation( {
  37923. lightDistance,
  37924. cutoffDistance: cutoffDistanceNode,
  37925. decayExponent: decayExponentNode
  37926. } );
  37927. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  37928. let projected, lightCoord;
  37929. if ( light.colorNode ) {
  37930. lightCoord = this.getLightCoord( builder );
  37931. projected = light.colorNode( lightCoord );
  37932. } else if ( light.map ) {
  37933. lightCoord = this.getLightCoord( builder );
  37934. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  37935. }
  37936. if ( projected ) {
  37937. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  37938. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  37939. }
  37940. return { lightColor, lightDirection };
  37941. }
  37942. }
  37943. /**
  37944. * An IES version of the default spot light node.
  37945. *
  37946. * @augments SpotLightNode
  37947. */
  37948. class IESSpotLightNode extends SpotLightNode {
  37949. static get type() {
  37950. return 'IESSpotLightNode';
  37951. }
  37952. /**
  37953. * Overwrites the default implementation to compute an IES conform spot attenuation.
  37954. *
  37955. * @param {NodeBuilder} builder - The node builder.
  37956. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  37957. * @return {Node<float>} The spot attenuation.
  37958. */
  37959. getSpotAttenuation( builder, angleCosine ) {
  37960. const iesMap = this.light.iesMap;
  37961. let spotAttenuation = null;
  37962. if ( iesMap && iesMap.isTexture === true ) {
  37963. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  37964. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  37965. } else {
  37966. spotAttenuation = super.getSpotAttenuation( angleCosine );
  37967. }
  37968. return spotAttenuation;
  37969. }
  37970. }
  37971. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  37972. const d = p.abs().sub( b );
  37973. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  37974. } );
  37975. /**
  37976. * An implementation of a projector light node.
  37977. *
  37978. * @augments SpotLightNode
  37979. */
  37980. class ProjectorLightNode extends SpotLightNode {
  37981. static get type() {
  37982. return 'ProjectorLightNode';
  37983. }
  37984. update( frame ) {
  37985. super.update( frame );
  37986. const light = this.light;
  37987. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  37988. if ( light.aspect === null ) {
  37989. let aspect = 1;
  37990. if ( light.map !== null ) {
  37991. aspect = light.map.width / light.map.height;
  37992. }
  37993. light.shadow.aspect = aspect;
  37994. } else {
  37995. light.shadow.aspect = light.aspect;
  37996. }
  37997. }
  37998. /**
  37999. * Overwrites the default implementation to compute projection attenuation.
  38000. *
  38001. * @param {NodeBuilder} builder - The node builder.
  38002. * @return {Node<float>} The spot attenuation.
  38003. */
  38004. getSpotAttenuation( builder ) {
  38005. const attenuation = float( 0 );
  38006. const penumbraCos = this.penumbraCosNode;
  38007. // compute the fragment's position in the light's clip space
  38008. const spotLightCoord = lightShadowMatrix( this.light ).mul( builder.context.positionWorld || positionWorld );
  38009. // the sign of w determines whether the current fragment is in front or behind the light.
  38010. // to avoid a back-projection, it's important to only compute an attenuation if w is positive
  38011. If( spotLightCoord.w.greaterThan( 0 ), () => {
  38012. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  38013. const boxDist = sdBox( projectionUV.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  38014. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  38015. attenuation.assign( saturate( boxDist.mul( -2 ).mul( angleFactor ) ) );
  38016. } );
  38017. return attenuation;
  38018. }
  38019. }
  38020. /**
  38021. * Module for representing ambient lights as nodes.
  38022. *
  38023. * @augments AnalyticLightNode
  38024. */
  38025. class AmbientLightNode extends AnalyticLightNode {
  38026. static get type() {
  38027. return 'AmbientLightNode';
  38028. }
  38029. /**
  38030. * Constructs a new ambient light node.
  38031. *
  38032. * @param {?AmbientLight} [light=null] - The ambient light source.
  38033. */
  38034. constructor( light = null ) {
  38035. super( light );
  38036. }
  38037. setup( { context } ) {
  38038. context.irradiance.addAssign( this.colorNode );
  38039. }
  38040. }
  38041. /**
  38042. * Module for representing hemisphere lights as nodes.
  38043. *
  38044. * @augments AnalyticLightNode
  38045. */
  38046. class HemisphereLightNode extends AnalyticLightNode {
  38047. static get type() {
  38048. return 'HemisphereLightNode';
  38049. }
  38050. /**
  38051. * Constructs a new hemisphere light node.
  38052. *
  38053. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  38054. */
  38055. constructor( light = null ) {
  38056. super( light );
  38057. /**
  38058. * Uniform node representing the light's position.
  38059. *
  38060. * @type {UniformNode<vec3>}
  38061. */
  38062. this.lightPositionNode = lightPosition( light );
  38063. /**
  38064. * A node representing the light's direction.
  38065. *
  38066. * @type {Node<vec3>}
  38067. */
  38068. this.lightDirectionNode = this.lightPositionNode.normalize();
  38069. /**
  38070. * Uniform node representing the light's ground color.
  38071. *
  38072. * @type {UniformNode<vec3>}
  38073. */
  38074. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  38075. }
  38076. /**
  38077. * Overwritten to updated hemisphere light specific uniforms.
  38078. *
  38079. * @param {NodeFrame} frame - A reference to the current node frame.
  38080. */
  38081. update( frame ) {
  38082. const { light } = this;
  38083. super.update( frame );
  38084. this.lightPositionNode.object3d = light;
  38085. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  38086. }
  38087. setup( builder ) {
  38088. const { colorNode, groundColorNode, lightDirectionNode } = this;
  38089. const dotNL = normalWorld.dot( lightDirectionNode );
  38090. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  38091. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  38092. builder.context.irradiance.addAssign( irradiance );
  38093. }
  38094. }
  38095. /**
  38096. * Module for representing light probes as nodes.
  38097. *
  38098. * @augments AnalyticLightNode
  38099. */
  38100. class LightProbeNode extends AnalyticLightNode {
  38101. static get type() {
  38102. return 'LightProbeNode';
  38103. }
  38104. /**
  38105. * Constructs a new light probe node.
  38106. *
  38107. * @param {?LightProbe} [light=null] - The light probe.
  38108. */
  38109. constructor( light = null ) {
  38110. super( light );
  38111. const array = [];
  38112. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  38113. /**
  38114. * Light probe represented as a uniform of spherical harmonics.
  38115. *
  38116. * @type {UniformArrayNode}
  38117. */
  38118. this.lightProbe = uniformArray( array );
  38119. }
  38120. /**
  38121. * Overwritten to updated light probe specific uniforms.
  38122. *
  38123. * @param {NodeFrame} frame - A reference to the current node frame.
  38124. */
  38125. update( frame ) {
  38126. const { light } = this;
  38127. super.update( frame );
  38128. //
  38129. for ( let i = 0; i < 9; i ++ ) {
  38130. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  38131. }
  38132. }
  38133. setup( builder ) {
  38134. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  38135. builder.context.irradiance.addAssign( irradiance );
  38136. }
  38137. }
  38138. /**
  38139. * Base class for node parsers. A derived parser must be implemented
  38140. * for each supported native shader language.
  38141. */
  38142. class NodeParser {
  38143. /**
  38144. * The method parses the given native code an returns a node function.
  38145. *
  38146. * @abstract
  38147. * @param {string} source - The native shader code.
  38148. * @return {NodeFunction} A node function.
  38149. */
  38150. parseFunction( /*source*/ ) {
  38151. warn( 'Abstract function.' );
  38152. }
  38153. }
  38154. /**
  38155. * Base class for node functions. A derived module must be implemented
  38156. * for each supported native shader language. Similar to other `Node*` modules,
  38157. * this class is only relevant during the building process and not used
  38158. * in user-level code.
  38159. */
  38160. class NodeFunction {
  38161. /**
  38162. * Constructs a new node function.
  38163. *
  38164. * @param {string} type - The node type. This type is the return type of the node function.
  38165. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  38166. * @param {string} [name=''] - The function's name.
  38167. * @param {string} [precision=''] - The precision qualifier.
  38168. */
  38169. constructor( type, inputs, name = '', precision = '' ) {
  38170. /**
  38171. * The node type. This type is the return type of the node function.
  38172. *
  38173. * @type {string}
  38174. */
  38175. this.type = type;
  38176. /**
  38177. * The function's inputs.
  38178. *
  38179. * @type {Array<NodeFunctionInput>}
  38180. */
  38181. this.inputs = inputs;
  38182. /**
  38183. * The name of the uniform.
  38184. *
  38185. * @type {string}
  38186. * @default ''
  38187. */
  38188. this.name = name;
  38189. /**
  38190. * The precision qualifier.
  38191. *
  38192. * @type {string}
  38193. * @default ''
  38194. */
  38195. this.precision = precision;
  38196. }
  38197. /**
  38198. * This method returns the native code of the node function.
  38199. *
  38200. * @abstract
  38201. * @param {string} name - The function's name.
  38202. * @return {string} A shader code.
  38203. */
  38204. getCode( /*name = this.name*/ ) {
  38205. warn( 'Abstract function.' );
  38206. }
  38207. }
  38208. NodeFunction.isNodeFunction = true;
  38209. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  38210. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  38211. const pragmaMain = '#pragma main';
  38212. const parse$1 = ( source ) => {
  38213. source = source.trim();
  38214. const pragmaMainIndex = source.indexOf( pragmaMain );
  38215. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  38216. const declaration = mainCode.match( declarationRegexp$1 );
  38217. if ( declaration !== null && declaration.length === 5 ) {
  38218. // tokenizer
  38219. const inputsCode = declaration[ 4 ];
  38220. const propsMatches = [];
  38221. let nameMatch = null;
  38222. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  38223. propsMatches.push( nameMatch );
  38224. }
  38225. // parser
  38226. const inputs = [];
  38227. let i = 0;
  38228. while ( i < propsMatches.length ) {
  38229. const isConst = propsMatches[ i ][ 0 ] === 'const';
  38230. if ( isConst === true ) {
  38231. i ++;
  38232. }
  38233. let qualifier = propsMatches[ i ][ 0 ];
  38234. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  38235. i ++;
  38236. } else {
  38237. qualifier = '';
  38238. }
  38239. const type = propsMatches[ i ++ ][ 0 ];
  38240. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  38241. if ( Number.isNaN( count ) === false ) i ++;
  38242. else count = null;
  38243. const name = propsMatches[ i ++ ][ 0 ];
  38244. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  38245. }
  38246. //
  38247. const blockCode = mainCode.substring( declaration[ 0 ].length );
  38248. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  38249. const type = declaration[ 2 ];
  38250. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  38251. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  38252. return {
  38253. type,
  38254. inputs,
  38255. name,
  38256. precision,
  38257. inputsCode,
  38258. blockCode,
  38259. headerCode
  38260. };
  38261. } else {
  38262. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  38263. }
  38264. };
  38265. /**
  38266. * This class represents a GLSL node function.
  38267. *
  38268. * @augments NodeFunction
  38269. */
  38270. class GLSLNodeFunction extends NodeFunction {
  38271. /**
  38272. * Constructs a new GLSL node function.
  38273. *
  38274. * @param {string} source - The GLSL source.
  38275. */
  38276. constructor( source ) {
  38277. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  38278. super( type, inputs, name, precision );
  38279. this.inputsCode = inputsCode;
  38280. this.blockCode = blockCode;
  38281. this.headerCode = headerCode;
  38282. }
  38283. /**
  38284. * This method returns the GLSL code of the node function.
  38285. *
  38286. * @param {string} [name=this.name] - The function's name.
  38287. * @return {string} The shader code.
  38288. */
  38289. getCode( name = this.name ) {
  38290. let code;
  38291. const blockCode = this.blockCode;
  38292. if ( blockCode !== '' ) {
  38293. const { type, inputsCode, headerCode, precision } = this;
  38294. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  38295. if ( precision !== '' ) {
  38296. declarationCode = `${ precision } ${ declarationCode }`;
  38297. }
  38298. code = headerCode + declarationCode + blockCode;
  38299. } else {
  38300. // interface function
  38301. code = '';
  38302. }
  38303. return code;
  38304. }
  38305. }
  38306. /**
  38307. * A GLSL node parser.
  38308. *
  38309. * @augments NodeParser
  38310. */
  38311. class GLSLNodeParser extends NodeParser {
  38312. /**
  38313. * The method parses the given GLSL code an returns a node function.
  38314. *
  38315. * @param {string} source - The GLSL code.
  38316. * @return {GLSLNodeFunction} A node function.
  38317. */
  38318. parseFunction( source ) {
  38319. return new GLSLNodeFunction( source );
  38320. }
  38321. }
  38322. const _outputNodeMap = new WeakMap();
  38323. const _chainKeys$2 = [];
  38324. const _cacheKeyValues = [];
  38325. /**
  38326. * This renderer module manages node-related objects and is the
  38327. * primary interface between the renderer and the node system.
  38328. *
  38329. * @private
  38330. * @augments DataMap
  38331. */
  38332. class Nodes extends DataMap {
  38333. /**
  38334. * Constructs a new nodes management component.
  38335. *
  38336. * @param {Renderer} renderer - The renderer.
  38337. * @param {Backend} backend - The renderer's backend.
  38338. */
  38339. constructor( renderer, backend ) {
  38340. super();
  38341. /**
  38342. * The renderer.
  38343. *
  38344. * @type {Renderer}
  38345. */
  38346. this.renderer = renderer;
  38347. /**
  38348. * The renderer's backend.
  38349. *
  38350. * @type {Backend}
  38351. */
  38352. this.backend = backend;
  38353. /**
  38354. * The node frame.
  38355. *
  38356. * @type {Renderer}
  38357. */
  38358. this.nodeFrame = new NodeFrame();
  38359. /**
  38360. * A cache for managing node builder states.
  38361. *
  38362. * @type {Map<number,NodeBuilderState>}
  38363. */
  38364. this.nodeBuilderCache = new Map();
  38365. /**
  38366. * A cache for managing data cache key data.
  38367. *
  38368. * @type {ChainMap}
  38369. */
  38370. this.callHashCache = new ChainMap();
  38371. /**
  38372. * A cache for managing node uniforms group data.
  38373. *
  38374. * @type {ChainMap}
  38375. */
  38376. this.groupsData = new ChainMap();
  38377. /**
  38378. * A cache for managing node objects of
  38379. * scene properties like fog or environments.
  38380. *
  38381. * @type {Object<string,WeakMap>}
  38382. */
  38383. this.cacheLib = {};
  38384. }
  38385. /**
  38386. * Returns `true` if the given node uniforms group must be updated or not.
  38387. *
  38388. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  38389. * @return {boolean} Whether the node uniforms group requires an update or not.
  38390. */
  38391. updateGroup( nodeUniformsGroup ) {
  38392. const groupNode = nodeUniformsGroup.groupNode;
  38393. const name = groupNode.name;
  38394. // objectGroup is always updated
  38395. if ( name === objectGroup.name ) return true;
  38396. // renderGroup is updated once per render/compute call
  38397. if ( name === renderGroup.name ) {
  38398. const uniformsGroupData = this.get( nodeUniformsGroup );
  38399. const renderId = this.nodeFrame.renderId;
  38400. if ( uniformsGroupData.renderId !== renderId ) {
  38401. uniformsGroupData.renderId = renderId;
  38402. return true;
  38403. }
  38404. return false;
  38405. }
  38406. // frameGroup is updated once per frame
  38407. if ( name === frameGroup.name ) {
  38408. const uniformsGroupData = this.get( nodeUniformsGroup );
  38409. const frameId = this.nodeFrame.frameId;
  38410. if ( uniformsGroupData.frameId !== frameId ) {
  38411. uniformsGroupData.frameId = frameId;
  38412. return true;
  38413. }
  38414. return false;
  38415. }
  38416. // other groups are updated just when groupNode.needsUpdate is true
  38417. _chainKeys$2[ 0 ] = groupNode;
  38418. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  38419. let groupData = this.groupsData.get( _chainKeys$2 );
  38420. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  38421. _chainKeys$2.length = 0;
  38422. if ( groupData.version !== groupNode.version ) {
  38423. groupData.version = groupNode.version;
  38424. return true;
  38425. }
  38426. return false;
  38427. }
  38428. /**
  38429. * Returns the cache key for the given render object.
  38430. *
  38431. * @param {RenderObject} renderObject - The render object.
  38432. * @return {number} The cache key.
  38433. */
  38434. getForRenderCacheKey( renderObject ) {
  38435. return renderObject.initialCacheKey;
  38436. }
  38437. /**
  38438. * Returns a node builder state for the given render object.
  38439. *
  38440. * @param {RenderObject} renderObject - The render object.
  38441. * @return {NodeBuilderState} The node builder state.
  38442. */
  38443. getForRender( renderObject ) {
  38444. const renderObjectData = this.get( renderObject );
  38445. let nodeBuilderState = renderObjectData.nodeBuilderState;
  38446. if ( nodeBuilderState === undefined ) {
  38447. const { nodeBuilderCache } = this;
  38448. const cacheKey = this.getForRenderCacheKey( renderObject );
  38449. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  38450. if ( nodeBuilderState === undefined ) {
  38451. const createNodeBuilder = ( material ) => {
  38452. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  38453. nodeBuilder.scene = renderObject.scene;
  38454. nodeBuilder.material = material;
  38455. nodeBuilder.camera = renderObject.camera;
  38456. nodeBuilder.context.material = material;
  38457. nodeBuilder.lightsNode = renderObject.lightsNode;
  38458. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  38459. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  38460. nodeBuilder.clippingContext = renderObject.clippingContext;
  38461. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  38462. nodeBuilder.enableMultiview();
  38463. }
  38464. return nodeBuilder;
  38465. };
  38466. let nodeBuilder = createNodeBuilder( renderObject.material );
  38467. try {
  38468. nodeBuilder.build();
  38469. } catch ( e ) {
  38470. nodeBuilder = createNodeBuilder( new NodeMaterial() );
  38471. nodeBuilder.build();
  38472. error( 'TSL: ' + e );
  38473. }
  38474. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  38475. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  38476. }
  38477. nodeBuilderState.usedTimes ++;
  38478. renderObjectData.nodeBuilderState = nodeBuilderState;
  38479. }
  38480. return nodeBuilderState;
  38481. }
  38482. /**
  38483. * Deletes the given object from the internal data map
  38484. *
  38485. * @param {any} object - The object to delete.
  38486. * @return {?Object} The deleted dictionary.
  38487. */
  38488. delete( object ) {
  38489. if ( object.isRenderObject ) {
  38490. const nodeBuilderState = this.get( object ).nodeBuilderState;
  38491. nodeBuilderState.usedTimes --;
  38492. if ( nodeBuilderState.usedTimes === 0 ) {
  38493. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  38494. }
  38495. }
  38496. return super.delete( object );
  38497. }
  38498. /**
  38499. * Returns a node builder state for the given compute node.
  38500. *
  38501. * @param {Node} computeNode - The compute node.
  38502. * @return {NodeBuilderState} The node builder state.
  38503. */
  38504. getForCompute( computeNode ) {
  38505. const computeData = this.get( computeNode );
  38506. let nodeBuilderState = computeData.nodeBuilderState;
  38507. if ( nodeBuilderState === undefined ) {
  38508. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  38509. nodeBuilder.build();
  38510. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  38511. computeData.nodeBuilderState = nodeBuilderState;
  38512. }
  38513. return nodeBuilderState;
  38514. }
  38515. /**
  38516. * Creates a node builder state for the given node builder.
  38517. *
  38518. * @private
  38519. * @param {NodeBuilder} nodeBuilder - The node builder.
  38520. * @return {NodeBuilderState} The node builder state.
  38521. */
  38522. _createNodeBuilderState( nodeBuilder ) {
  38523. return new NodeBuilderState(
  38524. nodeBuilder.vertexShader,
  38525. nodeBuilder.fragmentShader,
  38526. nodeBuilder.computeShader,
  38527. nodeBuilder.getAttributesArray(),
  38528. nodeBuilder.getBindings(),
  38529. nodeBuilder.updateNodes,
  38530. nodeBuilder.updateBeforeNodes,
  38531. nodeBuilder.updateAfterNodes,
  38532. nodeBuilder.observer,
  38533. nodeBuilder.transforms
  38534. );
  38535. }
  38536. /**
  38537. * Returns an environment node for the current configured
  38538. * scene environment.
  38539. *
  38540. * @param {Scene} scene - The scene.
  38541. * @return {Node} A node representing the current scene environment.
  38542. */
  38543. getEnvironmentNode( scene ) {
  38544. this.updateEnvironment( scene );
  38545. let environmentNode = null;
  38546. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  38547. environmentNode = scene.environmentNode;
  38548. } else {
  38549. const sceneData = this.get( scene );
  38550. if ( sceneData.environmentNode ) {
  38551. environmentNode = sceneData.environmentNode;
  38552. }
  38553. }
  38554. return environmentNode;
  38555. }
  38556. /**
  38557. * Returns a background node for the current configured
  38558. * scene background.
  38559. *
  38560. * @param {Scene} scene - The scene.
  38561. * @return {Node} A node representing the current scene background.
  38562. */
  38563. getBackgroundNode( scene ) {
  38564. this.updateBackground( scene );
  38565. let backgroundNode = null;
  38566. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  38567. backgroundNode = scene.backgroundNode;
  38568. } else {
  38569. const sceneData = this.get( scene );
  38570. if ( sceneData.backgroundNode ) {
  38571. backgroundNode = sceneData.backgroundNode;
  38572. }
  38573. }
  38574. return backgroundNode;
  38575. }
  38576. /**
  38577. * Returns a fog node for the current configured scene fog.
  38578. *
  38579. * @param {Scene} scene - The scene.
  38580. * @return {Node} A node representing the current scene fog.
  38581. */
  38582. getFogNode( scene ) {
  38583. this.updateFog( scene );
  38584. return scene.fogNode || this.get( scene ).fogNode || null;
  38585. }
  38586. /**
  38587. * Returns a cache key for the given scene and lights node.
  38588. * This key is used by `RenderObject` as a part of the dynamic
  38589. * cache key (a key that must be checked every time the render
  38590. * objects is drawn).
  38591. *
  38592. * @param {Scene} scene - The scene.
  38593. * @param {LightsNode} lightsNode - The lights node.
  38594. * @return {number} The cache key.
  38595. */
  38596. getCacheKey( scene, lightsNode ) {
  38597. _chainKeys$2[ 0 ] = scene;
  38598. _chainKeys$2[ 1 ] = lightsNode;
  38599. const callId = this.renderer.info.calls;
  38600. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  38601. if ( cacheKeyData.callId !== callId ) {
  38602. const environmentNode = this.getEnvironmentNode( scene );
  38603. const fogNode = this.getFogNode( scene );
  38604. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  38605. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  38606. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  38607. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  38608. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  38609. _cacheKeyValues.push( this.renderer.shadowMap.type );
  38610. cacheKeyData.callId = callId;
  38611. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  38612. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  38613. _cacheKeyValues.length = 0;
  38614. }
  38615. _chainKeys$2.length = 0;
  38616. return cacheKeyData.cacheKey;
  38617. }
  38618. /**
  38619. * A boolean that indicates whether tone mapping should be enabled
  38620. * or not.
  38621. *
  38622. * @type {boolean}
  38623. */
  38624. get isToneMappingState() {
  38625. return this.renderer.getRenderTarget() ? false : true;
  38626. }
  38627. /**
  38628. * If a scene background is configured, this method makes sure to
  38629. * represent the background with a corresponding node-based implementation.
  38630. *
  38631. * @param {Scene} scene - The scene.
  38632. */
  38633. updateBackground( scene ) {
  38634. const sceneData = this.get( scene );
  38635. const background = scene.background;
  38636. if ( background ) {
  38637. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  38638. if ( sceneData.background !== background || forceUpdate ) {
  38639. const backgroundNode = this.getCacheNode( 'background', background, () => {
  38640. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  38641. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  38642. return pmremTexture( background );
  38643. } else {
  38644. let envMap;
  38645. if ( background.isCubeTexture === true ) {
  38646. envMap = cubeTexture( background );
  38647. } else {
  38648. envMap = texture( background );
  38649. }
  38650. return cubeMapNode( envMap );
  38651. }
  38652. } else if ( background.isTexture === true ) {
  38653. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  38654. } else if ( background.isColor !== true ) {
  38655. error( 'WebGPUNodes: Unsupported background configuration.', background );
  38656. }
  38657. }, forceUpdate );
  38658. sceneData.backgroundNode = backgroundNode;
  38659. sceneData.background = background;
  38660. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  38661. }
  38662. } else if ( sceneData.backgroundNode ) {
  38663. delete sceneData.backgroundNode;
  38664. delete sceneData.background;
  38665. }
  38666. }
  38667. /**
  38668. * This method is part of the caching of nodes which are used to represents the
  38669. * scene's background, fog or environment.
  38670. *
  38671. * @param {string} type - The type of object to cache.
  38672. * @param {Object} object - The object.
  38673. * @param {Function} callback - A callback that produces a node representation for the given object.
  38674. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  38675. * @return {Node} The node representation.
  38676. */
  38677. getCacheNode( type, object, callback, forceUpdate = false ) {
  38678. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  38679. let node = nodeCache.get( object );
  38680. if ( node === undefined || forceUpdate ) {
  38681. node = callback();
  38682. nodeCache.set( object, node );
  38683. }
  38684. return node;
  38685. }
  38686. /**
  38687. * If a scene fog is configured, this method makes sure to
  38688. * represent the fog with a corresponding node-based implementation.
  38689. *
  38690. * @param {Scene} scene - The scene.
  38691. */
  38692. updateFog( scene ) {
  38693. const sceneData = this.get( scene );
  38694. const sceneFog = scene.fog;
  38695. if ( sceneFog ) {
  38696. if ( sceneData.fog !== sceneFog ) {
  38697. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  38698. if ( sceneFog.isFogExp2 ) {
  38699. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  38700. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  38701. return fog( color, densityFogFactor( density ) );
  38702. } else if ( sceneFog.isFog ) {
  38703. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  38704. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  38705. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  38706. return fog( color, rangeFogFactor( near, far ) );
  38707. } else {
  38708. error( 'Renderer: Unsupported fog configuration.', sceneFog );
  38709. }
  38710. } );
  38711. sceneData.fogNode = fogNode;
  38712. sceneData.fog = sceneFog;
  38713. }
  38714. } else {
  38715. delete sceneData.fogNode;
  38716. delete sceneData.fog;
  38717. }
  38718. }
  38719. /**
  38720. * If a scene environment is configured, this method makes sure to
  38721. * represent the environment with a corresponding node-based implementation.
  38722. *
  38723. * @param {Scene} scene - The scene.
  38724. */
  38725. updateEnvironment( scene ) {
  38726. const sceneData = this.get( scene );
  38727. const environment = scene.environment;
  38728. if ( environment ) {
  38729. if ( sceneData.environment !== environment ) {
  38730. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  38731. if ( environment.isCubeTexture === true ) {
  38732. return cubeTexture( environment );
  38733. } else if ( environment.isTexture === true ) {
  38734. return texture( environment );
  38735. } else {
  38736. error( 'Nodes: Unsupported environment configuration.', environment );
  38737. }
  38738. } );
  38739. sceneData.environmentNode = environmentNode;
  38740. sceneData.environment = environment;
  38741. }
  38742. } else if ( sceneData.environmentNode ) {
  38743. delete sceneData.environmentNode;
  38744. delete sceneData.environment;
  38745. }
  38746. }
  38747. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  38748. const nodeFrame = this.nodeFrame;
  38749. nodeFrame.renderer = renderer;
  38750. nodeFrame.scene = scene;
  38751. nodeFrame.object = object;
  38752. nodeFrame.camera = camera;
  38753. nodeFrame.material = material;
  38754. return nodeFrame;
  38755. }
  38756. getNodeFrameForRender( renderObject ) {
  38757. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  38758. }
  38759. /**
  38760. * Returns the current output cache key.
  38761. *
  38762. * @return {string} The output cache key.
  38763. */
  38764. getOutputCacheKey() {
  38765. const renderer = this.renderer;
  38766. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  38767. }
  38768. /**
  38769. * Checks if the output configuration (tone mapping and color space) for
  38770. * the given target has changed.
  38771. *
  38772. * @param {Texture} outputTarget - The output target.
  38773. * @return {boolean} Whether the output configuration has changed or not.
  38774. */
  38775. hasOutputChange( outputTarget ) {
  38776. const cacheKey = _outputNodeMap.get( outputTarget );
  38777. return cacheKey !== this.getOutputCacheKey();
  38778. }
  38779. /**
  38780. * Returns a node that represents the output configuration (tone mapping and
  38781. * color space) for the current target.
  38782. *
  38783. * @param {Texture} outputTarget - The output target.
  38784. * @return {Node} The output node.
  38785. */
  38786. getOutputNode( outputTarget ) {
  38787. const renderer = this.renderer;
  38788. const cacheKey = this.getOutputCacheKey();
  38789. const output = outputTarget.isArrayTexture ?
  38790. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  38791. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  38792. _outputNodeMap.set( outputTarget, cacheKey );
  38793. return output;
  38794. }
  38795. /**
  38796. * Triggers the call of `updateBefore()` methods
  38797. * for all nodes of the given render object.
  38798. *
  38799. * @param {RenderObject} renderObject - The render object.
  38800. */
  38801. updateBefore( renderObject ) {
  38802. const nodeBuilder = renderObject.getNodeBuilderState();
  38803. for ( const node of nodeBuilder.updateBeforeNodes ) {
  38804. // update frame state for each node
  38805. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  38806. }
  38807. }
  38808. /**
  38809. * Triggers the call of `updateAfter()` methods
  38810. * for all nodes of the given render object.
  38811. *
  38812. * @param {RenderObject} renderObject - The render object.
  38813. */
  38814. updateAfter( renderObject ) {
  38815. const nodeBuilder = renderObject.getNodeBuilderState();
  38816. for ( const node of nodeBuilder.updateAfterNodes ) {
  38817. // update frame state for each node
  38818. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  38819. }
  38820. }
  38821. /**
  38822. * Triggers the call of `update()` methods
  38823. * for all nodes of the given compute node.
  38824. *
  38825. * @param {Node} computeNode - The compute node.
  38826. */
  38827. updateForCompute( computeNode ) {
  38828. const nodeFrame = this.getNodeFrame();
  38829. const nodeBuilder = this.getForCompute( computeNode );
  38830. for ( const node of nodeBuilder.updateNodes ) {
  38831. nodeFrame.updateNode( node );
  38832. }
  38833. }
  38834. /**
  38835. * Triggers the call of `update()` methods
  38836. * for all nodes of the given compute node.
  38837. *
  38838. * @param {RenderObject} renderObject - The render object.
  38839. */
  38840. updateForRender( renderObject ) {
  38841. const nodeFrame = this.getNodeFrameForRender( renderObject );
  38842. const nodeBuilder = renderObject.getNodeBuilderState();
  38843. for ( const node of nodeBuilder.updateNodes ) {
  38844. nodeFrame.updateNode( node );
  38845. }
  38846. }
  38847. /**
  38848. * Returns `true` if the given render object requires a refresh.
  38849. *
  38850. * @param {RenderObject} renderObject - The render object.
  38851. * @return {boolean} Whether the given render object requires a refresh or not.
  38852. */
  38853. needsRefresh( renderObject ) {
  38854. const nodeFrame = this.getNodeFrameForRender( renderObject );
  38855. const monitor = renderObject.getMonitor();
  38856. return monitor.needsRefresh( renderObject, nodeFrame );
  38857. }
  38858. /**
  38859. * Frees the internal resources.
  38860. */
  38861. dispose() {
  38862. super.dispose();
  38863. this.nodeFrame = new NodeFrame();
  38864. this.nodeBuilderCache = new Map();
  38865. this.cacheLib = {};
  38866. }
  38867. }
  38868. const _plane = /*@__PURE__*/ new Plane();
  38869. /**
  38870. * Represents the state that is used to perform clipping via clipping planes.
  38871. * There is a default clipping context for each render context. When the
  38872. * scene holds instances of `ClippingGroup`, there will be a context for each
  38873. * group.
  38874. *
  38875. * @private
  38876. */
  38877. class ClippingContext {
  38878. /**
  38879. * Constructs a new clipping context.
  38880. *
  38881. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  38882. */
  38883. constructor( parentContext = null ) {
  38884. /**
  38885. * The clipping context's version.
  38886. *
  38887. * @type {number}
  38888. * @readonly
  38889. */
  38890. this.version = 0;
  38891. /**
  38892. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  38893. *
  38894. * @type {?boolean}
  38895. * @default null
  38896. */
  38897. this.clipIntersection = null;
  38898. /**
  38899. * The clipping context's cache key.
  38900. *
  38901. * @type {string}
  38902. */
  38903. this.cacheKey = '';
  38904. /**
  38905. * Whether the shadow pass is active or not.
  38906. *
  38907. * @type {boolean}
  38908. * @default false
  38909. */
  38910. this.shadowPass = false;
  38911. /**
  38912. * The view normal matrix.
  38913. *
  38914. * @type {Matrix3}
  38915. */
  38916. this.viewNormalMatrix = new Matrix3();
  38917. /**
  38918. * Internal cache for maintaining clipping contexts.
  38919. *
  38920. * @type {WeakMap<ClippingGroup,ClippingContext>}
  38921. */
  38922. this.clippingGroupContexts = new WeakMap();
  38923. /**
  38924. * The intersection planes.
  38925. *
  38926. * @type {Array<Vector4>}
  38927. */
  38928. this.intersectionPlanes = [];
  38929. /**
  38930. * The intersection planes.
  38931. *
  38932. * @type {Array<Vector4>}
  38933. */
  38934. this.unionPlanes = [];
  38935. /**
  38936. * The version of the clipping context's parent context.
  38937. *
  38938. * @type {?number}
  38939. * @readonly
  38940. */
  38941. this.parentVersion = null;
  38942. if ( parentContext !== null ) {
  38943. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  38944. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  38945. this.shadowPass = parentContext.shadowPass;
  38946. this.viewMatrix = parentContext.viewMatrix;
  38947. }
  38948. }
  38949. /**
  38950. * Projects the given source clipping planes and writes the result into the
  38951. * destination array.
  38952. *
  38953. * @param {Array<Plane>} source - The source clipping planes.
  38954. * @param {Array<Vector4>} destination - The destination.
  38955. * @param {number} offset - The offset.
  38956. */
  38957. projectPlanes( source, destination, offset ) {
  38958. const l = source.length;
  38959. for ( let i = 0; i < l; i ++ ) {
  38960. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  38961. const v = destination[ offset + i ];
  38962. const normal = _plane.normal;
  38963. v.x = - normal.x;
  38964. v.y = - normal.y;
  38965. v.z = - normal.z;
  38966. v.w = _plane.constant;
  38967. }
  38968. }
  38969. /**
  38970. * Updates the root clipping context of a scene.
  38971. *
  38972. * @param {Scene} scene - The scene.
  38973. * @param {Camera} camera - The camera that is used to render the scene.
  38974. */
  38975. updateGlobal( scene, camera ) {
  38976. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  38977. this.viewMatrix = camera.matrixWorldInverse;
  38978. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  38979. }
  38980. /**
  38981. * Updates the clipping context.
  38982. *
  38983. * @param {ClippingContext} parentContext - The parent context.
  38984. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  38985. */
  38986. update( parentContext, clippingGroup ) {
  38987. let update = false;
  38988. if ( parentContext.version !== this.parentVersion ) {
  38989. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  38990. this.unionPlanes = Array.from( parentContext.unionPlanes );
  38991. this.parentVersion = parentContext.version;
  38992. }
  38993. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  38994. this.clipIntersection = clippingGroup.clipIntersection;
  38995. if ( this.clipIntersection ) {
  38996. this.unionPlanes.length = parentContext.unionPlanes.length;
  38997. } else {
  38998. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  38999. }
  39000. }
  39001. const srcClippingPlanes = clippingGroup.clippingPlanes;
  39002. const l = srcClippingPlanes.length;
  39003. let dstClippingPlanes;
  39004. let offset;
  39005. if ( this.clipIntersection ) {
  39006. dstClippingPlanes = this.intersectionPlanes;
  39007. offset = parentContext.intersectionPlanes.length;
  39008. } else {
  39009. dstClippingPlanes = this.unionPlanes;
  39010. offset = parentContext.unionPlanes.length;
  39011. }
  39012. if ( dstClippingPlanes.length !== offset + l ) {
  39013. dstClippingPlanes.length = offset + l;
  39014. for ( let i = 0; i < l; i ++ ) {
  39015. dstClippingPlanes[ offset + i ] = new Vector4();
  39016. }
  39017. update = true;
  39018. }
  39019. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  39020. if ( update ) {
  39021. this.version ++;
  39022. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  39023. }
  39024. }
  39025. /**
  39026. * Returns a clipping context for the given clipping group.
  39027. *
  39028. * @param {ClippingGroup} clippingGroup - The clipping group.
  39029. * @return {ClippingContext} The clipping context.
  39030. */
  39031. getGroupContext( clippingGroup ) {
  39032. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  39033. let context = this.clippingGroupContexts.get( clippingGroup );
  39034. if ( context === undefined ) {
  39035. context = new ClippingContext( this );
  39036. this.clippingGroupContexts.set( clippingGroup, context );
  39037. }
  39038. context.update( this, clippingGroup );
  39039. return context;
  39040. }
  39041. /**
  39042. * The count of union clipping planes.
  39043. *
  39044. * @type {number}
  39045. * @readonly
  39046. */
  39047. get unionClippingCount() {
  39048. return this.unionPlanes.length;
  39049. }
  39050. }
  39051. /**
  39052. * This module is used to represent render bundles inside the renderer
  39053. * for further processing.
  39054. *
  39055. * @private
  39056. */
  39057. class RenderBundle {
  39058. /**
  39059. * Constructs a new bundle group.
  39060. *
  39061. * @param {BundleGroup} bundleGroup - The bundle group.
  39062. * @param {Camera} camera - The camera the bundle group is rendered with.
  39063. */
  39064. constructor( bundleGroup, camera ) {
  39065. this.bundleGroup = bundleGroup;
  39066. this.camera = camera;
  39067. }
  39068. }
  39069. const _chainKeys$1 = [];
  39070. /**
  39071. * This renderer module manages render bundles.
  39072. *
  39073. * @private
  39074. */
  39075. class RenderBundles {
  39076. /**
  39077. * Constructs a new render bundle management component.
  39078. */
  39079. constructor() {
  39080. /**
  39081. * A chain map for maintaining the render bundles.
  39082. *
  39083. * @type {ChainMap}
  39084. */
  39085. this.bundles = new ChainMap();
  39086. }
  39087. /**
  39088. * Returns a render bundle for the given bundle group and camera.
  39089. *
  39090. * @param {BundleGroup} bundleGroup - The bundle group.
  39091. * @param {Camera} camera - The camera the bundle group is rendered with.
  39092. * @return {RenderBundle} The render bundle.
  39093. */
  39094. get( bundleGroup, camera ) {
  39095. const bundles = this.bundles;
  39096. _chainKeys$1[ 0 ] = bundleGroup;
  39097. _chainKeys$1[ 1 ] = camera;
  39098. let bundle = bundles.get( _chainKeys$1 );
  39099. if ( bundle === undefined ) {
  39100. bundle = new RenderBundle( bundleGroup, camera );
  39101. bundles.set( _chainKeys$1, bundle );
  39102. }
  39103. _chainKeys$1.length = 0;
  39104. return bundle;
  39105. }
  39106. /**
  39107. * Frees all internal resources.
  39108. */
  39109. dispose() {
  39110. this.bundles = new ChainMap();
  39111. }
  39112. }
  39113. /**
  39114. * The purpose of a node library is to assign node implementations
  39115. * to existing library features. In `WebGPURenderer` lights, materials
  39116. * which are not based on `NodeMaterial` as well as tone mapping techniques
  39117. * are implemented with node-based modules.
  39118. *
  39119. * @private
  39120. */
  39121. class NodeLibrary {
  39122. /**
  39123. * Constructs a new node library.
  39124. */
  39125. constructor() {
  39126. /**
  39127. * A weak map that maps lights to light nodes.
  39128. *
  39129. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  39130. */
  39131. this.lightNodes = new WeakMap();
  39132. /**
  39133. * A map that maps materials to node materials.
  39134. *
  39135. * @type {Map<string,NodeMaterial.constructor>}
  39136. */
  39137. this.materialNodes = new Map();
  39138. /**
  39139. * A map that maps tone mapping techniques (constants)
  39140. * to tone mapping node functions.
  39141. *
  39142. * @type {Map<number,Function>}
  39143. */
  39144. this.toneMappingNodes = new Map();
  39145. }
  39146. /**
  39147. * Returns a matching node material instance for the given material object.
  39148. *
  39149. * This method also assigns/copies the properties of the given material object
  39150. * to the node material. This is done to make sure the current material
  39151. * configuration carries over to the node version.
  39152. *
  39153. * @param {Material} material - A material.
  39154. * @return {NodeMaterial} The corresponding node material.
  39155. */
  39156. fromMaterial( material ) {
  39157. if ( material.isNodeMaterial ) return material;
  39158. let nodeMaterial = null;
  39159. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  39160. if ( nodeMaterialClass !== null ) {
  39161. nodeMaterial = new nodeMaterialClass();
  39162. for ( const key in material ) {
  39163. nodeMaterial[ key ] = material[ key ];
  39164. }
  39165. }
  39166. return nodeMaterial;
  39167. }
  39168. /**
  39169. * Adds a tone mapping node function for a tone mapping technique (constant).
  39170. *
  39171. * @param {Function} toneMappingNode - The tone mapping node function.
  39172. * @param {number} toneMapping - The tone mapping.
  39173. */
  39174. addToneMapping( toneMappingNode, toneMapping ) {
  39175. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  39176. }
  39177. /**
  39178. * Returns a tone mapping node function for a tone mapping technique (constant).
  39179. *
  39180. * @param {number} toneMapping - The tone mapping.
  39181. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  39182. */
  39183. getToneMappingFunction( toneMapping ) {
  39184. return this.toneMappingNodes.get( toneMapping ) || null;
  39185. }
  39186. /**
  39187. * Returns a node material class definition for a material type.
  39188. *
  39189. * @param {string} materialType - The material type.
  39190. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  39191. */
  39192. getMaterialNodeClass( materialType ) {
  39193. return this.materialNodes.get( materialType ) || null;
  39194. }
  39195. /**
  39196. * Adds a node material class definition for a given material type.
  39197. *
  39198. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  39199. * @param {string} materialClassType - The material type.
  39200. */
  39201. addMaterial( materialNodeClass, materialClassType ) {
  39202. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  39203. }
  39204. /**
  39205. * Returns a light node class definition for a light class definition.
  39206. *
  39207. * @param {Light.constructor} light - The light class definition.
  39208. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  39209. */
  39210. getLightNodeClass( light ) {
  39211. return this.lightNodes.get( light ) || null;
  39212. }
  39213. /**
  39214. * Adds a light node class definition for a given light class definition.
  39215. *
  39216. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  39217. * @param {Light.constructor} lightClass - The light class definition.
  39218. */
  39219. addLight( lightNodeClass, lightClass ) {
  39220. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  39221. }
  39222. /**
  39223. * Adds a node class definition for the given type to the provided type library.
  39224. *
  39225. * @param {Node.constructor} nodeClass - The node class definition.
  39226. * @param {number|string} type - The object type.
  39227. * @param {Map<number|string,Node.constructor>} library - The type library.
  39228. */
  39229. addType( nodeClass, type, library ) {
  39230. if ( library.has( type ) ) {
  39231. warn( `Redefinition of node ${ type }` );
  39232. return;
  39233. }
  39234. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  39235. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  39236. library.set( type, nodeClass );
  39237. }
  39238. /**
  39239. * Adds a node class definition for the given class definition to the provided type library.
  39240. *
  39241. * @param {Node.constructor} nodeClass - The node class definition.
  39242. * @param {Node.constructor} baseClass - The class definition.
  39243. * @param {WeakMap<Node.constructor, Node.constructor>} library - The type library.
  39244. */
  39245. addClass( nodeClass, baseClass, library ) {
  39246. if ( library.has( baseClass ) ) {
  39247. warn( `Redefinition of node ${ baseClass.name }` );
  39248. return;
  39249. }
  39250. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  39251. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  39252. library.set( baseClass, nodeClass );
  39253. }
  39254. }
  39255. const _defaultLights = /*@__PURE__*/ new LightsNode();
  39256. const _chainKeys = [];
  39257. /**
  39258. * This renderer module manages the lights nodes which are unique
  39259. * per scene and camera combination.
  39260. *
  39261. * The lights node itself is later configured in the render list
  39262. * with the actual lights from the scene.
  39263. *
  39264. * @private
  39265. * @augments ChainMap
  39266. */
  39267. class Lighting extends ChainMap {
  39268. /**
  39269. * Constructs a lighting management component.
  39270. */
  39271. constructor() {
  39272. super();
  39273. }
  39274. /**
  39275. * Creates a new lights node for the given array of lights.
  39276. *
  39277. * @param {Array<Light>} lights - The render object.
  39278. * @return {LightsNode} The lights node.
  39279. */
  39280. createNode( lights = [] ) {
  39281. return new LightsNode().setLights( lights );
  39282. }
  39283. /**
  39284. * Returns a lights node for the given scene and camera.
  39285. *
  39286. * @param {Scene} scene - The scene.
  39287. * @param {Camera} camera - The camera.
  39288. * @return {LightsNode} The lights node.
  39289. */
  39290. getNode( scene, camera ) {
  39291. // ignore post-processing
  39292. if ( scene.isQuadMesh ) return _defaultLights;
  39293. _chainKeys[ 0 ] = scene;
  39294. _chainKeys[ 1 ] = camera;
  39295. let node = this.get( _chainKeys );
  39296. if ( node === undefined ) {
  39297. node = this.createNode();
  39298. this.set( _chainKeys, node );
  39299. }
  39300. _chainKeys.length = 0;
  39301. return node;
  39302. }
  39303. }
  39304. /**
  39305. * A special type of render target that is used when rendering
  39306. * with the WebXR Device API.
  39307. *
  39308. * @private
  39309. * @augments RenderTarget
  39310. */
  39311. class XRRenderTarget extends RenderTarget {
  39312. /**
  39313. * Constructs a new XR render target.
  39314. *
  39315. * @param {number} [width=1] - The width of the render target.
  39316. * @param {number} [height=1] - The height of the render target.
  39317. * @param {Object} [options={}] - The configuration options.
  39318. */
  39319. constructor( width = 1, height = 1, options = {} ) {
  39320. super( width, height, options );
  39321. /**
  39322. * This flag can be used for type testing.
  39323. *
  39324. * @type {boolean}
  39325. * @readonly
  39326. * @default true
  39327. */
  39328. this.isXRRenderTarget = true;
  39329. /**
  39330. * Whether the attachments of the render target
  39331. * are defined by external textures. This flag is
  39332. * set to `true` when using the WebXR Layers API.
  39333. *
  39334. * @private
  39335. * @type {boolean}
  39336. * @default false
  39337. */
  39338. this._hasExternalTextures = false;
  39339. /**
  39340. * Whether a depth buffer should automatically be allocated
  39341. * for this XR render target or not.
  39342. *
  39343. * Allocating a depth buffer is the default behavior of XR render
  39344. * targets. However, when using the WebXR Layers API, this flag
  39345. * must be set to `false` when the `ignoreDepthValues` property of
  39346. * the projection layers evaluates to `false`.
  39347. *
  39348. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  39349. *
  39350. * @private
  39351. * @type {boolean}
  39352. * @default true
  39353. */
  39354. this._autoAllocateDepthBuffer = true;
  39355. /**
  39356. * Whether this render target is associated with a XRWebGLLayer.
  39357. *
  39358. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  39359. * this means that you don't have access to its bound color,
  39360. * stencil and depth buffers. We need to handle this framebuffer
  39361. * differently since its textures are always bound.
  39362. *
  39363. * @private
  39364. * @type {boolean}
  39365. * @default false
  39366. * */
  39367. this._isOpaqueFramebuffer = false;
  39368. }
  39369. copy( source ) {
  39370. super.copy( source );
  39371. this._hasExternalTextures = source._hasExternalTextures;
  39372. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  39373. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  39374. return this;
  39375. }
  39376. }
  39377. const _cameraLPos = /*@__PURE__*/ new Vector3();
  39378. const _cameraRPos = /*@__PURE__*/ new Vector3();
  39379. /**
  39380. * The XR manager is built on top of the WebXR Device API to
  39381. * manage XR sessions with `WebGPURenderer`.
  39382. *
  39383. * XR is currently only supported with a WebGL 2 backend.
  39384. *
  39385. * @augments EventDispatcher
  39386. */
  39387. class XRManager extends EventDispatcher {
  39388. /**
  39389. * Constructs a new XR manager.
  39390. *
  39391. * @param {Renderer} renderer - The renderer.
  39392. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  39393. */
  39394. constructor( renderer, multiview = false ) {
  39395. super();
  39396. /**
  39397. * This flag globally enables XR rendering.
  39398. *
  39399. * @type {boolean}
  39400. * @default false
  39401. */
  39402. this.enabled = false;
  39403. /**
  39404. * Whether the XR device is currently presenting or not.
  39405. *
  39406. * @type {boolean}
  39407. * @default false
  39408. * @readonly
  39409. */
  39410. this.isPresenting = false;
  39411. /**
  39412. * Whether the XR camera should automatically be updated or not.
  39413. *
  39414. * @type {boolean}
  39415. * @default true
  39416. */
  39417. this.cameraAutoUpdate = true;
  39418. /**
  39419. * The renderer.
  39420. *
  39421. * @private
  39422. * @type {Renderer}
  39423. */
  39424. this._renderer = renderer;
  39425. // camera
  39426. /**
  39427. * Represents the camera for the left eye.
  39428. *
  39429. * @private
  39430. * @type {PerspectiveCamera}
  39431. */
  39432. this._cameraL = new PerspectiveCamera();
  39433. this._cameraL.viewport = new Vector4();
  39434. /**
  39435. * Represents the camera for the right eye.
  39436. *
  39437. * @private
  39438. * @type {PerspectiveCamera}
  39439. */
  39440. this._cameraR = new PerspectiveCamera();
  39441. this._cameraR.viewport = new Vector4();
  39442. /**
  39443. * A list of cameras used for rendering the XR views.
  39444. *
  39445. * @private
  39446. * @type {Array<Camera>}
  39447. */
  39448. this._cameras = [ this._cameraL, this._cameraR ];
  39449. /**
  39450. * The main XR camera.
  39451. *
  39452. * @private
  39453. * @type {ArrayCamera}
  39454. */
  39455. this._cameraXR = new ArrayCamera();
  39456. /**
  39457. * The current near value of the XR camera.
  39458. *
  39459. * @private
  39460. * @type {?number}
  39461. * @default null
  39462. */
  39463. this._currentDepthNear = null;
  39464. /**
  39465. * The current far value of the XR camera.
  39466. *
  39467. * @private
  39468. * @type {?number}
  39469. * @default null
  39470. */
  39471. this._currentDepthFar = null;
  39472. /**
  39473. * A list of WebXR controllers requested by the application.
  39474. *
  39475. * @private
  39476. * @type {Array<WebXRController>}
  39477. */
  39478. this._controllers = [];
  39479. /**
  39480. * A list of XR input source. Each input source belongs to
  39481. * an instance of WebXRController.
  39482. *
  39483. * @private
  39484. * @type {Array<XRInputSource?>}
  39485. */
  39486. this._controllerInputSources = [];
  39487. /**
  39488. * The XR render target that represents the rendering destination
  39489. * during an active XR session.
  39490. *
  39491. * @private
  39492. * @type {?RenderTarget}
  39493. * @default null
  39494. */
  39495. this._xrRenderTarget = null;
  39496. /**
  39497. * An array holding all the non-projection layers
  39498. *
  39499. * @private
  39500. * @type {Array<Object>}
  39501. * @default []
  39502. */
  39503. this._layers = [];
  39504. /**
  39505. * Whether the XR session uses layers.
  39506. *
  39507. * @private
  39508. * @type {boolean}
  39509. * @default false
  39510. */
  39511. this._sessionUsesLayers = false;
  39512. /**
  39513. * Whether the device supports binding gl objects.
  39514. *
  39515. * @private
  39516. * @type {boolean}
  39517. * @readonly
  39518. */
  39519. this._supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  39520. this._frameBufferTargets = null;
  39521. /**
  39522. * Helper function to create native WebXR Layer.
  39523. *
  39524. * @private
  39525. * @type {Function}
  39526. */
  39527. this._createXRLayer = createXRLayer.bind( this );
  39528. /**
  39529. * The current WebGL context.
  39530. *
  39531. * @private
  39532. * @type {?WebGL2RenderingContext}
  39533. * @default null
  39534. */
  39535. this._gl = null;
  39536. /**
  39537. * The current animation context.
  39538. *
  39539. * @private
  39540. * @type {?Window}
  39541. * @default null
  39542. */
  39543. this._currentAnimationContext = null;
  39544. /**
  39545. * The current animation loop.
  39546. *
  39547. * @private
  39548. * @type {?Function}
  39549. * @default null
  39550. */
  39551. this._currentAnimationLoop = null;
  39552. /**
  39553. * The current pixel ratio.
  39554. *
  39555. * @private
  39556. * @type {?number}
  39557. * @default null
  39558. */
  39559. this._currentPixelRatio = null;
  39560. /**
  39561. * The current size of the renderer's canvas
  39562. * in logical pixel unit.
  39563. *
  39564. * @private
  39565. * @type {Vector2}
  39566. */
  39567. this._currentSize = new Vector2();
  39568. /**
  39569. * The default event listener for handling events inside a XR session.
  39570. *
  39571. * @private
  39572. * @type {Function}
  39573. */
  39574. this._onSessionEvent = onSessionEvent.bind( this );
  39575. /**
  39576. * The event listener for handling the end of a XR session.
  39577. *
  39578. * @private
  39579. * @type {Function}
  39580. */
  39581. this._onSessionEnd = onSessionEnd.bind( this );
  39582. /**
  39583. * The event listener for handling the `inputsourceschange` event.
  39584. *
  39585. * @private
  39586. * @type {Function}
  39587. */
  39588. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  39589. /**
  39590. * The animation loop which is used as a replacement for the default
  39591. * animation loop of the application. It is only used when a XR session
  39592. * is active.
  39593. *
  39594. * @private
  39595. * @type {Function}
  39596. */
  39597. this._onAnimationFrame = onAnimationFrame.bind( this );
  39598. /**
  39599. * The current XR reference space.
  39600. *
  39601. * @private
  39602. * @type {?XRReferenceSpace}
  39603. * @default null
  39604. */
  39605. this._referenceSpace = null;
  39606. /**
  39607. * The current XR reference space type.
  39608. *
  39609. * @private
  39610. * @type {XRReferenceSpaceType}
  39611. * @default 'local-floor'
  39612. */
  39613. this._referenceSpaceType = 'local-floor';
  39614. /**
  39615. * A custom reference space defined by the application.
  39616. *
  39617. * @private
  39618. * @type {?XRReferenceSpace}
  39619. * @default null
  39620. */
  39621. this._customReferenceSpace = null;
  39622. /**
  39623. * The framebuffer scale factor.
  39624. *
  39625. * @private
  39626. * @type {number}
  39627. * @default 1
  39628. */
  39629. this._framebufferScaleFactor = 1;
  39630. /**
  39631. * The foveation factor.
  39632. *
  39633. * @private
  39634. * @type {number}
  39635. * @default 1
  39636. */
  39637. this._foveation = 1.0;
  39638. /**
  39639. * A reference to the current XR session.
  39640. *
  39641. * @private
  39642. * @type {?XRSession}
  39643. * @default null
  39644. */
  39645. this._session = null;
  39646. /**
  39647. * A reference to the current XR base layer.
  39648. *
  39649. * @private
  39650. * @type {?XRWebGLLayer}
  39651. * @default null
  39652. */
  39653. this._glBaseLayer = null;
  39654. /**
  39655. * A reference to the current XR binding.
  39656. *
  39657. * @private
  39658. * @type {?XRWebGLBinding}
  39659. * @default null
  39660. */
  39661. this._glBinding = null;
  39662. /**
  39663. * A reference to the current XR projection layer.
  39664. *
  39665. * @private
  39666. * @type {?XRProjectionLayer}
  39667. * @default null
  39668. */
  39669. this._glProjLayer = null;
  39670. /**
  39671. * A reference to the current XR frame.
  39672. *
  39673. * @private
  39674. * @type {?XRFrame}
  39675. * @default null
  39676. */
  39677. this._xrFrame = null;
  39678. /**
  39679. * Whether the browser supports the APIs necessary to use XRProjectionLayers.
  39680. *
  39681. * Note: this does not represent XRSession explicitly requesting
  39682. * `'layers'` as a feature - see `_sessionUsesLayers` and #30112
  39683. *
  39684. * @private
  39685. * @type {boolean}
  39686. * @readonly
  39687. */
  39688. this._supportsLayers = ( this._supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  39689. /**
  39690. * Whether the usage of multiview has been requested by the application or not.
  39691. *
  39692. * @private
  39693. * @type {boolean}
  39694. * @default false
  39695. * @readonly
  39696. */
  39697. this._useMultiviewIfPossible = multiview;
  39698. /**
  39699. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  39700. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  39701. *
  39702. * @private
  39703. * @type {boolean}
  39704. * @readonly
  39705. */
  39706. this._useMultiview = false;
  39707. }
  39708. /**
  39709. * Returns an instance of `THREE.Group` that represents the transformation
  39710. * of a XR controller in target ray space. The requested controller is defined
  39711. * by the given index.
  39712. *
  39713. * @param {number} index - The index of the XR controller.
  39714. * @return {Group} A group that represents the controller's transformation.
  39715. */
  39716. getController( index ) {
  39717. const controller = this._getController( index );
  39718. return controller.getTargetRaySpace();
  39719. }
  39720. /**
  39721. * Returns an instance of `THREE.Group` that represents the transformation
  39722. * of a XR controller in grip space. The requested controller is defined
  39723. * by the given index.
  39724. *
  39725. * @param {number} index - The index of the XR controller.
  39726. * @return {Group} A group that represents the controller's transformation.
  39727. */
  39728. getControllerGrip( index ) {
  39729. const controller = this._getController( index );
  39730. return controller.getGripSpace();
  39731. }
  39732. /**
  39733. * Returns an instance of `THREE.Group` that represents the transformation
  39734. * of a XR controller in hand space. The requested controller is defined
  39735. * by the given index.
  39736. *
  39737. * @param {number} index - The index of the XR controller.
  39738. * @return {Group} A group that represents the controller's transformation.
  39739. */
  39740. getHand( index ) {
  39741. const controller = this._getController( index );
  39742. return controller.getHandSpace();
  39743. }
  39744. /**
  39745. * Returns the foveation value.
  39746. *
  39747. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  39748. */
  39749. getFoveation() {
  39750. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  39751. return undefined;
  39752. }
  39753. return this._foveation;
  39754. }
  39755. /**
  39756. * Sets the foveation value.
  39757. *
  39758. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  39759. * and `1` means maximum foveation (the edges render at lower resolution).
  39760. */
  39761. setFoveation( foveation ) {
  39762. this._foveation = foveation;
  39763. if ( this._glProjLayer !== null ) {
  39764. this._glProjLayer.fixedFoveation = foveation;
  39765. }
  39766. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  39767. this._glBaseLayer.fixedFoveation = foveation;
  39768. }
  39769. }
  39770. /**
  39771. * Returns the framebuffer scale factor.
  39772. *
  39773. * @return {number} The framebuffer scale factor.
  39774. */
  39775. getFramebufferScaleFactor() {
  39776. return this._framebufferScaleFactor;
  39777. }
  39778. /**
  39779. * Sets the framebuffer scale factor.
  39780. *
  39781. * This method can not be used during a XR session.
  39782. *
  39783. * @param {number} factor - The framebuffer scale factor.
  39784. */
  39785. setFramebufferScaleFactor( factor ) {
  39786. this._framebufferScaleFactor = factor;
  39787. if ( this.isPresenting === true ) {
  39788. warn( 'XRManager: Cannot change framebuffer scale while presenting.' );
  39789. }
  39790. }
  39791. /**
  39792. * Returns the reference space type.
  39793. *
  39794. * @return {XRReferenceSpaceType} The reference space type.
  39795. */
  39796. getReferenceSpaceType() {
  39797. return this._referenceSpaceType;
  39798. }
  39799. /**
  39800. * Sets the reference space type.
  39801. *
  39802. * This method can not be used during a XR session.
  39803. *
  39804. * @param {XRReferenceSpaceType} type - The reference space type.
  39805. */
  39806. setReferenceSpaceType( type ) {
  39807. this._referenceSpaceType = type;
  39808. if ( this.isPresenting === true ) {
  39809. warn( 'XRManager: Cannot change reference space type while presenting.' );
  39810. }
  39811. }
  39812. /**
  39813. * Returns the XR reference space.
  39814. *
  39815. * @return {XRReferenceSpace} The XR reference space.
  39816. */
  39817. getReferenceSpace() {
  39818. return this._customReferenceSpace || this._referenceSpace;
  39819. }
  39820. /**
  39821. * Sets a custom XR reference space.
  39822. *
  39823. * @param {XRReferenceSpace} space - The XR reference space.
  39824. */
  39825. setReferenceSpace( space ) {
  39826. this._customReferenceSpace = space;
  39827. }
  39828. /**
  39829. * Returns the XR camera.
  39830. *
  39831. * @return {ArrayCamera} The XR camera.
  39832. */
  39833. getCamera() {
  39834. return this._cameraXR;
  39835. }
  39836. /**
  39837. * Returns the environment blend mode from the current XR session.
  39838. *
  39839. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  39840. */
  39841. getEnvironmentBlendMode() {
  39842. if ( this._session !== null ) {
  39843. return this._session.environmentBlendMode;
  39844. }
  39845. }
  39846. /**
  39847. * Returns the current XR binding.
  39848. *
  39849. * Creates a new binding if needed and the browser is
  39850. * capable of doing so.
  39851. *
  39852. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  39853. */
  39854. getBinding() {
  39855. if ( this._glBinding === null && this._supportsGlBinding ) {
  39856. this._glBinding = new XRWebGLBinding( this._session, this._gl );
  39857. }
  39858. return this._glBinding;
  39859. }
  39860. /**
  39861. * Returns the current XR frame.
  39862. *
  39863. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  39864. */
  39865. getFrame() {
  39866. return this._xrFrame;
  39867. }
  39868. /**
  39869. * Returns `true` if the engine renders to a multiview target.
  39870. *
  39871. * @return {boolean} Whether the engine renders to a multiview render target or not.
  39872. */
  39873. useMultiview() {
  39874. return this._useMultiview;
  39875. }
  39876. /**
  39877. * This method can be used in XR applications to create a quadratic layer that presents a separate
  39878. * rendered scene.
  39879. *
  39880. * @param {number} width - The width of the layer plane in world units.
  39881. * @param {number} height - The height of the layer plane in world units.
  39882. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  39883. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  39884. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  39885. * @param {number} pixelheight - The height of the layer's render target in pixels.
  39886. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  39887. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  39888. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  39889. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  39890. */
  39891. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  39892. const geometry = new PlaneGeometry( width, height );
  39893. const renderTarget = new XRRenderTarget(
  39894. pixelwidth,
  39895. pixelheight,
  39896. {
  39897. format: RGBAFormat,
  39898. type: UnsignedByteType,
  39899. depthTexture: new DepthTexture(
  39900. pixelwidth,
  39901. pixelheight,
  39902. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  39903. undefined,
  39904. undefined,
  39905. undefined,
  39906. undefined,
  39907. undefined,
  39908. undefined,
  39909. attributes.stencil ? DepthStencilFormat : DepthFormat
  39910. ),
  39911. stencilBuffer: attributes.stencil,
  39912. resolveDepthBuffer: false,
  39913. resolveStencilBuffer: false
  39914. } );
  39915. renderTarget._autoAllocateDepthBuffer = true;
  39916. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  39917. material.map = renderTarget.texture;
  39918. material.map.offset.y = 1;
  39919. material.map.repeat.y = -1;
  39920. const plane = new Mesh( geometry, material );
  39921. plane.position.copy( translation );
  39922. plane.quaternion.copy( quaternion );
  39923. const layer = {
  39924. type: 'quad',
  39925. width: width,
  39926. height: height,
  39927. translation: translation,
  39928. quaternion: quaternion,
  39929. pixelwidth: pixelwidth,
  39930. pixelheight: pixelheight,
  39931. plane: plane,
  39932. material: material,
  39933. rendercall: rendercall,
  39934. renderTarget: renderTarget };
  39935. this._layers.push( layer );
  39936. if ( this._session !== null ) {
  39937. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  39938. layer.plane.material.blending = CustomBlending;
  39939. layer.plane.material.blendEquation = AddEquation;
  39940. layer.plane.material.blendSrc = ZeroFactor;
  39941. layer.plane.material.blendDst = ZeroFactor;
  39942. layer.xrlayer = this._createXRLayer( layer );
  39943. const xrlayers = this._session.renderState.layers;
  39944. xrlayers.unshift( layer.xrlayer );
  39945. this._session.updateRenderState( { layers: xrlayers } );
  39946. } else {
  39947. renderTarget.isXRRenderTarget = false;
  39948. }
  39949. return plane;
  39950. }
  39951. /**
  39952. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  39953. * rendered scene.
  39954. *
  39955. * @param {number} radius - The radius of the cylinder in world units.
  39956. * @param {number} centralAngle - The central angle of the cylinder in radians.
  39957. * @param {number} aspectratio - The aspect ratio.
  39958. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  39959. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  39960. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  39961. * @param {number} pixelheight - The height of the layer's render target in pixels.
  39962. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  39963. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  39964. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  39965. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  39966. */
  39967. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  39968. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  39969. const renderTarget = new XRRenderTarget(
  39970. pixelwidth,
  39971. pixelheight,
  39972. {
  39973. format: RGBAFormat,
  39974. type: UnsignedByteType,
  39975. depthTexture: new DepthTexture(
  39976. pixelwidth,
  39977. pixelheight,
  39978. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  39979. undefined,
  39980. undefined,
  39981. undefined,
  39982. undefined,
  39983. undefined,
  39984. undefined,
  39985. attributes.stencil ? DepthStencilFormat : DepthFormat
  39986. ),
  39987. stencilBuffer: attributes.stencil,
  39988. resolveDepthBuffer: false,
  39989. resolveStencilBuffer: false
  39990. } );
  39991. renderTarget._autoAllocateDepthBuffer = true;
  39992. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  39993. material.map = renderTarget.texture;
  39994. material.map.offset.y = 1;
  39995. material.map.repeat.y = -1;
  39996. const plane = new Mesh( geometry, material );
  39997. plane.position.copy( translation );
  39998. plane.quaternion.copy( quaternion );
  39999. const layer = {
  40000. type: 'cylinder',
  40001. radius: radius,
  40002. centralAngle: centralAngle,
  40003. aspectratio: aspectratio,
  40004. translation: translation,
  40005. quaternion: quaternion,
  40006. pixelwidth: pixelwidth,
  40007. pixelheight: pixelheight,
  40008. plane: plane,
  40009. material: material,
  40010. rendercall: rendercall,
  40011. renderTarget: renderTarget };
  40012. this._layers.push( layer );
  40013. if ( this._session !== null ) {
  40014. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  40015. layer.plane.material.blending = CustomBlending;
  40016. layer.plane.material.blendEquation = AddEquation;
  40017. layer.plane.material.blendSrc = ZeroFactor;
  40018. layer.plane.material.blendDst = ZeroFactor;
  40019. layer.xrlayer = this._createXRLayer( layer );
  40020. const xrlayers = this._session.renderState.layers;
  40021. xrlayers.unshift( layer.xrlayer );
  40022. this._session.updateRenderState( { layers: xrlayers } );
  40023. } else {
  40024. renderTarget.isXRRenderTarget = false;
  40025. }
  40026. return plane;
  40027. }
  40028. /**
  40029. * Renders the XR layers that have been previously added to the scene.
  40030. *
  40031. * This method is usually called in your animation loop before rendering
  40032. * the actual scene via `renderer.render( scene, camera );`.
  40033. */
  40034. renderLayers( ) {
  40035. const translationObject = new Vector3();
  40036. const quaternionObject = new Quaternion();
  40037. const renderer = this._renderer;
  40038. const wasPresenting = this.isPresenting;
  40039. const rendererOutputTarget = renderer.getOutputRenderTarget();
  40040. const rendererFramebufferTarget = renderer._frameBufferTarget;
  40041. this.isPresenting = false;
  40042. const rendererSize = new Vector2();
  40043. renderer.getSize( rendererSize );
  40044. const rendererQuad = renderer._quad;
  40045. for ( const layer of this._layers ) {
  40046. layer.renderTarget.isXRRenderTarget = this._session !== null;
  40047. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  40048. if ( layer.renderTarget.isXRRenderTarget && this._sessionUsesLayers ) {
  40049. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  40050. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  40051. renderer.backend.setXRRenderTargetTextures(
  40052. layer.renderTarget,
  40053. glSubImage.colorTexture,
  40054. undefined );
  40055. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  40056. renderer.setOutputRenderTarget( layer.renderTarget );
  40057. renderer.setRenderTarget( null );
  40058. renderer._frameBufferTarget = null;
  40059. this._frameBufferTargets || ( this._frameBufferTargets = new WeakMap() );
  40060. const { frameBufferTarget, quad } = this._frameBufferTargets.get( layer.renderTarget ) || { frameBufferTarget: null, quad: null };
  40061. if ( ! frameBufferTarget ) {
  40062. renderer._quad = new QuadMesh( new NodeMaterial() );
  40063. this._frameBufferTargets.set( layer.renderTarget, { frameBufferTarget: renderer._getFrameBufferTarget(), quad: renderer._quad } );
  40064. } else {
  40065. renderer._frameBufferTarget = frameBufferTarget;
  40066. renderer._quad = quad;
  40067. }
  40068. layer.rendercall();
  40069. renderer._frameBufferTarget = null;
  40070. } else {
  40071. renderer.setRenderTarget( layer.renderTarget );
  40072. layer.rendercall();
  40073. }
  40074. }
  40075. renderer.setRenderTarget( null );
  40076. renderer.setOutputRenderTarget( rendererOutputTarget );
  40077. renderer._frameBufferTarget = rendererFramebufferTarget;
  40078. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  40079. renderer._quad = rendererQuad;
  40080. this.isPresenting = wasPresenting;
  40081. }
  40082. /**
  40083. * Returns the current XR session.
  40084. *
  40085. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  40086. */
  40087. getSession() {
  40088. return this._session;
  40089. }
  40090. /**
  40091. * After a XR session has been requested usually with one of the `*Button` modules, it
  40092. * is injected into the renderer with this method. This method triggers the start of
  40093. * the actual XR rendering.
  40094. *
  40095. * @async
  40096. * @param {XRSession} session - The XR session to set.
  40097. * @return {Promise} A Promise that resolves when the session has been set.
  40098. */
  40099. async setSession( session ) {
  40100. const renderer = this._renderer;
  40101. const backend = renderer.backend;
  40102. this._gl = renderer.getContext();
  40103. const gl = this._gl;
  40104. const attributes = gl.getContextAttributes();
  40105. this._session = session;
  40106. if ( session !== null ) {
  40107. 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.' );
  40108. session.addEventListener( 'select', this._onSessionEvent );
  40109. session.addEventListener( 'selectstart', this._onSessionEvent );
  40110. session.addEventListener( 'selectend', this._onSessionEvent );
  40111. session.addEventListener( 'squeeze', this._onSessionEvent );
  40112. session.addEventListener( 'squeezestart', this._onSessionEvent );
  40113. session.addEventListener( 'squeezeend', this._onSessionEvent );
  40114. session.addEventListener( 'end', this._onSessionEnd );
  40115. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  40116. await backend.makeXRCompatible();
  40117. this._currentPixelRatio = renderer.getPixelRatio();
  40118. renderer.getSize( this._currentSize );
  40119. this._currentAnimationContext = renderer._animation.getContext();
  40120. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  40121. renderer._animation.stop();
  40122. //
  40123. if ( this._supportsLayers === true ) {
  40124. // default path using XRProjectionLayer
  40125. let depthFormat = null;
  40126. let depthType = null;
  40127. let glDepthFormat = null;
  40128. if ( renderer.depth ) {
  40129. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  40130. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  40131. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  40132. }
  40133. const projectionlayerInit = {
  40134. colorFormat: gl.RGBA8,
  40135. depthFormat: glDepthFormat,
  40136. scaleFactor: this._framebufferScaleFactor,
  40137. clearOnAccess: false
  40138. };
  40139. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  40140. projectionlayerInit.textureType = 'texture-array';
  40141. this._useMultiview = true;
  40142. }
  40143. this._glBinding = this.getBinding();
  40144. const glProjLayer = this._glBinding.createProjectionLayer( projectionlayerInit );
  40145. const layersArray = [ glProjLayer ];
  40146. this._glProjLayer = glProjLayer;
  40147. renderer.setPixelRatio( 1 );
  40148. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  40149. const depth = this._useMultiview ? 2 : 1;
  40150. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  40151. this._xrRenderTarget = new XRRenderTarget(
  40152. glProjLayer.textureWidth,
  40153. glProjLayer.textureHeight,
  40154. {
  40155. format: RGBAFormat,
  40156. type: UnsignedByteType,
  40157. colorSpace: renderer.outputColorSpace,
  40158. depthTexture: depthTexture,
  40159. stencilBuffer: renderer.stencil,
  40160. samples: attributes.antialias ? 4 : 0,
  40161. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  40162. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  40163. depth: this._useMultiview ? 2 : 1,
  40164. multiview: this._useMultiview
  40165. } );
  40166. this._xrRenderTarget._hasExternalTextures = true;
  40167. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  40168. this._sessionUsesLayers = session.enabledFeatures.includes( 'layers' );
  40169. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  40170. if ( this._sessionUsesLayers ) {
  40171. // switch layers to native
  40172. for ( const layer of this._layers ) {
  40173. // change material so it "punches" out a hole to show the XR Layer.
  40174. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  40175. layer.plane.material.blending = CustomBlending;
  40176. layer.plane.material.blendEquation = AddEquation;
  40177. layer.plane.material.blendSrc = ZeroFactor;
  40178. layer.plane.material.blendDst = ZeroFactor;
  40179. layer.xrlayer = this._createXRLayer( layer );
  40180. layersArray.unshift( layer.xrlayer );
  40181. }
  40182. }
  40183. session.updateRenderState( { layers: layersArray } );
  40184. } else {
  40185. // fallback to XRWebGLLayer
  40186. const layerInit = {
  40187. antialias: renderer.currentSamples > 0,
  40188. alpha: true,
  40189. depth: renderer.depth,
  40190. stencil: renderer.stencil,
  40191. framebufferScaleFactor: this.getFramebufferScaleFactor()
  40192. };
  40193. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  40194. this._glBaseLayer = glBaseLayer;
  40195. session.updateRenderState( { baseLayer: glBaseLayer } );
  40196. renderer.setPixelRatio( 1 );
  40197. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  40198. this._xrRenderTarget = new XRRenderTarget(
  40199. glBaseLayer.framebufferWidth,
  40200. glBaseLayer.framebufferHeight,
  40201. {
  40202. format: RGBAFormat,
  40203. type: UnsignedByteType,
  40204. colorSpace: renderer.outputColorSpace,
  40205. stencilBuffer: renderer.stencil,
  40206. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  40207. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  40208. }
  40209. );
  40210. this._xrRenderTarget._isOpaqueFramebuffer = true;
  40211. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  40212. }
  40213. //
  40214. this.setFoveation( this.getFoveation() );
  40215. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  40216. renderer._animation.setContext( session );
  40217. renderer._animation.start();
  40218. this.isPresenting = true;
  40219. this.dispatchEvent( { type: 'sessionstart' } );
  40220. }
  40221. }
  40222. /**
  40223. * This method is called by the renderer per frame and updates the XR camera
  40224. * and it sub cameras based on the given camera. The given camera is the "user"
  40225. * camera created on application level and used for non-XR rendering.
  40226. *
  40227. * @param {PerspectiveCamera} camera - The camera.
  40228. */
  40229. updateCamera( camera ) {
  40230. const session = this._session;
  40231. if ( session === null ) return;
  40232. const depthNear = camera.near;
  40233. const depthFar = camera.far;
  40234. const cameraXR = this._cameraXR;
  40235. const cameraL = this._cameraL;
  40236. const cameraR = this._cameraR;
  40237. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  40238. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  40239. cameraXR.isMultiViewCamera = this._useMultiview;
  40240. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  40241. // Note that the new renderState won't apply until the next frame. See #18320
  40242. session.updateRenderState( {
  40243. depthNear: cameraXR.near,
  40244. depthFar: cameraXR.far
  40245. } );
  40246. this._currentDepthNear = cameraXR.near;
  40247. this._currentDepthFar = cameraXR.far;
  40248. }
  40249. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  40250. cameraXR.layers.mask = camera.layers.mask | 0b110;
  40251. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  40252. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  40253. const parent = camera.parent;
  40254. const cameras = cameraXR.cameras;
  40255. updateCamera( cameraXR, parent );
  40256. for ( let i = 0; i < cameras.length; i ++ ) {
  40257. updateCamera( cameras[ i ], parent );
  40258. }
  40259. // update projection matrix for proper view frustum culling
  40260. if ( cameras.length === 2 ) {
  40261. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  40262. } else {
  40263. // assume single camera setup (AR)
  40264. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  40265. }
  40266. // update user camera and its children
  40267. updateUserCamera( camera, cameraXR, parent );
  40268. }
  40269. /**
  40270. * Returns a WebXR controller for the given controller index.
  40271. *
  40272. * @private
  40273. * @param {number} index - The controller index.
  40274. * @return {WebXRController} The XR controller.
  40275. */
  40276. _getController( index ) {
  40277. let controller = this._controllers[ index ];
  40278. if ( controller === undefined ) {
  40279. controller = new WebXRController();
  40280. this._controllers[ index ] = controller;
  40281. }
  40282. return controller;
  40283. }
  40284. }
  40285. /**
  40286. * Assumes 2 cameras that are parallel and share an X-axis, and that
  40287. * the cameras' projection and world matrices have already been set.
  40288. * And that near and far planes are identical for both cameras.
  40289. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  40290. *
  40291. * @param {ArrayCamera} camera - The camera to update.
  40292. * @param {PerspectiveCamera} cameraL - The left camera.
  40293. * @param {PerspectiveCamera} cameraR - The right camera.
  40294. */
  40295. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  40296. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  40297. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  40298. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  40299. const projL = cameraL.projectionMatrix.elements;
  40300. const projR = cameraR.projectionMatrix.elements;
  40301. // VR systems will have identical far and near planes, and
  40302. // most likely identical top and bottom frustum extents.
  40303. // Use the left camera for these values.
  40304. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  40305. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  40306. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  40307. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  40308. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  40309. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  40310. const left = near * leftFov;
  40311. const right = near * rightFov;
  40312. // Calculate the new camera's position offset from the
  40313. // left camera. xOffset should be roughly half `ipd`.
  40314. const zOffset = ipd / ( - leftFov + rightFov );
  40315. const xOffset = zOffset * - leftFov;
  40316. // TODO: Better way to apply this offset?
  40317. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  40318. camera.translateX( xOffset );
  40319. camera.translateZ( zOffset );
  40320. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  40321. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  40322. // Check if the projection uses an infinite far plane.
  40323. if ( projL[ 10 ] === -1 ) {
  40324. // Use the projection matrix from the left eye.
  40325. // The camera offset is sufficient to include the view volumes
  40326. // of both eyes (assuming symmetric projections).
  40327. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  40328. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  40329. } else {
  40330. // Find the union of the frustum values of the cameras and scale
  40331. // the values so that the near plane's position does not change in world space,
  40332. // although must now be relative to the new union camera.
  40333. const near2 = near + zOffset;
  40334. const far2 = far + zOffset;
  40335. const left2 = left - xOffset;
  40336. const right2 = right + ( ipd - xOffset );
  40337. const top2 = topFov * far / far2 * near2;
  40338. const bottom2 = bottomFov * far / far2 * near2;
  40339. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  40340. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  40341. }
  40342. }
  40343. /**
  40344. * Updates the world matrices for the given camera based on the parent 3D object.
  40345. *
  40346. * @inner
  40347. * @param {Camera} camera - The camera to update.
  40348. * @param {Object3D} parent - The parent 3D object.
  40349. */
  40350. function updateCamera( camera, parent ) {
  40351. if ( parent === null ) {
  40352. camera.matrixWorld.copy( camera.matrix );
  40353. } else {
  40354. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  40355. }
  40356. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  40357. }
  40358. /**
  40359. * Updates the given camera with the transformation of the XR camera and parent object.
  40360. *
  40361. * @inner
  40362. * @param {Camera} camera - The camera to update.
  40363. * @param {ArrayCamera} cameraXR - The XR camera.
  40364. * @param {Object3D} parent - The parent 3D object.
  40365. */
  40366. function updateUserCamera( camera, cameraXR, parent ) {
  40367. if ( parent === null ) {
  40368. camera.matrix.copy( cameraXR.matrixWorld );
  40369. } else {
  40370. camera.matrix.copy( parent.matrixWorld );
  40371. camera.matrix.invert();
  40372. camera.matrix.multiply( cameraXR.matrixWorld );
  40373. }
  40374. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  40375. camera.updateMatrixWorld( true );
  40376. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  40377. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  40378. if ( camera.isPerspectiveCamera ) {
  40379. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  40380. camera.zoom = 1;
  40381. }
  40382. }
  40383. function onSessionEvent( event ) {
  40384. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  40385. if ( controllerIndex === -1 ) {
  40386. return;
  40387. }
  40388. const controller = this._controllers[ controllerIndex ];
  40389. if ( controller !== undefined ) {
  40390. const referenceSpace = this.getReferenceSpace();
  40391. controller.update( event.inputSource, event.frame, referenceSpace );
  40392. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  40393. }
  40394. }
  40395. function onSessionEnd() {
  40396. const session = this._session;
  40397. const renderer = this._renderer;
  40398. session.removeEventListener( 'select', this._onSessionEvent );
  40399. session.removeEventListener( 'selectstart', this._onSessionEvent );
  40400. session.removeEventListener( 'selectend', this._onSessionEvent );
  40401. session.removeEventListener( 'squeeze', this._onSessionEvent );
  40402. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  40403. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  40404. session.removeEventListener( 'end', this._onSessionEnd );
  40405. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  40406. for ( let i = 0; i < this._controllers.length; i ++ ) {
  40407. const inputSource = this._controllerInputSources[ i ];
  40408. if ( inputSource === null ) continue;
  40409. this._controllerInputSources[ i ] = null;
  40410. this._controllers[ i ].disconnect( inputSource );
  40411. }
  40412. this._currentDepthNear = null;
  40413. this._currentDepthFar = null;
  40414. // restore framebuffer/rendering state
  40415. renderer._resetXRState();
  40416. this._session = null;
  40417. this._xrRenderTarget = null;
  40418. this._glBinding = null;
  40419. this._glBaseLayer = null;
  40420. this._glProjLayer = null;
  40421. // switch layers back to emulated
  40422. if ( this._sessionUsesLayers === true ) {
  40423. for ( const layer of this._layers ) {
  40424. // Recreate layer render target to reset state
  40425. layer.renderTarget = new XRRenderTarget(
  40426. layer.pixelwidth,
  40427. layer.pixelheight,
  40428. {
  40429. format: RGBAFormat,
  40430. type: UnsignedByteType,
  40431. depthTexture: new DepthTexture(
  40432. layer.pixelwidth,
  40433. layer.pixelheight,
  40434. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  40435. undefined,
  40436. undefined,
  40437. undefined,
  40438. undefined,
  40439. undefined,
  40440. undefined,
  40441. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  40442. ),
  40443. stencilBuffer: layer.stencilBuffer,
  40444. resolveDepthBuffer: false,
  40445. resolveStencilBuffer: false
  40446. } );
  40447. layer.renderTarget.isXRRenderTarget = false;
  40448. layer.plane.material = layer.material;
  40449. layer.material.map = layer.renderTarget.texture;
  40450. layer.material.map.offset.y = 1;
  40451. layer.material.map.repeat.y = -1;
  40452. delete layer.xrlayer;
  40453. }
  40454. }
  40455. //
  40456. this.isPresenting = false;
  40457. this._useMultiview = false;
  40458. renderer._animation.stop();
  40459. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  40460. renderer._animation.setContext( this._currentAnimationContext );
  40461. renderer._animation.start();
  40462. renderer.setPixelRatio( this._currentPixelRatio );
  40463. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  40464. this.dispatchEvent( { type: 'sessionend' } );
  40465. }
  40466. function onInputSourcesChange( event ) {
  40467. const controllers = this._controllers;
  40468. const controllerInputSources = this._controllerInputSources;
  40469. // Notify disconnected
  40470. for ( let i = 0; i < event.removed.length; i ++ ) {
  40471. const inputSource = event.removed[ i ];
  40472. const index = controllerInputSources.indexOf( inputSource );
  40473. if ( index >= 0 ) {
  40474. controllerInputSources[ index ] = null;
  40475. controllers[ index ].disconnect( inputSource );
  40476. }
  40477. }
  40478. // Notify connected
  40479. for ( let i = 0; i < event.added.length; i ++ ) {
  40480. const inputSource = event.added[ i ];
  40481. let controllerIndex = controllerInputSources.indexOf( inputSource );
  40482. if ( controllerIndex === -1 ) {
  40483. // Assign input source a controller that currently has no input source
  40484. for ( let i = 0; i < controllers.length; i ++ ) {
  40485. if ( i >= controllerInputSources.length ) {
  40486. controllerInputSources.push( inputSource );
  40487. controllerIndex = i;
  40488. break;
  40489. } else if ( controllerInputSources[ i ] === null ) {
  40490. controllerInputSources[ i ] = inputSource;
  40491. controllerIndex = i;
  40492. break;
  40493. }
  40494. }
  40495. // If all controllers do currently receive input we ignore new ones
  40496. if ( controllerIndex === -1 ) break;
  40497. }
  40498. const controller = controllers[ controllerIndex ];
  40499. if ( controller ) {
  40500. controller.connect( inputSource );
  40501. }
  40502. }
  40503. }
  40504. // Creation method for native WebXR layers
  40505. function createXRLayer( layer ) {
  40506. if ( layer.type === 'quad' ) {
  40507. return this._glBinding.createQuadLayer( {
  40508. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  40509. width: layer.width / 2,
  40510. height: layer.height / 2,
  40511. space: this._referenceSpace,
  40512. viewPixelWidth: layer.pixelwidth,
  40513. viewPixelHeight: layer.pixelheight,
  40514. clearOnAccess: false
  40515. } );
  40516. } else {
  40517. return this._glBinding.createCylinderLayer( {
  40518. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  40519. radius: layer.radius,
  40520. centralAngle: layer.centralAngle,
  40521. aspectRatio: layer.aspectRatio,
  40522. space: this._referenceSpace,
  40523. viewPixelWidth: layer.pixelwidth,
  40524. viewPixelHeight: layer.pixelheight,
  40525. clearOnAccess: false
  40526. } );
  40527. }
  40528. }
  40529. // Animation Loop
  40530. function onAnimationFrame( time, frame ) {
  40531. if ( frame === undefined ) return;
  40532. const cameraXR = this._cameraXR;
  40533. const renderer = this._renderer;
  40534. const backend = renderer.backend;
  40535. const glBaseLayer = this._glBaseLayer;
  40536. const referenceSpace = this.getReferenceSpace();
  40537. const pose = frame.getViewerPose( referenceSpace );
  40538. this._xrFrame = frame;
  40539. if ( pose !== null ) {
  40540. const views = pose.views;
  40541. if ( this._glBaseLayer !== null ) {
  40542. backend.setXRTarget( glBaseLayer.framebuffer );
  40543. }
  40544. let cameraXRNeedsUpdate = false;
  40545. // check if it's necessary to rebuild cameraXR's camera list
  40546. if ( views.length !== cameraXR.cameras.length ) {
  40547. cameraXR.cameras.length = 0;
  40548. cameraXRNeedsUpdate = true;
  40549. }
  40550. for ( let i = 0; i < views.length; i ++ ) {
  40551. const view = views[ i ];
  40552. let viewport;
  40553. if ( this._supportsLayers === true ) {
  40554. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  40555. viewport = glSubImage.viewport;
  40556. // For side-by-side projection, we only produce a single texture for both eyes.
  40557. if ( i === 0 ) {
  40558. backend.setXRRenderTargetTextures(
  40559. this._xrRenderTarget,
  40560. glSubImage.colorTexture,
  40561. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  40562. );
  40563. }
  40564. } else {
  40565. viewport = glBaseLayer.getViewport( view );
  40566. }
  40567. let camera = this._cameras[ i ];
  40568. if ( camera === undefined ) {
  40569. camera = new PerspectiveCamera();
  40570. camera.layers.enable( i );
  40571. camera.viewport = new Vector4();
  40572. this._cameras[ i ] = camera;
  40573. }
  40574. camera.matrix.fromArray( view.transform.matrix );
  40575. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  40576. camera.projectionMatrix.fromArray( view.projectionMatrix );
  40577. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  40578. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  40579. if ( i === 0 ) {
  40580. cameraXR.matrix.copy( camera.matrix );
  40581. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  40582. }
  40583. if ( cameraXRNeedsUpdate === true ) {
  40584. cameraXR.cameras.push( camera );
  40585. }
  40586. }
  40587. renderer.setOutputRenderTarget( this._xrRenderTarget );
  40588. }
  40589. //
  40590. for ( let i = 0; i < this._controllers.length; i ++ ) {
  40591. const inputSource = this._controllerInputSources[ i ];
  40592. const controller = this._controllers[ i ];
  40593. if ( inputSource !== null && controller !== undefined ) {
  40594. controller.update( inputSource, frame, referenceSpace );
  40595. }
  40596. }
  40597. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  40598. if ( frame.detectedPlanes ) {
  40599. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  40600. }
  40601. this._xrFrame = null;
  40602. }
  40603. /**
  40604. * CanvasTarget is a class that represents the final output destination of the renderer.
  40605. *
  40606. * @augments EventDispatcher
  40607. */
  40608. class CanvasTarget extends EventDispatcher {
  40609. /**
  40610. * Constructs a new CanvasTarget.
  40611. *
  40612. * @param {HTMLCanvasElement|OffscreenCanvas} domElement - The canvas element to render to.
  40613. */
  40614. constructor( domElement ) {
  40615. super();
  40616. /**
  40617. * A reference to the canvas element the renderer is drawing to.
  40618. * This value of this property will automatically be created by
  40619. * the renderer.
  40620. *
  40621. * @type {HTMLCanvasElement|OffscreenCanvas}
  40622. */
  40623. this.domElement = domElement;
  40624. /**
  40625. * The renderer's pixel ratio.
  40626. *
  40627. * @private
  40628. * @type {number}
  40629. * @default 1
  40630. */
  40631. this._pixelRatio = 1;
  40632. /**
  40633. * The width of the renderer's default framebuffer in logical pixel unit.
  40634. *
  40635. * @private
  40636. * @type {number}
  40637. */
  40638. this._width = this.domElement.width;
  40639. /**
  40640. * The height of the renderer's default framebuffer in logical pixel unit.
  40641. *
  40642. * @private
  40643. * @type {number}
  40644. */
  40645. this._height = this.domElement.height;
  40646. /**
  40647. * The viewport of the renderer in logical pixel unit.
  40648. *
  40649. * @private
  40650. * @type {Vector4}
  40651. */
  40652. this._viewport = new Vector4( 0, 0, this._width, this._height );
  40653. /**
  40654. * The scissor rectangle of the renderer in logical pixel unit.
  40655. *
  40656. * @private
  40657. * @type {Vector4}
  40658. */
  40659. this._scissor = new Vector4( 0, 0, this._width, this._height );
  40660. /**
  40661. * Whether the scissor test should be enabled or not.
  40662. *
  40663. * @private
  40664. * @type {boolean}
  40665. */
  40666. this._scissorTest = false;
  40667. /**
  40668. * The color texture of the default framebuffer.
  40669. *
  40670. * @type {FramebufferTexture}
  40671. */
  40672. this.colorTexture = new FramebufferTexture();
  40673. /**
  40674. * The depth texture of the default framebuffer.
  40675. *
  40676. * @type {DepthTexture}
  40677. */
  40678. this.depthTexture = new DepthTexture();
  40679. }
  40680. /**
  40681. * Returns the pixel ratio.
  40682. *
  40683. * @return {number} The pixel ratio.
  40684. */
  40685. getPixelRatio() {
  40686. return this._pixelRatio;
  40687. }
  40688. /**
  40689. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  40690. *
  40691. * @param {Vector2} target - The method writes the result in this target object.
  40692. * @return {Vector2} The drawing buffer size.
  40693. */
  40694. getDrawingBufferSize( target ) {
  40695. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  40696. }
  40697. /**
  40698. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  40699. *
  40700. * @param {Vector2} target - The method writes the result in this target object.
  40701. * @return {Vector2} The renderer's size in logical pixels.
  40702. */
  40703. getSize( target ) {
  40704. return target.set( this._width, this._height );
  40705. }
  40706. /**
  40707. * Sets the given pixel ratio and resizes the canvas if necessary.
  40708. *
  40709. * @param {number} [value=1] - The pixel ratio.
  40710. */
  40711. setPixelRatio( value = 1 ) {
  40712. if ( this._pixelRatio === value ) return;
  40713. this._pixelRatio = value;
  40714. this.setSize( this._width, this._height, false );
  40715. }
  40716. /**
  40717. * This method allows to define the drawing buffer size by specifying
  40718. * width, height and pixel ratio all at once. The size of the drawing
  40719. * buffer is computed with this formula:
  40720. * ```js
  40721. * size.x = width * pixelRatio;
  40722. * size.y = height * pixelRatio;
  40723. * ```
  40724. *
  40725. * @param {number} width - The width in logical pixels.
  40726. * @param {number} height - The height in logical pixels.
  40727. * @param {number} pixelRatio - The pixel ratio.
  40728. */
  40729. setDrawingBufferSize( width, height, pixelRatio ) {
  40730. // Renderer can't be resized while presenting in XR.
  40731. if ( this.xr && this.xr.isPresenting ) return;
  40732. this._width = width;
  40733. this._height = height;
  40734. this._pixelRatio = pixelRatio;
  40735. this.domElement.width = Math.floor( width * pixelRatio );
  40736. this.domElement.height = Math.floor( height * pixelRatio );
  40737. this.setViewport( 0, 0, width, height );
  40738. this._dispatchResize();
  40739. }
  40740. /**
  40741. * Sets the size of the renderer.
  40742. *
  40743. * @param {number} width - The width in logical pixels.
  40744. * @param {number} height - The height in logical pixels.
  40745. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  40746. */
  40747. setSize( width, height, updateStyle = true ) {
  40748. // Renderer can't be resized while presenting in XR.
  40749. if ( this.xr && this.xr.isPresenting ) return;
  40750. this._width = width;
  40751. this._height = height;
  40752. this.domElement.width = Math.floor( width * this._pixelRatio );
  40753. this.domElement.height = Math.floor( height * this._pixelRatio );
  40754. if ( updateStyle === true ) {
  40755. this.domElement.style.width = width + 'px';
  40756. this.domElement.style.height = height + 'px';
  40757. }
  40758. this.setViewport( 0, 0, width, height );
  40759. this._dispatchResize();
  40760. }
  40761. /**
  40762. * Returns the scissor rectangle.
  40763. *
  40764. * @param {Vector4} target - The method writes the result in this target object.
  40765. * @return {Vector4} The scissor rectangle.
  40766. */
  40767. getScissor( target ) {
  40768. const scissor = this._scissor;
  40769. target.x = scissor.x;
  40770. target.y = scissor.y;
  40771. target.width = scissor.width;
  40772. target.height = scissor.height;
  40773. return target;
  40774. }
  40775. /**
  40776. * Defines the scissor rectangle.
  40777. *
  40778. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  40779. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  40780. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  40781. * @param {number} width - The width of the scissor box in logical pixel unit.
  40782. * @param {number} height - The height of the scissor box in logical pixel unit.
  40783. */
  40784. setScissor( x, y, width, height ) {
  40785. const scissor = this._scissor;
  40786. if ( x.isVector4 ) {
  40787. scissor.copy( x );
  40788. } else {
  40789. scissor.set( x, y, width, height );
  40790. }
  40791. }
  40792. /**
  40793. * Returns the scissor test value.
  40794. *
  40795. * @return {boolean} Whether the scissor test should be enabled or not.
  40796. */
  40797. getScissorTest() {
  40798. return this._scissorTest;
  40799. }
  40800. /**
  40801. * Defines the scissor test.
  40802. *
  40803. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  40804. */
  40805. setScissorTest( boolean ) {
  40806. this._scissorTest = boolean;
  40807. }
  40808. /**
  40809. * Returns the viewport definition.
  40810. *
  40811. * @param {Vector4} target - The method writes the result in this target object.
  40812. * @return {Vector4} The viewport definition.
  40813. */
  40814. getViewport( target ) {
  40815. return target.copy( this._viewport );
  40816. }
  40817. /**
  40818. * Defines the viewport.
  40819. *
  40820. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  40821. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  40822. * @param {number} width - The width of the viewport in logical pixel unit.
  40823. * @param {number} height - The height of the viewport in logical pixel unit.
  40824. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  40825. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  40826. */
  40827. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  40828. const viewport = this._viewport;
  40829. if ( x.isVector4 ) {
  40830. viewport.copy( x );
  40831. } else {
  40832. viewport.set( x, y, width, height );
  40833. }
  40834. viewport.minDepth = minDepth;
  40835. viewport.maxDepth = maxDepth;
  40836. }
  40837. /**
  40838. * Dispatches the resize event.
  40839. *
  40840. * @private
  40841. */
  40842. _dispatchResize() {
  40843. this.dispatchEvent( { type: 'resize' } );
  40844. }
  40845. /**
  40846. * Frees the GPU-related resources allocated by this instance. Call this
  40847. * method whenever this instance is no longer used in your app.
  40848. *
  40849. * @fires RenderTarget#dispose
  40850. */
  40851. dispose() {
  40852. this.dispatchEvent( { type: 'dispose' } );
  40853. }
  40854. }
  40855. const _scene = /*@__PURE__*/ new Scene();
  40856. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  40857. const _screen = /*@__PURE__*/ new Vector4();
  40858. const _frustum = /*@__PURE__*/ new Frustum();
  40859. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  40860. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  40861. const _vector4 = /*@__PURE__*/ new Vector4();
  40862. /**
  40863. * Base class for renderers.
  40864. */
  40865. class Renderer {
  40866. /**
  40867. * Renderer options.
  40868. *
  40869. * @typedef {Object} Renderer~Options
  40870. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  40871. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  40872. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  40873. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  40874. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  40875. * @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
  40876. * to overwrite the default.
  40877. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  40878. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  40879. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  40880. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  40881. */
  40882. /**
  40883. * Constructs a new renderer.
  40884. *
  40885. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  40886. * @param {Renderer~Options} [parameters] - The configuration parameter.
  40887. */
  40888. constructor( backend, parameters = {} ) {
  40889. /**
  40890. * This flag can be used for type testing.
  40891. *
  40892. * @type {boolean}
  40893. * @readonly
  40894. * @default true
  40895. */
  40896. this.isRenderer = true;
  40897. //
  40898. const {
  40899. logarithmicDepthBuffer = false,
  40900. alpha = true,
  40901. depth = true,
  40902. stencil = false,
  40903. antialias = false,
  40904. samples = 0,
  40905. getFallback = null,
  40906. colorBufferType = HalfFloatType,
  40907. multiview = false
  40908. } = parameters;
  40909. /**
  40910. * A reference to the current backend.
  40911. *
  40912. * @type {Backend}
  40913. */
  40914. this.backend = backend;
  40915. /**
  40916. * Whether the renderer should automatically clear the current rendering target
  40917. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  40918. * or the current bound render target (custom framebuffer).
  40919. *
  40920. * @type {boolean}
  40921. * @default true
  40922. */
  40923. this.autoClear = true;
  40924. /**
  40925. * When `autoClear` is set to `true`, this property defines whether the renderer
  40926. * should clear the color buffer.
  40927. *
  40928. * @type {boolean}
  40929. * @default true
  40930. */
  40931. this.autoClearColor = true;
  40932. /**
  40933. * When `autoClear` is set to `true`, this property defines whether the renderer
  40934. * should clear the depth buffer.
  40935. *
  40936. * @type {boolean}
  40937. * @default true
  40938. */
  40939. this.autoClearDepth = true;
  40940. /**
  40941. * When `autoClear` is set to `true`, this property defines whether the renderer
  40942. * should clear the stencil buffer.
  40943. *
  40944. * @type {boolean}
  40945. * @default true
  40946. */
  40947. this.autoClearStencil = true;
  40948. /**
  40949. * Whether the default framebuffer should be transparent or opaque.
  40950. *
  40951. * @type {boolean}
  40952. * @default true
  40953. */
  40954. this.alpha = alpha;
  40955. /**
  40956. * Whether logarithmic depth buffer is enabled or not.
  40957. *
  40958. * @type {boolean}
  40959. * @default false
  40960. */
  40961. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  40962. /**
  40963. * Defines the output color space of the renderer.
  40964. *
  40965. * @type {string}
  40966. * @default SRGBColorSpace
  40967. */
  40968. this.outputColorSpace = SRGBColorSpace;
  40969. /**
  40970. * Defines the tone mapping of the renderer.
  40971. *
  40972. * @type {number}
  40973. * @default NoToneMapping
  40974. */
  40975. this.toneMapping = NoToneMapping;
  40976. /**
  40977. * Defines the tone mapping exposure.
  40978. *
  40979. * @type {number}
  40980. * @default 1
  40981. */
  40982. this.toneMappingExposure = 1.0;
  40983. /**
  40984. * Whether the renderer should sort its render lists or not.
  40985. *
  40986. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  40987. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  40988. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  40989. * e.g. manually determining each object's rendering order.
  40990. *
  40991. * @type {boolean}
  40992. * @default true
  40993. */
  40994. this.sortObjects = true;
  40995. /**
  40996. * Whether the default framebuffer should have a depth buffer or not.
  40997. *
  40998. * @type {boolean}
  40999. * @default true
  41000. */
  41001. this.depth = depth;
  41002. /**
  41003. * Whether the default framebuffer should have a stencil buffer or not.
  41004. *
  41005. * @type {boolean}
  41006. * @default false
  41007. */
  41008. this.stencil = stencil;
  41009. /**
  41010. * Holds a series of statistical information about the GPU memory
  41011. * and the rendering process. Useful for debugging and monitoring.
  41012. *
  41013. * @type {Info}
  41014. */
  41015. this.info = new Info();
  41016. /**
  41017. * A global context node that stores override nodes for specific transformations or calculations.
  41018. * These nodes can be used to replace default behavior in the rendering pipeline.
  41019. *
  41020. * @type {ContextNode}
  41021. * @property {Object} value - The context value object.
  41022. */
  41023. this.contextNode = context();
  41024. /**
  41025. * The node library defines how certain library objects like materials, lights
  41026. * or tone mapping functions are mapped to node types. This is required since
  41027. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  41028. * be part of the scene graph, they are internally represented as nodes for
  41029. * further processing.
  41030. *
  41031. * @type {NodeLibrary}
  41032. */
  41033. this.library = new NodeLibrary();
  41034. /**
  41035. * A map-like data structure for managing lights.
  41036. *
  41037. * @type {Lighting}
  41038. */
  41039. this.lighting = new Lighting();
  41040. // internals
  41041. /**
  41042. * The number of MSAA samples.
  41043. *
  41044. * @private
  41045. * @type {number}
  41046. * @default 0
  41047. */
  41048. this._samples = samples || ( antialias === true ) ? 4 : 0;
  41049. /**
  41050. * OnCanvasTargetResize callback function.
  41051. *
  41052. * @private
  41053. * @type {Function}
  41054. */
  41055. this._onCanvasTargetResize = this._onCanvasTargetResize.bind( this );
  41056. /**
  41057. * The canvas target for rendering.
  41058. *
  41059. * @private
  41060. * @type {CanvasTarget}
  41061. */
  41062. this._canvasTarget = new CanvasTarget( backend.getDomElement() );
  41063. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  41064. this._canvasTarget.isDefaultCanvasTarget = true;
  41065. /**
  41066. * The inspector provides information about the internal renderer state.
  41067. *
  41068. * @private
  41069. * @type {InspectorBase}
  41070. */
  41071. this._inspector = new InspectorBase();
  41072. this._inspector.setRenderer( this );
  41073. /**
  41074. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  41075. *
  41076. * @private
  41077. * @type {?Function}
  41078. */
  41079. this._getFallback = getFallback;
  41080. /**
  41081. * A reference to a renderer module for managing shader attributes.
  41082. *
  41083. * @private
  41084. * @type {?Attributes}
  41085. * @default null
  41086. */
  41087. this._attributes = null;
  41088. /**
  41089. * A reference to a renderer module for managing geometries.
  41090. *
  41091. * @private
  41092. * @type {?Geometries}
  41093. * @default null
  41094. */
  41095. this._geometries = null;
  41096. /**
  41097. * A reference to a renderer module for managing node related logic.
  41098. *
  41099. * @private
  41100. * @type {?Nodes}
  41101. * @default null
  41102. */
  41103. this._nodes = null;
  41104. /**
  41105. * A reference to a renderer module for managing the internal animation loop.
  41106. *
  41107. * @private
  41108. * @type {?Animation}
  41109. * @default null
  41110. */
  41111. this._animation = null;
  41112. /**
  41113. * A reference to a renderer module for managing shader program bindings.
  41114. *
  41115. * @private
  41116. * @type {?Bindings}
  41117. * @default null
  41118. */
  41119. this._bindings = null;
  41120. /**
  41121. * A reference to a renderer module for managing render objects.
  41122. *
  41123. * @private
  41124. * @type {?RenderObjects}
  41125. * @default null
  41126. */
  41127. this._objects = null;
  41128. /**
  41129. * A reference to a renderer module for managing render and compute pipelines.
  41130. *
  41131. * @private
  41132. * @type {?Pipelines}
  41133. * @default null
  41134. */
  41135. this._pipelines = null;
  41136. /**
  41137. * A reference to a renderer module for managing render bundles.
  41138. *
  41139. * @private
  41140. * @type {?RenderBundles}
  41141. * @default null
  41142. */
  41143. this._bundles = null;
  41144. /**
  41145. * A reference to a renderer module for managing render lists.
  41146. *
  41147. * @private
  41148. * @type {?RenderLists}
  41149. * @default null
  41150. */
  41151. this._renderLists = null;
  41152. /**
  41153. * A reference to a renderer module for managing render contexts.
  41154. *
  41155. * @private
  41156. * @type {?RenderContexts}
  41157. * @default null
  41158. */
  41159. this._renderContexts = null;
  41160. /**
  41161. * A reference to a renderer module for managing textures.
  41162. *
  41163. * @private
  41164. * @type {?Textures}
  41165. * @default null
  41166. */
  41167. this._textures = null;
  41168. /**
  41169. * A reference to a renderer module for backgrounds.
  41170. *
  41171. * @private
  41172. * @type {?Background}
  41173. * @default null
  41174. */
  41175. this._background = null;
  41176. /**
  41177. * This fullscreen quad is used for internal render passes
  41178. * like the tone mapping and color space output pass.
  41179. *
  41180. * @private
  41181. * @type {QuadMesh}
  41182. */
  41183. this._quad = new QuadMesh( new NodeMaterial() );
  41184. this._quad.name = 'Output Color Transform';
  41185. this._quad.material.name = 'outputColorTransform';
  41186. /**
  41187. * A reference to the current render context.
  41188. *
  41189. * @private
  41190. * @type {?RenderContext}
  41191. * @default null
  41192. */
  41193. this._currentRenderContext = null;
  41194. /**
  41195. * A custom sort function for the opaque render list.
  41196. *
  41197. * @private
  41198. * @type {?Function}
  41199. * @default null
  41200. */
  41201. this._opaqueSort = null;
  41202. /**
  41203. * A custom sort function for the transparent render list.
  41204. *
  41205. * @private
  41206. * @type {?Function}
  41207. * @default null
  41208. */
  41209. this._transparentSort = null;
  41210. /**
  41211. * The framebuffer target.
  41212. *
  41213. * @private
  41214. * @type {?RenderTarget}
  41215. * @default null
  41216. */
  41217. this._frameBufferTarget = null;
  41218. const alphaClear = this.alpha === true ? 0 : 1;
  41219. /**
  41220. * The clear color value.
  41221. *
  41222. * @private
  41223. * @type {Color4}
  41224. */
  41225. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  41226. /**
  41227. * The clear depth value.
  41228. *
  41229. * @private
  41230. * @type {number}
  41231. * @default 1
  41232. */
  41233. this._clearDepth = 1;
  41234. /**
  41235. * The clear stencil value.
  41236. *
  41237. * @private
  41238. * @type {number}
  41239. * @default 0
  41240. */
  41241. this._clearStencil = 0;
  41242. /**
  41243. * The current render target.
  41244. *
  41245. * @private
  41246. * @type {?RenderTarget}
  41247. * @default null
  41248. */
  41249. this._renderTarget = null;
  41250. /**
  41251. * The active cube face.
  41252. *
  41253. * @private
  41254. * @type {number}
  41255. * @default 0
  41256. */
  41257. this._activeCubeFace = 0;
  41258. /**
  41259. * The active mipmap level.
  41260. *
  41261. * @private
  41262. * @type {number}
  41263. * @default 0
  41264. */
  41265. this._activeMipmapLevel = 0;
  41266. /**
  41267. * The current output render target.
  41268. *
  41269. * @private
  41270. * @type {?RenderTarget}
  41271. * @default null
  41272. */
  41273. this._outputRenderTarget = null;
  41274. /**
  41275. * The MRT setting.
  41276. *
  41277. * @private
  41278. * @type {?MRTNode}
  41279. * @default null
  41280. */
  41281. this._mrt = null;
  41282. /**
  41283. * This function defines how a render object is going
  41284. * to be rendered.
  41285. *
  41286. * @private
  41287. * @type {?Function}
  41288. * @default null
  41289. */
  41290. this._renderObjectFunction = null;
  41291. /**
  41292. * Used to keep track of the current render object function.
  41293. *
  41294. * @private
  41295. * @type {?Function}
  41296. * @default null
  41297. */
  41298. this._currentRenderObjectFunction = null;
  41299. /**
  41300. * Used to keep track of the current render bundle.
  41301. *
  41302. * @private
  41303. * @type {?RenderBundle}
  41304. * @default null
  41305. */
  41306. this._currentRenderBundle = null;
  41307. /**
  41308. * Next to `_renderObjectFunction()`, this function provides another hook
  41309. * for influencing the render process of a render object. It is meant for internal
  41310. * use and only relevant for `compileAsync()` right now. Instead of using
  41311. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  41312. * a different function might be used which performs no draw but just the node
  41313. * and pipeline updates.
  41314. *
  41315. * @private
  41316. * @type {?Function}
  41317. * @default null
  41318. */
  41319. this._handleObjectFunction = this._renderObjectDirect;
  41320. /**
  41321. * Indicates whether the device has been lost or not. In WebGL terms, the device
  41322. * lost is considered as a context lost. When this is set to `true`, rendering
  41323. * isn't possible anymore.
  41324. *
  41325. * @private
  41326. * @type {boolean}
  41327. * @default false
  41328. */
  41329. this._isDeviceLost = false;
  41330. /**
  41331. * A callback function that defines what should happen when a device/context lost occurs.
  41332. *
  41333. * @type {Function}
  41334. */
  41335. this.onDeviceLost = this._onDeviceLost;
  41336. /**
  41337. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  41338. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  41339. * This will reduce rendering quality though.
  41340. *
  41341. * @private
  41342. * @type {number}
  41343. * @default HalfFloatType
  41344. */
  41345. this._colorBufferType = colorBufferType;
  41346. /**
  41347. * A cache for shadow nodes per material
  41348. *
  41349. * @private
  41350. * @type {WeakMap<Material, Object>}
  41351. */
  41352. this._cacheShadowNodes = new WeakMap();
  41353. /**
  41354. * Whether the renderer has been initialized or not.
  41355. *
  41356. * @private
  41357. * @type {boolean}
  41358. * @default false
  41359. */
  41360. this._initialized = false;
  41361. /**
  41362. * A reference to the promise which initializes the renderer.
  41363. *
  41364. * @private
  41365. * @type {?Promise<this>}
  41366. * @default null
  41367. */
  41368. this._initPromise = null;
  41369. /**
  41370. * An array of compilation promises which are used in `compileAsync()`.
  41371. *
  41372. * @private
  41373. * @type {?Array<Promise>}
  41374. * @default null
  41375. */
  41376. this._compilationPromises = null;
  41377. /**
  41378. * Whether the renderer should render transparent render objects or not.
  41379. *
  41380. * @type {boolean}
  41381. * @default true
  41382. */
  41383. this.transparent = true;
  41384. /**
  41385. * Whether the renderer should render opaque render objects or not.
  41386. *
  41387. * @type {boolean}
  41388. * @default true
  41389. */
  41390. this.opaque = true;
  41391. /**
  41392. * Shadow map configuration
  41393. * @typedef {Object} ShadowMapConfig
  41394. * @property {boolean} enabled - Whether to globally enable shadows or not.
  41395. * @property {number} type - The shadow map type.
  41396. */
  41397. /**
  41398. * The renderer's shadow configuration.
  41399. *
  41400. * @type {ShadowMapConfig}
  41401. */
  41402. this.shadowMap = {
  41403. enabled: false,
  41404. type: PCFShadowMap
  41405. };
  41406. /**
  41407. * XR configuration.
  41408. * @typedef {Object} XRConfig
  41409. * @property {boolean} enabled - Whether to globally enable XR or not.
  41410. */
  41411. /**
  41412. * The renderer's XR manager.
  41413. *
  41414. * @type {XRManager}
  41415. */
  41416. this.xr = new XRManager( this, multiview );
  41417. /**
  41418. * Debug configuration.
  41419. * @typedef {Object} DebugConfig
  41420. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  41421. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  41422. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  41423. */
  41424. /**
  41425. * The renderer's debug configuration.
  41426. *
  41427. * @type {DebugConfig}
  41428. */
  41429. this.debug = {
  41430. checkShaderErrors: true,
  41431. onShaderError: null,
  41432. getShaderAsync: async ( scene, camera, object ) => {
  41433. await this.compileAsync( scene, camera );
  41434. const renderList = this._renderLists.get( scene, camera );
  41435. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget, this._mrt );
  41436. const material = scene.overrideMaterial || object.material;
  41437. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  41438. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  41439. return { fragmentShader, vertexShader };
  41440. }
  41441. };
  41442. }
  41443. /**
  41444. * Initializes the renderer so it is ready for usage.
  41445. *
  41446. * @async
  41447. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  41448. */
  41449. async init() {
  41450. if ( this._initPromise !== null ) {
  41451. return this._initPromise;
  41452. }
  41453. this._initPromise = new Promise( async ( resolve, reject ) => {
  41454. let backend = this.backend;
  41455. try {
  41456. await backend.init( this );
  41457. } catch ( error ) {
  41458. if ( this._getFallback !== null ) {
  41459. // try the fallback
  41460. try {
  41461. this.backend = backend = this._getFallback( error );
  41462. await backend.init( this );
  41463. } catch ( error ) {
  41464. reject( error );
  41465. return;
  41466. }
  41467. } else {
  41468. reject( error );
  41469. return;
  41470. }
  41471. }
  41472. this._nodes = new Nodes( this, backend );
  41473. this._animation = new Animation( this, this._nodes, this.info );
  41474. this._attributes = new Attributes( backend );
  41475. this._background = new Background( this, this._nodes );
  41476. this._geometries = new Geometries( this._attributes, this.info );
  41477. this._textures = new Textures( this, backend, this.info );
  41478. this._pipelines = new Pipelines( backend, this._nodes );
  41479. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  41480. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  41481. this._renderLists = new RenderLists( this.lighting );
  41482. this._bundles = new RenderBundles();
  41483. this._renderContexts = new RenderContexts();
  41484. //
  41485. this._animation.start();
  41486. this._initialized = true;
  41487. //
  41488. this._inspector.init();
  41489. //
  41490. resolve( this );
  41491. } );
  41492. return this._initPromise;
  41493. }
  41494. /**
  41495. * A reference to the canvas element the renderer is drawing to.
  41496. * This value of this property will automatically be created by
  41497. * the renderer.
  41498. *
  41499. * @type {HTMLCanvasElement|OffscreenCanvas}
  41500. */
  41501. get domElement() {
  41502. return this._canvasTarget.domElement;
  41503. }
  41504. /**
  41505. * The coordinate system of the renderer. The value of this property
  41506. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  41507. * `THREE.WebGPUCoordinateSystem`.
  41508. *
  41509. * @readonly
  41510. * @type {number}
  41511. */
  41512. get coordinateSystem() {
  41513. return this.backend.coordinateSystem;
  41514. }
  41515. /**
  41516. * Compiles all materials in the given scene. This can be useful to avoid a
  41517. * phenomenon which is called "shader compilation stutter", which occurs when
  41518. * rendering an object with a new shader for the first time.
  41519. *
  41520. * If you want to add a 3D object to an existing scene, use the third optional
  41521. * parameter for applying the target scene. Note that the (target) scene's lighting
  41522. * and environment must be configured before calling this method.
  41523. *
  41524. * @async
  41525. * @param {Object3D} scene - The scene or 3D object to precompile.
  41526. * @param {Camera} camera - The camera that is used to render the scene.
  41527. * @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.
  41528. * @return {Promise} A Promise that resolves when the compile has been finished.
  41529. */
  41530. async compileAsync( scene, camera, targetScene = null ) {
  41531. if ( this._isDeviceLost === true ) return;
  41532. if ( this._initialized === false ) await this.init();
  41533. // preserve render tree
  41534. const nodeFrame = this._nodes.nodeFrame;
  41535. const previousRenderId = nodeFrame.renderId;
  41536. const previousRenderContext = this._currentRenderContext;
  41537. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  41538. const previousCompilationPromises = this._compilationPromises;
  41539. //
  41540. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  41541. if ( targetScene === null ) targetScene = scene;
  41542. const renderTarget = this._renderTarget;
  41543. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget, this._mrt );
  41544. const activeMipmapLevel = this._activeMipmapLevel;
  41545. const compilationPromises = [];
  41546. this._currentRenderContext = renderContext;
  41547. this._currentRenderObjectFunction = this.renderObject;
  41548. this._handleObjectFunction = this._createObjectPipeline;
  41549. this._compilationPromises = compilationPromises;
  41550. nodeFrame.renderId ++;
  41551. //
  41552. nodeFrame.update();
  41553. //
  41554. renderContext.depth = this.depth;
  41555. renderContext.stencil = this.stencil;
  41556. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  41557. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  41558. //
  41559. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  41560. //
  41561. const renderList = this._renderLists.get( scene, camera );
  41562. renderList.begin();
  41563. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  41564. // include lights from target scene
  41565. if ( targetScene !== scene ) {
  41566. targetScene.traverseVisible( function ( object ) {
  41567. if ( object.isLight && object.layers.test( camera.layers ) ) {
  41568. renderList.pushLight( object );
  41569. }
  41570. } );
  41571. }
  41572. renderList.finish();
  41573. //
  41574. if ( renderTarget !== null ) {
  41575. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  41576. const renderTargetData = this._textures.get( renderTarget );
  41577. renderContext.textures = renderTargetData.textures;
  41578. renderContext.depthTexture = renderTargetData.depthTexture;
  41579. } else {
  41580. renderContext.textures = null;
  41581. renderContext.depthTexture = null;
  41582. }
  41583. //
  41584. this._background.update( sceneRef, renderList, renderContext );
  41585. // process render lists
  41586. const opaqueObjects = renderList.opaque;
  41587. const transparentObjects = renderList.transparent;
  41588. const transparentDoublePassObjects = renderList.transparentDoublePass;
  41589. const lightsNode = renderList.lightsNode;
  41590. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  41591. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  41592. // restore render tree
  41593. nodeFrame.renderId = previousRenderId;
  41594. this._currentRenderContext = previousRenderContext;
  41595. this._currentRenderObjectFunction = previousRenderObjectFunction;
  41596. this._compilationPromises = previousCompilationPromises;
  41597. this._handleObjectFunction = this._renderObjectDirect;
  41598. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  41599. await Promise.all( compilationPromises );
  41600. }
  41601. /**
  41602. * Renders the scene in an async fashion.
  41603. *
  41604. * @async
  41605. * @deprecated
  41606. * @param {Object3D} scene - The scene or 3D object to render.
  41607. * @param {Camera} camera - The camera.
  41608. * @return {Promise} A Promise that resolves when the render has been finished.
  41609. */
  41610. async renderAsync( scene, camera ) {
  41611. warnOnce( 'Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41612. await this.init();
  41613. this.render( scene, camera );
  41614. }
  41615. /**
  41616. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  41617. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  41618. *
  41619. * @async
  41620. * @deprecated
  41621. * @return {Promise} A Promise that resolves when synchronization has been finished.
  41622. */
  41623. async waitForGPU() {
  41624. error( 'Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.' );
  41625. }
  41626. //
  41627. set inspector( value ) {
  41628. if ( this._inspector !== null ) {
  41629. this._inspector.setRenderer( null );
  41630. }
  41631. this._inspector = value;
  41632. this._inspector.setRenderer( this );
  41633. }
  41634. /**
  41635. * The inspector instance. The inspector can be any class that extends from `InspectorBase`.
  41636. *
  41637. * @type {InspectorBase}
  41638. */
  41639. get inspector() {
  41640. return this._inspector;
  41641. }
  41642. /**
  41643. * Enables or disables high precision for model-view and normal-view matrices.
  41644. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  41645. *
  41646. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  41647. *
  41648. * @param {boolean} value - Whether to enable or disable high precision.
  41649. * @type {boolean}
  41650. */
  41651. set highPrecision( value ) {
  41652. const contextNodeData = this.contextNode.value;
  41653. if ( value === true ) {
  41654. contextNodeData.modelViewMatrix = highpModelViewMatrix;
  41655. contextNodeData.modelNormalViewMatrix = highpModelNormalViewMatrix;
  41656. } else if ( this.highPrecision ) {
  41657. delete contextNodeData.modelViewMatrix;
  41658. delete contextNodeData.modelNormalViewMatrix;
  41659. }
  41660. }
  41661. /**
  41662. * Returns whether high precision is enabled or not.
  41663. *
  41664. * @return {boolean} Whether high precision is enabled or not.
  41665. * @type {boolean}
  41666. */
  41667. get highPrecision() {
  41668. const contextNodeData = this.contextNode.value;
  41669. return contextNodeData.modelViewMatrix === highpModelViewMatrix && contextNodeData.modelNormalViewMatrix === highpModelNormalViewMatrix;
  41670. }
  41671. /**
  41672. * Sets the given MRT configuration.
  41673. *
  41674. * @param {MRTNode} mrt - The MRT node to set.
  41675. * @return {Renderer} A reference to this renderer.
  41676. */
  41677. setMRT( mrt ) {
  41678. this._mrt = mrt;
  41679. return this;
  41680. }
  41681. /**
  41682. * Returns the MRT configuration.
  41683. *
  41684. * @return {MRTNode} The MRT configuration.
  41685. */
  41686. getMRT() {
  41687. return this._mrt;
  41688. }
  41689. /**
  41690. * Returns the color buffer type.
  41691. *
  41692. * @return {number} The color buffer type.
  41693. */
  41694. getColorBufferType() {
  41695. return this._colorBufferType;
  41696. }
  41697. /**
  41698. * Default implementation of the device lost callback.
  41699. *
  41700. * @private
  41701. * @param {Object} info - Information about the context lost.
  41702. */
  41703. _onDeviceLost( info ) {
  41704. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  41705. if ( info.reason ) {
  41706. errorMessage += `\nReason: ${info.reason}`;
  41707. }
  41708. error( errorMessage );
  41709. this._isDeviceLost = true;
  41710. }
  41711. /**
  41712. * Renders the given render bundle.
  41713. *
  41714. * @private
  41715. * @param {Object} bundle - Render bundle data.
  41716. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  41717. * @param {LightsNode} lightsNode - The lights node.
  41718. */
  41719. _renderBundle( bundle, sceneRef, lightsNode ) {
  41720. const { bundleGroup, camera, renderList } = bundle;
  41721. const renderContext = this._currentRenderContext;
  41722. //
  41723. const renderBundle = this._bundles.get( bundleGroup, camera );
  41724. const renderBundleData = this.backend.get( renderBundle );
  41725. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  41726. //
  41727. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  41728. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  41729. renderBundleData.renderContexts.add( renderContext );
  41730. if ( renderBundleNeedsUpdate ) {
  41731. this.backend.beginBundle( renderContext );
  41732. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  41733. renderBundleData.renderObjects = [];
  41734. }
  41735. this._currentRenderBundle = renderBundle;
  41736. const {
  41737. transparentDoublePass: transparentDoublePassObjects,
  41738. transparent: transparentObjects,
  41739. opaque: opaqueObjects
  41740. } = renderList;
  41741. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  41742. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  41743. this._currentRenderBundle = null;
  41744. //
  41745. this.backend.finishBundle( renderContext, renderBundle );
  41746. renderBundleData.version = bundleGroup.version;
  41747. } else {
  41748. const { renderObjects } = renderBundleData;
  41749. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  41750. const renderObject = renderObjects[ i ];
  41751. if ( this._nodes.needsRefresh( renderObject ) ) {
  41752. this._nodes.updateBefore( renderObject );
  41753. this._nodes.updateForRender( renderObject );
  41754. this._bindings.updateForRender( renderObject );
  41755. this._nodes.updateAfter( renderObject );
  41756. }
  41757. }
  41758. }
  41759. this.backend.addBundle( renderContext, renderBundle );
  41760. }
  41761. /**
  41762. * Renders the scene or 3D object with the given camera. This method can only be called
  41763. * if the renderer has been initialized. When using `render()` inside an animation loop,
  41764. * it's guaranteed the renderer will be initialized. The animation loop must be defined
  41765. * with {@link Renderer#setAnimationLoop} though.
  41766. *
  41767. * For all other use cases (like when using on-demand rendering), you must call
  41768. * {@link Renderer#init} before rendering.
  41769. *
  41770. * The target of the method is the default framebuffer (meaning the canvas)
  41771. * or alternatively a render target when specified via `setRenderTarget()`.
  41772. *
  41773. * @param {Object3D} scene - The scene or 3D object to render.
  41774. * @param {Camera} camera - The camera to render the scene with.
  41775. */
  41776. render( scene, camera ) {
  41777. if ( this._initialized === false ) {
  41778. throw new Error( 'Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.' );
  41779. }
  41780. this._renderScene( scene, camera );
  41781. }
  41782. /**
  41783. * Returns whether the renderer has been initialized or not.
  41784. *
  41785. * @readonly
  41786. * @return {boolean} Whether the renderer has been initialized or not.
  41787. */
  41788. get initialized() {
  41789. return this._initialized;
  41790. }
  41791. /**
  41792. * Returns an internal render target which is used when computing the output tone mapping
  41793. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  41794. * pass and not inline to achieve more correct results.
  41795. *
  41796. * @private
  41797. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  41798. */
  41799. _getFrameBufferTarget() {
  41800. const { currentToneMapping, currentColorSpace } = this;
  41801. const useToneMapping = currentToneMapping !== NoToneMapping;
  41802. const useColorSpace = currentColorSpace !== ColorManagement.workingColorSpace;
  41803. if ( useToneMapping === false && useColorSpace === false ) return null;
  41804. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  41805. const { depth, stencil } = this;
  41806. let frameBufferTarget = this._frameBufferTarget;
  41807. if ( frameBufferTarget === null ) {
  41808. frameBufferTarget = new RenderTarget( width, height, {
  41809. depthBuffer: depth,
  41810. stencilBuffer: stencil,
  41811. type: this._colorBufferType,
  41812. format: RGBAFormat,
  41813. colorSpace: ColorManagement.workingColorSpace,
  41814. generateMipmaps: false,
  41815. minFilter: LinearFilter,
  41816. magFilter: LinearFilter,
  41817. samples: this.samples
  41818. } );
  41819. frameBufferTarget.isPostProcessingRenderTarget = true;
  41820. this._frameBufferTarget = frameBufferTarget;
  41821. }
  41822. const outputRenderTarget = this.getOutputRenderTarget();
  41823. frameBufferTarget.depthBuffer = depth;
  41824. frameBufferTarget.stencilBuffer = stencil;
  41825. if ( outputRenderTarget !== null ) {
  41826. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  41827. } else {
  41828. frameBufferTarget.setSize( width, height, 1 );
  41829. }
  41830. const canvasTarget = this._canvasTarget;
  41831. frameBufferTarget.viewport.copy( canvasTarget._viewport );
  41832. frameBufferTarget.scissor.copy( canvasTarget._scissor );
  41833. frameBufferTarget.viewport.multiplyScalar( canvasTarget._pixelRatio );
  41834. frameBufferTarget.scissor.multiplyScalar( canvasTarget._pixelRatio );
  41835. frameBufferTarget.scissorTest = canvasTarget._scissorTest;
  41836. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  41837. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  41838. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  41839. return frameBufferTarget;
  41840. }
  41841. /**
  41842. * Renders the scene or 3D object with the given camera.
  41843. *
  41844. * @private
  41845. * @param {Object3D} scene - The scene or 3D object to render.
  41846. * @param {Camera} camera - The camera to render the scene with.
  41847. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  41848. * @return {RenderContext} The current render context.
  41849. */
  41850. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  41851. if ( this._isDeviceLost === true ) return;
  41852. //
  41853. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  41854. // preserve render tree
  41855. const nodeFrame = this._nodes.nodeFrame;
  41856. const previousRenderId = nodeFrame.renderId;
  41857. const previousRenderContext = this._currentRenderContext;
  41858. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  41859. //
  41860. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  41861. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  41862. const activeCubeFace = this._activeCubeFace;
  41863. const activeMipmapLevel = this._activeMipmapLevel;
  41864. //
  41865. let renderTarget;
  41866. if ( frameBufferTarget !== null ) {
  41867. renderTarget = frameBufferTarget;
  41868. this.setRenderTarget( renderTarget );
  41869. } else {
  41870. renderTarget = outputRenderTarget;
  41871. }
  41872. //
  41873. const renderContext = this._renderContexts.get( scene, camera, renderTarget, this._mrt );
  41874. this._currentRenderContext = renderContext;
  41875. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  41876. //
  41877. this.info.calls ++;
  41878. this.info.render.calls ++;
  41879. this.info.render.frameCalls ++;
  41880. nodeFrame.renderId = this.info.calls;
  41881. //
  41882. this.backend.updateTimeStampUID( renderContext );
  41883. this.inspector.beginRender( this.backend.getTimestampUID( renderContext ), scene, camera, renderTarget );
  41884. //
  41885. const coordinateSystem = this.coordinateSystem;
  41886. const xr = this.xr;
  41887. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  41888. camera.coordinateSystem = coordinateSystem;
  41889. camera.updateProjectionMatrix();
  41890. if ( camera.isArrayCamera ) {
  41891. for ( const subCamera of camera.cameras ) {
  41892. subCamera.coordinateSystem = coordinateSystem;
  41893. subCamera.updateProjectionMatrix();
  41894. }
  41895. }
  41896. }
  41897. //
  41898. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  41899. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  41900. if ( xr.enabled === true && xr.isPresenting === true ) {
  41901. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  41902. camera = xr.getCamera(); // use XR camera for rendering
  41903. }
  41904. //
  41905. const canvasTarget = this._canvasTarget;
  41906. let viewport = canvasTarget._viewport;
  41907. let scissor = canvasTarget._scissor;
  41908. let pixelRatio = canvasTarget._pixelRatio;
  41909. if ( renderTarget !== null ) {
  41910. viewport = renderTarget.viewport;
  41911. scissor = renderTarget.scissor;
  41912. pixelRatio = 1;
  41913. }
  41914. this.getDrawingBufferSize( _drawingBufferSize );
  41915. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  41916. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  41917. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  41918. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  41919. renderContext.viewportValue.width >>= activeMipmapLevel;
  41920. renderContext.viewportValue.height >>= activeMipmapLevel;
  41921. renderContext.viewportValue.minDepth = minDepth;
  41922. renderContext.viewportValue.maxDepth = maxDepth;
  41923. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  41924. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  41925. renderContext.scissor = canvasTarget._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  41926. renderContext.scissorValue.width >>= activeMipmapLevel;
  41927. renderContext.scissorValue.height >>= activeMipmapLevel;
  41928. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  41929. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  41930. //
  41931. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  41932. //
  41933. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  41934. if ( ! camera.isArrayCamera ) {
  41935. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  41936. frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  41937. }
  41938. const renderList = this._renderLists.get( scene, camera );
  41939. renderList.begin();
  41940. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  41941. renderList.finish();
  41942. if ( this.sortObjects === true ) {
  41943. renderList.sort( this._opaqueSort, this._transparentSort );
  41944. }
  41945. //
  41946. if ( renderTarget !== null ) {
  41947. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  41948. const renderTargetData = this._textures.get( renderTarget );
  41949. renderContext.textures = renderTargetData.textures;
  41950. renderContext.depthTexture = renderTargetData.depthTexture;
  41951. renderContext.width = renderTargetData.width;
  41952. renderContext.height = renderTargetData.height;
  41953. renderContext.renderTarget = renderTarget;
  41954. renderContext.depth = renderTarget.depthBuffer;
  41955. renderContext.stencil = renderTarget.stencilBuffer;
  41956. } else {
  41957. renderContext.textures = null;
  41958. renderContext.depthTexture = null;
  41959. renderContext.width = _drawingBufferSize.width;
  41960. renderContext.height = _drawingBufferSize.height;
  41961. renderContext.depth = this.depth;
  41962. renderContext.stencil = this.stencil;
  41963. }
  41964. renderContext.width >>= activeMipmapLevel;
  41965. renderContext.height >>= activeMipmapLevel;
  41966. renderContext.activeCubeFace = activeCubeFace;
  41967. renderContext.activeMipmapLevel = activeMipmapLevel;
  41968. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  41969. //
  41970. renderContext.scissorValue.max( _vector4.set( 0, 0, 0, 0 ) );
  41971. if ( renderContext.scissorValue.x + renderContext.scissorValue.width > renderContext.width ) {
  41972. renderContext.scissorValue.width = Math.max( renderContext.width - renderContext.scissorValue.x, 0 );
  41973. }
  41974. if ( renderContext.scissorValue.y + renderContext.scissorValue.height > renderContext.height ) {
  41975. renderContext.scissorValue.height = Math.max( renderContext.height - renderContext.scissorValue.y, 0 );
  41976. }
  41977. //
  41978. this._background.update( sceneRef, renderList, renderContext );
  41979. //
  41980. renderContext.camera = camera;
  41981. this.backend.beginRender( renderContext );
  41982. // process render lists
  41983. const {
  41984. bundles,
  41985. lightsNode,
  41986. transparentDoublePass: transparentDoublePassObjects,
  41987. transparent: transparentObjects,
  41988. opaque: opaqueObjects
  41989. } = renderList;
  41990. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  41991. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  41992. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  41993. // finish render pass
  41994. this.backend.finishRender( renderContext );
  41995. // restore render tree
  41996. nodeFrame.renderId = previousRenderId;
  41997. this._currentRenderContext = previousRenderContext;
  41998. this._currentRenderObjectFunction = previousRenderObjectFunction;
  41999. //
  42000. if ( frameBufferTarget !== null ) {
  42001. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  42002. this._renderOutput( renderTarget );
  42003. }
  42004. //
  42005. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  42006. //
  42007. this.inspector.finishRender( this.backend.getTimestampUID( renderContext ) );
  42008. //
  42009. return renderContext;
  42010. }
  42011. _setXRLayerSize( width, height ) {
  42012. // TODO: Find a better solution to resize the canvas when in XR.
  42013. this._canvasTarget._width = width;
  42014. this._canvasTarget._height = height;
  42015. this.setViewport( 0, 0, width, height );
  42016. }
  42017. /**
  42018. * The output pass performs tone mapping and color space conversion.
  42019. *
  42020. * @private
  42021. * @param {RenderTarget} renderTarget - The current render target.
  42022. */
  42023. _renderOutput( renderTarget ) {
  42024. const quad = this._quad;
  42025. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  42026. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  42027. quad.material.needsUpdate = true;
  42028. }
  42029. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  42030. const currentAutoClear = this.autoClear;
  42031. const currentXR = this.xr.enabled;
  42032. this.autoClear = false;
  42033. this.xr.enabled = false;
  42034. this._renderScene( quad, quad.camera, false );
  42035. this.autoClear = currentAutoClear;
  42036. this.xr.enabled = currentXR;
  42037. }
  42038. /**
  42039. * Returns the maximum available anisotropy for texture filtering.
  42040. *
  42041. * @return {number} The maximum available anisotropy.
  42042. */
  42043. getMaxAnisotropy() {
  42044. return this.backend.getMaxAnisotropy();
  42045. }
  42046. /**
  42047. * Returns the active cube face.
  42048. *
  42049. * @return {number} The active cube face.
  42050. */
  42051. getActiveCubeFace() {
  42052. return this._activeCubeFace;
  42053. }
  42054. /**
  42055. * Returns the active mipmap level.
  42056. *
  42057. * @return {number} The active mipmap level.
  42058. */
  42059. getActiveMipmapLevel() {
  42060. return this._activeMipmapLevel;
  42061. }
  42062. /**
  42063. * Applications are advised to always define the animation loop
  42064. * with this method and not manually with `requestAnimationFrame()`
  42065. * for best compatibility.
  42066. *
  42067. * @async
  42068. * @param {?onAnimationCallback} callback - The application's animation loop.
  42069. * @return {Promise} A Promise that resolves when the set has been executed.
  42070. */
  42071. async setAnimationLoop( callback ) {
  42072. if ( this._initialized === false ) await this.init();
  42073. this._animation.setAnimationLoop( callback );
  42074. }
  42075. /**
  42076. * Returns the current animation loop callback.
  42077. *
  42078. * @return {?Function} The current animation loop callback.
  42079. */
  42080. getAnimationLoop() {
  42081. return this._animation.getAnimationLoop();
  42082. }
  42083. /**
  42084. * Can be used to transfer buffer data from a storage buffer attribute
  42085. * from the GPU to the CPU in context of compute shaders.
  42086. *
  42087. * @async
  42088. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  42089. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  42090. */
  42091. async getArrayBufferAsync( attribute ) {
  42092. return await this.backend.getArrayBufferAsync( attribute );
  42093. }
  42094. /**
  42095. * Returns the rendering context.
  42096. *
  42097. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  42098. */
  42099. getContext() {
  42100. return this.backend.getContext();
  42101. }
  42102. /**
  42103. * Returns the pixel ratio.
  42104. *
  42105. * @return {number} The pixel ratio.
  42106. */
  42107. getPixelRatio() {
  42108. return this._canvasTarget.getPixelRatio();
  42109. }
  42110. /**
  42111. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  42112. *
  42113. * @param {Vector2} target - The method writes the result in this target object.
  42114. * @return {Vector2} The drawing buffer size.
  42115. */
  42116. getDrawingBufferSize( target ) {
  42117. return this._canvasTarget.getDrawingBufferSize( target );
  42118. }
  42119. /**
  42120. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  42121. *
  42122. * @param {Vector2} target - The method writes the result in this target object.
  42123. * @return {Vector2} The renderer's size in logical pixels.
  42124. */
  42125. getSize( target ) {
  42126. return this._canvasTarget.getSize( target );
  42127. }
  42128. /**
  42129. * Sets the given pixel ratio and resizes the canvas if necessary.
  42130. *
  42131. * @param {number} [value=1] - The pixel ratio.
  42132. */
  42133. setPixelRatio( value = 1 ) {
  42134. this._canvasTarget.setPixelRatio( value );
  42135. }
  42136. /**
  42137. * This method allows to define the drawing buffer size by specifying
  42138. * width, height and pixel ratio all at once. The size of the drawing
  42139. * buffer is computed with this formula:
  42140. * ```js
  42141. * size.x = width * pixelRatio;
  42142. * size.y = height * pixelRatio;
  42143. * ```
  42144. *
  42145. * @param {number} width - The width in logical pixels.
  42146. * @param {number} height - The height in logical pixels.
  42147. * @param {number} pixelRatio - The pixel ratio.
  42148. */
  42149. setDrawingBufferSize( width, height, pixelRatio ) {
  42150. // Renderer can't be resized while presenting in XR.
  42151. if ( this.xr && this.xr.isPresenting ) return;
  42152. this._canvasTarget.setDrawingBufferSize( width, height, pixelRatio );
  42153. }
  42154. /**
  42155. * Sets the size of the renderer.
  42156. *
  42157. * @param {number} width - The width in logical pixels.
  42158. * @param {number} height - The height in logical pixels.
  42159. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  42160. */
  42161. setSize( width, height, updateStyle = true ) {
  42162. // Renderer can't be resized while presenting in XR.
  42163. if ( this.xr && this.xr.isPresenting ) return;
  42164. this._canvasTarget.setSize( width, height, updateStyle );
  42165. }
  42166. /**
  42167. * Defines a manual sort function for the opaque render list.
  42168. * Pass `null` to use the default sort.
  42169. *
  42170. * @param {Function} method - The sort function.
  42171. */
  42172. setOpaqueSort( method ) {
  42173. this._opaqueSort = method;
  42174. }
  42175. /**
  42176. * Defines a manual sort function for the transparent render list.
  42177. * Pass `null` to use the default sort.
  42178. *
  42179. * @param {Function} method - The sort function.
  42180. */
  42181. setTransparentSort( method ) {
  42182. this._transparentSort = method;
  42183. }
  42184. /**
  42185. * Returns the scissor rectangle.
  42186. *
  42187. * @param {Vector4} target - The method writes the result in this target object.
  42188. * @return {Vector4} The scissor rectangle.
  42189. */
  42190. getScissor( target ) {
  42191. return this._canvasTarget.getScissor( target );
  42192. }
  42193. /**
  42194. * Defines the scissor rectangle.
  42195. *
  42196. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  42197. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  42198. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  42199. * @param {number} width - The width of the scissor box in logical pixel unit.
  42200. * @param {number} height - The height of the scissor box in logical pixel unit.
  42201. */
  42202. setScissor( x, y, width, height ) {
  42203. this._canvasTarget.setScissor( x, y, width, height );
  42204. }
  42205. /**
  42206. * Returns the scissor test value.
  42207. *
  42208. * @return {boolean} Whether the scissor test should be enabled or not.
  42209. */
  42210. getScissorTest() {
  42211. return this._canvasTarget.getScissorTest();
  42212. }
  42213. /**
  42214. * Defines the scissor test.
  42215. *
  42216. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  42217. */
  42218. setScissorTest( boolean ) {
  42219. this._canvasTarget.setScissorTest( boolean );
  42220. // TODO: Move it to CanvasTarget event listener.
  42221. this.backend.setScissorTest( boolean );
  42222. }
  42223. /**
  42224. * Returns the viewport definition.
  42225. *
  42226. * @param {Vector4} target - The method writes the result in this target object.
  42227. * @return {Vector4} The viewport definition.
  42228. */
  42229. getViewport( target ) {
  42230. return this._canvasTarget.getViewport( target );
  42231. }
  42232. /**
  42233. * Defines the viewport.
  42234. *
  42235. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  42236. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  42237. * @param {number} width - The width of the viewport in logical pixel unit.
  42238. * @param {number} height - The height of the viewport in logical pixel unit.
  42239. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  42240. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  42241. */
  42242. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  42243. this._canvasTarget.setViewport( x, y, width, height, minDepth, maxDepth );
  42244. }
  42245. /**
  42246. * Returns the clear color.
  42247. *
  42248. * @param {Color} target - The method writes the result in this target object.
  42249. * @return {Color} The clear color.
  42250. */
  42251. getClearColor( target ) {
  42252. return target.copy( this._clearColor );
  42253. }
  42254. /**
  42255. * Defines the clear color and optionally the clear alpha.
  42256. *
  42257. * @param {Color} color - The clear color.
  42258. * @param {number} [alpha=1] - The clear alpha.
  42259. */
  42260. setClearColor( color, alpha = 1 ) {
  42261. this._clearColor.set( color );
  42262. this._clearColor.a = alpha;
  42263. }
  42264. /**
  42265. * Returns the clear alpha.
  42266. *
  42267. * @return {number} The clear alpha.
  42268. */
  42269. getClearAlpha() {
  42270. return this._clearColor.a;
  42271. }
  42272. /**
  42273. * Defines the clear alpha.
  42274. *
  42275. * @param {number} alpha - The clear alpha.
  42276. */
  42277. setClearAlpha( alpha ) {
  42278. this._clearColor.a = alpha;
  42279. }
  42280. /**
  42281. * Returns the clear depth.
  42282. *
  42283. * @return {number} The clear depth.
  42284. */
  42285. getClearDepth() {
  42286. return this._clearDepth;
  42287. }
  42288. /**
  42289. * Defines the clear depth.
  42290. *
  42291. * @param {number} depth - The clear depth.
  42292. */
  42293. setClearDepth( depth ) {
  42294. this._clearDepth = depth;
  42295. }
  42296. /**
  42297. * Returns the clear stencil.
  42298. *
  42299. * @return {number} The clear stencil.
  42300. */
  42301. getClearStencil() {
  42302. return this._clearStencil;
  42303. }
  42304. /**
  42305. * Defines the clear stencil.
  42306. *
  42307. * @param {number} stencil - The clear stencil.
  42308. */
  42309. setClearStencil( stencil ) {
  42310. this._clearStencil = stencil;
  42311. }
  42312. /**
  42313. * This method performs an occlusion query for the given 3D object.
  42314. * It returns `true` if the given 3D object is fully occluded by other
  42315. * 3D objects in the scene.
  42316. *
  42317. * @param {Object3D} object - The 3D object to test.
  42318. * @return {boolean} Whether the 3D object is fully occluded or not.
  42319. */
  42320. isOccluded( object ) {
  42321. const renderContext = this._currentRenderContext;
  42322. return renderContext && this.backend.isOccluded( renderContext, object );
  42323. }
  42324. /**
  42325. * Performs a manual clear operation. This method ignores `autoClear` properties.
  42326. *
  42327. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  42328. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  42329. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  42330. */
  42331. clear( color = true, depth = true, stencil = true ) {
  42332. if ( this._initialized === false ) {
  42333. throw new Error( 'Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  42334. }
  42335. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  42336. let renderContext = null;
  42337. if ( renderTarget !== null ) {
  42338. this._textures.updateRenderTarget( renderTarget );
  42339. const renderTargetData = this._textures.get( renderTarget );
  42340. renderContext = this._renderContexts.getForClear( renderTarget );
  42341. renderContext.textures = renderTargetData.textures;
  42342. renderContext.depthTexture = renderTargetData.depthTexture;
  42343. renderContext.width = renderTargetData.width;
  42344. renderContext.height = renderTargetData.height;
  42345. renderContext.renderTarget = renderTarget;
  42346. renderContext.depth = renderTarget.depthBuffer;
  42347. renderContext.stencil = renderTarget.stencilBuffer;
  42348. // #30329
  42349. renderContext.clearColorValue = this.backend.getClearColor();
  42350. renderContext.activeCubeFace = this.getActiveCubeFace();
  42351. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  42352. }
  42353. this.backend.clear( color, depth, stencil, renderContext );
  42354. if ( renderTarget !== null && this._renderTarget === null ) {
  42355. this._renderOutput( renderTarget );
  42356. }
  42357. }
  42358. /**
  42359. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  42360. */
  42361. clearColor() {
  42362. this.clear( true, false, false );
  42363. }
  42364. /**
  42365. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  42366. */
  42367. clearDepth() {
  42368. this.clear( false, true, false );
  42369. }
  42370. /**
  42371. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  42372. */
  42373. clearStencil() {
  42374. this.clear( false, false, true );
  42375. }
  42376. /**
  42377. * Async version of {@link Renderer#clear}.
  42378. *
  42379. * @async
  42380. * @deprecated
  42381. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  42382. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  42383. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  42384. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42385. */
  42386. async clearAsync( color = true, depth = true, stencil = true ) {
  42387. warnOnce( 'Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42388. await this.init();
  42389. this.clear( color, depth, stencil );
  42390. }
  42391. /**
  42392. * Async version of {@link Renderer#clearColor}.
  42393. *
  42394. * @async
  42395. * @deprecated
  42396. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42397. */
  42398. async clearColorAsync() {
  42399. warnOnce( 'Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42400. this.clear( true, false, false );
  42401. }
  42402. /**
  42403. * Async version of {@link Renderer#clearDepth}.
  42404. *
  42405. * @async
  42406. * @deprecated
  42407. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42408. */
  42409. async clearDepthAsync() {
  42410. warnOnce( 'Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42411. this.clear( false, true, false );
  42412. }
  42413. /**
  42414. * Async version of {@link Renderer#clearStencil}.
  42415. *
  42416. * @async
  42417. * @deprecated
  42418. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42419. */
  42420. async clearStencilAsync() {
  42421. warnOnce( 'Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42422. this.clear( false, false, true );
  42423. }
  42424. /**
  42425. * Returns `true` if a framebuffer target is needed to perform tone mapping or color space conversion.
  42426. * If this is the case, the renderer allocates an internal render target for that purpose.
  42427. *
  42428. */
  42429. get needsFrameBufferTarget() {
  42430. const useToneMapping = this.currentToneMapping !== NoToneMapping;
  42431. const useColorSpace = this.currentColorSpace !== ColorManagement.workingColorSpace;
  42432. return useToneMapping || useColorSpace;
  42433. }
  42434. /**
  42435. * The number of samples used for multi-sample anti-aliasing (MSAA).
  42436. *
  42437. * @type {number}
  42438. * @default 0
  42439. */
  42440. get samples() {
  42441. return this._samples;
  42442. }
  42443. /**
  42444. * The current number of samples used for multi-sample anti-aliasing (MSAA).
  42445. *
  42446. * When rendering to a custom render target, the number of samples of that render target is used.
  42447. * If the renderer needs an internal framebuffer target for tone mapping or color space conversion,
  42448. * the number of samples is set to 0.
  42449. *
  42450. * @type {number}
  42451. */
  42452. get currentSamples() {
  42453. let samples = this._samples;
  42454. if ( this._renderTarget !== null ) {
  42455. samples = this._renderTarget.samples;
  42456. } else if ( this.needsFrameBufferTarget ) {
  42457. samples = 0;
  42458. }
  42459. return samples;
  42460. }
  42461. /**
  42462. * The current tone mapping of the renderer. When not producing screen output,
  42463. * the tone mapping is always `NoToneMapping`.
  42464. *
  42465. * @type {number}
  42466. */
  42467. get currentToneMapping() {
  42468. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  42469. }
  42470. /**
  42471. * The current color space of the renderer. When not producing screen output,
  42472. * the color space is always the working color space.
  42473. *
  42474. * @type {string}
  42475. */
  42476. get currentColorSpace() {
  42477. return this.isOutputTarget ? this.outputColorSpace : ColorManagement.workingColorSpace;
  42478. }
  42479. /**
  42480. * Returns `true` if the rendering settings are set to screen output.
  42481. *
  42482. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  42483. */
  42484. get isOutputTarget() {
  42485. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  42486. }
  42487. /**
  42488. * Frees all internal resources of the renderer. Call this method if the renderer
  42489. * is no longer in use by your app.
  42490. */
  42491. dispose() {
  42492. if ( this._initialized === true ) {
  42493. this.info.dispose();
  42494. this.backend.dispose();
  42495. this._animation.dispose();
  42496. this._objects.dispose();
  42497. this._geometries.dispose();
  42498. this._pipelines.dispose();
  42499. this._nodes.dispose();
  42500. this._bindings.dispose();
  42501. this._renderLists.dispose();
  42502. this._renderContexts.dispose();
  42503. this._textures.dispose();
  42504. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  42505. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  42506. if ( queryPool !== null ) queryPool.dispose();
  42507. } );
  42508. }
  42509. this.setRenderTarget( null );
  42510. this.setAnimationLoop( null );
  42511. }
  42512. /**
  42513. * Sets the given render target. Calling this method means the renderer does not
  42514. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  42515. * Use `null` as the first argument to reset the state.
  42516. *
  42517. * @param {?RenderTarget} renderTarget - The render target to set.
  42518. * @param {number} [activeCubeFace=0] - The active cube face.
  42519. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  42520. */
  42521. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  42522. this._renderTarget = renderTarget;
  42523. this._activeCubeFace = activeCubeFace;
  42524. this._activeMipmapLevel = activeMipmapLevel;
  42525. }
  42526. /**
  42527. * Returns the current render target.
  42528. *
  42529. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  42530. */
  42531. getRenderTarget() {
  42532. return this._renderTarget;
  42533. }
  42534. /**
  42535. * Sets the output render target for the renderer.
  42536. *
  42537. * @param {Object} renderTarget - The render target to set as the output target.
  42538. */
  42539. setOutputRenderTarget( renderTarget ) {
  42540. this._outputRenderTarget = renderTarget;
  42541. }
  42542. /**
  42543. * Returns the current output target.
  42544. *
  42545. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  42546. */
  42547. getOutputRenderTarget() {
  42548. return this._outputRenderTarget;
  42549. }
  42550. /**
  42551. * Sets the canvas target. The canvas target manages the HTML canvas
  42552. * or the offscreen canvas the renderer draws into.
  42553. *
  42554. * @param {CanvasTarget} canvasTarget - The canvas target.
  42555. */
  42556. setCanvasTarget( canvasTarget ) {
  42557. this._canvasTarget.removeEventListener( 'resize', this._onCanvasTargetResize );
  42558. this._canvasTarget = canvasTarget;
  42559. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  42560. }
  42561. /**
  42562. * Returns the current canvas target.
  42563. *
  42564. * @return {CanvasTarget} The current canvas target.
  42565. */
  42566. getCanvasTarget() {
  42567. return this._canvasTarget;
  42568. }
  42569. /**
  42570. * Resets the renderer to the initial state before WebXR started.
  42571. *
  42572. * @private
  42573. */
  42574. _resetXRState() {
  42575. this.backend.setXRTarget( null );
  42576. this.setOutputRenderTarget( null );
  42577. this.setRenderTarget( null );
  42578. this._frameBufferTarget.dispose();
  42579. this._frameBufferTarget = null;
  42580. }
  42581. /**
  42582. * Callback for {@link Renderer#setRenderObjectFunction}.
  42583. *
  42584. * @callback renderObjectFunction
  42585. * @param {Object3D} object - The 3D object.
  42586. * @param {Scene} scene - The scene the 3D object belongs to.
  42587. * @param {Camera} camera - The camera the object should be rendered with.
  42588. * @param {BufferGeometry} geometry - The object's geometry.
  42589. * @param {Material} material - The object's material.
  42590. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  42591. * @param {LightsNode} lightsNode - The current lights node.
  42592. * @param {ClippingContext} clippingContext - The clipping context.
  42593. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  42594. */
  42595. /**
  42596. * Sets the given render object function. Calling this method overwrites the default implementation
  42597. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  42598. * if you want to modify the way objects are rendered. For example you can define things like "every
  42599. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  42600. * The custom function must always call `renderObject()` in its implementation.
  42601. *
  42602. * Use `null` as the first argument to reset the state.
  42603. *
  42604. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  42605. */
  42606. setRenderObjectFunction( renderObjectFunction ) {
  42607. this._renderObjectFunction = renderObjectFunction;
  42608. }
  42609. /**
  42610. * Returns the current render object function.
  42611. *
  42612. * @return {?Function} The current render object function. Returns `null` if no function is set.
  42613. */
  42614. getRenderObjectFunction() {
  42615. return this._renderObjectFunction;
  42616. }
  42617. /**
  42618. * Execute a single or an array of compute nodes. This method can only be called
  42619. * if the renderer has been initialized.
  42620. *
  42621. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  42622. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  42623. * - A single number representing count, or
  42624. * - An array [x, y, z] representing dispatch size, or
  42625. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  42626. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  42627. */
  42628. compute( computeNodes, dispatchSize = null ) {
  42629. if ( this._isDeviceLost === true ) return;
  42630. if ( this._initialized === false ) {
  42631. warn( 'Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  42632. return this.computeAsync( computeNodes, dispatchSize );
  42633. }
  42634. //
  42635. const nodeFrame = this._nodes.nodeFrame;
  42636. const previousRenderId = nodeFrame.renderId;
  42637. //
  42638. this.info.calls ++;
  42639. this.info.compute.calls ++;
  42640. this.info.compute.frameCalls ++;
  42641. nodeFrame.renderId = this.info.calls;
  42642. //
  42643. this.backend.updateTimeStampUID( computeNodes );
  42644. this.inspector.beginCompute( this.backend.getTimestampUID( computeNodes ), computeNodes );
  42645. //
  42646. const backend = this.backend;
  42647. const pipelines = this._pipelines;
  42648. const bindings = this._bindings;
  42649. const nodes = this._nodes;
  42650. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  42651. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  42652. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  42653. }
  42654. backend.beginCompute( computeNodes );
  42655. for ( const computeNode of computeList ) {
  42656. // onInit
  42657. if ( pipelines.has( computeNode ) === false ) {
  42658. const dispose = () => {
  42659. computeNode.removeEventListener( 'dispose', dispose );
  42660. pipelines.delete( computeNode );
  42661. bindings.deleteForCompute( computeNode );
  42662. nodes.delete( computeNode );
  42663. };
  42664. computeNode.addEventListener( 'dispose', dispose );
  42665. //
  42666. const onInitFn = computeNode.onInitFunction;
  42667. if ( onInitFn !== null ) {
  42668. onInitFn.call( computeNode, { renderer: this } );
  42669. }
  42670. }
  42671. nodes.updateForCompute( computeNode );
  42672. bindings.updateForCompute( computeNode );
  42673. const computeBindings = bindings.getForCompute( computeNode );
  42674. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  42675. backend.compute( computeNodes, computeNode, computeBindings, computePipeline, dispatchSize );
  42676. }
  42677. backend.finishCompute( computeNodes );
  42678. //
  42679. nodeFrame.renderId = previousRenderId;
  42680. //
  42681. this.inspector.finishCompute( this.backend.getTimestampUID( computeNodes ) );
  42682. }
  42683. /**
  42684. * Execute a single or an array of compute nodes.
  42685. *
  42686. * @async
  42687. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  42688. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  42689. * - A single number representing count, or
  42690. * - An array [x, y, z] representing dispatch size, or
  42691. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  42692. * @return {Promise} A Promise that resolve when the compute has finished.
  42693. */
  42694. async computeAsync( computeNodes, dispatchSize = null ) {
  42695. if ( this._initialized === false ) await this.init();
  42696. this.compute( computeNodes, dispatchSize );
  42697. }
  42698. /**
  42699. * Checks if the given feature is supported by the selected backend.
  42700. *
  42701. * @async
  42702. * @deprecated
  42703. * @param {string} name - The feature's name.
  42704. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  42705. */
  42706. async hasFeatureAsync( name ) {
  42707. warnOnce( 'Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42708. await this.init();
  42709. return this.hasFeature( name );
  42710. }
  42711. async resolveTimestampsAsync( type = 'render' ) {
  42712. if ( this._initialized === false ) await this.init();
  42713. return this.backend.resolveTimestampsAsync( type );
  42714. }
  42715. /**
  42716. * Checks if the given feature is supported by the selected backend. If the
  42717. * renderer has not been initialized, this method always returns `false`.
  42718. *
  42719. * @param {string} name - The feature's name.
  42720. * @return {boolean} Whether the feature is supported or not.
  42721. */
  42722. hasFeature( name ) {
  42723. if ( this._initialized === false ) {
  42724. throw new Error( 'Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  42725. }
  42726. return this.backend.hasFeature( name );
  42727. }
  42728. /**
  42729. * Returns `true` when the renderer has been initialized.
  42730. *
  42731. * @return {boolean} Whether the renderer has been initialized or not.
  42732. */
  42733. hasInitialized() {
  42734. return this._initialized;
  42735. }
  42736. /**
  42737. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  42738. * (which can cause noticeable lags due to decode and GPU upload overhead).
  42739. *
  42740. * @async
  42741. * @deprecated
  42742. * @param {Texture} texture - The texture.
  42743. * @return {Promise} A Promise that resolves when the texture has been initialized.
  42744. */
  42745. async initTextureAsync( texture ) {
  42746. warnOnce( 'Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42747. await this.init();
  42748. this.initTexture( texture );
  42749. }
  42750. /**
  42751. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  42752. * (which can cause noticeable lags due to decode and GPU upload overhead).
  42753. *
  42754. * This method can only be used if the renderer has been initialized.
  42755. *
  42756. * @param {Texture} texture - The texture.
  42757. */
  42758. initTexture( texture ) {
  42759. if ( this._initialized === false ) {
  42760. throw new Error( 'Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  42761. }
  42762. this._textures.updateTexture( texture );
  42763. }
  42764. /**
  42765. * Copies the current bound framebuffer into the given texture.
  42766. *
  42767. * @param {FramebufferTexture} framebufferTexture - The texture.
  42768. * @param {?(Vector2|Vector4)} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  42769. */
  42770. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  42771. if ( rectangle !== null ) {
  42772. if ( rectangle.isVector2 ) {
  42773. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  42774. } else if ( rectangle.isVector4 ) {
  42775. rectangle = _vector4.copy( rectangle ).floor();
  42776. } else {
  42777. error( 'Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  42778. return;
  42779. }
  42780. } else {
  42781. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  42782. }
  42783. //
  42784. let renderContext = this._currentRenderContext;
  42785. let renderTarget;
  42786. if ( renderContext !== null ) {
  42787. renderTarget = renderContext.renderTarget;
  42788. } else {
  42789. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  42790. if ( renderTarget !== null ) {
  42791. this._textures.updateRenderTarget( renderTarget );
  42792. renderContext = this._textures.get( renderTarget );
  42793. }
  42794. }
  42795. //
  42796. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  42797. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  42798. this._inspector.copyFramebufferToTexture( framebufferTexture );
  42799. }
  42800. /**
  42801. * Copies data of the given source texture into a destination texture.
  42802. *
  42803. * @param {Texture} srcTexture - The source texture.
  42804. * @param {Texture} dstTexture - The destination texture.
  42805. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  42806. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  42807. * @param {number} [srcLevel=0] - The source mip level to copy from.
  42808. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  42809. */
  42810. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  42811. this._textures.updateTexture( srcTexture );
  42812. this._textures.updateTexture( dstTexture );
  42813. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  42814. this._inspector.copyTextureToTexture( srcTexture, dstTexture );
  42815. }
  42816. /**
  42817. * Reads pixel data from the given render target.
  42818. *
  42819. * @async
  42820. * @param {RenderTarget} renderTarget - The render target to read from.
  42821. * @param {number} x - The `x` coordinate of the copy region's origin.
  42822. * @param {number} y - The `y` coordinate of the copy region's origin.
  42823. * @param {number} width - The width of the copy region.
  42824. * @param {number} height - The height of the copy region.
  42825. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  42826. * @param {number} [faceIndex=0] - The active cube face index.
  42827. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  42828. */
  42829. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  42830. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  42831. }
  42832. /**
  42833. * Analyzes the given 3D object's hierarchy and builds render lists from the
  42834. * processed hierarchy.
  42835. *
  42836. * @private
  42837. * @param {Object3D} object - The 3D object to process (usually a scene).
  42838. * @param {Camera} camera - The camera the object is rendered with.
  42839. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  42840. * @param {RenderList} renderList - The current render list.
  42841. * @param {ClippingContext} clippingContext - The current clipping context.
  42842. */
  42843. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  42844. if ( object.visible === false ) return;
  42845. const visible = object.layers.test( camera.layers );
  42846. if ( visible ) {
  42847. if ( object.isGroup ) {
  42848. groupOrder = object.renderOrder;
  42849. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  42850. } else if ( object.isLOD ) {
  42851. if ( object.autoUpdate === true ) object.update( camera );
  42852. } else if ( object.isLight ) {
  42853. renderList.pushLight( object );
  42854. } else if ( object.isSprite ) {
  42855. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  42856. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  42857. if ( this.sortObjects === true ) {
  42858. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  42859. }
  42860. const { geometry, material } = object;
  42861. if ( material.visible ) {
  42862. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  42863. }
  42864. }
  42865. } else if ( object.isLineLoop ) {
  42866. error( 'Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  42867. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  42868. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  42869. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  42870. const { geometry, material } = object;
  42871. if ( this.sortObjects === true ) {
  42872. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  42873. _vector4
  42874. .copy( geometry.boundingSphere.center )
  42875. .applyMatrix4( object.matrixWorld )
  42876. .applyMatrix4( _projScreenMatrix );
  42877. }
  42878. if ( Array.isArray( material ) ) {
  42879. const groups = geometry.groups;
  42880. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  42881. const group = groups[ i ];
  42882. const groupMaterial = material[ group.materialIndex ];
  42883. if ( groupMaterial && groupMaterial.visible ) {
  42884. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  42885. }
  42886. }
  42887. } else if ( material.visible ) {
  42888. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  42889. }
  42890. }
  42891. }
  42892. }
  42893. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  42894. const baseRenderList = renderList;
  42895. // replace render list
  42896. renderList = this._renderLists.get( object, camera );
  42897. renderList.begin();
  42898. baseRenderList.pushBundle( {
  42899. bundleGroup: object,
  42900. camera,
  42901. renderList,
  42902. } );
  42903. renderList.finish();
  42904. }
  42905. const children = object.children;
  42906. for ( let i = 0, l = children.length; i < l; i ++ ) {
  42907. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  42908. }
  42909. }
  42910. /**
  42911. * Renders the given render bundles.
  42912. *
  42913. * @private
  42914. * @param {Array<Object>} bundles - Array with render bundle data.
  42915. * @param {Scene} sceneRef - The scene the render bundles belong to.
  42916. * @param {LightsNode} lightsNode - The current lights node.
  42917. */
  42918. _renderBundles( bundles, sceneRef, lightsNode ) {
  42919. for ( const bundle of bundles ) {
  42920. this._renderBundle( bundle, sceneRef, lightsNode );
  42921. }
  42922. }
  42923. /**
  42924. * Renders the transparent objects from the given render lists.
  42925. *
  42926. * @private
  42927. * @param {Array<Object>} renderList - The transparent render list.
  42928. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  42929. * @param {Camera} camera - The camera the render list should be rendered with.
  42930. * @param {Scene} scene - The scene the render list belongs to.
  42931. * @param {LightsNode} lightsNode - The current lights node.
  42932. */
  42933. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  42934. if ( doublePassList.length > 0 ) {
  42935. // render back side
  42936. for ( const { material } of doublePassList ) {
  42937. material.side = BackSide;
  42938. }
  42939. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  42940. // render front side
  42941. for ( const { material } of doublePassList ) {
  42942. material.side = FrontSide;
  42943. }
  42944. this._renderObjects( renderList, camera, scene, lightsNode );
  42945. // restore
  42946. for ( const { material } of doublePassList ) {
  42947. material.side = DoubleSide;
  42948. }
  42949. } else {
  42950. this._renderObjects( renderList, camera, scene, lightsNode );
  42951. }
  42952. }
  42953. /**
  42954. * Renders the objects from the given render list.
  42955. *
  42956. * @private
  42957. * @param {Array<Object>} renderList - The render list.
  42958. * @param {Camera} camera - The camera the render list should be rendered with.
  42959. * @param {Scene} scene - The scene the render list belongs to.
  42960. * @param {LightsNode} lightsNode - The current lights node.
  42961. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  42962. */
  42963. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  42964. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  42965. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  42966. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  42967. }
  42968. }
  42969. /**
  42970. * Retrieves shadow nodes for the given material. This is used to setup shadow passes.
  42971. * The result is cached per material and updated when the material's version changes.
  42972. *
  42973. * @private
  42974. * @param {Material} material
  42975. * @returns {Object} - The shadow nodes for the material.
  42976. */
  42977. _getShadowNodes( material ) {
  42978. const version = material.version;
  42979. let cache = this._cacheShadowNodes.get( material );
  42980. if ( cache === undefined || cache.version !== version ) {
  42981. const hasMap = material.map !== null;
  42982. const hasColorNode = material.colorNode && material.colorNode.isNode;
  42983. const hasCastShadowNode = material.castShadowNode && material.castShadowNode.isNode;
  42984. let positionNode = null;
  42985. let colorNode = null;
  42986. let depthNode = null;
  42987. if ( hasMap || hasColorNode || hasCastShadowNode ) {
  42988. let shadowRGB;
  42989. let shadowAlpha;
  42990. if ( hasCastShadowNode ) {
  42991. shadowRGB = material.castShadowNode.rgb;
  42992. shadowAlpha = material.castShadowNode.a;
  42993. } else {
  42994. shadowRGB = vec3( 0 );
  42995. shadowAlpha = float( 1 );
  42996. }
  42997. if ( hasMap ) {
  42998. shadowAlpha = shadowAlpha.mul( reference( 'map', 'texture', material ).a );
  42999. }
  43000. if ( hasColorNode ) {
  43001. shadowAlpha = shadowAlpha.mul( material.colorNode.a );
  43002. }
  43003. colorNode = vec4( shadowRGB, shadowAlpha );
  43004. }
  43005. if ( material.depthNode && material.depthNode.isNode ) {
  43006. depthNode = material.depthNode;
  43007. }
  43008. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  43009. positionNode = material.castShadowPositionNode;
  43010. } else if ( material.positionNode && material.positionNode.isNode ) {
  43011. positionNode = material.positionNode;
  43012. }
  43013. cache = {
  43014. version,
  43015. colorNode,
  43016. depthNode,
  43017. positionNode
  43018. };
  43019. this._cacheShadowNodes.set( material, cache );
  43020. }
  43021. return cache;
  43022. }
  43023. /**
  43024. * This method represents the default render object function that manages the render lifecycle
  43025. * of the object.
  43026. *
  43027. * @param {Object3D} object - The 3D object.
  43028. * @param {Scene} scene - The scene the 3D object belongs to.
  43029. * @param {Camera} camera - The camera the object should be rendered with.
  43030. * @param {BufferGeometry} geometry - The object's geometry.
  43031. * @param {Material} material - The object's material.
  43032. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  43033. * @param {LightsNode} lightsNode - The current lights node.
  43034. * @param {?ClippingContext} clippingContext - The clipping context.
  43035. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  43036. */
  43037. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  43038. let materialOverride = false;
  43039. let materialColorNode;
  43040. let materialDepthNode;
  43041. let materialPositionNode;
  43042. let materialSide;
  43043. //
  43044. object.onBeforeRender( this, scene, camera, geometry, material, group );
  43045. //
  43046. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  43047. const overrideMaterial = scene.overrideMaterial;
  43048. materialOverride = true;
  43049. // store original nodes
  43050. materialColorNode = scene.overrideMaterial.colorNode;
  43051. materialDepthNode = scene.overrideMaterial.depthNode;
  43052. materialPositionNode = scene.overrideMaterial.positionNode;
  43053. materialSide = scene.overrideMaterial.side;
  43054. if ( material.positionNode && material.positionNode.isNode ) {
  43055. overrideMaterial.positionNode = material.positionNode;
  43056. }
  43057. overrideMaterial.alphaTest = material.alphaTest;
  43058. overrideMaterial.alphaMap = material.alphaMap;
  43059. overrideMaterial.transparent = material.transparent || material.transmission > 0 ||
  43060. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  43061. ( material.backdropNode && material.backdropNode.isNode );
  43062. if ( overrideMaterial.isShadowPassMaterial ) {
  43063. const { colorNode, depthNode, positionNode } = this._getShadowNodes( material );
  43064. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  43065. if ( colorNode !== null ) overrideMaterial.colorNode = colorNode;
  43066. if ( depthNode !== null ) overrideMaterial.depthNode = depthNode;
  43067. if ( positionNode !== null ) overrideMaterial.positionNode = positionNode;
  43068. }
  43069. material = overrideMaterial;
  43070. }
  43071. //
  43072. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  43073. material.side = BackSide;
  43074. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  43075. material.side = FrontSide;
  43076. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  43077. material.side = DoubleSide;
  43078. } else {
  43079. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  43080. }
  43081. //
  43082. if ( materialOverride ) {
  43083. scene.overrideMaterial.colorNode = materialColorNode;
  43084. scene.overrideMaterial.depthNode = materialDepthNode;
  43085. scene.overrideMaterial.positionNode = materialPositionNode;
  43086. scene.overrideMaterial.side = materialSide;
  43087. }
  43088. //
  43089. object.onAfterRender( this, scene, camera, geometry, material, group );
  43090. }
  43091. /**
  43092. * This method represents the default `_handleObjectFunction` implementation which creates
  43093. * a render object from the given data and performs the draw command with the selected backend.
  43094. *
  43095. * @private
  43096. * @param {Object3D} object - The 3D object.
  43097. * @param {Material} material - The object's material.
  43098. * @param {Scene} scene - The scene the 3D object belongs to.
  43099. * @param {Camera} camera - The camera the object should be rendered with.
  43100. * @param {LightsNode} lightsNode - The current lights node.
  43101. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  43102. * @param {ClippingContext} clippingContext - The clipping context.
  43103. * @param {string} [passId] - An optional ID for identifying the pass.
  43104. */
  43105. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  43106. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  43107. renderObject.drawRange = object.geometry.drawRange;
  43108. renderObject.group = group;
  43109. //
  43110. const needsRefresh = this._nodes.needsRefresh( renderObject );
  43111. if ( needsRefresh ) {
  43112. this._nodes.updateBefore( renderObject );
  43113. this._geometries.updateForRender( renderObject );
  43114. this._nodes.updateForRender( renderObject );
  43115. this._bindings.updateForRender( renderObject );
  43116. }
  43117. this._pipelines.updateForRender( renderObject );
  43118. //
  43119. if ( this._currentRenderBundle !== null ) {
  43120. const renderBundleData = this.backend.get( this._currentRenderBundle );
  43121. renderBundleData.renderObjects.push( renderObject );
  43122. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  43123. }
  43124. this.backend.draw( renderObject, this.info );
  43125. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  43126. }
  43127. /**
  43128. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  43129. * Used in `compileAsync()`.
  43130. *
  43131. * @private
  43132. * @param {Object3D} object - The 3D object.
  43133. * @param {Material} material - The object's material.
  43134. * @param {Scene} scene - The scene the 3D object belongs to.
  43135. * @param {Camera} camera - The camera the object should be rendered with.
  43136. * @param {LightsNode} lightsNode - The current lights node.
  43137. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  43138. * @param {ClippingContext} clippingContext - The clipping context.
  43139. * @param {string} [passId] - An optional ID for identifying the pass.
  43140. */
  43141. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  43142. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  43143. renderObject.drawRange = object.geometry.drawRange;
  43144. renderObject.group = group;
  43145. //
  43146. this._nodes.updateBefore( renderObject );
  43147. this._geometries.updateForRender( renderObject );
  43148. this._nodes.updateForRender( renderObject );
  43149. this._bindings.updateForRender( renderObject );
  43150. this._pipelines.getForRender( renderObject, this._compilationPromises );
  43151. this._nodes.updateAfter( renderObject );
  43152. }
  43153. /**
  43154. * Callback when the canvas has been resized.
  43155. *
  43156. * @private
  43157. */
  43158. _onCanvasTargetResize() {
  43159. if ( this._initialized ) this.backend.updateSize();
  43160. }
  43161. /**
  43162. * Alias for `compileAsync()`.
  43163. *
  43164. * @method
  43165. * @param {Object3D} scene - The scene or 3D object to precompile.
  43166. * @param {Camera} camera - The camera that is used to render the scene.
  43167. * @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.
  43168. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  43169. */
  43170. get compile() {
  43171. return this.compileAsync;
  43172. }
  43173. }
  43174. /**
  43175. * A binding represents the connection between a resource (like a texture, sampler
  43176. * or uniform buffer) and the resource definition in a shader stage.
  43177. *
  43178. * This module is an abstract base class for all concrete bindings types.
  43179. *
  43180. * @abstract
  43181. * @private
  43182. */
  43183. class Binding {
  43184. /**
  43185. * Constructs a new binding.
  43186. *
  43187. * @param {string} [name=''] - The binding's name.
  43188. */
  43189. constructor( name = '' ) {
  43190. /**
  43191. * The binding's name.
  43192. *
  43193. * @type {string}
  43194. */
  43195. this.name = name;
  43196. /**
  43197. * A bitmask that defines in what shader stages the
  43198. * binding's resource is accessible.
  43199. *
  43200. * @type {number}
  43201. */
  43202. this.visibility = 0;
  43203. }
  43204. /**
  43205. * Makes sure binding's resource is visible for the given shader stage.
  43206. *
  43207. * @param {number} visibility - The shader stage.
  43208. */
  43209. setVisibility( visibility ) {
  43210. this.visibility |= visibility;
  43211. }
  43212. /**
  43213. * The shader stages in which the binding's resource is visible.
  43214. *
  43215. * @return {number} The visibility bitmask.
  43216. */
  43217. getVisibility() {
  43218. return this.visibility;
  43219. }
  43220. /**
  43221. * Clones the binding.
  43222. *
  43223. * @return {Binding} The cloned binding.
  43224. */
  43225. clone() {
  43226. return Object.assign( new this.constructor(), this );
  43227. }
  43228. }
  43229. /**
  43230. * This function is usually called with the length in bytes of an array buffer.
  43231. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  43232. *
  43233. * @function
  43234. * @param {number} floatLength - The buffer length.
  43235. * @return {number} The padded length.
  43236. */
  43237. function getFloatLength( floatLength ) {
  43238. // ensure chunk size alignment (STD140 layout)
  43239. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  43240. }
  43241. /**
  43242. * Represents a buffer binding type.
  43243. *
  43244. * @private
  43245. * @abstract
  43246. * @augments Binding
  43247. */
  43248. class Buffer extends Binding {
  43249. /**
  43250. * Constructs a new buffer.
  43251. *
  43252. * @param {string} name - The buffer's name.
  43253. * @param {TypedArray} [buffer=null] - The buffer.
  43254. */
  43255. constructor( name, buffer = null ) {
  43256. super( name );
  43257. /**
  43258. * This flag can be used for type testing.
  43259. *
  43260. * @type {boolean}
  43261. * @readonly
  43262. * @default true
  43263. */
  43264. this.isBuffer = true;
  43265. /**
  43266. * The bytes per element.
  43267. *
  43268. * @type {number}
  43269. */
  43270. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  43271. /**
  43272. * A reference to the internal buffer.
  43273. *
  43274. * @private
  43275. * @type {TypedArray}
  43276. */
  43277. this._buffer = buffer;
  43278. /**
  43279. * An array of update ranges.
  43280. *
  43281. * @private
  43282. * @type {Array<{start: number, count: number}>}
  43283. */
  43284. this._updateRanges = [];
  43285. }
  43286. /**
  43287. * The array of update ranges.
  43288. *
  43289. * @type {Array<{start: number, count: number}>}
  43290. */
  43291. get updateRanges() {
  43292. return this._updateRanges;
  43293. }
  43294. /**
  43295. * Adds an update range.
  43296. *
  43297. * @param {number} start - The start index.
  43298. * @param {number} count - The number of elements.
  43299. */
  43300. addUpdateRange( start, count ) {
  43301. this.updateRanges.push( { start, count } );
  43302. }
  43303. /**
  43304. * Clears all update ranges.
  43305. */
  43306. clearUpdateRanges() {
  43307. this.updateRanges.length = 0;
  43308. }
  43309. /**
  43310. * The buffer's byte length.
  43311. *
  43312. * @type {number}
  43313. * @readonly
  43314. */
  43315. get byteLength() {
  43316. return getFloatLength( this._buffer.byteLength );
  43317. }
  43318. /**
  43319. * A reference to the internal buffer.
  43320. *
  43321. * @type {Float32Array}
  43322. * @readonly
  43323. */
  43324. get buffer() {
  43325. return this._buffer;
  43326. }
  43327. /**
  43328. * Updates the binding.
  43329. *
  43330. * @return {boolean} Whether the buffer has been updated and must be
  43331. * uploaded to the GPU.
  43332. */
  43333. update() {
  43334. return true;
  43335. }
  43336. }
  43337. /**
  43338. * Represents a uniform buffer binding type.
  43339. *
  43340. * @private
  43341. * @augments Buffer
  43342. */
  43343. class UniformBuffer extends Buffer {
  43344. /**
  43345. * Constructs a new uniform buffer.
  43346. *
  43347. * @param {string} name - The buffer's name.
  43348. * @param {TypedArray} [buffer=null] - The buffer.
  43349. */
  43350. constructor( name, buffer = null ) {
  43351. super( name, buffer );
  43352. /**
  43353. * This flag can be used for type testing.
  43354. *
  43355. * @type {boolean}
  43356. * @readonly
  43357. * @default true
  43358. */
  43359. this.isUniformBuffer = true;
  43360. }
  43361. }
  43362. let _id$4 = 0;
  43363. /**
  43364. * A special form of uniform buffer binding type.
  43365. * It's buffer value is managed by a node object.
  43366. *
  43367. * @private
  43368. * @augments UniformBuffer
  43369. */
  43370. class NodeUniformBuffer extends UniformBuffer {
  43371. /**
  43372. * Constructs a new node-based uniform buffer.
  43373. *
  43374. * @param {BufferNode} nodeUniform - The uniform buffer node.
  43375. * @param {UniformGroupNode} groupNode - The uniform group node.
  43376. */
  43377. constructor( nodeUniform, groupNode ) {
  43378. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  43379. /**
  43380. * The uniform buffer node.
  43381. *
  43382. * @type {BufferNode}
  43383. */
  43384. this.nodeUniform = nodeUniform;
  43385. /**
  43386. * The uniform group node.
  43387. *
  43388. * @type {UniformGroupNode}
  43389. */
  43390. this.groupNode = groupNode;
  43391. /**
  43392. * This flag can be used for type testing.
  43393. *
  43394. * @type {boolean}
  43395. * @readonly
  43396. * @default true
  43397. */
  43398. this.isNodeUniformBuffer = true;
  43399. }
  43400. /**
  43401. * The array of update ranges.
  43402. *
  43403. * @param {Array<{start: number, count: number}>} value - The update ranges.
  43404. */
  43405. set updateRanges( value ) {
  43406. this.nodeUniform.updateRanges = value;
  43407. }
  43408. /**
  43409. * The array of update ranges.
  43410. *
  43411. * @type {Array<{start: number, count: number}>}
  43412. */
  43413. get updateRanges() {
  43414. return this.nodeUniform.updateRanges;
  43415. }
  43416. /**
  43417. * Adds a range of data in the data array to be updated on the GPU.
  43418. *
  43419. * @param {number} start - Position at which to start update.
  43420. * @param {number} count - The number of components to update.
  43421. */
  43422. addUpdateRange( start, count ) {
  43423. this.nodeUniform.addUpdateRange( start, count );
  43424. }
  43425. /**
  43426. * Clears all update ranges.
  43427. */
  43428. clearUpdateRanges() {
  43429. this.nodeUniform.clearUpdateRanges();
  43430. }
  43431. /**
  43432. * The uniform buffer.
  43433. *
  43434. * @type {Float32Array}
  43435. */
  43436. get buffer() {
  43437. return this.nodeUniform.value;
  43438. }
  43439. }
  43440. /**
  43441. * This class represents a uniform buffer binding but with
  43442. * an API that allows to maintain individual uniform objects.
  43443. *
  43444. * @private
  43445. * @augments UniformBuffer
  43446. */
  43447. class UniformsGroup extends UniformBuffer {
  43448. /**
  43449. * Constructs a new uniforms group.
  43450. *
  43451. * @param {string} name - The group's name.
  43452. */
  43453. constructor( name ) {
  43454. super( name );
  43455. /**
  43456. * This flag can be used for type testing.
  43457. *
  43458. * @type {boolean}
  43459. * @readonly
  43460. * @default true
  43461. */
  43462. this.isUniformsGroup = true;
  43463. /**
  43464. * An array with the raw uniform values.
  43465. *
  43466. * @private
  43467. * @type {?Array<number>}
  43468. * @default null
  43469. */
  43470. this._values = null;
  43471. /**
  43472. * An array of uniform objects.
  43473. *
  43474. * The order of uniforms in this array must match the order of uniforms in the shader.
  43475. *
  43476. * @type {Array<Uniform>}
  43477. */
  43478. this.uniforms = [];
  43479. }
  43480. /**
  43481. * Adds a uniform to this group.
  43482. *
  43483. * @param {Uniform} uniform - The uniform to add.
  43484. * @return {UniformsGroup} A reference to this group.
  43485. */
  43486. addUniform( uniform ) {
  43487. this.uniforms.push( uniform );
  43488. return this;
  43489. }
  43490. /**
  43491. * Removes a uniform from this group.
  43492. *
  43493. * @param {Uniform} uniform - The uniform to remove.
  43494. * @return {UniformsGroup} A reference to this group.
  43495. */
  43496. removeUniform( uniform ) {
  43497. const index = this.uniforms.indexOf( uniform );
  43498. if ( index !== -1 ) {
  43499. this.uniforms.splice( index, 1 );
  43500. }
  43501. return this;
  43502. }
  43503. /**
  43504. * An array with the raw uniform values.
  43505. *
  43506. * @type {Array<number>}
  43507. */
  43508. get values() {
  43509. if ( this._values === null ) {
  43510. this._values = Array.from( this.buffer );
  43511. }
  43512. return this._values;
  43513. }
  43514. /**
  43515. * A Float32 array buffer with the uniform values.
  43516. *
  43517. * @type {Float32Array}
  43518. */
  43519. get buffer() {
  43520. let buffer = this._buffer;
  43521. if ( buffer === null ) {
  43522. const byteLength = this.byteLength;
  43523. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  43524. this._buffer = buffer;
  43525. }
  43526. return buffer;
  43527. }
  43528. /**
  43529. * The byte length of the buffer with correct buffer alignment.
  43530. *
  43531. * @type {number}
  43532. */
  43533. get byteLength() {
  43534. const bytesPerElement = this.bytesPerElement;
  43535. let offset = 0; // global buffer offset in bytes
  43536. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  43537. const uniform = this.uniforms[ i ];
  43538. const boundary = uniform.boundary;
  43539. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  43540. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  43541. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  43542. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  43543. offset += chunkPadding;
  43544. // Check for chunk overflow
  43545. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  43546. // Add padding to the end of the chunk
  43547. offset += ( GPU_CHUNK_BYTES - chunkStart );
  43548. }
  43549. uniform.offset = offset / bytesPerElement;
  43550. offset += itemSize;
  43551. }
  43552. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  43553. }
  43554. /**
  43555. * Updates this group by updating each uniform object of
  43556. * the internal uniform list. The uniform objects check if their
  43557. * values has actually changed so this method only returns
  43558. * `true` if there is a real value change.
  43559. *
  43560. * @return {boolean} Whether the uniforms have been updated and
  43561. * must be uploaded to the GPU.
  43562. */
  43563. update() {
  43564. let updated = false;
  43565. for ( const uniform of this.uniforms ) {
  43566. if ( this.updateByType( uniform ) === true ) {
  43567. updated = true;
  43568. }
  43569. }
  43570. return updated;
  43571. }
  43572. /**
  43573. * Updates a given uniform by calling an update method matching
  43574. * the uniforms type.
  43575. *
  43576. * @param {Uniform} uniform - The uniform to update.
  43577. * @return {boolean} Whether the uniform has been updated or not.
  43578. */
  43579. updateByType( uniform ) {
  43580. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  43581. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  43582. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  43583. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  43584. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  43585. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  43586. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  43587. error( 'WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  43588. }
  43589. /**
  43590. * Updates a given Number uniform.
  43591. *
  43592. * @param {NumberUniform} uniform - The Number uniform.
  43593. * @return {boolean} Whether the uniform has been updated or not.
  43594. */
  43595. updateNumber( uniform ) {
  43596. let updated = false;
  43597. const a = this.values;
  43598. const v = uniform.getValue();
  43599. const offset = uniform.offset;
  43600. const type = uniform.getType();
  43601. if ( a[ offset ] !== v ) {
  43602. const b = this._getBufferForType( type );
  43603. b[ offset ] = a[ offset ] = v;
  43604. updated = true;
  43605. }
  43606. return updated;
  43607. }
  43608. /**
  43609. * Updates a given Vector2 uniform.
  43610. *
  43611. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  43612. * @return {boolean} Whether the uniform has been updated or not.
  43613. */
  43614. updateVector2( uniform ) {
  43615. let updated = false;
  43616. const a = this.values;
  43617. const v = uniform.getValue();
  43618. const offset = uniform.offset;
  43619. const type = uniform.getType();
  43620. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  43621. const b = this._getBufferForType( type );
  43622. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  43623. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  43624. updated = true;
  43625. }
  43626. return updated;
  43627. }
  43628. /**
  43629. * Updates a given Vector3 uniform.
  43630. *
  43631. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  43632. * @return {boolean} Whether the uniform has been updated or not.
  43633. */
  43634. updateVector3( uniform ) {
  43635. let updated = false;
  43636. const a = this.values;
  43637. const v = uniform.getValue();
  43638. const offset = uniform.offset;
  43639. const type = uniform.getType();
  43640. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  43641. const b = this._getBufferForType( type );
  43642. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  43643. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  43644. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  43645. updated = true;
  43646. }
  43647. return updated;
  43648. }
  43649. /**
  43650. * Updates a given Vector4 uniform.
  43651. *
  43652. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  43653. * @return {boolean} Whether the uniform has been updated or not.
  43654. */
  43655. updateVector4( uniform ) {
  43656. let updated = false;
  43657. const a = this.values;
  43658. const v = uniform.getValue();
  43659. const offset = uniform.offset;
  43660. const type = uniform.getType();
  43661. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  43662. const b = this._getBufferForType( type );
  43663. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  43664. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  43665. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  43666. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  43667. updated = true;
  43668. }
  43669. return updated;
  43670. }
  43671. /**
  43672. * Updates a given Color uniform.
  43673. *
  43674. * @param {ColorUniform} uniform - The Color uniform.
  43675. * @return {boolean} Whether the uniform has been updated or not.
  43676. */
  43677. updateColor( uniform ) {
  43678. let updated = false;
  43679. const a = this.values;
  43680. const c = uniform.getValue();
  43681. const offset = uniform.offset;
  43682. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  43683. const b = this.buffer;
  43684. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  43685. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  43686. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  43687. updated = true;
  43688. }
  43689. return updated;
  43690. }
  43691. /**
  43692. * Updates a given Matrix3 uniform.
  43693. *
  43694. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  43695. * @return {boolean} Whether the uniform has been updated or not.
  43696. */
  43697. updateMatrix3( uniform ) {
  43698. let updated = false;
  43699. const a = this.values;
  43700. const e = uniform.getValue().elements;
  43701. const offset = uniform.offset;
  43702. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  43703. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  43704. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  43705. const b = this.buffer;
  43706. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  43707. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  43708. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  43709. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  43710. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  43711. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  43712. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  43713. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  43714. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  43715. updated = true;
  43716. }
  43717. return updated;
  43718. }
  43719. /**
  43720. * Updates a given Matrix4 uniform.
  43721. *
  43722. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  43723. * @return {boolean} Whether the uniform has been updated or not.
  43724. */
  43725. updateMatrix4( uniform ) {
  43726. let updated = false;
  43727. const a = this.values;
  43728. const e = uniform.getValue().elements;
  43729. const offset = uniform.offset;
  43730. if ( arraysEqual( a, e, offset ) === false ) {
  43731. const b = this.buffer;
  43732. b.set( e, offset );
  43733. setArray( a, e, offset );
  43734. updated = true;
  43735. }
  43736. return updated;
  43737. }
  43738. /**
  43739. * Returns a typed array that matches the given data type.
  43740. *
  43741. * @private
  43742. * @param {string} type - The data type.
  43743. * @return {TypedArray} The typed array.
  43744. */
  43745. _getBufferForType( type ) {
  43746. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  43747. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  43748. return this.buffer;
  43749. }
  43750. }
  43751. /**
  43752. * Sets the values of the second array to the first array.
  43753. *
  43754. * @private
  43755. * @param {TypedArray} a - The first array.
  43756. * @param {TypedArray} b - The second array.
  43757. * @param {number} offset - An index offset for the first array.
  43758. */
  43759. function setArray( a, b, offset ) {
  43760. for ( let i = 0, l = b.length; i < l; i ++ ) {
  43761. a[ offset + i ] = b[ i ];
  43762. }
  43763. }
  43764. /**
  43765. * Returns `true` if the given arrays are equal.
  43766. *
  43767. * @private
  43768. * @param {TypedArray} a - The first array.
  43769. * @param {TypedArray} b - The second array.
  43770. * @param {number} offset - An index offset for the first array.
  43771. * @return {boolean} Whether the given arrays are equal or not.
  43772. */
  43773. function arraysEqual( a, b, offset ) {
  43774. for ( let i = 0, l = b.length; i < l; i ++ ) {
  43775. if ( a[ offset + i ] !== b[ i ] ) return false;
  43776. }
  43777. return true;
  43778. }
  43779. let _id$3 = 0;
  43780. /**
  43781. * A special form of uniforms group that represents
  43782. * the individual uniforms as node-based uniforms.
  43783. *
  43784. * @private
  43785. * @augments UniformsGroup
  43786. */
  43787. class NodeUniformsGroup extends UniformsGroup {
  43788. /**
  43789. * Constructs a new node-based uniforms group.
  43790. *
  43791. * @param {string} name - The group's name.
  43792. * @param {UniformGroupNode} groupNode - The uniform group node.
  43793. */
  43794. constructor( name, groupNode ) {
  43795. super( name );
  43796. /**
  43797. * The group's ID.
  43798. *
  43799. * @type {number}
  43800. */
  43801. this.id = _id$3 ++;
  43802. /**
  43803. * The uniform group node.
  43804. *
  43805. * @type {UniformGroupNode}
  43806. */
  43807. this.groupNode = groupNode;
  43808. /**
  43809. * This flag can be used for type testing.
  43810. *
  43811. * @type {boolean}
  43812. * @readonly
  43813. * @default true
  43814. */
  43815. this.isNodeUniformsGroup = true;
  43816. }
  43817. }
  43818. /**
  43819. * Represents a sampler binding type.
  43820. *
  43821. * @private
  43822. * @augments Binding
  43823. */
  43824. class Sampler extends Binding {
  43825. /**
  43826. * Constructs a new sampler.
  43827. *
  43828. * @param {string} name - The samplers's name.
  43829. * @param {?Texture} texture - The texture this binding is referring to.
  43830. */
  43831. constructor( name, texture ) {
  43832. super( name );
  43833. /**
  43834. * The texture the sampler is referring to.
  43835. *
  43836. * @private
  43837. * @type {?Texture}
  43838. */
  43839. this._texture = null;
  43840. /**
  43841. * An event listener which is added to {@link texture}'s dispose event.
  43842. *
  43843. * @private
  43844. * @type {Function}
  43845. */
  43846. this._onTextureDispose = () => {
  43847. this.generation = null;
  43848. this.version = 0;
  43849. };
  43850. // Assignment to the texture via a setter must occur after "_onTextureDispose" is initialized.
  43851. this.texture = texture;
  43852. /**
  43853. * The binding's version.
  43854. *
  43855. * @type {number}
  43856. */
  43857. this.version = texture ? texture.version : 0;
  43858. /**
  43859. * The binding's generation which is an additional version
  43860. * qualifier.
  43861. *
  43862. * @type {?number}
  43863. * @default null
  43864. */
  43865. this.generation = null;
  43866. /**
  43867. * The binding's sampler key.
  43868. *
  43869. * @type {string}
  43870. * @default ''
  43871. */
  43872. this.samplerKey = '';
  43873. /**
  43874. * This flag can be used for type testing.
  43875. *
  43876. * @type {boolean}
  43877. * @readonly
  43878. * @default true
  43879. */
  43880. this.isSampler = true;
  43881. }
  43882. /**
  43883. * Sets the texture of this sampler.
  43884. *
  43885. * @param {Texture} value - The texture to set.
  43886. */
  43887. set texture( value ) {
  43888. if ( this._texture === value ) return;
  43889. if ( this._texture ) {
  43890. this._texture.removeEventListener( 'dispose', this._onTextureDispose );
  43891. }
  43892. this._texture = value;
  43893. this.generation = null;
  43894. this.version = 0;
  43895. if ( this._texture ) {
  43896. this._texture.addEventListener( 'dispose', this._onTextureDispose );
  43897. }
  43898. }
  43899. /**
  43900. * Gets the texture of this sampler.
  43901. * @return {?Texture} The texture.
  43902. */
  43903. get texture() {
  43904. return this._texture;
  43905. }
  43906. /**
  43907. * Updates the binding.
  43908. *
  43909. * @return {boolean} Whether the texture has been updated and must be
  43910. * uploaded to the GPU.
  43911. */
  43912. update() {
  43913. const { texture, version } = this;
  43914. if ( version !== texture.version ) {
  43915. this.version = texture.version;
  43916. return true;
  43917. }
  43918. return false;
  43919. }
  43920. clone() {
  43921. const clonedSampler = super.clone();
  43922. // fix dispose handler for cloned instances
  43923. // TODO: Find better solution, see #31747
  43924. clonedSampler._texture = null;
  43925. clonedSampler._onTextureDispose = () => {
  43926. clonedSampler.generation = null;
  43927. clonedSampler.version = 0;
  43928. };
  43929. clonedSampler.texture = this.texture;
  43930. return clonedSampler;
  43931. }
  43932. }
  43933. let _id$2 = 0;
  43934. /**
  43935. * Represents a sampled texture binding type.
  43936. *
  43937. * @private
  43938. * @augments Sampler
  43939. */
  43940. class SampledTexture extends Sampler {
  43941. /**
  43942. * Constructs a new sampled texture.
  43943. *
  43944. * @param {string} name - The sampled texture's name.
  43945. * @param {?Texture} texture - The texture this binding is referring to.
  43946. */
  43947. constructor( name, texture ) {
  43948. super( name, texture );
  43949. /**
  43950. * This identifier.
  43951. *
  43952. * @type {number}
  43953. */
  43954. this.id = _id$2 ++;
  43955. /**
  43956. * Whether the texture is a storage texture or not.
  43957. *
  43958. * @type {boolean}
  43959. * @default false
  43960. */
  43961. this.store = false;
  43962. /**
  43963. * The mip level to bind for storage textures.
  43964. *
  43965. * @type {number}
  43966. * @default 0
  43967. */
  43968. this.mipLevel = 0;
  43969. /**
  43970. * This flag can be used for type testing.
  43971. *
  43972. * @type {boolean}
  43973. * @readonly
  43974. * @default true
  43975. */
  43976. this.isSampledTexture = true;
  43977. }
  43978. }
  43979. /**
  43980. * A special form of sampled texture binding type.
  43981. * It's texture value is managed by a node object.
  43982. *
  43983. * @private
  43984. * @augments SampledTexture
  43985. */
  43986. class NodeSampledTexture extends SampledTexture {
  43987. /**
  43988. * Constructs a new node-based sampled texture.
  43989. *
  43990. * @param {string} name - The textures's name.
  43991. * @param {TextureNode} textureNode - The texture node.
  43992. * @param {UniformGroupNode} groupNode - The uniform group node.
  43993. * @param {?string} [access=null] - The access type.
  43994. */
  43995. constructor( name, textureNode, groupNode, access = null ) {
  43996. super( name, textureNode ? textureNode.value : null );
  43997. /**
  43998. * The texture node.
  43999. *
  44000. * @type {TextureNode}
  44001. */
  44002. this.textureNode = textureNode;
  44003. /**
  44004. * The uniform group node.
  44005. *
  44006. * @type {UniformGroupNode}
  44007. */
  44008. this.groupNode = groupNode;
  44009. /**
  44010. * The access type.
  44011. *
  44012. * @type {?string}
  44013. * @default null
  44014. */
  44015. this.access = access;
  44016. }
  44017. /**
  44018. * Updates the binding.
  44019. *
  44020. * @return {boolean} Whether the texture has been updated and must be
  44021. * uploaded to the GPU.
  44022. */
  44023. update() {
  44024. const { textureNode } = this;
  44025. if ( this.texture !== textureNode.value ) {
  44026. this.texture = textureNode.value;
  44027. return true;
  44028. }
  44029. return super.update();
  44030. }
  44031. }
  44032. /**
  44033. * A special form of sampled cube texture binding type.
  44034. * It's texture value is managed by a node object.
  44035. *
  44036. * @private
  44037. * @augments NodeSampledTexture
  44038. */
  44039. class NodeSampledCubeTexture extends NodeSampledTexture {
  44040. /**
  44041. * Constructs a new node-based sampled cube texture.
  44042. *
  44043. * @param {string} name - The textures's name.
  44044. * @param {TextureNode} textureNode - The texture node.
  44045. * @param {UniformGroupNode} groupNode - The uniform group node.
  44046. * @param {?string} [access=null] - The access type.
  44047. */
  44048. constructor( name, textureNode, groupNode, access = null ) {
  44049. super( name, textureNode, groupNode, access );
  44050. /**
  44051. * This flag can be used for type testing.
  44052. *
  44053. * @type {boolean}
  44054. * @readonly
  44055. * @default true
  44056. */
  44057. this.isSampledCubeTexture = true;
  44058. }
  44059. }
  44060. /**
  44061. * A special form of sampled 3D texture binding type.
  44062. * It's texture value is managed by a node object.
  44063. *
  44064. * @private
  44065. * @augments NodeSampledTexture
  44066. */
  44067. class NodeSampledTexture3D extends NodeSampledTexture {
  44068. /**
  44069. * Constructs a new node-based sampled 3D texture.
  44070. *
  44071. * @param {string} name - The textures's name.
  44072. * @param {TextureNode} textureNode - The texture node.
  44073. * @param {UniformGroupNode} groupNode - The uniform group node.
  44074. * @param {?string} [access=null] - The access type.
  44075. */
  44076. constructor( name, textureNode, groupNode, access = null ) {
  44077. super( name, textureNode, groupNode, access );
  44078. /**
  44079. * This flag can be used for type testing.
  44080. *
  44081. * @type {boolean}
  44082. * @readonly
  44083. * @default true
  44084. */
  44085. this.isSampledTexture3D = true;
  44086. }
  44087. }
  44088. const glslPolyfills = {
  44089. bitcast_int_uint: new CodeNode( /* glsl */'uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }' ),
  44090. bitcast_uint_int: new CodeNode( /* glsl */'uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }' )
  44091. };
  44092. const glslMethods = {
  44093. textureDimensions: 'textureSize',
  44094. equals: 'equal',
  44095. bitcast_float_int: 'floatBitsToInt',
  44096. bitcast_int_float: 'intBitsToFloat',
  44097. bitcast_uint_float: 'uintBitsToFloat',
  44098. bitcast_float_uint: 'floatBitsToUint',
  44099. bitcast_uint_int: 'tsl_bitcast_uint_to_int',
  44100. bitcast_int_uint: 'tsl_bitcast_int_to_uint',
  44101. floatpack_snorm_2x16: 'packSnorm2x16',
  44102. floatpack_unorm_2x16: 'packUnorm2x16',
  44103. floatpack_float16_2x16: 'packHalf2x16',
  44104. floatunpack_snorm_2x16: 'unpackSnorm2x16',
  44105. floatunpack_unorm_2x16: 'unpackUnorm2x16',
  44106. floatunpack_float16_2x16: 'unpackHalf2x16'
  44107. };
  44108. const precisionLib = {
  44109. low: 'lowp',
  44110. medium: 'mediump',
  44111. high: 'highp'
  44112. };
  44113. const supports$1 = {
  44114. swizzleAssign: true,
  44115. storageBuffer: false
  44116. };
  44117. const interpolationTypeMap = {
  44118. perspective: 'smooth',
  44119. linear: 'noperspective'
  44120. };
  44121. const interpolationModeMap = {
  44122. 'centroid': 'centroid'
  44123. };
  44124. const defaultPrecisions = `
  44125. precision highp float;
  44126. precision highp int;
  44127. precision highp sampler2D;
  44128. precision highp sampler3D;
  44129. precision highp samplerCube;
  44130. precision highp sampler2DArray;
  44131. precision highp usampler2D;
  44132. precision highp usampler3D;
  44133. precision highp usamplerCube;
  44134. precision highp usampler2DArray;
  44135. precision highp isampler2D;
  44136. precision highp isampler3D;
  44137. precision highp isamplerCube;
  44138. precision highp isampler2DArray;
  44139. precision lowp sampler2DShadow;
  44140. precision lowp sampler2DArrayShadow;
  44141. precision lowp samplerCubeShadow;
  44142. `;
  44143. /**
  44144. * A node builder targeting GLSL.
  44145. *
  44146. * This module generates GLSL shader code from node materials and also
  44147. * generates the respective bindings and vertex buffer definitions. These
  44148. * data are later used by the renderer to create render and compute pipelines
  44149. * for render objects.
  44150. *
  44151. * @augments NodeBuilder
  44152. */
  44153. class GLSLNodeBuilder extends NodeBuilder {
  44154. /**
  44155. * Constructs a new GLSL node builder renderer.
  44156. *
  44157. * @param {Object3D} object - The 3D object.
  44158. * @param {Renderer} renderer - The renderer.
  44159. */
  44160. constructor( object, renderer ) {
  44161. super( object, renderer, new GLSLNodeParser() );
  44162. /**
  44163. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  44164. * another dictionary which manages UBOs per group ('render','frame','object').
  44165. *
  44166. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  44167. */
  44168. this.uniformGroups = {};
  44169. /**
  44170. * An array that holds objects defining the varying and attribute data in
  44171. * context of Transform Feedback.
  44172. *
  44173. * @type {Array<Object<string,AttributeNode|string>>}
  44174. */
  44175. this.transforms = [];
  44176. /**
  44177. * A dictionary that holds for each shader stage a Map of used extensions.
  44178. *
  44179. * @type {Object<string,Map<string,Object>>}
  44180. */
  44181. this.extensions = {};
  44182. /**
  44183. * A dictionary that holds for each shader stage an Array of used builtins.
  44184. *
  44185. * @type {Object<string,Array<string>>}
  44186. */
  44187. this.builtins = { vertex: [], fragment: [], compute: [] };
  44188. }
  44189. /**
  44190. * Checks if the given texture requires a manual conversion to the working color space.
  44191. *
  44192. * @param {Texture} texture - The texture to check.
  44193. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  44194. */
  44195. needsToWorkingColorSpace( texture ) {
  44196. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  44197. }
  44198. /**
  44199. * Includes the given method name into the current
  44200. * function node.
  44201. *
  44202. * @private
  44203. * @param {string} name - The method name to include.
  44204. * @return {CodeNode} The respective code node.
  44205. */
  44206. _include( name ) {
  44207. const codeNode = glslPolyfills[ name ];
  44208. codeNode.build( this );
  44209. this.addInclude( codeNode );
  44210. return codeNode;
  44211. }
  44212. /**
  44213. * Returns the native shader method name for a given generic name.
  44214. *
  44215. * @param {string} method - The method name to resolve.
  44216. * @return {string} The resolved GLSL method name.
  44217. */
  44218. getMethod( method ) {
  44219. if ( glslPolyfills[ method ] !== undefined ) {
  44220. this._include( method );
  44221. }
  44222. return glslMethods[ method ] || method;
  44223. }
  44224. /**
  44225. * Returns the bitcast method name for a given input and outputType.
  44226. *
  44227. * @param {string} type - The output type to bitcast to.
  44228. * @param {string} inputType - The input type of the.
  44229. * @return {string} The resolved WGSL bitcast invocation.
  44230. */
  44231. getBitcastMethod( type, inputType ) {
  44232. return this.getMethod( `bitcast_${ inputType }_${ type }` );
  44233. }
  44234. /**
  44235. * Returns the float packing method name for a given numeric encoding.
  44236. *
  44237. * @param {string} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  44238. * @returns {string} The resolved GLSL float packing method name.
  44239. */
  44240. getFloatPackingMethod( encoding ) {
  44241. return this.getMethod( `floatpack_${ encoding }_2x16` );
  44242. }
  44243. /**
  44244. * Returns the float unpacking method name for a given numeric encoding.
  44245. *
  44246. * @param {string} encoding - The numeric encoding that describes how the integer values are mapped to the float range.
  44247. * @returns {string} The resolved GLSL float unpacking method name.
  44248. */
  44249. getFloatUnpackingMethod( encoding ) {
  44250. return this.getMethod( `floatunpack_${ encoding }_2x16` );
  44251. }
  44252. /**
  44253. * Returns the native snippet for a ternary operation.
  44254. *
  44255. * @param {string} condSnippet - The condition determining which expression gets resolved.
  44256. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  44257. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  44258. * @return {string} The resolved method name.
  44259. */
  44260. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  44261. return `${condSnippet} ? ${ifSnippet} : ${elseSnippet}`;
  44262. }
  44263. /**
  44264. * Returns the output struct name. Not relevant for GLSL.
  44265. *
  44266. * @return {string}
  44267. */
  44268. getOutputStructName() {
  44269. return '';
  44270. }
  44271. /**
  44272. * Builds the given shader node.
  44273. *
  44274. * @param {ShaderNodeInternal} shaderNode - The shader node.
  44275. * @return {string} The GLSL function code.
  44276. */
  44277. buildFunctionCode( shaderNode ) {
  44278. const layout = shaderNode.layout;
  44279. const flowData = this.flowShaderNode( shaderNode );
  44280. const parameters = [];
  44281. for ( const input of layout.inputs ) {
  44282. parameters.push( this.getType( input.type ) + ' ' + input.name );
  44283. }
  44284. //
  44285. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  44286. ${ flowData.vars }
  44287. ${ flowData.code }
  44288. return ${ flowData.result };
  44289. }`;
  44290. //
  44291. return code;
  44292. }
  44293. /**
  44294. * Setups the Pixel Buffer Object (PBO) for the given storage
  44295. * buffer node.
  44296. *
  44297. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  44298. */
  44299. setupPBO( storageBufferNode ) {
  44300. const attribute = storageBufferNode.value;
  44301. if ( attribute.pbo === undefined ) {
  44302. const originalArray = attribute.array;
  44303. const numElements = attribute.count * attribute.itemSize;
  44304. const { itemSize } = attribute;
  44305. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  44306. let format = isInteger ? RedIntegerFormat : RedFormat;
  44307. if ( itemSize === 2 ) {
  44308. format = isInteger ? RGIntegerFormat : RGFormat;
  44309. } else if ( itemSize === 3 ) {
  44310. format = isInteger ? RGBIntegerFormat : RGBFormat;
  44311. } else if ( itemSize === 4 ) {
  44312. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  44313. }
  44314. const typeMap = {
  44315. Float32Array: FloatType,
  44316. Uint8Array: UnsignedByteType,
  44317. Uint16Array: UnsignedShortType,
  44318. Uint32Array: UnsignedIntType,
  44319. Int8Array: ByteType,
  44320. Int16Array: ShortType,
  44321. Int32Array: IntType,
  44322. Uint8ClampedArray: UnsignedByteType,
  44323. };
  44324. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  44325. let height = Math.ceil( ( numElements / itemSize ) / width );
  44326. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  44327. const newSize = width * height * itemSize;
  44328. const newArray = new originalArray.constructor( newSize );
  44329. newArray.set( originalArray, 0 );
  44330. attribute.array = newArray;
  44331. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  44332. pboTexture.needsUpdate = true;
  44333. pboTexture.isPBOTexture = true;
  44334. const pbo = new TextureNode( pboTexture, null, null );
  44335. pbo.setPrecision( 'high' );
  44336. attribute.pboNode = pbo;
  44337. attribute.pbo = pbo.value;
  44338. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  44339. }
  44340. }
  44341. /**
  44342. * Returns a GLSL snippet that represents the property name of the given node.
  44343. *
  44344. * @param {Node} node - The node.
  44345. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44346. * @return {string} The property name.
  44347. */
  44348. getPropertyName( node, shaderStage = this.shaderStage ) {
  44349. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  44350. return shaderStage.charAt( 0 ) + '_' + node.name;
  44351. }
  44352. return super.getPropertyName( node, shaderStage );
  44353. }
  44354. /**
  44355. * Setups the Pixel Buffer Object (PBO) for the given storage
  44356. * buffer node.
  44357. *
  44358. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  44359. * @return {string} The property name.
  44360. */
  44361. generatePBO( storageArrayElementNode ) {
  44362. const { node, indexNode } = storageArrayElementNode;
  44363. const attribute = node.value;
  44364. if ( this.renderer.backend.has( attribute ) ) {
  44365. const attributeData = this.renderer.backend.get( attribute );
  44366. attributeData.pbo = attribute.pbo;
  44367. }
  44368. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  44369. const textureName = this.getPropertyName( nodeUniform );
  44370. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  44371. const indexSnippet = indexNode.build( this, 'uint' );
  44372. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  44373. let propertyName = elementNodeData.propertyName;
  44374. if ( propertyName === undefined ) {
  44375. // property element
  44376. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  44377. propertyName = this.getPropertyName( nodeVar );
  44378. // property size
  44379. const bufferNodeData = this.getDataFromNode( node );
  44380. let propertySizeName = bufferNodeData.propertySizeName;
  44381. if ( propertySizeName === undefined ) {
  44382. propertySizeName = propertyName + 'Size';
  44383. this.getVarFromNode( node, propertySizeName, 'uint' );
  44384. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  44385. bufferNodeData.propertySizeName = propertySizeName;
  44386. }
  44387. //
  44388. const { itemSize } = attribute;
  44389. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  44390. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  44391. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, '0', null, null );
  44392. //
  44393. let prefix = 'vec4';
  44394. if ( attribute.pbo.type === UnsignedIntType ) {
  44395. prefix = 'uvec4';
  44396. } else if ( attribute.pbo.type === IntType ) {
  44397. prefix = 'ivec4';
  44398. }
  44399. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  44400. elementNodeData.propertyName = propertyName;
  44401. }
  44402. return propertyName;
  44403. }
  44404. /**
  44405. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  44406. *
  44407. * @param {?Texture} texture - The texture.
  44408. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44409. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44410. * @param {?string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44411. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  44412. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44413. * @return {string} The GLSL snippet.
  44414. */
  44415. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  44416. if ( levelSnippet === null ) levelSnippet = '0';
  44417. let snippet;
  44418. if ( depthSnippet ) {
  44419. if ( offsetSnippet ) {
  44420. snippet = `texelFetchOffset( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet }, ${ offsetSnippet } )`;
  44421. } else {
  44422. snippet = `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  44423. }
  44424. } else {
  44425. if ( offsetSnippet ) {
  44426. snippet = `texelFetchOffset( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  44427. } else {
  44428. snippet = `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  44429. }
  44430. }
  44431. if ( texture !== null && texture.isDepthTexture ) {
  44432. snippet += '.x';
  44433. }
  44434. return snippet;
  44435. }
  44436. /**
  44437. * Generates the GLSL snippet for sampling/loading the given texture.
  44438. *
  44439. * @param {Texture} texture - The texture.
  44440. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44441. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44442. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  44443. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44444. * @return {string} The GLSL snippet.
  44445. */
  44446. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet ) {
  44447. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  44448. if ( texture.isDepthTexture ) {
  44449. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } ).x`;
  44450. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  44451. }
  44452. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } )`;
  44453. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  44454. }
  44455. /**
  44456. * Generates the GLSL snippet when sampling textures with explicit mip level.
  44457. *
  44458. * @param {Texture} texture - The texture.
  44459. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44460. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44461. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44462. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44463. * @return {string} The GLSL snippet.
  44464. */
  44465. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, offsetSnippet ) {
  44466. if ( offsetSnippet ) {
  44467. return `textureLodOffset( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  44468. }
  44469. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  44470. }
  44471. /**
  44472. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  44473. *
  44474. * @param {Texture} texture - The texture.
  44475. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44476. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44477. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  44478. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44479. * @return {string} The GLSL snippet.
  44480. */
  44481. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, offsetSnippet ) {
  44482. if ( offsetSnippet ) {
  44483. return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ biasSnippet } )`;
  44484. }
  44485. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  44486. }
  44487. /**
  44488. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  44489. *
  44490. * @param {Texture} texture - The texture.
  44491. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44492. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44493. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  44494. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44495. * @return {string} The GLSL snippet.
  44496. */
  44497. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, offsetSnippet ) {
  44498. if ( offsetSnippet ) {
  44499. return `textureGradOffset( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  44500. }
  44501. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  44502. }
  44503. /**
  44504. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  44505. * against a reference value.
  44506. *
  44507. * @param {Texture} texture - The texture.
  44508. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44509. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44510. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  44511. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  44512. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44513. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44514. * @return {string} The GLSL snippet.
  44515. */
  44516. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  44517. if ( shaderStage === 'fragment' ) {
  44518. // Cube shadow maps use vec4(direction, compareValue)
  44519. if ( texture.isCubeTexture ) {
  44520. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ compareSnippet } ) )`;
  44521. }
  44522. if ( depthSnippet ) {
  44523. if ( offsetSnippet ) {
  44524. return `textureOffset( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  44525. }
  44526. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  44527. }
  44528. if ( offsetSnippet ) {
  44529. return `textureOffset( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  44530. }
  44531. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  44532. } else {
  44533. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  44534. }
  44535. }
  44536. /**
  44537. * Returns the variables of the given shader stage as a GLSL string.
  44538. *
  44539. * @param {string} shaderStage - The shader stage.
  44540. * @return {string} The GLSL snippet that defines the variables.
  44541. */
  44542. getVars( shaderStage ) {
  44543. const snippets = [];
  44544. const vars = this.vars[ shaderStage ];
  44545. if ( vars !== undefined ) {
  44546. for ( const variable of vars ) {
  44547. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  44548. }
  44549. }
  44550. return snippets.join( '\n\t' );
  44551. }
  44552. /**
  44553. * Returns the uniforms of the given shader stage as a GLSL string.
  44554. *
  44555. * @param {string} shaderStage - The shader stage.
  44556. * @return {string} The GLSL snippet that defines the uniforms.
  44557. */
  44558. getUniforms( shaderStage ) {
  44559. const uniforms = this.uniforms[ shaderStage ];
  44560. const bindingSnippets = [];
  44561. const uniformGroups = {};
  44562. for ( const uniform of uniforms ) {
  44563. let snippet = null;
  44564. let group = false;
  44565. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  44566. const texture = uniform.node.value;
  44567. let typePrefix = '';
  44568. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  44569. if ( texture.type === UnsignedIntType ) {
  44570. typePrefix = 'u';
  44571. } else if ( texture.type === IntType ) {
  44572. typePrefix = 'i';
  44573. }
  44574. }
  44575. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  44576. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  44577. } else if ( texture.compareFunction ) {
  44578. if ( texture.isArrayTexture === true ) {
  44579. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  44580. } else {
  44581. snippet = `sampler2DShadow ${ uniform.name };`;
  44582. }
  44583. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  44584. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  44585. } else {
  44586. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  44587. }
  44588. } else if ( uniform.type === 'cubeTexture' ) {
  44589. snippet = `samplerCube ${ uniform.name };`;
  44590. } else if ( uniform.type === 'cubeDepthTexture' ) {
  44591. snippet = `samplerCubeShadow ${ uniform.name };`;
  44592. } else if ( uniform.type === 'buffer' ) {
  44593. const bufferNode = uniform.node;
  44594. const bufferType = this.getType( bufferNode.bufferType );
  44595. const bufferCount = bufferNode.bufferCount;
  44596. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  44597. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  44598. } else {
  44599. const vectorType = this.getVectorType( uniform.type );
  44600. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  44601. group = true;
  44602. }
  44603. const precision = uniform.node.precision;
  44604. if ( precision !== null ) {
  44605. snippet = precisionLib[ precision ] + ' ' + snippet;
  44606. }
  44607. if ( group ) {
  44608. snippet = '\t' + snippet;
  44609. const groupName = uniform.groupNode.name;
  44610. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  44611. groupSnippets.push( snippet );
  44612. } else {
  44613. snippet = 'uniform ' + snippet;
  44614. bindingSnippets.push( snippet );
  44615. }
  44616. }
  44617. let output = '';
  44618. for ( const name in uniformGroups ) {
  44619. const groupSnippets = uniformGroups[ name ];
  44620. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  44621. }
  44622. output += bindingSnippets.join( '\n' );
  44623. return output;
  44624. }
  44625. /**
  44626. * Returns the type for a given buffer attribute.
  44627. *
  44628. * @param {BufferAttribute} attribute - The buffer attribute.
  44629. * @return {string} The type.
  44630. */
  44631. getTypeFromAttribute( attribute ) {
  44632. let nodeType = super.getTypeFromAttribute( attribute );
  44633. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  44634. let dataAttribute = attribute;
  44635. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  44636. const array = dataAttribute.array;
  44637. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  44638. nodeType = nodeType.slice( 1 );
  44639. }
  44640. }
  44641. return nodeType;
  44642. }
  44643. /**
  44644. * Returns the shader attributes of the given shader stage as a GLSL string.
  44645. *
  44646. * @param {string} shaderStage - The shader stage.
  44647. * @return {string} The GLSL snippet that defines the shader attributes.
  44648. */
  44649. getAttributes( shaderStage ) {
  44650. let snippet = '';
  44651. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  44652. const attributes = this.getAttributesArray();
  44653. let location = 0;
  44654. for ( const attribute of attributes ) {
  44655. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  44656. }
  44657. }
  44658. return snippet;
  44659. }
  44660. /**
  44661. * Returns the members of the given struct type node as a GLSL string.
  44662. *
  44663. * @param {StructTypeNode} struct - The struct type node.
  44664. * @return {string} The GLSL snippet that defines the struct members.
  44665. */
  44666. getStructMembers( struct ) {
  44667. const snippets = [];
  44668. for ( const member of struct.members ) {
  44669. snippets.push( `\t${ member.type } ${ member.name };` );
  44670. }
  44671. return snippets.join( '\n' );
  44672. }
  44673. /**
  44674. * Returns the structs of the given shader stage as a GLSL string.
  44675. *
  44676. * @param {string} shaderStage - The shader stage.
  44677. * @return {string} The GLSL snippet that defines the structs.
  44678. */
  44679. getStructs( shaderStage ) {
  44680. const snippets = [];
  44681. const structs = this.structs[ shaderStage ];
  44682. const outputSnippet = [];
  44683. for ( const struct of structs ) {
  44684. if ( struct.output ) {
  44685. for ( const member of struct.members ) {
  44686. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  44687. }
  44688. } else {
  44689. let snippet = 'struct ' + struct.name + ' {\n';
  44690. snippet += this.getStructMembers( struct );
  44691. snippet += '\n};\n';
  44692. snippets.push( snippet );
  44693. }
  44694. }
  44695. if ( outputSnippet.length === 0 ) {
  44696. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  44697. }
  44698. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  44699. }
  44700. /**
  44701. * Returns the varyings of the given shader stage as a GLSL string.
  44702. *
  44703. * @param {string} shaderStage - The shader stage.
  44704. * @return {string} The GLSL snippet that defines the varyings.
  44705. */
  44706. getVaryings( shaderStage ) {
  44707. let snippet = '';
  44708. const varyings = this.varyings;
  44709. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  44710. for ( const varying of varyings ) {
  44711. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  44712. const type = this.getType( varying.type );
  44713. if ( varying.needsInterpolation ) {
  44714. if ( varying.interpolationType ) {
  44715. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  44716. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  44717. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  44718. } else {
  44719. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  44720. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  44721. }
  44722. } else {
  44723. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  44724. }
  44725. }
  44726. } else if ( shaderStage === 'fragment' ) {
  44727. for ( const varying of varyings ) {
  44728. if ( varying.needsInterpolation ) {
  44729. const type = this.getType( varying.type );
  44730. if ( varying.interpolationType ) {
  44731. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  44732. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  44733. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  44734. } else {
  44735. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  44736. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  44737. }
  44738. }
  44739. }
  44740. }
  44741. for ( const builtin of this.builtins[ shaderStage ] ) {
  44742. snippet += `${builtin};\n`;
  44743. }
  44744. return snippet;
  44745. }
  44746. /**
  44747. * Returns the vertex index builtin.
  44748. *
  44749. * @return {string} The vertex index.
  44750. */
  44751. getVertexIndex() {
  44752. return 'uint( gl_VertexID )';
  44753. }
  44754. /**
  44755. * Contextually returns either the vertex stage instance index builtin
  44756. * or the linearized index of an compute invocation within a grid of workgroups.
  44757. *
  44758. * @return {string} The instance index.
  44759. */
  44760. getInstanceIndex() {
  44761. return 'uint( gl_InstanceID )';
  44762. }
  44763. /**
  44764. * Returns a builtin representing the index of an invocation within its workgroup.
  44765. *
  44766. * @return {string} The invocation local index.
  44767. */
  44768. getInvocationLocalIndex() {
  44769. const workgroupSize = this.object.workgroupSize;
  44770. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  44771. return `uint( gl_InstanceID ) % ${size}u`;
  44772. }
  44773. /**
  44774. * Returns a builtin representing the size of a subgroup within the current shader.
  44775. */
  44776. getSubgroupSize() {
  44777. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node' );
  44778. }
  44779. /**
  44780. * Returns a builtin representing the index of an invocation within its subgroup.
  44781. */
  44782. getInvocationSubgroupIndex() {
  44783. error( 'GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node' );
  44784. }
  44785. /**
  44786. * Returns a builtin representing the index of the current invocation's subgroup within its workgroup.
  44787. */
  44788. getSubgroupIndex() {
  44789. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node' );
  44790. }
  44791. /**
  44792. * Returns the draw index builtin.
  44793. *
  44794. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  44795. */
  44796. getDrawIndex() {
  44797. const extensions = this.renderer.backend.extensions;
  44798. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  44799. return 'uint( gl_DrawID )';
  44800. }
  44801. return null;
  44802. }
  44803. /**
  44804. * Returns the front facing builtin.
  44805. *
  44806. * @return {string} The front facing builtin.
  44807. */
  44808. getFrontFacing() {
  44809. return 'gl_FrontFacing';
  44810. }
  44811. /**
  44812. * Returns the frag coord builtin.
  44813. *
  44814. * @return {string} The frag coord builtin.
  44815. */
  44816. getFragCoord() {
  44817. return 'gl_FragCoord.xy';
  44818. }
  44819. /**
  44820. * Returns the frag depth builtin.
  44821. *
  44822. * @return {string} The frag depth builtin.
  44823. */
  44824. getFragDepth() {
  44825. return 'gl_FragDepth';
  44826. }
  44827. /**
  44828. * Enables the given extension.
  44829. *
  44830. * @param {string} name - The extension name.
  44831. * @param {string} behavior - The extension behavior.
  44832. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  44833. */
  44834. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  44835. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  44836. if ( map.has( name ) === false ) {
  44837. map.set( name, {
  44838. name,
  44839. behavior
  44840. } );
  44841. }
  44842. }
  44843. /**
  44844. * Returns the enabled extensions of the given shader stage as a GLSL string.
  44845. *
  44846. * @param {string} shaderStage - The shader stage.
  44847. * @return {string} The GLSL snippet that defines the enabled extensions.
  44848. */
  44849. getExtensions( shaderStage ) {
  44850. const snippets = [];
  44851. if ( shaderStage === 'vertex' ) {
  44852. const ext = this.renderer.backend.extensions;
  44853. const isBatchedMesh = this.object.isBatchedMesh;
  44854. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  44855. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  44856. }
  44857. }
  44858. const extensions = this.extensions[ shaderStage ];
  44859. if ( extensions !== undefined ) {
  44860. for ( const { name, behavior } of extensions.values() ) {
  44861. snippets.push( `#extension ${name} : ${behavior}` );
  44862. }
  44863. }
  44864. return snippets.join( '\n' );
  44865. }
  44866. /**
  44867. * Returns the clip distances builtin.
  44868. *
  44869. * @return {string} The clip distances builtin.
  44870. */
  44871. getClipDistance() {
  44872. return 'gl_ClipDistance';
  44873. }
  44874. /**
  44875. * Whether the requested feature is available or not.
  44876. *
  44877. * @param {string} name - The requested feature.
  44878. * @return {boolean} Whether the requested feature is supported or not.
  44879. */
  44880. isAvailable( name ) {
  44881. let result = supports$1[ name ];
  44882. if ( result === undefined ) {
  44883. let extensionName;
  44884. result = false;
  44885. switch ( name ) {
  44886. case 'float32Filterable':
  44887. extensionName = 'OES_texture_float_linear';
  44888. break;
  44889. case 'clipDistance':
  44890. extensionName = 'WEBGL_clip_cull_distance';
  44891. break;
  44892. }
  44893. if ( extensionName !== undefined ) {
  44894. const extensions = this.renderer.backend.extensions;
  44895. if ( extensions.has( extensionName ) ) {
  44896. extensions.get( extensionName );
  44897. result = true;
  44898. }
  44899. }
  44900. supports$1[ name ] = result;
  44901. }
  44902. return result;
  44903. }
  44904. /**
  44905. * Whether to flip texture data along its vertical axis or not.
  44906. *
  44907. * @return {boolean} Returns always `true` in context of GLSL.
  44908. */
  44909. isFlipY() {
  44910. return true;
  44911. }
  44912. /**
  44913. * Enables hardware clipping.
  44914. *
  44915. * @param {string} planeCount - The clipping plane count.
  44916. */
  44917. enableHardwareClipping( planeCount ) {
  44918. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  44919. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  44920. }
  44921. /**
  44922. * Enables multiview.
  44923. */
  44924. enableMultiview() {
  44925. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  44926. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  44927. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  44928. }
  44929. /**
  44930. * Registers a transform in context of Transform Feedback.
  44931. *
  44932. * @param {string} varyingName - The varying name.
  44933. * @param {AttributeNode} attributeNode - The attribute node.
  44934. */
  44935. registerTransform( varyingName, attributeNode ) {
  44936. this.transforms.push( { varyingName, attributeNode } );
  44937. }
  44938. /**
  44939. * Returns the transforms of the given shader stage as a GLSL string.
  44940. *
  44941. * @param {string} shaderStage - The shader stage.
  44942. * @return {string} The GLSL snippet that defines the transforms.
  44943. */
  44944. getTransforms( /* shaderStage */ ) {
  44945. const transforms = this.transforms;
  44946. let snippet = '';
  44947. for ( let i = 0; i < transforms.length; i ++ ) {
  44948. const transform = transforms[ i ];
  44949. const attributeName = this.getPropertyName( transform.attributeNode );
  44950. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  44951. }
  44952. return snippet;
  44953. }
  44954. /**
  44955. * Returns a GLSL struct based on the given name and variables.
  44956. *
  44957. * @private
  44958. * @param {string} name - The struct name.
  44959. * @param {string} vars - The struct variables.
  44960. * @return {string} The GLSL snippet representing a struct.
  44961. */
  44962. _getGLSLUniformStruct( name, vars ) {
  44963. return `
  44964. layout( std140 ) uniform ${name} {
  44965. ${vars}
  44966. };`;
  44967. }
  44968. /**
  44969. * Returns a GLSL vertex shader based on the given shader data.
  44970. *
  44971. * @private
  44972. * @param {Object} shaderData - The shader data.
  44973. * @return {string} The vertex shader.
  44974. */
  44975. _getGLSLVertexCode( shaderData ) {
  44976. return `#version 300 es
  44977. ${ this.getSignature() }
  44978. // extensions
  44979. ${shaderData.extensions}
  44980. // precision
  44981. ${ defaultPrecisions }
  44982. // uniforms
  44983. ${shaderData.uniforms}
  44984. // varyings
  44985. ${shaderData.varyings}
  44986. // attributes
  44987. ${shaderData.attributes}
  44988. // codes
  44989. ${shaderData.codes}
  44990. void main() {
  44991. // vars
  44992. ${shaderData.vars}
  44993. // transforms
  44994. ${shaderData.transforms}
  44995. // flow
  44996. ${shaderData.flow}
  44997. gl_PointSize = 1.0;
  44998. }
  44999. `;
  45000. }
  45001. /**
  45002. * Returns a GLSL fragment shader based on the given shader data.
  45003. *
  45004. * @private
  45005. * @param {Object} shaderData - The shader data.
  45006. * @return {string} The vertex shader.
  45007. */
  45008. _getGLSLFragmentCode( shaderData ) {
  45009. return `#version 300 es
  45010. ${ this.getSignature() }
  45011. // extensions
  45012. ${shaderData.extensions}
  45013. // precision
  45014. ${ defaultPrecisions }
  45015. // structs
  45016. ${shaderData.structs}
  45017. // uniforms
  45018. ${shaderData.uniforms}
  45019. // varyings
  45020. ${shaderData.varyings}
  45021. // codes
  45022. ${shaderData.codes}
  45023. void main() {
  45024. // vars
  45025. ${shaderData.vars}
  45026. // flow
  45027. ${shaderData.flow}
  45028. }
  45029. `;
  45030. }
  45031. /**
  45032. * Controls the code build of the shader stages.
  45033. */
  45034. buildCode() {
  45035. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  45036. this.sortBindingGroups();
  45037. for ( const shaderStage in shadersData ) {
  45038. let flow = '// code\n\n';
  45039. flow += this.flowCode[ shaderStage ];
  45040. const flowNodes = this.flowNodes[ shaderStage ];
  45041. const mainNode = flowNodes[ flowNodes.length - 1 ];
  45042. for ( const node of flowNodes ) {
  45043. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  45044. const slotName = node.name;
  45045. if ( slotName ) {
  45046. if ( flow.length > 0 ) flow += '\n';
  45047. flow += `\t// flow -> ${ slotName }\n\t`;
  45048. }
  45049. flow += `${ flowSlotData.code }\n\t`;
  45050. if ( node === mainNode && shaderStage !== 'compute' ) {
  45051. flow += '// result\n\t';
  45052. if ( shaderStage === 'vertex' ) {
  45053. flow += 'gl_Position = ';
  45054. flow += `${ flowSlotData.result };`;
  45055. } else if ( shaderStage === 'fragment' ) {
  45056. if ( ! node.outputNode.isOutputStructNode ) {
  45057. flow += 'fragColor = ';
  45058. flow += `${ flowSlotData.result };`;
  45059. }
  45060. }
  45061. }
  45062. }
  45063. const stageData = shadersData[ shaderStage ];
  45064. stageData.extensions = this.getExtensions( shaderStage );
  45065. stageData.uniforms = this.getUniforms( shaderStage );
  45066. stageData.attributes = this.getAttributes( shaderStage );
  45067. stageData.varyings = this.getVaryings( shaderStage );
  45068. stageData.vars = this.getVars( shaderStage );
  45069. stageData.structs = this.getStructs( shaderStage );
  45070. stageData.codes = this.getCodes( shaderStage );
  45071. stageData.transforms = this.getTransforms( shaderStage );
  45072. stageData.flow = flow;
  45073. }
  45074. if ( this.material !== null ) {
  45075. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  45076. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  45077. } else {
  45078. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  45079. }
  45080. }
  45081. /**
  45082. * This method is one of the more important ones since it's responsible
  45083. * for generating a matching binding instance for the given uniform node.
  45084. *
  45085. * These bindings are later used in the renderer to create bind groups
  45086. * and layouts.
  45087. *
  45088. * @param {UniformNode} node - The uniform node.
  45089. * @param {string} type - The node data type.
  45090. * @param {string} shaderStage - The shader stage.
  45091. * @param {?string} [name=null] - An optional uniform name.
  45092. * @return {NodeUniform} The node uniform object.
  45093. */
  45094. getUniformFromNode( node, type, shaderStage, name = null ) {
  45095. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  45096. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  45097. let uniformGPU = nodeData.uniformGPU;
  45098. if ( uniformGPU === undefined ) {
  45099. const group = node.groupNode;
  45100. const groupName = group.name;
  45101. const bindings = this.getBindGroupArray( groupName, shaderStage );
  45102. if ( type === 'texture' ) {
  45103. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  45104. bindings.push( uniformGPU );
  45105. } else if ( type === 'cubeTexture' || type === 'cubeDepthTexture' ) {
  45106. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  45107. bindings.push( uniformGPU );
  45108. } else if ( type === 'texture3D' ) {
  45109. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  45110. bindings.push( uniformGPU );
  45111. } else if ( type === 'buffer' ) {
  45112. uniformNode.name = `buffer${ node.id }`;
  45113. const sharedData = this.getSharedDataFromNode( node );
  45114. let buffer = sharedData.buffer;
  45115. if ( buffer === undefined ) {
  45116. node.name = `NodeBuffer_${ node.id }`;
  45117. buffer = new NodeUniformBuffer( node, group );
  45118. buffer.name = node.name;
  45119. sharedData.buffer = buffer;
  45120. }
  45121. bindings.push( buffer );
  45122. uniformGPU = buffer;
  45123. } else {
  45124. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  45125. let uniformsGroup = uniformsStage[ groupName ];
  45126. if ( uniformsGroup === undefined ) {
  45127. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  45128. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  45129. uniformsStage[ groupName ] = uniformsGroup;
  45130. bindings.push( uniformsGroup );
  45131. }
  45132. uniformGPU = this.getNodeUniform( uniformNode, type );
  45133. uniformsGroup.addUniform( uniformGPU );
  45134. }
  45135. nodeData.uniformGPU = uniformGPU;
  45136. }
  45137. return uniformNode;
  45138. }
  45139. }
  45140. let _vector2 = null;
  45141. let _color4 = null;
  45142. /**
  45143. * Most of the rendering related logic is implemented in the
  45144. * {@link Renderer} module and related management components.
  45145. * Sometimes it is required though to execute commands which are
  45146. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  45147. * This abstract base class defines an interface that encapsulates
  45148. * all backend-related logic. Derived classes for each backend must
  45149. * implement the interface.
  45150. *
  45151. * @abstract
  45152. * @private
  45153. */
  45154. class Backend {
  45155. /**
  45156. * Constructs a new backend.
  45157. *
  45158. * @param {Object} parameters - An object holding parameters for the backend.
  45159. */
  45160. constructor( parameters = {} ) {
  45161. /**
  45162. * The parameters of the backend.
  45163. *
  45164. * @type {Object}
  45165. */
  45166. this.parameters = Object.assign( {}, parameters );
  45167. /**
  45168. * This weak map holds backend-specific data of objects
  45169. * like textures, attributes or render targets.
  45170. *
  45171. * @type {WeakMap<Object, Object>}
  45172. */
  45173. this.data = new WeakMap();
  45174. /**
  45175. * A reference to the renderer.
  45176. *
  45177. * @type {?Renderer}
  45178. * @default null
  45179. */
  45180. this.renderer = null;
  45181. /**
  45182. * A reference to the canvas element the renderer is drawing to.
  45183. *
  45184. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  45185. * @default null
  45186. */
  45187. this.domElement = null;
  45188. /**
  45189. * A reference to the timestamp query pool.
  45190. *
  45191. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  45192. */
  45193. this.timestampQueryPool = {
  45194. [ TimestampQuery.RENDER ]: null,
  45195. [ TimestampQuery.COMPUTE ]: null
  45196. };
  45197. /**
  45198. * Whether to track timestamps with a Timestamp Query API or not.
  45199. *
  45200. * @type {boolean}
  45201. * @default false
  45202. */
  45203. this.trackTimestamp = ( parameters.trackTimestamp === true );
  45204. }
  45205. /**
  45206. * Initializes the backend so it is ready for usage. Concrete backends
  45207. * are supposed to implement their rendering context creation and related
  45208. * operations in this method.
  45209. *
  45210. * @async
  45211. * @param {Renderer} renderer - The renderer.
  45212. * @return {Promise} A Promise that resolves when the backend has been initialized.
  45213. */
  45214. async init( renderer ) {
  45215. this.renderer = renderer;
  45216. }
  45217. /**
  45218. * The coordinate system of the backend.
  45219. *
  45220. * @abstract
  45221. * @type {number}
  45222. * @readonly
  45223. */
  45224. get coordinateSystem() {}
  45225. // render context
  45226. /**
  45227. * This method is executed at the beginning of a render call and
  45228. * can be used by the backend to prepare the state for upcoming
  45229. * draw calls.
  45230. *
  45231. * @abstract
  45232. * @param {RenderContext} renderContext - The render context.
  45233. */
  45234. beginRender( /*renderContext*/ ) {}
  45235. /**
  45236. * This method is executed at the end of a render call and
  45237. * can be used by the backend to finalize work after draw
  45238. * calls.
  45239. *
  45240. * @abstract
  45241. * @param {RenderContext} renderContext - The render context.
  45242. */
  45243. finishRender( /*renderContext*/ ) {}
  45244. /**
  45245. * This method is executed at the beginning of a compute call and
  45246. * can be used by the backend to prepare the state for upcoming
  45247. * compute tasks.
  45248. *
  45249. * @abstract
  45250. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  45251. */
  45252. beginCompute( /*computeGroup*/ ) {}
  45253. /**
  45254. * This method is executed at the end of a compute call and
  45255. * can be used by the backend to finalize work after compute
  45256. * tasks.
  45257. *
  45258. * @abstract
  45259. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  45260. */
  45261. finishCompute( /*computeGroup*/ ) {}
  45262. // render object
  45263. /**
  45264. * Executes a draw command for the given render object.
  45265. *
  45266. * @abstract
  45267. * @param {RenderObject} renderObject - The render object to draw.
  45268. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  45269. */
  45270. draw( /*renderObject, info*/ ) { }
  45271. // compute node
  45272. /**
  45273. * Executes a compute command for the given compute node.
  45274. *
  45275. * @abstract
  45276. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  45277. * @param {Node} computeNode - The compute node.
  45278. * @param {Array<BindGroup>} bindings - The bindings.
  45279. * @param {ComputePipeline} computePipeline - The compute pipeline.
  45280. */
  45281. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  45282. // program
  45283. /**
  45284. * Creates a shader program from the given programmable stage.
  45285. *
  45286. * @abstract
  45287. * @param {ProgrammableStage} program - The programmable stage.
  45288. */
  45289. createProgram( /*program*/ ) { }
  45290. /**
  45291. * Destroys the shader program of the given programmable stage.
  45292. *
  45293. * @abstract
  45294. * @param {ProgrammableStage} program - The programmable stage.
  45295. */
  45296. destroyProgram( /*program*/ ) { }
  45297. // bindings
  45298. /**
  45299. * Creates bindings from the given bind group definition.
  45300. *
  45301. * @abstract
  45302. * @param {BindGroup} bindGroup - The bind group.
  45303. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45304. * @param {number} cacheIndex - The cache index.
  45305. * @param {number} version - The version.
  45306. */
  45307. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  45308. /**
  45309. * Updates the given bind group definition.
  45310. *
  45311. * @abstract
  45312. * @param {BindGroup} bindGroup - The bind group.
  45313. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45314. * @param {number} cacheIndex - The cache index.
  45315. * @param {number} version - The version.
  45316. */
  45317. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  45318. /**
  45319. * Updates a buffer binding.
  45320. *
  45321. * @abstract
  45322. * @param {Buffer} binding - The buffer binding to update.
  45323. */
  45324. updateBinding( /*binding*/ ) { }
  45325. // pipeline
  45326. /**
  45327. * Creates a render pipeline for the given render object.
  45328. *
  45329. * @abstract
  45330. * @param {RenderObject} renderObject - The render object.
  45331. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  45332. */
  45333. createRenderPipeline( /*renderObject, promises*/ ) { }
  45334. /**
  45335. * Creates a compute pipeline for the given compute node.
  45336. *
  45337. * @abstract
  45338. * @param {ComputePipeline} computePipeline - The compute pipeline.
  45339. * @param {Array<BindGroup>} bindings - The bindings.
  45340. */
  45341. createComputePipeline( /*computePipeline, bindings*/ ) { }
  45342. // cache key
  45343. /**
  45344. * Returns `true` if the render pipeline requires an update.
  45345. *
  45346. * @abstract
  45347. * @param {RenderObject} renderObject - The render object.
  45348. * @return {boolean} Whether the render pipeline requires an update or not.
  45349. */
  45350. needsRenderUpdate( /*renderObject*/ ) { }
  45351. /**
  45352. * Returns a cache key that is used to identify render pipelines.
  45353. *
  45354. * @abstract
  45355. * @param {RenderObject} renderObject - The render object.
  45356. * @return {string} The cache key.
  45357. */
  45358. getRenderCacheKey( /*renderObject*/ ) { }
  45359. // node builder
  45360. /**
  45361. * Returns a node builder for the given render object.
  45362. *
  45363. * @abstract
  45364. * @param {RenderObject} renderObject - The render object.
  45365. * @param {Renderer} renderer - The renderer.
  45366. * @return {NodeBuilder} The node builder.
  45367. */
  45368. createNodeBuilder( /*renderObject, renderer*/ ) { }
  45369. // textures
  45370. /**
  45371. * Updates a GPU sampler for the given texture.
  45372. *
  45373. * @abstract
  45374. * @param {Texture} texture - The texture to update the sampler for.
  45375. * @return {string} The current sampler key.
  45376. */
  45377. updateSampler( /*texture*/ ) { }
  45378. /**
  45379. * Creates a default texture for the given texture that can be used
  45380. * as a placeholder until the actual texture is ready for usage.
  45381. *
  45382. * @abstract
  45383. * @param {Texture} texture - The texture to create a default texture for.
  45384. */
  45385. createDefaultTexture( /*texture*/ ) { }
  45386. /**
  45387. * Defines a texture on the GPU for the given texture object.
  45388. *
  45389. * @abstract
  45390. * @param {Texture} texture - The texture.
  45391. * @param {Object} [options={}] - Optional configuration parameter.
  45392. */
  45393. createTexture( /*texture, options={}*/ ) { }
  45394. /**
  45395. * Uploads the updated texture data to the GPU.
  45396. *
  45397. * @abstract
  45398. * @param {Texture} texture - The texture.
  45399. * @param {Object} [options={}] - Optional configuration parameter.
  45400. */
  45401. updateTexture( /*texture, options = {}*/ ) { }
  45402. /**
  45403. * Generates mipmaps for the given texture.
  45404. *
  45405. * @abstract
  45406. * @param {Texture} texture - The texture.
  45407. */
  45408. generateMipmaps( /*texture*/ ) { }
  45409. /**
  45410. * Destroys the GPU data for the given texture object.
  45411. *
  45412. * @abstract
  45413. * @param {Texture} texture - The texture.
  45414. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  45415. */
  45416. destroyTexture( /*texture, isDefaultTexture*/ ) { }
  45417. /**
  45418. * Returns texture data as a typed array.
  45419. *
  45420. * @abstract
  45421. * @async
  45422. * @param {Texture} texture - The texture to copy.
  45423. * @param {number} x - The x coordinate of the copy origin.
  45424. * @param {number} y - The y coordinate of the copy origin.
  45425. * @param {number} width - The width of the copy.
  45426. * @param {number} height - The height of the copy.
  45427. * @param {number} faceIndex - The face index.
  45428. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  45429. */
  45430. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  45431. /**
  45432. * Copies data of the given source texture to the given destination texture.
  45433. *
  45434. * @abstract
  45435. * @param {Texture} srcTexture - The source texture.
  45436. * @param {Texture} dstTexture - The destination texture.
  45437. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  45438. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  45439. * @param {number} [srcLevel=0] - The source mip level to copy from.
  45440. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  45441. */
  45442. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  45443. /**
  45444. * Copies the current bound framebuffer to the given texture.
  45445. *
  45446. * @abstract
  45447. * @param {Texture} texture - The destination texture.
  45448. * @param {RenderContext} renderContext - The render context.
  45449. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  45450. */
  45451. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  45452. // attributes
  45453. /**
  45454. * Creates the GPU buffer of a shader attribute.
  45455. *
  45456. * @abstract
  45457. * @param {BufferAttribute} attribute - The buffer attribute.
  45458. */
  45459. createAttribute( /*attribute*/ ) { }
  45460. /**
  45461. * Creates the GPU buffer of an indexed shader attribute.
  45462. *
  45463. * @abstract
  45464. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  45465. */
  45466. createIndexAttribute( /*attribute*/ ) { }
  45467. /**
  45468. * Creates the GPU buffer of a storage attribute.
  45469. *
  45470. * @abstract
  45471. * @param {BufferAttribute} attribute - The buffer attribute.
  45472. */
  45473. createStorageAttribute( /*attribute*/ ) { }
  45474. /**
  45475. * Updates the GPU buffer of a shader attribute.
  45476. *
  45477. * @abstract
  45478. * @param {BufferAttribute} attribute - The buffer attribute to update.
  45479. */
  45480. updateAttribute( /*attribute*/ ) { }
  45481. /**
  45482. * Destroys the GPU buffer of a shader attribute.
  45483. *
  45484. * @abstract
  45485. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  45486. */
  45487. destroyAttribute( /*attribute*/ ) { }
  45488. // canvas
  45489. /**
  45490. * Returns the backend's rendering context.
  45491. *
  45492. * @abstract
  45493. * @return {Object} The rendering context.
  45494. */
  45495. getContext() { }
  45496. /**
  45497. * Backends can use this method if they have to run
  45498. * logic when the renderer gets resized.
  45499. *
  45500. * @abstract
  45501. */
  45502. updateSize() { }
  45503. /**
  45504. * Updates the viewport with the values from the given render context.
  45505. *
  45506. * @abstract
  45507. * @param {RenderContext} renderContext - The render context.
  45508. */
  45509. updateViewport( /*renderContext*/ ) {}
  45510. // utils
  45511. /**
  45512. * Updates a unique identifier for the given render context that can be used
  45513. * to allocate resources like occlusion queries or timestamp queries.
  45514. *
  45515. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  45516. */
  45517. updateTimeStampUID( abstractRenderContext ) {
  45518. const contextData = this.get( abstractRenderContext );
  45519. const frame = this.renderer.info.frame;
  45520. let prefix;
  45521. if ( abstractRenderContext.isComputeNode === true ) {
  45522. prefix = 'c:' + this.renderer.info.compute.frameCalls;
  45523. } else {
  45524. prefix = 'r:' + this.renderer.info.render.frameCalls;
  45525. }
  45526. contextData.timestampUID = prefix + ':' + abstractRenderContext.id + ':f' + frame;
  45527. }
  45528. /**
  45529. * Returns a unique identifier for the given render context that can be used
  45530. * to allocate resources like occlusion queries or timestamp queries.
  45531. *
  45532. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  45533. * @return {string} The unique identifier.
  45534. */
  45535. getTimestampUID( abstractRenderContext ) {
  45536. return this.get( abstractRenderContext ).timestampUID;
  45537. }
  45538. /**
  45539. * Returns all timestamp frames for the given type.
  45540. *
  45541. * @param {string} type - The type of the time stamp.
  45542. * @return {Array<number>} The timestamp frames.
  45543. */
  45544. getTimestampFrames( type ) {
  45545. const queryPool = this.timestampQueryPool[ type ];
  45546. return queryPool ? queryPool.getTimestampFrames() : [];
  45547. }
  45548. /**
  45549. * Returns the query pool for the given uid.
  45550. *
  45551. * @param {string} uid - The unique identifier.
  45552. * @return {TimestampQueryPool} The query pool.
  45553. */
  45554. _getQueryPool( uid ) {
  45555. const type = uid.startsWith( 'c:' ) ? TimestampQuery.COMPUTE : TimestampQuery.RENDER;
  45556. const queryPool = this.timestampQueryPool[ type ];
  45557. return queryPool;
  45558. }
  45559. /**
  45560. * Returns the timestamp for the given uid.
  45561. *
  45562. * @param {string} uid - The unique identifier.
  45563. * @return {number} The timestamp.
  45564. */
  45565. getTimestamp( uid ) {
  45566. const queryPool = this._getQueryPool( uid );
  45567. return queryPool.getTimestamp( uid );
  45568. }
  45569. /**
  45570. * Returns `true` if a timestamp for the given uid is available.
  45571. *
  45572. * @param {string} uid - The unique identifier.
  45573. * @return {boolean} Whether the timestamp is available or not.
  45574. */
  45575. hasTimestamp( uid ) {
  45576. const queryPool = this._getQueryPool( uid );
  45577. return queryPool.hasTimestamp( uid );
  45578. }
  45579. /**
  45580. * Returns `true` if the given 3D object is fully occluded by other
  45581. * 3D objects in the scene. Backends must implement this method by using
  45582. * a Occlusion Query API.
  45583. *
  45584. * @abstract
  45585. * @param {RenderContext} renderContext - The render context.
  45586. * @param {Object3D} object - The 3D object to test.
  45587. * @return {boolean} Whether the 3D object is fully occluded or not.
  45588. */
  45589. isOccluded( /*renderContext, object*/ ) {}
  45590. /**
  45591. * Resolves the time stamp for the given render context and type.
  45592. *
  45593. * @async
  45594. * @abstract
  45595. * @param {string} [type='render'] - The type of the time stamp.
  45596. * @return {Promise<number>} A Promise that resolves with the time stamp.
  45597. */
  45598. async resolveTimestampsAsync( type = 'render' ) {
  45599. if ( ! this.trackTimestamp ) {
  45600. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  45601. return;
  45602. }
  45603. const queryPool = this.timestampQueryPool[ type ];
  45604. if ( ! queryPool ) {
  45605. return;
  45606. }
  45607. const duration = await queryPool.resolveQueriesAsync();
  45608. this.renderer.info[ type ].timestamp = duration;
  45609. return duration;
  45610. }
  45611. /**
  45612. * This method performs a readback operation by moving buffer data from
  45613. * a storage buffer attribute from the GPU to the CPU.
  45614. *
  45615. * @async
  45616. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  45617. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  45618. */
  45619. async getArrayBufferAsync( /* attribute */ ) {}
  45620. /**
  45621. * Checks if the given feature is supported by the backend.
  45622. *
  45623. * @async
  45624. * @abstract
  45625. * @param {string} name - The feature's name.
  45626. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  45627. */
  45628. async hasFeatureAsync( /*name*/ ) { }
  45629. /**
  45630. * Checks if the given feature is supported by the backend.
  45631. *
  45632. * @abstract
  45633. * @param {string} name - The feature's name.
  45634. * @return {boolean} Whether the feature is supported or not.
  45635. */
  45636. hasFeature( /*name*/ ) {}
  45637. /**
  45638. * Returns the maximum anisotropy texture filtering value.
  45639. *
  45640. * @abstract
  45641. * @return {number} The maximum anisotropy texture filtering value.
  45642. */
  45643. getMaxAnisotropy() {}
  45644. /**
  45645. * Returns the drawing buffer size.
  45646. *
  45647. * @return {Vector2} The drawing buffer size.
  45648. */
  45649. getDrawingBufferSize() {
  45650. _vector2 = _vector2 || new Vector2();
  45651. return this.renderer.getDrawingBufferSize( _vector2 );
  45652. }
  45653. /**
  45654. * Defines the scissor test.
  45655. *
  45656. * @abstract
  45657. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  45658. */
  45659. setScissorTest( /*boolean*/ ) { }
  45660. /**
  45661. * Returns the clear color and alpha into a single
  45662. * color object.
  45663. *
  45664. * @return {Color4} The clear color.
  45665. */
  45666. getClearColor() {
  45667. const renderer = this.renderer;
  45668. _color4 = _color4 || new Color4();
  45669. renderer.getClearColor( _color4 );
  45670. _color4.getRGB( _color4 );
  45671. return _color4;
  45672. }
  45673. /**
  45674. * Returns the DOM element. If no DOM element exists, the backend
  45675. * creates a new one.
  45676. *
  45677. * @return {HTMLCanvasElement} The DOM element.
  45678. */
  45679. getDomElement() {
  45680. let domElement = this.domElement;
  45681. if ( domElement === null ) {
  45682. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  45683. // OffscreenCanvas does not have setAttribute, see #22811
  45684. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  45685. this.domElement = domElement;
  45686. }
  45687. return domElement;
  45688. }
  45689. /**
  45690. * Sets a dictionary for the given object into the
  45691. * internal data structure.
  45692. *
  45693. * @param {Object} object - The object.
  45694. * @param {Object} value - The dictionary to set.
  45695. */
  45696. set( object, value ) {
  45697. this.data.set( object, value );
  45698. }
  45699. /**
  45700. * Returns the dictionary for the given object.
  45701. *
  45702. * @param {Object} object - The object.
  45703. * @return {Object} The object's dictionary.
  45704. */
  45705. get( object ) {
  45706. let map = this.data.get( object );
  45707. if ( map === undefined ) {
  45708. map = {};
  45709. this.data.set( object, map );
  45710. }
  45711. return map;
  45712. }
  45713. /**
  45714. * Checks if the given object has a dictionary
  45715. * with data defined.
  45716. *
  45717. * @param {Object} object - The object.
  45718. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  45719. */
  45720. has( object ) {
  45721. return this.data.has( object );
  45722. }
  45723. /**
  45724. * Deletes an object from the internal data structure.
  45725. *
  45726. * @param {Object} object - The object to delete.
  45727. */
  45728. delete( object ) {
  45729. this.data.delete( object );
  45730. }
  45731. /**
  45732. * Frees internal resources.
  45733. *
  45734. * @abstract
  45735. */
  45736. dispose() { }
  45737. }
  45738. let _id$1 = 0;
  45739. /**
  45740. * This module is internally used in context of compute shaders.
  45741. * This type of shader is not natively supported in WebGL 2 and
  45742. * thus implemented via Transform Feedback. `DualAttributeData`
  45743. * manages the related data.
  45744. *
  45745. * @private
  45746. */
  45747. class DualAttributeData {
  45748. constructor( attributeData, dualBuffer ) {
  45749. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  45750. this.type = attributeData.type;
  45751. this.bufferType = attributeData.bufferType;
  45752. this.pbo = attributeData.pbo;
  45753. this.byteLength = attributeData.byteLength;
  45754. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  45755. this.version = attributeData.version;
  45756. this.isInteger = attributeData.isInteger;
  45757. this.activeBufferIndex = 0;
  45758. this.baseId = attributeData.id;
  45759. }
  45760. get id() {
  45761. return `${ this.baseId }|${ this.activeBufferIndex }`;
  45762. }
  45763. get bufferGPU() {
  45764. return this.buffers[ this.activeBufferIndex ];
  45765. }
  45766. get transformBuffer() {
  45767. return this.buffers[ this.activeBufferIndex ^ 1 ];
  45768. }
  45769. switchBuffers() {
  45770. this.activeBufferIndex ^= 1;
  45771. }
  45772. }
  45773. /**
  45774. * A WebGL 2 backend utility module for managing shader attributes.
  45775. *
  45776. * @private
  45777. */
  45778. class WebGLAttributeUtils {
  45779. /**
  45780. * Constructs a new utility object.
  45781. *
  45782. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45783. */
  45784. constructor( backend ) {
  45785. /**
  45786. * A reference to the WebGL 2 backend.
  45787. *
  45788. * @type {WebGLBackend}
  45789. */
  45790. this.backend = backend;
  45791. }
  45792. /**
  45793. * Creates the GPU buffer for the given buffer attribute.
  45794. *
  45795. * @param {BufferAttribute} attribute - The buffer attribute.
  45796. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  45797. */
  45798. createAttribute( attribute, bufferType ) {
  45799. const backend = this.backend;
  45800. const { gl } = backend;
  45801. const array = attribute.array;
  45802. const usage = attribute.usage || gl.STATIC_DRAW;
  45803. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  45804. const bufferData = backend.get( bufferAttribute );
  45805. let bufferGPU = bufferData.bufferGPU;
  45806. if ( bufferGPU === undefined ) {
  45807. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  45808. bufferData.bufferGPU = bufferGPU;
  45809. bufferData.bufferType = bufferType;
  45810. bufferData.version = bufferAttribute.version;
  45811. }
  45812. //attribute.onUploadCallback();
  45813. let type;
  45814. if ( array instanceof Float32Array ) {
  45815. type = gl.FLOAT;
  45816. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  45817. type = gl.HALF_FLOAT;
  45818. } else if ( array instanceof Uint16Array ) {
  45819. if ( attribute.isFloat16BufferAttribute ) {
  45820. type = gl.HALF_FLOAT;
  45821. } else {
  45822. type = gl.UNSIGNED_SHORT;
  45823. }
  45824. } else if ( array instanceof Int16Array ) {
  45825. type = gl.SHORT;
  45826. } else if ( array instanceof Uint32Array ) {
  45827. type = gl.UNSIGNED_INT;
  45828. } else if ( array instanceof Int32Array ) {
  45829. type = gl.INT;
  45830. } else if ( array instanceof Int8Array ) {
  45831. type = gl.BYTE;
  45832. } else if ( array instanceof Uint8Array ) {
  45833. type = gl.UNSIGNED_BYTE;
  45834. } else if ( array instanceof Uint8ClampedArray ) {
  45835. type = gl.UNSIGNED_BYTE;
  45836. } else {
  45837. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  45838. }
  45839. let attributeData = {
  45840. bufferGPU,
  45841. bufferType,
  45842. type,
  45843. byteLength: array.byteLength,
  45844. bytesPerElement: array.BYTES_PER_ELEMENT,
  45845. version: attribute.version,
  45846. pbo: attribute.pbo,
  45847. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  45848. id: _id$1 ++
  45849. };
  45850. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  45851. // create buffer for transform feedback use
  45852. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  45853. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  45854. }
  45855. backend.set( attribute, attributeData );
  45856. }
  45857. /**
  45858. * Updates the GPU buffer of the given buffer attribute.
  45859. *
  45860. * @param {BufferAttribute} attribute - The buffer attribute.
  45861. */
  45862. updateAttribute( attribute ) {
  45863. const backend = this.backend;
  45864. const { gl } = backend;
  45865. const array = attribute.array;
  45866. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  45867. const bufferData = backend.get( bufferAttribute );
  45868. const bufferType = bufferData.bufferType;
  45869. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  45870. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  45871. if ( updateRanges.length === 0 ) {
  45872. // Not using update ranges
  45873. gl.bufferSubData( bufferType, 0, array );
  45874. } else {
  45875. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  45876. const range = updateRanges[ i ];
  45877. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  45878. array, range.start, range.count );
  45879. }
  45880. bufferAttribute.clearUpdateRanges();
  45881. }
  45882. gl.bindBuffer( bufferType, null );
  45883. bufferData.version = bufferAttribute.version;
  45884. }
  45885. /**
  45886. * Destroys the GPU buffer of the given buffer attribute.
  45887. *
  45888. * @param {BufferAttribute} attribute - The buffer attribute.
  45889. */
  45890. destroyAttribute( attribute ) {
  45891. const backend = this.backend;
  45892. const { gl } = backend;
  45893. if ( attribute.isInterleavedBufferAttribute ) {
  45894. backend.delete( attribute.data );
  45895. }
  45896. const attributeData = backend.get( attribute );
  45897. gl.deleteBuffer( attributeData.bufferGPU );
  45898. backend.delete( attribute );
  45899. }
  45900. /**
  45901. * This method performs a readback operation by moving buffer data from
  45902. * a storage buffer attribute from the GPU to the CPU.
  45903. *
  45904. * @async
  45905. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  45906. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  45907. */
  45908. async getArrayBufferAsync( attribute ) {
  45909. const backend = this.backend;
  45910. const { gl } = backend;
  45911. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  45912. const { bufferGPU } = backend.get( bufferAttribute );
  45913. const array = attribute.array;
  45914. const byteLength = array.byteLength;
  45915. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  45916. const writeBuffer = gl.createBuffer();
  45917. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  45918. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  45919. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  45920. await backend.utils._clientWaitAsync();
  45921. const dstBuffer = new attribute.array.constructor( array.length );
  45922. // Ensure the buffer is bound before reading
  45923. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  45924. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  45925. gl.deleteBuffer( writeBuffer );
  45926. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  45927. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  45928. return dstBuffer.buffer;
  45929. }
  45930. /**
  45931. * Creates a WebGL buffer with the given data.
  45932. *
  45933. * @private
  45934. * @param {WebGL2RenderingContext} gl - The rendering context.
  45935. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  45936. * @param {TypedArray} array - The array of the buffer attribute.
  45937. * @param {GLenum} usage - The usage.
  45938. * @return {WebGLBuffer} The WebGL buffer.
  45939. */
  45940. _createBuffer( gl, bufferType, array, usage ) {
  45941. const bufferGPU = gl.createBuffer();
  45942. gl.bindBuffer( bufferType, bufferGPU );
  45943. gl.bufferData( bufferType, array, usage );
  45944. gl.bindBuffer( bufferType, null );
  45945. return bufferGPU;
  45946. }
  45947. }
  45948. let equationToGL, factorToGL;
  45949. /**
  45950. * A WebGL 2 backend utility module for managing the WebGL state.
  45951. *
  45952. * The major goal of this module is to reduce the number of state changes
  45953. * by caching the WEbGL state with a series of variables. In this way, the
  45954. * renderer only executes state change commands when necessary which
  45955. * improves the overall performance.
  45956. *
  45957. * @private
  45958. */
  45959. class WebGLState {
  45960. /**
  45961. * Constructs a new utility object.
  45962. *
  45963. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45964. */
  45965. constructor( backend ) {
  45966. /**
  45967. * A reference to the WebGL 2 backend.
  45968. *
  45969. * @type {WebGLBackend}
  45970. */
  45971. this.backend = backend;
  45972. /**
  45973. * A reference to the rendering context.
  45974. *
  45975. * @type {WebGL2RenderingContext}
  45976. */
  45977. this.gl = this.backend.gl;
  45978. // Below properties are intended to cache
  45979. // the WebGL state and are not explicitly
  45980. // documented for convenience reasons.
  45981. this.enabled = {};
  45982. this.currentFlipSided = null;
  45983. this.currentCullFace = null;
  45984. this.currentProgram = null;
  45985. this.currentBlendingEnabled = false;
  45986. this.currentBlending = null;
  45987. this.currentBlendSrc = null;
  45988. this.currentBlendDst = null;
  45989. this.currentBlendSrcAlpha = null;
  45990. this.currentBlendDstAlpha = null;
  45991. this.currentPremultipledAlpha = null;
  45992. this.currentPolygonOffsetFactor = null;
  45993. this.currentPolygonOffsetUnits = null;
  45994. this.currentColorMask = null;
  45995. this.currentDepthFunc = null;
  45996. this.currentDepthMask = null;
  45997. this.currentStencilFunc = null;
  45998. this.currentStencilRef = null;
  45999. this.currentStencilFuncMask = null;
  46000. this.currentStencilFail = null;
  46001. this.currentStencilZFail = null;
  46002. this.currentStencilZPass = null;
  46003. this.currentStencilMask = null;
  46004. this.currentLineWidth = null;
  46005. this.currentClippingPlanes = 0;
  46006. this.currentVAO = null;
  46007. this.currentIndex = null;
  46008. this.currentBoundFramebuffers = {};
  46009. this.currentDrawbuffers = new WeakMap();
  46010. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  46011. this.currentTextureSlot = null;
  46012. this.currentBoundTextures = {};
  46013. this.currentBoundBufferBases = {};
  46014. this._init();
  46015. }
  46016. /**
  46017. * Inits the state of the utility.
  46018. *
  46019. * @private
  46020. */
  46021. _init() {
  46022. const gl = this.gl;
  46023. // Store only WebGL constants here.
  46024. equationToGL = {
  46025. [ AddEquation ]: gl.FUNC_ADD,
  46026. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  46027. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  46028. };
  46029. factorToGL = {
  46030. [ ZeroFactor ]: gl.ZERO,
  46031. [ OneFactor ]: gl.ONE,
  46032. [ SrcColorFactor ]: gl.SRC_COLOR,
  46033. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  46034. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  46035. [ DstColorFactor ]: gl.DST_COLOR,
  46036. [ DstAlphaFactor ]: gl.DST_ALPHA,
  46037. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  46038. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  46039. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  46040. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  46041. };
  46042. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  46043. const viewportParam = gl.getParameter( gl.VIEWPORT );
  46044. this.currentScissor = new Vector4().fromArray( scissorParam );
  46045. this.currentViewport = new Vector4().fromArray( viewportParam );
  46046. this._tempVec4 = new Vector4();
  46047. }
  46048. /**
  46049. * Enables the given WebGL capability.
  46050. *
  46051. * This method caches the capability state so
  46052. * `gl.enable()` is only called when necessary.
  46053. *
  46054. * @param {GLenum} id - The capability to enable.
  46055. */
  46056. enable( id ) {
  46057. const { enabled } = this;
  46058. if ( enabled[ id ] !== true ) {
  46059. this.gl.enable( id );
  46060. enabled[ id ] = true;
  46061. }
  46062. }
  46063. /**
  46064. * Disables the given WebGL capability.
  46065. *
  46066. * This method caches the capability state so
  46067. * `gl.disable()` is only called when necessary.
  46068. *
  46069. * @param {GLenum} id - The capability to enable.
  46070. */
  46071. disable( id ) {
  46072. const { enabled } = this;
  46073. if ( enabled[ id ] !== false ) {
  46074. this.gl.disable( id );
  46075. enabled[ id ] = false;
  46076. }
  46077. }
  46078. /**
  46079. * Specifies whether polygons are front- or back-facing
  46080. * by setting the winding orientation.
  46081. *
  46082. * This method caches the state so `gl.frontFace()` is only
  46083. * called when necessary.
  46084. *
  46085. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  46086. */
  46087. setFlipSided( flipSided ) {
  46088. if ( this.currentFlipSided !== flipSided ) {
  46089. const { gl } = this;
  46090. if ( flipSided ) {
  46091. gl.frontFace( gl.CW );
  46092. } else {
  46093. gl.frontFace( gl.CCW );
  46094. }
  46095. this.currentFlipSided = flipSided;
  46096. }
  46097. }
  46098. /**
  46099. * Specifies whether or not front- and/or back-facing
  46100. * polygons can be culled.
  46101. *
  46102. * This method caches the state so `gl.cullFace()` is only
  46103. * called when necessary.
  46104. *
  46105. * @param {number} cullFace - Defines which polygons are candidates for culling.
  46106. */
  46107. setCullFace( cullFace ) {
  46108. const { gl } = this;
  46109. if ( cullFace !== CullFaceNone ) {
  46110. this.enable( gl.CULL_FACE );
  46111. if ( cullFace !== this.currentCullFace ) {
  46112. if ( cullFace === CullFaceBack ) {
  46113. gl.cullFace( gl.BACK );
  46114. } else if ( cullFace === CullFaceFront ) {
  46115. gl.cullFace( gl.FRONT );
  46116. } else {
  46117. gl.cullFace( gl.FRONT_AND_BACK );
  46118. }
  46119. }
  46120. } else {
  46121. this.disable( gl.CULL_FACE );
  46122. }
  46123. this.currentCullFace = cullFace;
  46124. }
  46125. /**
  46126. * Specifies the width of line primitives.
  46127. *
  46128. * This method caches the state so `gl.lineWidth()` is only
  46129. * called when necessary.
  46130. *
  46131. * @param {number} width - The line width.
  46132. */
  46133. setLineWidth( width ) {
  46134. const { currentLineWidth, gl } = this;
  46135. if ( width !== currentLineWidth ) {
  46136. gl.lineWidth( width );
  46137. this.currentLineWidth = width;
  46138. }
  46139. }
  46140. setMRTBlending( textures ) {
  46141. const gl = this.gl;
  46142. const drawBuffersIndexedExt = this.backend.drawBuffersIndexedExt;
  46143. if ( ! drawBuffersIndexedExt ) return;
  46144. for ( let i = 1; i < textures.length; i ++ ) {
  46145. // use opaque blending for additional render targets
  46146. drawBuffersIndexedExt.blendFuncSeparateiOES( i, gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  46147. }
  46148. }
  46149. /**
  46150. * Defines the blending.
  46151. *
  46152. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  46153. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  46154. *
  46155. * @param {number} blending - The blending type.
  46156. * @param {number} blendEquation - The blending equation.
  46157. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  46158. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  46159. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  46160. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  46161. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  46162. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  46163. */
  46164. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  46165. const { gl } = this;
  46166. if ( blending === NoBlending ) {
  46167. if ( this.currentBlendingEnabled === true ) {
  46168. this.disable( gl.BLEND );
  46169. this.currentBlendingEnabled = false;
  46170. }
  46171. return;
  46172. }
  46173. if ( this.currentBlendingEnabled === false ) {
  46174. this.enable( gl.BLEND );
  46175. this.currentBlendingEnabled = true;
  46176. }
  46177. if ( blending !== CustomBlending ) {
  46178. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  46179. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  46180. gl.blendEquation( gl.FUNC_ADD );
  46181. this.currentBlendEquation = AddEquation;
  46182. this.currentBlendEquationAlpha = AddEquation;
  46183. }
  46184. if ( premultipliedAlpha ) {
  46185. switch ( blending ) {
  46186. case NormalBlending:
  46187. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  46188. break;
  46189. case AdditiveBlending:
  46190. gl.blendFunc( gl.ONE, gl.ONE );
  46191. break;
  46192. case SubtractiveBlending:
  46193. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  46194. break;
  46195. case MultiplyBlending:
  46196. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  46197. break;
  46198. default:
  46199. error( 'WebGLState: Invalid blending: ', blending );
  46200. break;
  46201. }
  46202. } else {
  46203. switch ( blending ) {
  46204. case NormalBlending:
  46205. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  46206. break;
  46207. case AdditiveBlending:
  46208. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  46209. break;
  46210. case SubtractiveBlending:
  46211. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  46212. break;
  46213. case MultiplyBlending:
  46214. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  46215. break;
  46216. default:
  46217. error( 'WebGLState: Invalid blending: ', blending );
  46218. break;
  46219. }
  46220. }
  46221. this.currentBlendSrc = null;
  46222. this.currentBlendDst = null;
  46223. this.currentBlendSrcAlpha = null;
  46224. this.currentBlendDstAlpha = null;
  46225. this.currentBlending = blending;
  46226. this.currentPremultipledAlpha = premultipliedAlpha;
  46227. }
  46228. return;
  46229. }
  46230. // custom blending
  46231. blendEquationAlpha = blendEquationAlpha || blendEquation;
  46232. blendSrcAlpha = blendSrcAlpha || blendSrc;
  46233. blendDstAlpha = blendDstAlpha || blendDst;
  46234. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  46235. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  46236. this.currentBlendEquation = blendEquation;
  46237. this.currentBlendEquationAlpha = blendEquationAlpha;
  46238. }
  46239. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  46240. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  46241. this.currentBlendSrc = blendSrc;
  46242. this.currentBlendDst = blendDst;
  46243. this.currentBlendSrcAlpha = blendSrcAlpha;
  46244. this.currentBlendDstAlpha = blendDstAlpha;
  46245. }
  46246. this.currentBlending = blending;
  46247. this.currentPremultipledAlpha = false;
  46248. }
  46249. /**
  46250. * Specifies whether colors can be written when rendering
  46251. * into a framebuffer or not.
  46252. *
  46253. * This method caches the state so `gl.colorMask()` is only
  46254. * called when necessary.
  46255. *
  46256. * @param {boolean} colorMask - The color mask.
  46257. */
  46258. setColorMask( colorMask ) {
  46259. if ( this.currentColorMask !== colorMask ) {
  46260. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  46261. this.currentColorMask = colorMask;
  46262. }
  46263. }
  46264. /**
  46265. * Specifies whether the depth test is enabled or not.
  46266. *
  46267. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  46268. */
  46269. setDepthTest( depthTest ) {
  46270. const { gl } = this;
  46271. if ( depthTest ) {
  46272. this.enable( gl.DEPTH_TEST );
  46273. } else {
  46274. this.disable( gl.DEPTH_TEST );
  46275. }
  46276. }
  46277. /**
  46278. * Specifies whether depth values can be written when rendering
  46279. * into a framebuffer or not.
  46280. *
  46281. * This method caches the state so `gl.depthMask()` is only
  46282. * called when necessary.
  46283. *
  46284. * @param {boolean} depthMask - The depth mask.
  46285. */
  46286. setDepthMask( depthMask ) {
  46287. if ( this.currentDepthMask !== depthMask ) {
  46288. this.gl.depthMask( depthMask );
  46289. this.currentDepthMask = depthMask;
  46290. }
  46291. }
  46292. /**
  46293. * Specifies the depth compare function.
  46294. *
  46295. * This method caches the state so `gl.depthFunc()` is only
  46296. * called when necessary.
  46297. *
  46298. * @param {number} depthFunc - The depth compare function.
  46299. */
  46300. setDepthFunc( depthFunc ) {
  46301. if ( this.currentDepthFunc !== depthFunc ) {
  46302. const { gl } = this;
  46303. switch ( depthFunc ) {
  46304. case NeverDepth:
  46305. gl.depthFunc( gl.NEVER );
  46306. break;
  46307. case AlwaysDepth:
  46308. gl.depthFunc( gl.ALWAYS );
  46309. break;
  46310. case LessDepth:
  46311. gl.depthFunc( gl.LESS );
  46312. break;
  46313. case LessEqualDepth:
  46314. gl.depthFunc( gl.LEQUAL );
  46315. break;
  46316. case EqualDepth:
  46317. gl.depthFunc( gl.EQUAL );
  46318. break;
  46319. case GreaterEqualDepth:
  46320. gl.depthFunc( gl.GEQUAL );
  46321. break;
  46322. case GreaterDepth:
  46323. gl.depthFunc( gl.GREATER );
  46324. break;
  46325. case NotEqualDepth:
  46326. gl.depthFunc( gl.NOTEQUAL );
  46327. break;
  46328. default:
  46329. gl.depthFunc( gl.LEQUAL );
  46330. }
  46331. this.currentDepthFunc = depthFunc;
  46332. }
  46333. }
  46334. /**
  46335. * Specifies the scissor box.
  46336. *
  46337. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  46338. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  46339. * @param {number} width - The width of the viewport.
  46340. * @param {number} height - The height of the viewport.
  46341. *
  46342. */
  46343. scissor( x, y, width, height ) {
  46344. const scissor = this._tempVec4.set( x, y, width, height );
  46345. if ( this.currentScissor.equals( scissor ) === false ) {
  46346. const { gl } = this;
  46347. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  46348. this.currentScissor.copy( scissor );
  46349. }
  46350. }
  46351. /**
  46352. * Specifies the viewport.
  46353. *
  46354. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  46355. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  46356. * @param {number} width - The width of the viewport.
  46357. * @param {number} height - The height of the viewport.
  46358. *
  46359. */
  46360. viewport( x, y, width, height ) {
  46361. const viewport = this._tempVec4.set( x, y, width, height );
  46362. if ( this.currentViewport.equals( viewport ) === false ) {
  46363. const { gl } = this;
  46364. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  46365. this.currentViewport.copy( viewport );
  46366. }
  46367. }
  46368. /**
  46369. * Defines the scissor test.
  46370. *
  46371. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  46372. */
  46373. setScissorTest( boolean ) {
  46374. const gl = this.gl;
  46375. if ( boolean ) {
  46376. gl.enable( gl.SCISSOR_TEST );
  46377. } else {
  46378. gl.disable( gl.SCISSOR_TEST );
  46379. }
  46380. }
  46381. /**
  46382. * Specifies whether the stencil test is enabled or not.
  46383. *
  46384. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  46385. */
  46386. setStencilTest( stencilTest ) {
  46387. const { gl } = this;
  46388. if ( stencilTest ) {
  46389. this.enable( gl.STENCIL_TEST );
  46390. } else {
  46391. this.disable( gl.STENCIL_TEST );
  46392. }
  46393. }
  46394. /**
  46395. * Specifies whether stencil values can be written when rendering
  46396. * into a framebuffer or not.
  46397. *
  46398. * This method caches the state so `gl.stencilMask()` is only
  46399. * called when necessary.
  46400. *
  46401. * @param {boolean} stencilMask - The stencil mask.
  46402. */
  46403. setStencilMask( stencilMask ) {
  46404. if ( this.currentStencilMask !== stencilMask ) {
  46405. this.gl.stencilMask( stencilMask );
  46406. this.currentStencilMask = stencilMask;
  46407. }
  46408. }
  46409. /**
  46410. * Specifies whether the stencil test functions.
  46411. *
  46412. * This method caches the state so `gl.stencilFunc()` is only
  46413. * called when necessary.
  46414. *
  46415. * @param {number} stencilFunc - The stencil compare function.
  46416. * @param {number} stencilRef - The reference value for the stencil test.
  46417. * @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.
  46418. */
  46419. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  46420. if ( this.currentStencilFunc !== stencilFunc ||
  46421. this.currentStencilRef !== stencilRef ||
  46422. this.currentStencilFuncMask !== stencilMask ) {
  46423. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  46424. this.currentStencilFunc = stencilFunc;
  46425. this.currentStencilRef = stencilRef;
  46426. this.currentStencilFuncMask = stencilMask;
  46427. }
  46428. }
  46429. /**
  46430. * Specifies whether the stencil test operation.
  46431. *
  46432. * This method caches the state so `gl.stencilOp()` is only
  46433. * called when necessary.
  46434. *
  46435. * @param {number} stencilFail - The function to use when the stencil test fails.
  46436. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  46437. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  46438. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  46439. */
  46440. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  46441. if ( this.currentStencilFail !== stencilFail ||
  46442. this.currentStencilZFail !== stencilZFail ||
  46443. this.currentStencilZPass !== stencilZPass ) {
  46444. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  46445. this.currentStencilFail = stencilFail;
  46446. this.currentStencilZFail = stencilZFail;
  46447. this.currentStencilZPass = stencilZPass;
  46448. }
  46449. }
  46450. /**
  46451. * Configures the WebGL state for the given material.
  46452. *
  46453. * @param {Material} material - The material to configure the state for.
  46454. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  46455. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  46456. */
  46457. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  46458. const { gl } = this;
  46459. material.side === DoubleSide
  46460. ? this.disable( gl.CULL_FACE )
  46461. : this.enable( gl.CULL_FACE );
  46462. let flipSided = ( material.side === BackSide );
  46463. if ( frontFaceCW ) flipSided = ! flipSided;
  46464. this.setFlipSided( flipSided );
  46465. ( material.blending === NormalBlending && material.transparent === false )
  46466. ? this.setBlending( NoBlending )
  46467. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  46468. this.setDepthFunc( material.depthFunc );
  46469. this.setDepthTest( material.depthTest );
  46470. this.setDepthMask( material.depthWrite );
  46471. this.setColorMask( material.colorWrite );
  46472. const stencilWrite = material.stencilWrite;
  46473. this.setStencilTest( stencilWrite );
  46474. if ( stencilWrite ) {
  46475. this.setStencilMask( material.stencilWriteMask );
  46476. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  46477. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  46478. }
  46479. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  46480. material.alphaToCoverage === true && this.backend.renderer.currentSamples > 0
  46481. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  46482. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  46483. if ( hardwareClippingPlanes > 0 ) {
  46484. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  46485. const CLIP_DISTANCE0_WEBGL = 0x3000;
  46486. for ( let i = 0; i < 8; i ++ ) {
  46487. if ( i < hardwareClippingPlanes ) {
  46488. this.enable( CLIP_DISTANCE0_WEBGL + i );
  46489. } else {
  46490. this.disable( CLIP_DISTANCE0_WEBGL + i );
  46491. }
  46492. }
  46493. }
  46494. }
  46495. }
  46496. /**
  46497. * Specifies the polygon offset.
  46498. *
  46499. * This method caches the state so `gl.polygonOffset()` is only
  46500. * called when necessary.
  46501. *
  46502. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  46503. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  46504. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  46505. */
  46506. setPolygonOffset( polygonOffset, factor, units ) {
  46507. const { gl } = this;
  46508. if ( polygonOffset ) {
  46509. this.enable( gl.POLYGON_OFFSET_FILL );
  46510. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  46511. gl.polygonOffset( factor, units );
  46512. this.currentPolygonOffsetFactor = factor;
  46513. this.currentPolygonOffsetUnits = units;
  46514. }
  46515. } else {
  46516. this.disable( gl.POLYGON_OFFSET_FILL );
  46517. }
  46518. }
  46519. /**
  46520. * Defines the usage of the given WebGL program.
  46521. *
  46522. * This method caches the state so `gl.useProgram()` is only
  46523. * called when necessary.
  46524. *
  46525. * @param {WebGLProgram} program - The WebGL program to use.
  46526. * @return {boolean} Whether a program change has been executed or not.
  46527. */
  46528. useProgram( program ) {
  46529. if ( this.currentProgram !== program ) {
  46530. this.gl.useProgram( program );
  46531. this.currentProgram = program;
  46532. return true;
  46533. }
  46534. return false;
  46535. }
  46536. /**
  46537. * Sets the vertex state by binding the given VAO and element buffer.
  46538. *
  46539. * @param {WebGLVertexArrayObject} vao - The VAO.
  46540. * @param {?WebGLBuffer} indexBuffer - The index buffer.
  46541. * @return {boolean} Whether a vertex state has been changed or not.
  46542. */
  46543. setVertexState( vao, indexBuffer = null ) {
  46544. const gl = this.gl;
  46545. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  46546. gl.bindVertexArray( vao );
  46547. if ( indexBuffer !== null ) {
  46548. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  46549. }
  46550. this.currentVAO = vao;
  46551. this.currentIndex = indexBuffer;
  46552. return true;
  46553. }
  46554. return false;
  46555. }
  46556. /**
  46557. * Resets the vertex array state by resetting the VAO and element buffer.
  46558. */
  46559. resetVertexState() {
  46560. const gl = this.gl;
  46561. gl.bindVertexArray( null );
  46562. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  46563. this.currentVAO = null;
  46564. this.currentIndex = null;
  46565. }
  46566. // framebuffer
  46567. /**
  46568. * Binds the given framebuffer.
  46569. *
  46570. * This method caches the state so `gl.bindFramebuffer()` is only
  46571. * called when necessary.
  46572. *
  46573. * @param {number} target - The binding point (target).
  46574. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  46575. * @return {boolean} Whether a bind has been executed or not.
  46576. */
  46577. bindFramebuffer( target, framebuffer ) {
  46578. const { gl, currentBoundFramebuffers } = this;
  46579. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  46580. gl.bindFramebuffer( target, framebuffer );
  46581. currentBoundFramebuffers[ target ] = framebuffer;
  46582. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  46583. if ( target === gl.DRAW_FRAMEBUFFER ) {
  46584. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  46585. }
  46586. if ( target === gl.FRAMEBUFFER ) {
  46587. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  46588. }
  46589. return true;
  46590. }
  46591. return false;
  46592. }
  46593. /**
  46594. * Defines draw buffers to which fragment colors are written into.
  46595. * Configures the MRT setup of custom framebuffers.
  46596. *
  46597. * This method caches the state so `gl.drawBuffers()` is only
  46598. * called when necessary.
  46599. *
  46600. * @param {RenderContext} renderContext - The render context.
  46601. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  46602. */
  46603. drawBuffers( renderContext, framebuffer ) {
  46604. const { gl } = this;
  46605. let drawBuffers = [];
  46606. let needsUpdate = false;
  46607. if ( renderContext.textures !== null ) {
  46608. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  46609. if ( drawBuffers === undefined ) {
  46610. drawBuffers = [];
  46611. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  46612. }
  46613. const textures = renderContext.textures;
  46614. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  46615. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  46616. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  46617. }
  46618. drawBuffers.length = textures.length;
  46619. needsUpdate = true;
  46620. }
  46621. } else {
  46622. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  46623. drawBuffers[ 0 ] = gl.BACK;
  46624. needsUpdate = true;
  46625. }
  46626. }
  46627. if ( needsUpdate ) {
  46628. gl.drawBuffers( drawBuffers );
  46629. }
  46630. }
  46631. // texture
  46632. /**
  46633. * Makes the given texture unit active.
  46634. *
  46635. * This method caches the state so `gl.activeTexture()` is only
  46636. * called when necessary.
  46637. *
  46638. * @param {number} webglSlot - The texture unit to make active.
  46639. */
  46640. activeTexture( webglSlot ) {
  46641. const { gl, currentTextureSlot, maxTextures } = this;
  46642. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  46643. if ( currentTextureSlot !== webglSlot ) {
  46644. gl.activeTexture( webglSlot );
  46645. this.currentTextureSlot = webglSlot;
  46646. }
  46647. }
  46648. /**
  46649. * Binds the given WebGL texture to a target.
  46650. *
  46651. * This method caches the state so `gl.bindTexture()` is only
  46652. * called when necessary.
  46653. *
  46654. * @param {number} webglType - The binding point (target).
  46655. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  46656. * @param {number} webglSlot - The texture.
  46657. */
  46658. bindTexture( webglType, webglTexture, webglSlot ) {
  46659. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  46660. if ( webglSlot === undefined ) {
  46661. if ( currentTextureSlot === null ) {
  46662. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  46663. } else {
  46664. webglSlot = currentTextureSlot;
  46665. }
  46666. }
  46667. let boundTexture = currentBoundTextures[ webglSlot ];
  46668. if ( boundTexture === undefined ) {
  46669. boundTexture = { type: undefined, texture: undefined };
  46670. currentBoundTextures[ webglSlot ] = boundTexture;
  46671. }
  46672. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  46673. if ( currentTextureSlot !== webglSlot ) {
  46674. gl.activeTexture( webglSlot );
  46675. this.currentTextureSlot = webglSlot;
  46676. }
  46677. gl.bindTexture( webglType, webglTexture );
  46678. boundTexture.type = webglType;
  46679. boundTexture.texture = webglTexture;
  46680. }
  46681. }
  46682. /**
  46683. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  46684. *
  46685. * This method caches the state so `gl.bindBufferBase()` is only
  46686. * called when necessary.
  46687. *
  46688. * @param {number} target - The target for the bind operation.
  46689. * @param {number} index - The index of the target.
  46690. * @param {WebGLBuffer} buffer - The WebGL buffer.
  46691. * @return {boolean} Whether a bind has been executed or not.
  46692. */
  46693. bindBufferBase( target, index, buffer ) {
  46694. const { gl } = this;
  46695. const key = `${target}-${index}`;
  46696. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  46697. gl.bindBufferBase( target, index, buffer );
  46698. this.currentBoundBufferBases[ key ] = buffer;
  46699. return true;
  46700. }
  46701. return false;
  46702. }
  46703. /**
  46704. * Unbinds the current bound texture.
  46705. *
  46706. * This method caches the state so `gl.bindTexture()` is only
  46707. * called when necessary.
  46708. */
  46709. unbindTexture() {
  46710. const { gl, currentTextureSlot, currentBoundTextures } = this;
  46711. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  46712. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  46713. gl.bindTexture( boundTexture.type, null );
  46714. boundTexture.type = undefined;
  46715. boundTexture.texture = undefined;
  46716. }
  46717. }
  46718. }
  46719. /**
  46720. * A WebGL 2 backend utility module with common helpers.
  46721. *
  46722. * @private
  46723. */
  46724. class WebGLUtils {
  46725. /**
  46726. * Constructs a new utility object.
  46727. *
  46728. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46729. */
  46730. constructor( backend ) {
  46731. /**
  46732. * A reference to the WebGL 2 backend.
  46733. *
  46734. * @type {WebGLBackend}
  46735. */
  46736. this.backend = backend;
  46737. /**
  46738. * A reference to the rendering context.
  46739. *
  46740. * @type {WebGL2RenderingContext}
  46741. */
  46742. this.gl = this.backend.gl;
  46743. /**
  46744. * A reference to a backend module holding extension-related
  46745. * utility functions.
  46746. *
  46747. * @type {WebGLExtensions}
  46748. */
  46749. this.extensions = backend.extensions;
  46750. }
  46751. /**
  46752. * Converts the given three.js constant into a WebGL constant.
  46753. * The method currently supports the conversion of texture formats
  46754. * and types.
  46755. *
  46756. * @param {number} p - The three.js constant.
  46757. * @param {string} [colorSpace=NoColorSpace] - The color space.
  46758. * @return {?number} The corresponding WebGL constant.
  46759. */
  46760. convert( p, colorSpace = NoColorSpace ) {
  46761. const { gl, extensions } = this;
  46762. let extension;
  46763. const transfer = ColorManagement.getTransfer( colorSpace );
  46764. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  46765. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  46766. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  46767. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  46768. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  46769. if ( p === ByteType ) return gl.BYTE;
  46770. if ( p === ShortType ) return gl.SHORT;
  46771. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  46772. if ( p === IntType ) return gl.INT;
  46773. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  46774. if ( p === FloatType ) return gl.FLOAT;
  46775. if ( p === HalfFloatType ) {
  46776. return gl.HALF_FLOAT;
  46777. }
  46778. if ( p === AlphaFormat ) return gl.ALPHA;
  46779. if ( p === RGBFormat ) return gl.RGB;
  46780. if ( p === RGBAFormat ) return gl.RGBA;
  46781. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  46782. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  46783. // WebGL2 formats.
  46784. if ( p === RedFormat ) return gl.RED;
  46785. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  46786. if ( p === RGFormat ) return gl.RG;
  46787. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  46788. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  46789. // S3TC
  46790. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  46791. if ( transfer === SRGBTransfer ) {
  46792. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  46793. if ( extension !== null ) {
  46794. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  46795. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  46796. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  46797. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  46798. } else {
  46799. return null;
  46800. }
  46801. } else {
  46802. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  46803. if ( extension !== null ) {
  46804. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  46805. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  46806. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  46807. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  46808. } else {
  46809. return null;
  46810. }
  46811. }
  46812. }
  46813. // PVRTC
  46814. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  46815. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  46816. if ( extension !== null ) {
  46817. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  46818. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  46819. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  46820. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  46821. } else {
  46822. return null;
  46823. }
  46824. }
  46825. // ETC
  46826. 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 ) {
  46827. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  46828. if ( extension !== null ) {
  46829. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  46830. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  46831. if ( p === R11_EAC_Format ) return extension.COMPRESSED_R11_EAC;
  46832. if ( p === SIGNED_R11_EAC_Format ) return extension.COMPRESSED_SIGNED_R11_EAC;
  46833. if ( p === RG11_EAC_Format ) return extension.COMPRESSED_RG11_EAC;
  46834. if ( p === SIGNED_RG11_EAC_Format ) return extension.COMPRESSED_SIGNED_RG11_EAC;
  46835. } else {
  46836. return null;
  46837. }
  46838. }
  46839. // ASTC
  46840. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  46841. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  46842. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  46843. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  46844. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  46845. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  46846. if ( extension !== null ) {
  46847. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  46848. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  46849. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  46850. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  46851. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  46852. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  46853. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  46854. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  46855. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  46856. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  46857. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  46858. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  46859. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  46860. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  46861. } else {
  46862. return null;
  46863. }
  46864. }
  46865. // BPTC
  46866. if ( p === RGBA_BPTC_Format ) {
  46867. extension = extensions.get( 'EXT_texture_compression_bptc' );
  46868. if ( extension !== null ) {
  46869. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  46870. } else {
  46871. return null;
  46872. }
  46873. }
  46874. // RGTC
  46875. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  46876. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  46877. if ( extension !== null ) {
  46878. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  46879. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  46880. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  46881. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  46882. } else {
  46883. return null;
  46884. }
  46885. }
  46886. //
  46887. if ( p === UnsignedInt248Type ) {
  46888. return gl.UNSIGNED_INT_24_8;
  46889. }
  46890. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  46891. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  46892. }
  46893. /**
  46894. * This method can be used to synchronize the CPU with the GPU by waiting until
  46895. * ongoing GPU commands have been completed.
  46896. *
  46897. * @private
  46898. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  46899. */
  46900. _clientWaitAsync() {
  46901. const { gl } = this;
  46902. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  46903. gl.flush();
  46904. return new Promise( ( resolve, reject ) => {
  46905. function test() {
  46906. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  46907. if ( res === gl.WAIT_FAILED ) {
  46908. gl.deleteSync( sync );
  46909. reject();
  46910. return;
  46911. }
  46912. if ( res === gl.TIMEOUT_EXPIRED ) {
  46913. requestAnimationFrame( test );
  46914. return;
  46915. }
  46916. gl.deleteSync( sync );
  46917. resolve();
  46918. }
  46919. test();
  46920. } );
  46921. }
  46922. }
  46923. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  46924. /**
  46925. * A WebGL 2 backend utility module for managing textures.
  46926. *
  46927. * @private
  46928. */
  46929. class WebGLTextureUtils {
  46930. /**
  46931. * Constructs a new utility object.
  46932. *
  46933. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46934. */
  46935. constructor( backend ) {
  46936. /**
  46937. * A reference to the WebGL 2 backend.
  46938. *
  46939. * @type {WebGLBackend}
  46940. */
  46941. this.backend = backend;
  46942. /**
  46943. * A reference to the rendering context.
  46944. *
  46945. * @type {WebGL2RenderingContext}
  46946. */
  46947. this.gl = backend.gl;
  46948. /**
  46949. * A reference to a backend module holding extension-related
  46950. * utility functions.
  46951. *
  46952. * @type {WebGLExtensions}
  46953. */
  46954. this.extensions = backend.extensions;
  46955. /**
  46956. * A dictionary for managing default textures. The key
  46957. * is the binding point (target), the value the WEbGL texture object.
  46958. *
  46959. * @type {Object<GLenum,WebGLTexture>}
  46960. */
  46961. this.defaultTextures = {};
  46962. /**
  46963. * A scratch framebuffer used for attaching the source texture in
  46964. * {@link copyTextureToTexture}.
  46965. *
  46966. * @private
  46967. * @type {?WebGLFramebuffer}
  46968. */
  46969. this._srcFramebuffer = null;
  46970. /**
  46971. * A scratch framebuffer used for attaching the destination texture in
  46972. * {@link copyTextureToTexture}.
  46973. *
  46974. * @private
  46975. * @type {?WebGLFramebuffer}
  46976. */
  46977. this._dstFramebuffer = null;
  46978. if ( initialized === false ) {
  46979. this._init();
  46980. initialized = true;
  46981. }
  46982. }
  46983. /**
  46984. * Inits the state of the utility.
  46985. *
  46986. * @private
  46987. */
  46988. _init() {
  46989. const gl = this.gl;
  46990. // Store only WebGL constants here.
  46991. wrappingToGL = {
  46992. [ RepeatWrapping ]: gl.REPEAT,
  46993. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  46994. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  46995. };
  46996. filterToGL = {
  46997. [ NearestFilter ]: gl.NEAREST,
  46998. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  46999. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  47000. [ LinearFilter ]: gl.LINEAR,
  47001. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  47002. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  47003. };
  47004. compareToGL = {
  47005. [ NeverCompare ]: gl.NEVER,
  47006. [ AlwaysCompare ]: gl.ALWAYS,
  47007. [ LessCompare ]: gl.LESS,
  47008. [ LessEqualCompare ]: gl.LEQUAL,
  47009. [ EqualCompare ]: gl.EQUAL,
  47010. [ GreaterEqualCompare ]: gl.GEQUAL,
  47011. [ GreaterCompare ]: gl.GREATER,
  47012. [ NotEqualCompare ]: gl.NOTEQUAL
  47013. };
  47014. }
  47015. /**
  47016. * Returns the native texture type for the given texture.
  47017. *
  47018. * @param {Texture} texture - The texture.
  47019. * @return {GLenum} The native texture type.
  47020. */
  47021. getGLTextureType( texture ) {
  47022. const { gl } = this;
  47023. let glTextureType;
  47024. if ( texture.isCubeTexture === true ) {
  47025. glTextureType = gl.TEXTURE_CUBE_MAP;
  47026. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  47027. glTextureType = gl.TEXTURE_2D_ARRAY;
  47028. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  47029. glTextureType = gl.TEXTURE_3D;
  47030. } else {
  47031. glTextureType = gl.TEXTURE_2D;
  47032. }
  47033. return glTextureType;
  47034. }
  47035. /**
  47036. * Returns the native texture type for the given texture.
  47037. *
  47038. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  47039. * @param {GLenum} glFormat - The WebGL format.
  47040. * @param {GLenum} glType - The WebGL type.
  47041. * @param {string} colorSpace - The texture's color space.
  47042. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  47043. * @return {GLenum} The internal format.
  47044. */
  47045. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  47046. const { gl, extensions } = this;
  47047. if ( internalFormatName !== null ) {
  47048. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  47049. warn( 'WebGLBackend: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  47050. }
  47051. let internalFormat = glFormat;
  47052. if ( glFormat === gl.RED ) {
  47053. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  47054. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  47055. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  47056. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  47057. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  47058. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  47059. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  47060. if ( glType === gl.INT ) internalFormat = gl.R32I;
  47061. }
  47062. if ( glFormat === gl.RED_INTEGER ) {
  47063. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  47064. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  47065. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  47066. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  47067. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  47068. if ( glType === gl.INT ) internalFormat = gl.R32I;
  47069. }
  47070. if ( glFormat === gl.RG ) {
  47071. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  47072. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  47073. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  47074. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  47075. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  47076. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  47077. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  47078. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  47079. }
  47080. if ( glFormat === gl.RG_INTEGER ) {
  47081. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  47082. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  47083. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  47084. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  47085. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  47086. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  47087. }
  47088. if ( glFormat === gl.RGB ) {
  47089. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  47090. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  47091. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  47092. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  47093. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  47094. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  47095. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  47096. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  47097. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  47098. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  47099. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  47100. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  47101. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  47102. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  47103. if ( glType === gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = gl.R11F_G11F_B10F;
  47104. }
  47105. if ( glFormat === gl.RGB_INTEGER ) {
  47106. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  47107. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  47108. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  47109. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  47110. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  47111. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  47112. }
  47113. if ( glFormat === gl.RGBA ) {
  47114. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  47115. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  47116. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  47117. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  47118. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  47119. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  47120. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  47121. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  47122. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  47123. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  47124. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  47125. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  47126. }
  47127. if ( glFormat === gl.RGBA_INTEGER ) {
  47128. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  47129. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  47130. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  47131. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  47132. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  47133. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  47134. }
  47135. if ( glFormat === gl.DEPTH_COMPONENT ) {
  47136. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  47137. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  47138. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  47139. }
  47140. if ( glFormat === gl.DEPTH_STENCIL ) {
  47141. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  47142. }
  47143. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  47144. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  47145. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  47146. extensions.get( 'EXT_color_buffer_float' );
  47147. }
  47148. return internalFormat;
  47149. }
  47150. /**
  47151. * Sets the texture parameters for the given texture.
  47152. *
  47153. * @param {GLenum} textureType - The texture type.
  47154. * @param {Texture} texture - The texture.
  47155. */
  47156. setTextureParameters( textureType, texture ) {
  47157. const { gl, extensions, backend } = this;
  47158. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  47159. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  47160. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  47161. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  47162. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  47163. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  47164. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  47165. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  47166. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  47167. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  47168. // WebGL 2 does not support wrapping for depth 2D array textures
  47169. if ( ! texture.isArrayTexture ) {
  47170. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  47171. }
  47172. }
  47173. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  47174. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  47175. // follow WebGPU backend mapping for texture filtering
  47176. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  47177. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  47178. if ( texture.compareFunction ) {
  47179. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  47180. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  47181. }
  47182. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  47183. if ( texture.magFilter === NearestFilter ) return;
  47184. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  47185. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  47186. if ( texture.anisotropy > 1 ) {
  47187. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  47188. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  47189. }
  47190. }
  47191. }
  47192. /**
  47193. * Creates a default texture for the given texture that can be used
  47194. * as a placeholder until the actual texture is ready for usage.
  47195. *
  47196. * @param {Texture} texture - The texture to create a default texture for.
  47197. */
  47198. createDefaultTexture( texture ) {
  47199. const { gl, backend, defaultTextures } = this;
  47200. const glTextureType = this.getGLTextureType( texture );
  47201. let textureGPU = defaultTextures[ glTextureType ];
  47202. if ( textureGPU === undefined ) {
  47203. textureGPU = gl.createTexture();
  47204. backend.state.bindTexture( glTextureType, textureGPU );
  47205. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  47206. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  47207. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  47208. defaultTextures[ glTextureType ] = textureGPU;
  47209. }
  47210. backend.set( texture, {
  47211. textureGPU,
  47212. glTextureType
  47213. } );
  47214. }
  47215. /**
  47216. * Defines a texture on the GPU for the given texture object.
  47217. *
  47218. * @param {Texture} texture - The texture.
  47219. * @param {Object} [options={}] - Optional configuration parameter.
  47220. * @return {undefined}
  47221. */
  47222. createTexture( texture, options ) {
  47223. const { gl, backend } = this;
  47224. const { levels, width, height, depth } = options;
  47225. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  47226. const glType = backend.utils.convert( texture.type );
  47227. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  47228. const textureGPU = gl.createTexture();
  47229. const glTextureType = this.getGLTextureType( texture );
  47230. backend.state.bindTexture( glTextureType, textureGPU );
  47231. this.setTextureParameters( glTextureType, texture );
  47232. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  47233. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  47234. } else if ( texture.isData3DTexture ) {
  47235. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  47236. } else if ( ! texture.isVideoTexture ) {
  47237. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  47238. }
  47239. backend.set( texture, {
  47240. textureGPU,
  47241. glTextureType,
  47242. glFormat,
  47243. glType,
  47244. glInternalFormat
  47245. } );
  47246. }
  47247. /**
  47248. * Uploads texture buffer data to the GPU memory.
  47249. *
  47250. * @param {WebGLBuffer} buffer - The buffer data.
  47251. * @param {Texture} texture - The texture,
  47252. */
  47253. copyBufferToTexture( buffer, texture ) {
  47254. const { gl, backend } = this;
  47255. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  47256. const { width, height } = texture.source.data;
  47257. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  47258. backend.state.bindTexture( glTextureType, textureGPU );
  47259. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  47260. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  47261. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  47262. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  47263. backend.state.unbindTexture();
  47264. // debug
  47265. // const framebuffer = gl.createFramebuffer();
  47266. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  47267. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  47268. // const readout = new Float32Array( width * height * 4 );
  47269. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  47270. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  47271. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  47272. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  47273. // log( readout );
  47274. }
  47275. /**
  47276. * Uploads the updated texture data to the GPU.
  47277. *
  47278. * @param {Texture} texture - The texture.
  47279. * @param {Object} [options={}] - Optional configuration parameter.
  47280. */
  47281. updateTexture( texture, options ) {
  47282. const { gl } = this;
  47283. const { width, height } = options;
  47284. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  47285. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  47286. return;
  47287. this.backend.state.bindTexture( glTextureType, textureGPU );
  47288. this.setTextureParameters( glTextureType, texture );
  47289. if ( texture.isCompressedTexture ) {
  47290. const mipmaps = texture.mipmaps;
  47291. const image = options.image;
  47292. for ( let i = 0; i < mipmaps.length; i ++ ) {
  47293. const mipmap = mipmaps[ i ];
  47294. if ( texture.isCompressedArrayTexture ) {
  47295. if ( texture.format !== gl.RGBA ) {
  47296. if ( glFormat !== null ) {
  47297. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  47298. } else {
  47299. warn( 'WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  47300. }
  47301. } else {
  47302. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  47303. }
  47304. } else {
  47305. if ( glFormat !== null ) {
  47306. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  47307. } else {
  47308. warn( 'WebGLBackend: Unsupported compressed texture format' );
  47309. }
  47310. }
  47311. }
  47312. } else if ( texture.isCubeTexture ) {
  47313. const images = options.images;
  47314. const mipmaps = texture.mipmaps;
  47315. for ( let i = 0; i < 6; i ++ ) {
  47316. const image = getImage( images[ i ] );
  47317. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  47318. for ( let j = 0; j < mipmaps.length; j ++ ) {
  47319. const mipmap = mipmaps[ j ];
  47320. const image = getImage( mipmap.images[ i ] );
  47321. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, image.width, image.height, glFormat, glType, image );
  47322. }
  47323. }
  47324. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  47325. const image = options.image;
  47326. if ( texture.layerUpdates.size > 0 ) {
  47327. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  47328. for ( const layerIndex of texture.layerUpdates ) {
  47329. const layerData = image.data.subarray(
  47330. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  47331. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  47332. );
  47333. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  47334. }
  47335. texture.clearLayerUpdates();
  47336. } else {
  47337. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  47338. }
  47339. } else if ( texture.isData3DTexture ) {
  47340. const image = options.image;
  47341. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  47342. } else if ( texture.isVideoTexture ) {
  47343. texture.update();
  47344. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  47345. } else {
  47346. const mipmaps = texture.mipmaps;
  47347. if ( mipmaps.length > 0 ) {
  47348. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  47349. const mipmap = mipmaps[ i ];
  47350. const image = getImage( mipmap );
  47351. gl.texSubImage2D( glTextureType, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, image );
  47352. }
  47353. } else {
  47354. const image = getImage( options.image );
  47355. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  47356. }
  47357. }
  47358. }
  47359. /**
  47360. * Generates mipmaps for the given texture.
  47361. *
  47362. * @param {Texture} texture - The texture.
  47363. */
  47364. generateMipmaps( texture ) {
  47365. const { gl, backend } = this;
  47366. const { textureGPU, glTextureType } = backend.get( texture );
  47367. backend.state.bindTexture( glTextureType, textureGPU );
  47368. gl.generateMipmap( glTextureType );
  47369. }
  47370. /**
  47371. * Deallocates the render buffers of the given render target.
  47372. *
  47373. * @param {RenderTarget} renderTarget - The render target.
  47374. */
  47375. deallocateRenderBuffers( renderTarget ) {
  47376. const { gl, backend } = this;
  47377. // remove framebuffer reference
  47378. if ( renderTarget ) {
  47379. const renderContextData = backend.get( renderTarget );
  47380. renderContextData.renderBufferStorageSetup = undefined;
  47381. if ( renderContextData.framebuffers ) {
  47382. for ( const cacheKey in renderContextData.framebuffers ) {
  47383. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  47384. }
  47385. delete renderContextData.framebuffers;
  47386. }
  47387. if ( renderContextData.depthRenderbuffer ) {
  47388. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  47389. delete renderContextData.depthRenderbuffer;
  47390. }
  47391. if ( renderContextData.stencilRenderbuffer ) {
  47392. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  47393. delete renderContextData.stencilRenderbuffer;
  47394. }
  47395. if ( renderContextData.msaaFrameBuffer ) {
  47396. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  47397. delete renderContextData.msaaFrameBuffer;
  47398. }
  47399. if ( renderContextData.msaaRenderbuffers ) {
  47400. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  47401. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  47402. }
  47403. delete renderContextData.msaaRenderbuffers;
  47404. }
  47405. }
  47406. }
  47407. /**
  47408. * Destroys the GPU data for the given texture object.
  47409. *
  47410. * @param {Texture} texture - The texture.
  47411. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  47412. */
  47413. destroyTexture( texture, isDefaultTexture = false ) {
  47414. const { gl, backend } = this;
  47415. const { textureGPU, renderTarget } = backend.get( texture );
  47416. this.deallocateRenderBuffers( renderTarget );
  47417. if ( isDefaultTexture === false ) {
  47418. gl.deleteTexture( textureGPU );
  47419. }
  47420. backend.delete( texture );
  47421. }
  47422. /**
  47423. * Copies data of the given source texture to the given destination texture.
  47424. *
  47425. * @param {Texture} srcTexture - The source texture.
  47426. * @param {Texture} dstTexture - The destination texture.
  47427. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  47428. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  47429. * @param {number} [srcLevel=0] - The source mip level to copy from.
  47430. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  47431. */
  47432. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  47433. const { gl, backend } = this;
  47434. const { state } = this.backend;
  47435. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  47436. state.bindTexture( glTextureType, dstTextureGPU );
  47437. // gather the necessary dimensions to copy
  47438. let width, height, depth, minX, minY, minZ;
  47439. let dstX, dstY, dstZ;
  47440. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  47441. if ( srcRegion !== null ) {
  47442. width = srcRegion.max.x - srcRegion.min.x;
  47443. height = srcRegion.max.y - srcRegion.min.y;
  47444. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  47445. minX = srcRegion.min.x;
  47446. minY = srcRegion.min.y;
  47447. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  47448. } else {
  47449. const levelScale = Math.pow( 2, - srcLevel );
  47450. width = Math.floor( image.width * levelScale );
  47451. height = Math.floor( image.height * levelScale );
  47452. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  47453. depth = image.depth;
  47454. } else if ( srcTexture.isData3DTexture ) {
  47455. depth = Math.floor( image.depth * levelScale );
  47456. } else {
  47457. depth = 1;
  47458. }
  47459. minX = 0;
  47460. minY = 0;
  47461. minZ = 0;
  47462. }
  47463. if ( dstPosition !== null ) {
  47464. dstX = dstPosition.x;
  47465. dstY = dstPosition.y;
  47466. dstZ = dstPosition.z;
  47467. } else {
  47468. dstX = 0;
  47469. dstY = 0;
  47470. dstZ = 0;
  47471. }
  47472. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  47473. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  47474. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  47475. // used for copying data from cpu
  47476. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  47477. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  47478. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  47479. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  47480. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  47481. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  47482. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  47483. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  47484. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  47485. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  47486. // set up the src texture
  47487. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture || dstTexture.isArrayTexture;
  47488. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  47489. if ( srcTexture.isDepthTexture ) {
  47490. const srcTextureData = backend.get( srcTexture );
  47491. const dstTextureData = backend.get( dstTexture );
  47492. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  47493. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  47494. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  47495. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  47496. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  47497. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  47498. for ( let i = 0; i < depth; i ++ ) {
  47499. // if the source or destination are a 3d target then a layer needs to be bound
  47500. if ( isSrc3D ) {
  47501. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  47502. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  47503. }
  47504. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.DEPTH_BUFFER_BIT, gl.NEAREST );
  47505. }
  47506. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  47507. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  47508. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || backend.has( srcTexture ) ) {
  47509. // get the appropriate frame buffers
  47510. const srcTextureData = backend.get( srcTexture );
  47511. if ( this._srcFramebuffer === null ) this._srcFramebuffer = gl.createFramebuffer();
  47512. if ( this._dstFramebuffer === null ) this._dstFramebuffer = gl.createFramebuffer();
  47513. // bind the frame buffer targets
  47514. state.bindFramebuffer( gl.READ_FRAMEBUFFER, this._srcFramebuffer );
  47515. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, this._dstFramebuffer );
  47516. for ( let i = 0; i < depth; i ++ ) {
  47517. // assign the correct layers and mip maps to the frame buffers
  47518. if ( isSrc3D ) {
  47519. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  47520. } else {
  47521. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, srcTextureData.textureGPU, srcLevel );
  47522. }
  47523. if ( isDst3D ) {
  47524. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  47525. } else {
  47526. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dstTextureGPU, dstLevel );
  47527. }
  47528. // copy the data using the fastest function that can achieve the copy
  47529. if ( srcLevel !== 0 ) {
  47530. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST );
  47531. } else if ( isDst3D ) {
  47532. gl.copyTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  47533. } else {
  47534. gl.copyTexSubImage2D( glTextureType, dstLevel, dstX, dstY, minX, minY, width, height );
  47535. }
  47536. }
  47537. // unbind read, draw buffers
  47538. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  47539. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  47540. } else {
  47541. if ( isDst3D ) {
  47542. // copy data into the 3d texture
  47543. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  47544. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  47545. } else if ( dstTexture.isCompressedArrayTexture ) {
  47546. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  47547. } else {
  47548. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  47549. }
  47550. } else {
  47551. // copy data into the 2d texture
  47552. if ( srcTexture.isDataTexture ) {
  47553. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  47554. } else if ( srcTexture.isCompressedTexture ) {
  47555. gl.compressedTexSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  47556. } else {
  47557. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  47558. }
  47559. }
  47560. }
  47561. // reset values
  47562. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  47563. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  47564. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  47565. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  47566. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  47567. // Generate mipmaps only when copying level 0
  47568. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  47569. gl.generateMipmap( glTextureType );
  47570. }
  47571. state.unbindTexture();
  47572. }
  47573. /**
  47574. * Copies the current bound framebuffer to the given texture.
  47575. *
  47576. * @param {Texture} texture - The destination texture.
  47577. * @param {RenderContext} renderContext - The render context.
  47578. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  47579. */
  47580. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  47581. const { gl } = this;
  47582. const { state } = this.backend;
  47583. const { textureGPU } = this.backend.get( texture );
  47584. const { x, y, z: width, w: height } = rectangle;
  47585. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  47586. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  47587. if ( requireDrawFrameBuffer ) {
  47588. const partial = ( x !== 0 || y !== 0 );
  47589. let mask;
  47590. let attachment;
  47591. if ( texture.isDepthTexture === true ) {
  47592. mask = gl.DEPTH_BUFFER_BIT;
  47593. attachment = gl.DEPTH_ATTACHMENT;
  47594. if ( renderContext.stencil ) {
  47595. mask |= gl.STENCIL_BUFFER_BIT;
  47596. }
  47597. } else {
  47598. mask = gl.COLOR_BUFFER_BIT;
  47599. attachment = gl.COLOR_ATTACHMENT0;
  47600. }
  47601. if ( partial ) {
  47602. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  47603. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  47604. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  47605. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  47606. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  47607. const flippedY = srcHeight - y - height;
  47608. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  47609. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  47610. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  47611. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  47612. state.unbindTexture();
  47613. } else {
  47614. const fb = gl.createFramebuffer();
  47615. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  47616. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  47617. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  47618. gl.deleteFramebuffer( fb );
  47619. }
  47620. } else {
  47621. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  47622. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  47623. state.unbindTexture();
  47624. }
  47625. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  47626. this.backend._setFramebuffer( renderContext );
  47627. }
  47628. /**
  47629. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  47630. *
  47631. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  47632. * @param {RenderContext} renderContext - The render context.
  47633. * @param {number} samples - The MSAA sample count.
  47634. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  47635. */
  47636. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  47637. const { gl } = this;
  47638. const renderTarget = renderContext.renderTarget;
  47639. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  47640. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  47641. if ( depthBuffer && ! stencilBuffer ) {
  47642. let glInternalFormat = gl.DEPTH_COMPONENT24;
  47643. if ( useMultisampledRTT === true ) {
  47644. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  47645. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  47646. } else if ( samples > 0 ) {
  47647. if ( depthTexture && depthTexture.isDepthTexture ) {
  47648. if ( depthTexture.type === gl.FLOAT ) {
  47649. glInternalFormat = gl.DEPTH_COMPONENT32F;
  47650. }
  47651. }
  47652. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  47653. } else {
  47654. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  47655. }
  47656. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  47657. } else if ( depthBuffer && stencilBuffer ) {
  47658. if ( samples > 0 ) {
  47659. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  47660. } else {
  47661. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  47662. }
  47663. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  47664. }
  47665. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  47666. }
  47667. /**
  47668. * Returns texture data as a typed array.
  47669. *
  47670. * @async
  47671. * @param {Texture} texture - The texture to copy.
  47672. * @param {number} x - The x coordinate of the copy origin.
  47673. * @param {number} y - The y coordinate of the copy origin.
  47674. * @param {number} width - The width of the copy.
  47675. * @param {number} height - The height of the copy.
  47676. * @param {number} faceIndex - The face index.
  47677. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  47678. */
  47679. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  47680. const { backend, gl } = this;
  47681. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  47682. const fb = gl.createFramebuffer();
  47683. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  47684. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  47685. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  47686. const typedArrayType = this._getTypedArrayType( glType );
  47687. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  47688. const elementCount = width * height;
  47689. const byteLength = elementCount * bytesPerTexel;
  47690. const buffer = gl.createBuffer();
  47691. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  47692. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  47693. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  47694. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  47695. await backend.utils._clientWaitAsync();
  47696. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  47697. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  47698. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  47699. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  47700. gl.deleteFramebuffer( fb );
  47701. return dstBuffer;
  47702. }
  47703. /**
  47704. * Returns the corresponding typed array type for the given WebGL data type.
  47705. *
  47706. * @private
  47707. * @param {GLenum} glType - The WebGL data type.
  47708. * @return {TypedArray.constructor} The typed array type.
  47709. */
  47710. _getTypedArrayType( glType ) {
  47711. const { gl } = this;
  47712. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  47713. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  47714. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  47715. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  47716. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  47717. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  47718. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  47719. if ( glType === gl.FLOAT ) return Float32Array;
  47720. throw new Error( `Unsupported WebGL type: ${glType}` );
  47721. }
  47722. /**
  47723. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  47724. *
  47725. * @private
  47726. * @param {GLenum} glType - The WebGL data type.
  47727. * @param {GLenum} glFormat - The WebGL texture format.
  47728. * @return {number} The bytes-per-texel.
  47729. */
  47730. _getBytesPerTexel( glType, glFormat ) {
  47731. const { gl } = this;
  47732. let bytesPerComponent = 0;
  47733. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  47734. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  47735. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  47736. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  47737. glType === gl.UNSIGNED_SHORT ||
  47738. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  47739. if ( glType === gl.UNSIGNED_INT ||
  47740. glType === gl.FLOAT ) bytesPerComponent = 4;
  47741. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  47742. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  47743. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  47744. }
  47745. /**
  47746. * Frees the internal resources.
  47747. */
  47748. dispose() {
  47749. const { gl } = this;
  47750. if ( this._srcFramebuffer !== null ) gl.deleteFramebuffer( this._srcFramebuffer );
  47751. if ( this._dstFramebuffer !== null ) gl.deleteFramebuffer( this._dstFramebuffer );
  47752. }
  47753. }
  47754. function getImage( source ) {
  47755. if ( source.isDataTexture ) {
  47756. return source.image.data;
  47757. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  47758. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  47759. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  47760. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  47761. return source;
  47762. }
  47763. return source.data;
  47764. }
  47765. /**
  47766. * A WebGL 2 backend utility module for managing extensions.
  47767. *
  47768. * @private
  47769. */
  47770. class WebGLExtensions {
  47771. /**
  47772. * Constructs a new utility object.
  47773. *
  47774. * @param {WebGLBackend} backend - The WebGL 2 backend.
  47775. */
  47776. constructor( backend ) {
  47777. /**
  47778. * A reference to the WebGL 2 backend.
  47779. *
  47780. * @type {WebGLBackend}
  47781. */
  47782. this.backend = backend;
  47783. /**
  47784. * A reference to the rendering context.
  47785. *
  47786. * @type {WebGL2RenderingContext}
  47787. */
  47788. this.gl = this.backend.gl;
  47789. /**
  47790. * A list with all the supported WebGL extensions.
  47791. *
  47792. * @type {Array<string>}
  47793. */
  47794. this.availableExtensions = this.gl.getSupportedExtensions();
  47795. /**
  47796. * A dictionary with requested WebGL extensions.
  47797. * The key is the name of the extension, the value
  47798. * the requested extension object.
  47799. *
  47800. * @type {Object<string,Object>}
  47801. */
  47802. this.extensions = {};
  47803. }
  47804. /**
  47805. * Returns the extension object for the given extension name.
  47806. *
  47807. * @param {string} name - The extension name.
  47808. * @return {Object} The extension object.
  47809. */
  47810. get( name ) {
  47811. let extension = this.extensions[ name ];
  47812. if ( extension === undefined ) {
  47813. extension = this.gl.getExtension( name );
  47814. this.extensions[ name ] = extension;
  47815. }
  47816. return extension;
  47817. }
  47818. /**
  47819. * Returns `true` if the requested extension is available.
  47820. *
  47821. * @param {string} name - The extension name.
  47822. * @return {boolean} Whether the given extension is available or not.
  47823. */
  47824. has( name ) {
  47825. return this.availableExtensions.includes( name );
  47826. }
  47827. }
  47828. /**
  47829. * A WebGL 2 backend utility module for managing the device's capabilities.
  47830. *
  47831. * @private
  47832. */
  47833. class WebGLCapabilities {
  47834. /**
  47835. * Constructs a new utility object.
  47836. *
  47837. * @param {WebGLBackend} backend - The WebGL 2 backend.
  47838. */
  47839. constructor( backend ) {
  47840. /**
  47841. * A reference to the WebGL 2 backend.
  47842. *
  47843. * @type {WebGLBackend}
  47844. */
  47845. this.backend = backend;
  47846. /**
  47847. * This value holds the cached max anisotropy value.
  47848. *
  47849. * @type {?number}
  47850. * @default null
  47851. */
  47852. this.maxAnisotropy = null;
  47853. }
  47854. /**
  47855. * Returns the maximum anisotropy texture filtering value. This value
  47856. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  47857. * WebGL extension.
  47858. *
  47859. * @return {number} The maximum anisotropy texture filtering value.
  47860. */
  47861. getMaxAnisotropy() {
  47862. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  47863. const gl = this.backend.gl;
  47864. const extensions = this.backend.extensions;
  47865. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  47866. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  47867. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  47868. } else {
  47869. this.maxAnisotropy = 0;
  47870. }
  47871. return this.maxAnisotropy;
  47872. }
  47873. }
  47874. const GLFeatureName = {
  47875. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  47876. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  47877. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  47878. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  47879. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  47880. 'WEBGL_compressed_texture_s3tc': 'texture-compression-s3tc',
  47881. 'EXT_texture_compression_bptc': 'texture-compression-bc',
  47882. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  47883. 'OVR_multiview2': 'OVR_multiview2'
  47884. };
  47885. class WebGLBufferRenderer {
  47886. constructor( backend ) {
  47887. this.gl = backend.gl;
  47888. this.extensions = backend.extensions;
  47889. this.info = backend.renderer.info;
  47890. this.mode = null;
  47891. this.index = 0;
  47892. this.type = null;
  47893. this.object = null;
  47894. }
  47895. render( start, count ) {
  47896. const { gl, mode, object, type, info, index } = this;
  47897. if ( index !== 0 ) {
  47898. gl.drawElements( mode, count, type, start );
  47899. } else {
  47900. gl.drawArrays( mode, start, count );
  47901. }
  47902. info.update( object, count, 1 );
  47903. }
  47904. renderInstances( start, count, primcount ) {
  47905. const { gl, mode, type, index, object, info } = this;
  47906. if ( primcount === 0 ) return;
  47907. if ( index !== 0 ) {
  47908. gl.drawElementsInstanced( mode, count, type, start, primcount );
  47909. } else {
  47910. gl.drawArraysInstanced( mode, start, count, primcount );
  47911. }
  47912. info.update( object, count, primcount );
  47913. }
  47914. renderMultiDraw( starts, counts, drawCount ) {
  47915. const { extensions, mode, object, info } = this;
  47916. if ( drawCount === 0 ) return;
  47917. const extension = extensions.get( 'WEBGL_multi_draw' );
  47918. if ( extension === null ) {
  47919. for ( let i = 0; i < drawCount; i ++ ) {
  47920. this.render( starts[ i ], counts[ i ] );
  47921. }
  47922. } else {
  47923. if ( this.index !== 0 ) {
  47924. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  47925. } else {
  47926. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  47927. }
  47928. let elementCount = 0;
  47929. for ( let i = 0; i < drawCount; i ++ ) {
  47930. elementCount += counts[ i ];
  47931. }
  47932. info.update( object, elementCount, 1 );
  47933. }
  47934. }
  47935. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  47936. const { extensions, mode, object, info } = this;
  47937. if ( drawCount === 0 ) return;
  47938. const extension = extensions.get( 'WEBGL_multi_draw' );
  47939. if ( extension === null ) {
  47940. for ( let i = 0; i < drawCount; i ++ ) {
  47941. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  47942. }
  47943. } else {
  47944. if ( this.index !== 0 ) {
  47945. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  47946. } else {
  47947. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  47948. }
  47949. let elementCount = 0;
  47950. for ( let i = 0; i < drawCount; i ++ ) {
  47951. elementCount += counts[ i ] * primcount[ i ];
  47952. }
  47953. info.update( object, elementCount, 1 );
  47954. }
  47955. }
  47956. //
  47957. }
  47958. /**
  47959. * Abstract base class of a timestamp query pool.
  47960. *
  47961. * @abstract
  47962. */
  47963. class TimestampQueryPool {
  47964. /**
  47965. * Creates a new timestamp query pool.
  47966. *
  47967. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  47968. */
  47969. constructor( maxQueries = 256 ) {
  47970. /**
  47971. * Whether to track timestamps or not.
  47972. *
  47973. * @type {boolean}
  47974. * @default true
  47975. */
  47976. this.trackTimestamp = true;
  47977. /**
  47978. * Maximum number of queries this pool can hold.
  47979. *
  47980. * @type {number}
  47981. * @default 256
  47982. */
  47983. this.maxQueries = maxQueries;
  47984. /**
  47985. * How many queries allocated so far.
  47986. *
  47987. * @type {number}
  47988. * @default 0
  47989. */
  47990. this.currentQueryIndex = 0;
  47991. /**
  47992. * Tracks offsets for different contexts.
  47993. *
  47994. * @type {Map<string, number>}
  47995. */
  47996. this.queryOffsets = new Map();
  47997. /**
  47998. * Whether the pool has been disposed or not.
  47999. *
  48000. * @type {boolean}
  48001. * @default false
  48002. */
  48003. this.isDisposed = false;
  48004. /**
  48005. * TODO
  48006. *
  48007. * @type {number}
  48008. * @default 0
  48009. */
  48010. this.lastValue = 0;
  48011. /**
  48012. * Stores all timestamp frames.
  48013. *
  48014. * @type {Array<number>}
  48015. */
  48016. this.frames = [];
  48017. /**
  48018. * TODO
  48019. *
  48020. * @type {boolean}
  48021. * @default false
  48022. */
  48023. this.pendingResolve = false;
  48024. /**
  48025. * Stores the latest timestamp for each render context.
  48026. *
  48027. * @type {Map<string, number>}
  48028. */
  48029. this.timestamps = new Map();
  48030. }
  48031. /**
  48032. * Returns all timestamp frames.
  48033. *
  48034. * @return {Array<number>} The timestamp frames.
  48035. */
  48036. getTimestampFrames() {
  48037. return this.frames;
  48038. }
  48039. /**
  48040. * Returns the timestamp for a given render context.
  48041. *
  48042. * @param {string} uid - A unique identifier for the render context.
  48043. * @return {?number} The timestamp, or undefined if not available.
  48044. */
  48045. getTimestamp( uid ) {
  48046. let timestamp = this.timestamps.get( uid );
  48047. if ( timestamp === undefined ) {
  48048. warn( `TimestampQueryPool: No timestamp available for uid ${ uid }.` );
  48049. timestamp = 0;
  48050. }
  48051. return timestamp;
  48052. }
  48053. /**
  48054. * Returns whether a timestamp is available for a given render context.
  48055. *
  48056. * @param {string} uid - A unique identifier for the render context.
  48057. * @return {boolean} True if a timestamp is available, false otherwise.
  48058. */
  48059. hasTimestamp( uid ) {
  48060. return this.timestamps.has( uid );
  48061. }
  48062. /**
  48063. * Allocate queries for a specific uid.
  48064. *
  48065. * @abstract
  48066. * @param {string} uid - A unique identifier for the render context.
  48067. * @param {number} frameId - The current frame identifier.
  48068. * @returns {?number}
  48069. */
  48070. allocateQueriesForContext( /* uid, frameId */ ) {}
  48071. /**
  48072. * Resolve all timestamps and return data (or process them).
  48073. *
  48074. * @abstract
  48075. * @async
  48076. * @returns {Promise<number>|number} The resolved timestamp value.
  48077. */
  48078. async resolveQueriesAsync() {}
  48079. /**
  48080. * Dispose of the query pool.
  48081. *
  48082. * @abstract
  48083. */
  48084. dispose() {}
  48085. }
  48086. /**
  48087. * Manages a pool of WebGL timestamp queries for performance measurement.
  48088. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  48089. *
  48090. * @augments TimestampQueryPool
  48091. */
  48092. class WebGLTimestampQueryPool extends TimestampQueryPool {
  48093. /**
  48094. * Creates a new WebGL timestamp query pool.
  48095. *
  48096. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  48097. * @param {string} type - The type identifier for this query pool.
  48098. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  48099. */
  48100. constructor( gl, type, maxQueries = 2048 ) {
  48101. super( maxQueries );
  48102. this.gl = gl;
  48103. this.type = type;
  48104. // Check for timer query extensions
  48105. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  48106. gl.getExtension( 'EXT_disjoint_timer_query' );
  48107. if ( ! this.ext ) {
  48108. warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  48109. this.trackTimestamp = false;
  48110. return;
  48111. }
  48112. // Create query objects
  48113. this.queries = [];
  48114. for ( let i = 0; i < this.maxQueries; i ++ ) {
  48115. this.queries.push( gl.createQuery() );
  48116. }
  48117. this.activeQuery = null;
  48118. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  48119. }
  48120. /**
  48121. * Allocates a pair of queries for a given render context.
  48122. *
  48123. * @param {string} uid - A unique identifier for the render context.
  48124. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  48125. */
  48126. allocateQueriesForContext( uid ) {
  48127. if ( ! this.trackTimestamp ) return null;
  48128. // Check if we have enough space for a new query pair
  48129. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  48130. 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() } ).` );
  48131. return null;
  48132. }
  48133. const baseOffset = this.currentQueryIndex;
  48134. this.currentQueryIndex += 2;
  48135. // Initialize query states
  48136. this.queryStates.set( baseOffset, 'inactive' );
  48137. this.queryOffsets.set( uid, baseOffset );
  48138. return baseOffset;
  48139. }
  48140. /**
  48141. * Begins a timestamp query for the specified render context.
  48142. *
  48143. * @param {string} uid - A unique identifier for the render context.
  48144. */
  48145. beginQuery( uid ) {
  48146. if ( ! this.trackTimestamp || this.isDisposed ) {
  48147. return;
  48148. }
  48149. const baseOffset = this.queryOffsets.get( uid );
  48150. if ( baseOffset == null ) {
  48151. return;
  48152. }
  48153. // Don't start a new query if there's an active one
  48154. if ( this.activeQuery !== null ) {
  48155. return;
  48156. }
  48157. const query = this.queries[ baseOffset ];
  48158. if ( ! query ) {
  48159. return;
  48160. }
  48161. try {
  48162. // Only begin if query is inactive
  48163. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  48164. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  48165. this.activeQuery = baseOffset;
  48166. this.queryStates.set( baseOffset, 'started' );
  48167. }
  48168. } catch ( e ) {
  48169. error( 'Error in beginQuery:', e );
  48170. this.activeQuery = null;
  48171. this.queryStates.set( baseOffset, 'inactive' );
  48172. }
  48173. }
  48174. /**
  48175. * Ends the active timestamp query for the specified render context.
  48176. *
  48177. * @param {string} uid - A unique identifier for the render context.
  48178. */
  48179. endQuery( uid ) {
  48180. if ( ! this.trackTimestamp || this.isDisposed ) {
  48181. return;
  48182. }
  48183. const baseOffset = this.queryOffsets.get( uid );
  48184. if ( baseOffset == null ) {
  48185. return;
  48186. }
  48187. // Only end if this is the active query
  48188. if ( this.activeQuery !== baseOffset ) {
  48189. return;
  48190. }
  48191. try {
  48192. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  48193. this.queryStates.set( baseOffset, 'ended' );
  48194. this.activeQuery = null;
  48195. } catch ( e ) {
  48196. error( 'Error in endQuery:', e );
  48197. // Reset state on error
  48198. this.queryStates.set( baseOffset, 'inactive' );
  48199. this.activeQuery = null;
  48200. }
  48201. }
  48202. /**
  48203. * Asynchronously resolves all completed queries and returns the total duration.
  48204. *
  48205. * @async
  48206. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  48207. */
  48208. async resolveQueriesAsync() {
  48209. if ( ! this.trackTimestamp || this.pendingResolve ) {
  48210. return this.lastValue;
  48211. }
  48212. this.pendingResolve = true;
  48213. try {
  48214. // Wait for all ended queries to complete
  48215. const resolvePromises = new Map();
  48216. for ( const [ uid, baseOffset ] of this.queryOffsets ) {
  48217. const state = this.queryStates.get( baseOffset );
  48218. if ( state === 'ended' ) {
  48219. const query = this.queries[ baseOffset ];
  48220. resolvePromises.set( uid, this.resolveQuery( query ) );
  48221. }
  48222. }
  48223. if ( resolvePromises.size === 0 ) {
  48224. return this.lastValue;
  48225. }
  48226. //
  48227. const framesDuration = {};
  48228. const frames = [];
  48229. for ( const [ uid, promise ] of resolvePromises ) {
  48230. const match = uid.match( /^(.*):f(\d+)$/ );
  48231. const frame = parseInt( match[ 2 ] );
  48232. if ( frames.includes( frame ) === false ) {
  48233. frames.push( frame );
  48234. }
  48235. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  48236. const duration = await promise;
  48237. this.timestamps.set( uid, duration );
  48238. framesDuration[ frame ] += duration;
  48239. }
  48240. // Return the total duration of the last frame
  48241. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  48242. // Store the last valid result
  48243. this.lastValue = totalDuration;
  48244. this.frames = frames;
  48245. // Reset states
  48246. this.currentQueryIndex = 0;
  48247. this.queryOffsets.clear();
  48248. this.queryStates.clear();
  48249. this.activeQuery = null;
  48250. return totalDuration;
  48251. } catch ( e ) {
  48252. error( 'Error resolving queries:', e );
  48253. return this.lastValue;
  48254. } finally {
  48255. this.pendingResolve = false;
  48256. }
  48257. }
  48258. /**
  48259. * Resolves a single query, checking for completion and disjoint operation.
  48260. *
  48261. * @async
  48262. * @param {WebGLQuery} query - The query object to resolve.
  48263. * @returns {Promise<number>} The elapsed time in milliseconds.
  48264. */
  48265. async resolveQuery( query ) {
  48266. return new Promise( ( resolve ) => {
  48267. if ( this.isDisposed ) {
  48268. resolve( this.lastValue );
  48269. return;
  48270. }
  48271. let timeoutId;
  48272. let isResolved = false;
  48273. const cleanup = () => {
  48274. if ( timeoutId ) {
  48275. clearTimeout( timeoutId );
  48276. timeoutId = null;
  48277. }
  48278. };
  48279. const finalizeResolution = ( value ) => {
  48280. if ( ! isResolved ) {
  48281. isResolved = true;
  48282. cleanup();
  48283. resolve( value );
  48284. }
  48285. };
  48286. const checkQuery = () => {
  48287. if ( this.isDisposed ) {
  48288. finalizeResolution( this.lastValue );
  48289. return;
  48290. }
  48291. try {
  48292. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  48293. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  48294. if ( disjoint ) {
  48295. finalizeResolution( this.lastValue );
  48296. return;
  48297. }
  48298. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  48299. if ( ! available ) {
  48300. timeoutId = setTimeout( checkQuery, 1 );
  48301. return;
  48302. }
  48303. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  48304. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  48305. } catch ( e ) {
  48306. error( 'Error checking query:', e );
  48307. resolve( this.lastValue );
  48308. }
  48309. };
  48310. checkQuery();
  48311. } );
  48312. }
  48313. /**
  48314. * Releases all resources held by this query pool.
  48315. * This includes deleting all query objects and clearing internal state.
  48316. */
  48317. dispose() {
  48318. if ( this.isDisposed ) {
  48319. return;
  48320. }
  48321. this.isDisposed = true;
  48322. if ( ! this.trackTimestamp ) return;
  48323. for ( const query of this.queries ) {
  48324. this.gl.deleteQuery( query );
  48325. }
  48326. this.queries = [];
  48327. this.queryStates.clear();
  48328. this.queryOffsets.clear();
  48329. this.lastValue = 0;
  48330. this.activeQuery = null;
  48331. }
  48332. }
  48333. /**
  48334. * A backend implementation targeting WebGL 2.
  48335. *
  48336. * @private
  48337. * @augments Backend
  48338. */
  48339. class WebGLBackend extends Backend {
  48340. /**
  48341. * WebGLBackend options.
  48342. *
  48343. * @typedef {Object} WebGLBackend~Options
  48344. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  48345. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  48346. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  48347. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  48348. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  48349. * @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.
  48350. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  48351. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  48352. */
  48353. /**
  48354. * Constructs a new WebGPU backend.
  48355. *
  48356. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  48357. */
  48358. constructor( parameters = {} ) {
  48359. super( parameters );
  48360. /**
  48361. * This flag can be used for type testing.
  48362. *
  48363. * @type {boolean}
  48364. * @readonly
  48365. * @default true
  48366. */
  48367. this.isWebGLBackend = true;
  48368. /**
  48369. * A reference to a backend module holding shader attribute-related
  48370. * utility functions.
  48371. *
  48372. * @type {?WebGLAttributeUtils}
  48373. * @default null
  48374. */
  48375. this.attributeUtils = null;
  48376. /**
  48377. * A reference to a backend module holding extension-related
  48378. * utility functions.
  48379. *
  48380. * @type {?WebGLExtensions}
  48381. * @default null
  48382. */
  48383. this.extensions = null;
  48384. /**
  48385. * A reference to a backend module holding capability-related
  48386. * utility functions.
  48387. *
  48388. * @type {?WebGLCapabilities}
  48389. * @default null
  48390. */
  48391. this.capabilities = null;
  48392. /**
  48393. * A reference to a backend module holding texture-related
  48394. * utility functions.
  48395. *
  48396. * @type {?WebGLTextureUtils}
  48397. * @default null
  48398. */
  48399. this.textureUtils = null;
  48400. /**
  48401. * A reference to a backend module holding renderer-related
  48402. * utility functions.
  48403. *
  48404. * @type {?WebGLBufferRenderer}
  48405. * @default null
  48406. */
  48407. this.bufferRenderer = null;
  48408. /**
  48409. * A reference to the rendering context.
  48410. *
  48411. * @type {?WebGL2RenderingContext}
  48412. * @default null
  48413. */
  48414. this.gl = null;
  48415. /**
  48416. * A reference to a backend module holding state-related
  48417. * utility functions.
  48418. *
  48419. * @type {?WebGLState}
  48420. * @default null
  48421. */
  48422. this.state = null;
  48423. /**
  48424. * A reference to a backend module holding common
  48425. * utility functions.
  48426. *
  48427. * @type {?WebGLUtils}
  48428. * @default null
  48429. */
  48430. this.utils = null;
  48431. /**
  48432. * Dictionary for caching VAOs.
  48433. *
  48434. * @type {Object<string,WebGLVertexArrayObject>}
  48435. */
  48436. this.vaoCache = {};
  48437. /**
  48438. * Dictionary for caching transform feedback objects.
  48439. *
  48440. * @type {Object<string,WebGLTransformFeedback>}
  48441. */
  48442. this.transformFeedbackCache = {};
  48443. /**
  48444. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  48445. * Only relevant when using compute shaders.
  48446. *
  48447. * @type {boolean}
  48448. * @default false
  48449. */
  48450. this.discard = false;
  48451. /**
  48452. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  48453. * device does not support the extension.
  48454. *
  48455. * @type {?EXTDisjointTimerQueryWebGL2}
  48456. * @default null
  48457. */
  48458. this.disjoint = null;
  48459. /**
  48460. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  48461. * device does not support the extension.
  48462. *
  48463. * @type {?KHRParallelShaderCompile}
  48464. * @default null
  48465. */
  48466. this.parallel = null;
  48467. /**
  48468. * A reference to the current render context.
  48469. *
  48470. * @private
  48471. * @type {RenderContext}
  48472. * @default null
  48473. */
  48474. this._currentContext = null;
  48475. /**
  48476. * A unique collection of bindings.
  48477. *
  48478. * @private
  48479. * @type {WeakSet<Array<BindGroup>>}
  48480. */
  48481. this._knownBindings = new WeakSet();
  48482. /**
  48483. * Whether the device supports framebuffers invalidation or not.
  48484. *
  48485. * @private
  48486. * @type {boolean}
  48487. */
  48488. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  48489. /**
  48490. * The target framebuffer when rendering with
  48491. * the WebXR device API.
  48492. *
  48493. * @private
  48494. * @type {?WebGLFramebuffer}
  48495. * @default null
  48496. */
  48497. this._xrFramebuffer = null;
  48498. }
  48499. /**
  48500. * Initializes the backend so it is ready for usage.
  48501. *
  48502. * @param {Renderer} renderer - The renderer.
  48503. */
  48504. init( renderer ) {
  48505. super.init( renderer );
  48506. //
  48507. const parameters = this.parameters;
  48508. const contextAttributes = {
  48509. antialias: renderer.currentSamples > 0,
  48510. alpha: true, // always true for performance reasons
  48511. depth: renderer.depth,
  48512. stencil: renderer.stencil
  48513. };
  48514. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  48515. function onContextLost( event ) {
  48516. event.preventDefault();
  48517. const contextLossInfo = {
  48518. api: 'WebGL',
  48519. message: event.statusMessage || 'Unknown reason',
  48520. reason: null,
  48521. originalEvent: event
  48522. };
  48523. renderer.onDeviceLost( contextLossInfo );
  48524. }
  48525. this._onContextLost = onContextLost;
  48526. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  48527. this.gl = glContext;
  48528. this.extensions = new WebGLExtensions( this );
  48529. this.capabilities = new WebGLCapabilities( this );
  48530. this.attributeUtils = new WebGLAttributeUtils( this );
  48531. this.textureUtils = new WebGLTextureUtils( this );
  48532. this.bufferRenderer = new WebGLBufferRenderer( this );
  48533. this.state = new WebGLState( this );
  48534. this.utils = new WebGLUtils( this );
  48535. this.extensions.get( 'EXT_color_buffer_float' );
  48536. this.extensions.get( 'WEBGL_clip_cull_distance' );
  48537. this.extensions.get( 'OES_texture_float_linear' );
  48538. this.extensions.get( 'EXT_color_buffer_half_float' );
  48539. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  48540. this.extensions.get( 'WEBGL_render_shared_exponent' );
  48541. this.extensions.get( 'WEBGL_multi_draw' );
  48542. this.extensions.get( 'OVR_multiview2' );
  48543. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  48544. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  48545. this.drawBuffersIndexedExt = this.extensions.get( 'OES_draw_buffers_indexed' );
  48546. }
  48547. /**
  48548. * The coordinate system of the backend.
  48549. *
  48550. * @type {number}
  48551. * @readonly
  48552. */
  48553. get coordinateSystem() {
  48554. return WebGLCoordinateSystem;
  48555. }
  48556. /**
  48557. * This method performs a readback operation by moving buffer data from
  48558. * a storage buffer attribute from the GPU to the CPU.
  48559. *
  48560. * @async
  48561. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  48562. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  48563. */
  48564. async getArrayBufferAsync( attribute ) {
  48565. return await this.attributeUtils.getArrayBufferAsync( attribute );
  48566. }
  48567. /**
  48568. * Ensures the backend is XR compatible.
  48569. *
  48570. * @async
  48571. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  48572. */
  48573. async makeXRCompatible() {
  48574. const attributes = this.gl.getContextAttributes();
  48575. if ( attributes.xrCompatible !== true ) {
  48576. await this.gl.makeXRCompatible();
  48577. }
  48578. }
  48579. /**
  48580. * Sets the XR rendering destination.
  48581. *
  48582. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  48583. */
  48584. setXRTarget( xrFramebuffer ) {
  48585. this._xrFramebuffer = xrFramebuffer;
  48586. }
  48587. /**
  48588. * Configures the given XR render target with external textures.
  48589. *
  48590. * This method is only relevant when using the WebXR Layers API.
  48591. *
  48592. * @param {XRRenderTarget} renderTarget - The XR render target.
  48593. * @param {WebGLTexture} colorTexture - A native color texture.
  48594. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  48595. */
  48596. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  48597. const gl = this.gl;
  48598. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  48599. if ( depthTexture !== null ) {
  48600. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  48601. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  48602. // The multisample_render_to_texture extension doesn't work properly if there
  48603. // are midframe flushes and an external depth texture.
  48604. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  48605. warn( 'WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  48606. }
  48607. renderTarget._autoAllocateDepthBuffer = false;
  48608. }
  48609. }
  48610. /**
  48611. * Inits a time stamp query for the given render context.
  48612. *
  48613. * @param {string} type - The type of the timestamp query.
  48614. * @param {string} uid - A unique identifier for the timestamp query.
  48615. */
  48616. initTimestampQuery( type, uid ) {
  48617. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  48618. if ( ! this.timestampQueryPool[ type ] ) {
  48619. // TODO: Variable maxQueries?
  48620. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  48621. }
  48622. const timestampQueryPool = this.timestampQueryPool[ type ];
  48623. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  48624. if ( baseOffset !== null ) {
  48625. timestampQueryPool.beginQuery( uid );
  48626. }
  48627. }
  48628. // timestamp utils
  48629. /**
  48630. * Prepares the timestamp buffer.
  48631. *
  48632. * @param {string} type - The type of the timestamp query.
  48633. * @param {string} uid - A unique identifier for the timestamp query.
  48634. */
  48635. prepareTimestampBuffer( type, uid ) {
  48636. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  48637. const timestampQueryPool = this.timestampQueryPool[ type ];
  48638. timestampQueryPool.endQuery( uid );
  48639. }
  48640. /**
  48641. * Returns the backend's rendering context.
  48642. *
  48643. * @return {WebGL2RenderingContext} The rendering context.
  48644. */
  48645. getContext() {
  48646. return this.gl;
  48647. }
  48648. /**
  48649. * This method is executed at the beginning of a render call and prepares
  48650. * the WebGL state for upcoming render calls
  48651. *
  48652. * @param {RenderContext} renderContext - The render context.
  48653. */
  48654. beginRender( renderContext ) {
  48655. const { state } = this;
  48656. const renderContextData = this.get( renderContext );
  48657. //
  48658. if ( renderContext.viewport ) {
  48659. this.updateViewport( renderContext );
  48660. } else {
  48661. const { width, height } = this.getDrawingBufferSize();
  48662. state.viewport( 0, 0, width, height );
  48663. }
  48664. if ( renderContext.scissor ) {
  48665. const { x, y, width, height } = renderContext.scissorValue;
  48666. state.scissor( x, renderContext.height - height - y, width, height );
  48667. }
  48668. //
  48669. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  48670. renderContextData.previousContext = this._currentContext;
  48671. this._currentContext = renderContext;
  48672. this._setFramebuffer( renderContext );
  48673. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  48674. const occlusionQueryCount = renderContext.occlusionQueryCount;
  48675. if ( occlusionQueryCount > 0 ) {
  48676. // Get a reference to the array of objects with queries. The renderContextData property
  48677. // can be changed by another render pass before the async reading of all previous queries complete
  48678. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  48679. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  48680. renderContextData.lastOcclusionObject = null;
  48681. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  48682. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  48683. renderContextData.occlusionQueryIndex = 0;
  48684. }
  48685. }
  48686. /**
  48687. * This method is executed at the end of a render call and finalizes work
  48688. * after draw calls.
  48689. *
  48690. * @param {RenderContext} renderContext - The render context.
  48691. */
  48692. finishRender( renderContext ) {
  48693. const { gl, state } = this;
  48694. const renderContextData = this.get( renderContext );
  48695. const previousContext = renderContextData.previousContext;
  48696. state.resetVertexState();
  48697. const occlusionQueryCount = renderContext.occlusionQueryCount;
  48698. if ( occlusionQueryCount > 0 ) {
  48699. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  48700. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  48701. }
  48702. this.resolveOccludedAsync( renderContext );
  48703. }
  48704. const textures = renderContext.textures;
  48705. if ( textures !== null ) {
  48706. for ( let i = 0; i < textures.length; i ++ ) {
  48707. const texture = textures[ i ];
  48708. if ( texture.generateMipmaps ) {
  48709. this.generateMipmaps( texture );
  48710. }
  48711. }
  48712. }
  48713. this._currentContext = previousContext;
  48714. this._resolveRenderTarget( renderContext );
  48715. if ( previousContext !== null ) {
  48716. this._setFramebuffer( previousContext );
  48717. if ( previousContext.viewport ) {
  48718. this.updateViewport( previousContext );
  48719. } else {
  48720. const { width, height } = this.getDrawingBufferSize();
  48721. state.viewport( 0, 0, width, height );
  48722. }
  48723. }
  48724. this.prepareTimestampBuffer( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  48725. }
  48726. /**
  48727. * This method processes the result of occlusion queries and writes it
  48728. * into render context data.
  48729. *
  48730. * @async
  48731. * @param {RenderContext} renderContext - The render context.
  48732. */
  48733. resolveOccludedAsync( renderContext ) {
  48734. const renderContextData = this.get( renderContext );
  48735. // handle occlusion query results
  48736. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  48737. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  48738. const occluded = new WeakSet();
  48739. const { gl } = this;
  48740. renderContextData.currentOcclusionQueryObjects = null;
  48741. renderContextData.currentOcclusionQueries = null;
  48742. const check = () => {
  48743. let completed = 0;
  48744. // check all queries and requeue as appropriate
  48745. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  48746. const query = currentOcclusionQueries[ i ];
  48747. if ( query === null ) continue;
  48748. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  48749. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  48750. currentOcclusionQueries[ i ] = null;
  48751. gl.deleteQuery( query );
  48752. completed ++;
  48753. }
  48754. }
  48755. if ( completed < currentOcclusionQueries.length ) {
  48756. requestAnimationFrame( check );
  48757. } else {
  48758. renderContextData.occluded = occluded;
  48759. }
  48760. };
  48761. check();
  48762. }
  48763. }
  48764. /**
  48765. * Returns `true` if the given 3D object is fully occluded by other
  48766. * 3D objects in the scene.
  48767. *
  48768. * @param {RenderContext} renderContext - The render context.
  48769. * @param {Object3D} object - The 3D object to test.
  48770. * @return {boolean} Whether the 3D object is fully occluded or not.
  48771. */
  48772. isOccluded( renderContext, object ) {
  48773. const renderContextData = this.get( renderContext );
  48774. return renderContextData.occluded && renderContextData.occluded.has( object );
  48775. }
  48776. /**
  48777. * Updates the viewport with the values from the given render context.
  48778. *
  48779. * @param {RenderContext} renderContext - The render context.
  48780. */
  48781. updateViewport( renderContext ) {
  48782. const { state } = this;
  48783. const { x, y, width, height } = renderContext.viewportValue;
  48784. state.viewport( x, renderContext.height - height - y, width, height );
  48785. }
  48786. /**
  48787. * Defines the scissor test.
  48788. *
  48789. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  48790. */
  48791. setScissorTest( boolean ) {
  48792. const state = this.state;
  48793. state.setScissorTest( boolean );
  48794. }
  48795. /**
  48796. * Returns the clear color and alpha into a single
  48797. * color object.
  48798. *
  48799. * @return {Color4} The clear color.
  48800. */
  48801. getClearColor() {
  48802. const clearColor = super.getClearColor();
  48803. // Since the canvas is always created with alpha: true,
  48804. // WebGL must always premultiply the clear color.
  48805. clearColor.r *= clearColor.a;
  48806. clearColor.g *= clearColor.a;
  48807. clearColor.b *= clearColor.a;
  48808. return clearColor;
  48809. }
  48810. /**
  48811. * Performs a clear operation.
  48812. *
  48813. * @param {boolean} color - Whether the color buffer should be cleared or not.
  48814. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  48815. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  48816. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  48817. * @param {boolean} [setFrameBuffer=true] - Controls whether the intermediate framebuffer should be set or not.
  48818. * @param {boolean} [resolveRenderTarget=true] - Controls whether an active render target should be resolved
  48819. * or not. Only relevant for explicit clears.
  48820. */
  48821. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true, resolveRenderTarget = true ) {
  48822. const { gl, renderer } = this;
  48823. if ( descriptor === null ) {
  48824. const clearColor = this.getClearColor();
  48825. descriptor = {
  48826. textures: null,
  48827. clearColorValue: clearColor
  48828. };
  48829. }
  48830. //
  48831. let clear = 0;
  48832. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  48833. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  48834. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  48835. if ( clear !== 0 ) {
  48836. let clearColor;
  48837. if ( descriptor.clearColorValue ) {
  48838. clearColor = descriptor.clearColorValue;
  48839. } else {
  48840. clearColor = this.getClearColor();
  48841. }
  48842. const clearDepth = renderer.getClearDepth();
  48843. const clearStencil = renderer.getClearStencil();
  48844. if ( depth ) this.state.setDepthMask( true );
  48845. if ( descriptor.textures === null ) {
  48846. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  48847. gl.clear( clear );
  48848. } else {
  48849. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  48850. if ( color ) {
  48851. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  48852. if ( i === 0 ) {
  48853. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  48854. } else {
  48855. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  48856. }
  48857. }
  48858. }
  48859. if ( depth && stencil ) {
  48860. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  48861. } else if ( depth ) {
  48862. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  48863. } else if ( stencil ) {
  48864. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  48865. }
  48866. if ( setFrameBuffer && resolveRenderTarget ) this._resolveRenderTarget( descriptor );
  48867. }
  48868. }
  48869. }
  48870. /**
  48871. * This method is executed at the beginning of a compute call and
  48872. * prepares the state for upcoming compute tasks.
  48873. *
  48874. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  48875. */
  48876. beginCompute( computeGroup ) {
  48877. const { state, gl } = this;
  48878. //
  48879. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  48880. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  48881. }
  48882. /**
  48883. * Executes a compute command for the given compute node.
  48884. *
  48885. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  48886. * @param {Node} computeNode - The compute node.
  48887. * @param {Array<BindGroup>} bindings - The bindings.
  48888. * @param {ComputePipeline} pipeline - The compute pipeline.
  48889. * @param {?number} [count=null] - The count of compute invocations. If `null`, the count is determined by the compute node.
  48890. */
  48891. compute( computeGroup, computeNode, bindings, pipeline, count = null ) {
  48892. const { state, gl } = this;
  48893. if ( this.discard === false ) {
  48894. // required here to handle async behaviour of render.compute()
  48895. gl.enable( gl.RASTERIZER_DISCARD );
  48896. this.discard = true;
  48897. }
  48898. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  48899. const vaoKey = this._getVaoKey( attributes );
  48900. const vaoGPU = this.vaoCache[ vaoKey ];
  48901. if ( vaoGPU === undefined ) {
  48902. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  48903. } else {
  48904. state.setVertexState( vaoGPU );
  48905. }
  48906. state.useProgram( programGPU );
  48907. this._bindUniforms( bindings );
  48908. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  48909. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  48910. gl.beginTransformFeedback( gl.POINTS );
  48911. count = ( count !== null ) ? count : computeNode.count;
  48912. if ( Array.isArray( count ) ) {
  48913. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not an array.' );
  48914. count = count[ 0 ];
  48915. } else if ( count && typeof count === 'object' && count.isIndirectStorageBufferAttribute ) {
  48916. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute' );
  48917. count = computeNode.count;
  48918. }
  48919. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  48920. gl.drawArraysInstanced( gl.POINTS, 0, 1, count );
  48921. } else {
  48922. gl.drawArrays( gl.POINTS, 0, count );
  48923. }
  48924. gl.endTransformFeedback();
  48925. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  48926. // switch active buffers
  48927. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  48928. const dualAttributeData = transformBuffers[ i ];
  48929. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  48930. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  48931. }
  48932. dualAttributeData.switchBuffers();
  48933. }
  48934. }
  48935. /**
  48936. * This method is executed at the end of a compute call and
  48937. * finalizes work after compute tasks.
  48938. *
  48939. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  48940. */
  48941. finishCompute( computeGroup ) {
  48942. const gl = this.gl;
  48943. this.discard = false;
  48944. gl.disable( gl.RASTERIZER_DISCARD );
  48945. this.prepareTimestampBuffer( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  48946. if ( this._currentContext ) {
  48947. this._setFramebuffer( this._currentContext );
  48948. }
  48949. }
  48950. /**
  48951. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  48952. *
  48953. * @param {RenderContext} renderContext - The render context.
  48954. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  48955. *
  48956. * @private
  48957. */
  48958. _isRenderCameraDepthArray( renderContext ) {
  48959. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  48960. }
  48961. /**
  48962. * Executes a draw command for the given render object.
  48963. *
  48964. * @param {RenderObject} renderObject - The render object to draw.
  48965. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  48966. */
  48967. draw( renderObject/*, info*/ ) {
  48968. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  48969. const { programGPU } = this.get( pipeline );
  48970. const { gl, state } = this;
  48971. const contextData = this.get( context );
  48972. const drawParams = renderObject.getDrawParameters();
  48973. if ( drawParams === null ) return;
  48974. //
  48975. this._bindUniforms( renderObject.getBindings() );
  48976. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  48977. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  48978. if ( context.textures !== null && context.textures.length > 1 ) {
  48979. state.setMRTBlending( context.textures );
  48980. }
  48981. state.useProgram( programGPU );
  48982. // vertex state
  48983. const attributes = renderObject.getAttributes();
  48984. const attributesData = this.get( attributes );
  48985. let vaoGPU = attributesData.vaoGPU;
  48986. if ( vaoGPU === undefined ) {
  48987. const vaoKey = this._getVaoKey( attributes );
  48988. vaoGPU = this.vaoCache[ vaoKey ];
  48989. if ( vaoGPU === undefined ) {
  48990. vaoGPU = this._createVao( attributes );
  48991. this.vaoCache[ vaoKey ] = vaoGPU;
  48992. attributesData.vaoGPU = vaoGPU;
  48993. }
  48994. }
  48995. const index = renderObject.getIndex();
  48996. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  48997. state.setVertexState( vaoGPU, indexGPU );
  48998. //
  48999. const lastObject = contextData.lastOcclusionObject;
  49000. if ( lastObject !== object && lastObject !== undefined ) {
  49001. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  49002. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  49003. contextData.occlusionQueryIndex ++;
  49004. }
  49005. if ( object.occlusionTest === true ) {
  49006. const query = gl.createQuery();
  49007. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  49008. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  49009. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  49010. }
  49011. contextData.lastOcclusionObject = object;
  49012. }
  49013. //
  49014. const renderer = this.bufferRenderer;
  49015. if ( object.isPoints ) renderer.mode = gl.POINTS;
  49016. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  49017. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  49018. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  49019. else {
  49020. if ( material.wireframe === true ) {
  49021. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  49022. renderer.mode = gl.LINES;
  49023. } else {
  49024. renderer.mode = gl.TRIANGLES;
  49025. }
  49026. }
  49027. //
  49028. const { vertexCount, instanceCount } = drawParams;
  49029. let { firstVertex } = drawParams;
  49030. renderer.object = object;
  49031. if ( index !== null ) {
  49032. firstVertex *= index.array.BYTES_PER_ELEMENT;
  49033. const indexData = this.get( index );
  49034. renderer.index = index.count;
  49035. renderer.type = indexData.type;
  49036. } else {
  49037. renderer.index = 0;
  49038. }
  49039. const draw = () => {
  49040. if ( object.isBatchedMesh ) {
  49041. if ( object._multiDrawInstances !== null ) {
  49042. // @deprecated, r174
  49043. warnOnce( 'WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  49044. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  49045. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  49046. warnOnce( 'WebGLBackend: WEBGL_multi_draw not supported.' );
  49047. } else {
  49048. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  49049. }
  49050. } else if ( instanceCount > 1 ) {
  49051. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  49052. } else {
  49053. renderer.render( firstVertex, vertexCount );
  49054. }
  49055. };
  49056. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  49057. const cameraData = this.get( renderObject.camera );
  49058. const cameras = renderObject.camera.cameras;
  49059. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  49060. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  49061. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  49062. const indexesGPU = [];
  49063. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  49064. const bufferGPU = gl.createBuffer();
  49065. data[ 0 ] = i;
  49066. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49067. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  49068. indexesGPU.push( bufferGPU );
  49069. }
  49070. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  49071. }
  49072. const cameraIndexData = this.get( cameraIndex );
  49073. const pixelRatio = this.renderer.getPixelRatio();
  49074. const renderTarget = this._currentContext.renderTarget;
  49075. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  49076. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  49077. if ( isRenderCameraDepthArray ) {
  49078. // Clear the depth texture
  49079. const textureData = this.get( renderTarget.depthTexture );
  49080. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  49081. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  49082. const { stencilBuffer } = renderTarget;
  49083. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  49084. this.renderer._activeCubeFace = i;
  49085. this._currentContext.activeCubeFace = i;
  49086. this._setFramebuffer( this._currentContext );
  49087. this.clear( false, true, stencilBuffer, this._currentContext, false, false );
  49088. }
  49089. this.renderer._activeCubeFace = prevActiveCubeFace;
  49090. this._currentContext.activeCubeFace = prevActiveCubeFace;
  49091. }
  49092. }
  49093. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  49094. const subCamera = cameras[ i ];
  49095. if ( object.layers.test( subCamera.layers ) ) {
  49096. if ( isRenderCameraDepthArray ) {
  49097. // Update the active layer
  49098. this.renderer._activeCubeFace = i;
  49099. this._currentContext.activeCubeFace = i;
  49100. this._setFramebuffer( this._currentContext );
  49101. }
  49102. const vp = subCamera.viewport;
  49103. if ( vp !== undefined ) {
  49104. const x = vp.x * pixelRatio;
  49105. const y = vp.y * pixelRatio;
  49106. const width = vp.width * pixelRatio;
  49107. const height = vp.height * pixelRatio;
  49108. state.viewport(
  49109. Math.floor( x ),
  49110. Math.floor( renderObject.context.height - height - y ),
  49111. Math.floor( width ),
  49112. Math.floor( height )
  49113. );
  49114. }
  49115. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  49116. draw();
  49117. }
  49118. this._currentContext.activeCubeFace = prevActiveCubeFace;
  49119. this.renderer._activeCubeFace = prevActiveCubeFace;
  49120. }
  49121. } else {
  49122. draw();
  49123. }
  49124. }
  49125. /**
  49126. * Explain why always null is returned.
  49127. *
  49128. * @param {RenderObject} renderObject - The render object.
  49129. * @return {boolean} Whether the render pipeline requires an update or not.
  49130. */
  49131. needsRenderUpdate( /*renderObject*/ ) {
  49132. return false;
  49133. }
  49134. /**
  49135. * Explain why no cache key is computed.
  49136. *
  49137. * @param {RenderObject} renderObject - The render object.
  49138. * @return {string} The cache key.
  49139. */
  49140. getRenderCacheKey( /*renderObject*/ ) {
  49141. return '';
  49142. }
  49143. // textures
  49144. /**
  49145. * Creates a default texture for the given texture that can be used
  49146. * as a placeholder until the actual texture is ready for usage.
  49147. *
  49148. * @param {Texture} texture - The texture to create a default texture for.
  49149. */
  49150. createDefaultTexture( texture ) {
  49151. this.textureUtils.createDefaultTexture( texture );
  49152. }
  49153. /**
  49154. * Defines a texture on the GPU for the given texture object.
  49155. *
  49156. * @param {Texture} texture - The texture.
  49157. * @param {Object} [options={}] - Optional configuration parameter.
  49158. */
  49159. createTexture( texture, options ) {
  49160. this.textureUtils.createTexture( texture, options );
  49161. }
  49162. /**
  49163. * Uploads the updated texture data to the GPU.
  49164. *
  49165. * @param {Texture} texture - The texture.
  49166. * @param {Object} [options={}] - Optional configuration parameter.
  49167. */
  49168. updateTexture( texture, options ) {
  49169. this.textureUtils.updateTexture( texture, options );
  49170. }
  49171. /**
  49172. * Generates mipmaps for the given texture.
  49173. *
  49174. * @param {Texture} texture - The texture.
  49175. */
  49176. generateMipmaps( texture ) {
  49177. this.textureUtils.generateMipmaps( texture );
  49178. }
  49179. /**
  49180. * Destroys the GPU data for the given texture object.
  49181. *
  49182. * @param {Texture} texture - The texture.
  49183. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  49184. */
  49185. destroyTexture( texture, isDefaultTexture = false ) {
  49186. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  49187. }
  49188. /**
  49189. * Returns texture data as a typed array.
  49190. *
  49191. * @async
  49192. * @param {Texture} texture - The texture to copy.
  49193. * @param {number} x - The x coordinate of the copy origin.
  49194. * @param {number} y - The y coordinate of the copy origin.
  49195. * @param {number} width - The width of the copy.
  49196. * @param {number} height - The height of the copy.
  49197. * @param {number} faceIndex - The face index.
  49198. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  49199. */
  49200. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  49201. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  49202. }
  49203. /**
  49204. * This method does nothing since WebGL 2 has no concept of samplers.
  49205. *
  49206. * @param {Texture} texture - The texture to update the sampler for.
  49207. * @return {string} The current sampler key.
  49208. */
  49209. updateSampler( /*texture*/ ) {
  49210. return '';
  49211. }
  49212. // node builder
  49213. /**
  49214. * Returns a node builder for the given render object.
  49215. *
  49216. * @param {RenderObject} object - The render object.
  49217. * @param {Renderer} renderer - The renderer.
  49218. * @return {GLSLNodeBuilder} The node builder.
  49219. */
  49220. createNodeBuilder( object, renderer ) {
  49221. return new GLSLNodeBuilder( object, renderer );
  49222. }
  49223. // program
  49224. /**
  49225. * Creates a shader program from the given programmable stage.
  49226. *
  49227. * @param {ProgrammableStage} program - The programmable stage.
  49228. */
  49229. createProgram( program ) {
  49230. const gl = this.gl;
  49231. const { stage, code } = program;
  49232. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  49233. gl.shaderSource( shader, code );
  49234. gl.compileShader( shader );
  49235. this.set( program, {
  49236. shaderGPU: shader
  49237. } );
  49238. }
  49239. /**
  49240. * Destroys the shader program of the given programmable stage.
  49241. *
  49242. * @param {ProgrammableStage} program - The programmable stage.
  49243. */
  49244. destroyProgram( program ) {
  49245. this.delete( program );
  49246. }
  49247. /**
  49248. * Creates a render pipeline for the given render object.
  49249. *
  49250. * @param {RenderObject} renderObject - The render object.
  49251. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  49252. */
  49253. createRenderPipeline( renderObject, promises ) {
  49254. const gl = this.gl;
  49255. const pipeline = renderObject.pipeline;
  49256. // Program
  49257. const { fragmentProgram, vertexProgram } = pipeline;
  49258. const programGPU = gl.createProgram();
  49259. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  49260. const vertexShader = this.get( vertexProgram ).shaderGPU;
  49261. gl.attachShader( programGPU, fragmentShader );
  49262. gl.attachShader( programGPU, vertexShader );
  49263. gl.linkProgram( programGPU );
  49264. this.set( pipeline, {
  49265. programGPU,
  49266. fragmentShader,
  49267. vertexShader
  49268. } );
  49269. if ( promises !== null && this.parallel ) {
  49270. const p = new Promise( ( resolve /*, reject*/ ) => {
  49271. const parallel = this.parallel;
  49272. const checkStatus = () => {
  49273. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  49274. this._completeCompile( renderObject, pipeline );
  49275. resolve();
  49276. } else {
  49277. requestAnimationFrame( checkStatus );
  49278. }
  49279. };
  49280. checkStatus();
  49281. } );
  49282. promises.push( p );
  49283. return;
  49284. }
  49285. this._completeCompile( renderObject, pipeline );
  49286. }
  49287. /**
  49288. * Formats the source code of error messages.
  49289. *
  49290. * @private
  49291. * @param {string} string - The code.
  49292. * @param {number} errorLine - The error line.
  49293. * @return {string} The formatted code.
  49294. */
  49295. _handleSource( string, errorLine ) {
  49296. const lines = string.split( '\n' );
  49297. const lines2 = [];
  49298. const from = Math.max( errorLine - 6, 0 );
  49299. const to = Math.min( errorLine + 6, lines.length );
  49300. for ( let i = from; i < to; i ++ ) {
  49301. const line = i + 1;
  49302. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  49303. }
  49304. return lines2.join( '\n' );
  49305. }
  49306. /**
  49307. * Gets the shader compilation errors from the info log.
  49308. *
  49309. * @private
  49310. * @param {WebGL2RenderingContext} gl - The rendering context.
  49311. * @param {WebGLShader} shader - The WebGL shader object.
  49312. * @param {string} type - The shader type.
  49313. * @return {string} The shader errors.
  49314. */
  49315. _getShaderErrors( gl, shader, type ) {
  49316. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  49317. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  49318. const errors = shaderInfoLog.trim();
  49319. if ( status && errors === '' ) return '';
  49320. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  49321. if ( errorMatches ) {
  49322. const errorLine = parseInt( errorMatches[ 1 ] );
  49323. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  49324. } else {
  49325. return errors;
  49326. }
  49327. }
  49328. /**
  49329. * Logs shader compilation errors.
  49330. *
  49331. * @private
  49332. * @param {WebGLProgram} programGPU - The WebGL program.
  49333. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  49334. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  49335. */
  49336. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  49337. if ( this.renderer.debug.checkShaderErrors ) {
  49338. const gl = this.gl;
  49339. const programInfoLog = gl.getProgramInfoLog( programGPU ) || '';
  49340. const programLog = programInfoLog.trim();
  49341. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  49342. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  49343. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  49344. } else {
  49345. // default error reporting
  49346. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  49347. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  49348. error(
  49349. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  49350. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  49351. 'Program Info Log: ' + programLog + '\n' +
  49352. vertexErrors + '\n' +
  49353. fragmentErrors
  49354. );
  49355. }
  49356. } else if ( programLog !== '' ) {
  49357. warn( 'WebGLProgram: Program Info Log:', programLog );
  49358. }
  49359. }
  49360. }
  49361. /**
  49362. * Completes the shader program setup for the given render object.
  49363. *
  49364. * @private
  49365. * @param {RenderObject} renderObject - The render object.
  49366. * @param {RenderPipeline} pipeline - The render pipeline.
  49367. */
  49368. _completeCompile( renderObject, pipeline ) {
  49369. const { state, gl } = this;
  49370. const pipelineData = this.get( pipeline );
  49371. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  49372. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  49373. this._logProgramError( programGPU, fragmentShader, vertexShader );
  49374. }
  49375. state.useProgram( programGPU );
  49376. // Bindings
  49377. const bindings = renderObject.getBindings();
  49378. this._setupBindings( bindings, programGPU );
  49379. //
  49380. this.set( pipeline, {
  49381. programGPU
  49382. } );
  49383. }
  49384. /**
  49385. * Creates a compute pipeline for the given compute node.
  49386. *
  49387. * @param {ComputePipeline} computePipeline - The compute pipeline.
  49388. * @param {Array<BindGroup>} bindings - The bindings.
  49389. */
  49390. createComputePipeline( computePipeline, bindings ) {
  49391. const { state, gl } = this;
  49392. // Program
  49393. const fragmentProgram = {
  49394. stage: 'fragment',
  49395. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  49396. };
  49397. this.createProgram( fragmentProgram );
  49398. const { computeProgram } = computePipeline;
  49399. const programGPU = gl.createProgram();
  49400. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  49401. const vertexShader = this.get( computeProgram ).shaderGPU;
  49402. const transforms = computeProgram.transforms;
  49403. const transformVaryingNames = [];
  49404. const transformAttributeNodes = [];
  49405. for ( let i = 0; i < transforms.length; i ++ ) {
  49406. const transform = transforms[ i ];
  49407. transformVaryingNames.push( transform.varyingName );
  49408. transformAttributeNodes.push( transform.attributeNode );
  49409. }
  49410. gl.attachShader( programGPU, fragmentShader );
  49411. gl.attachShader( programGPU, vertexShader );
  49412. gl.transformFeedbackVaryings(
  49413. programGPU,
  49414. transformVaryingNames,
  49415. gl.SEPARATE_ATTRIBS
  49416. );
  49417. gl.linkProgram( programGPU );
  49418. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  49419. this._logProgramError( programGPU, fragmentShader, vertexShader );
  49420. }
  49421. state.useProgram( programGPU );
  49422. // Bindings
  49423. this._setupBindings( bindings, programGPU );
  49424. const attributeNodes = computeProgram.attributes;
  49425. const attributes = [];
  49426. const transformBuffers = [];
  49427. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  49428. const attribute = attributeNodes[ i ].node.attribute;
  49429. attributes.push( attribute );
  49430. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49431. }
  49432. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  49433. const attribute = transformAttributeNodes[ i ].attribute;
  49434. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49435. const attributeData = this.get( attribute );
  49436. transformBuffers.push( attributeData );
  49437. }
  49438. //
  49439. this.set( computePipeline, {
  49440. programGPU,
  49441. transformBuffers,
  49442. attributes
  49443. } );
  49444. }
  49445. /**
  49446. * Creates bindings from the given bind group definition.
  49447. *
  49448. * @param {BindGroup} bindGroup - The bind group.
  49449. * @param {Array<BindGroup>} bindings - Array of bind groups.
  49450. * @param {number} cacheIndex - The cache index.
  49451. * @param {number} version - The version.
  49452. */
  49453. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  49454. if ( this._knownBindings.has( bindings ) === false ) {
  49455. this._knownBindings.add( bindings );
  49456. let uniformBuffers = 0;
  49457. let textures = 0;
  49458. for ( const bindGroup of bindings ) {
  49459. this.set( bindGroup, {
  49460. textures: textures,
  49461. uniformBuffers: uniformBuffers
  49462. } );
  49463. for ( const binding of bindGroup.bindings ) {
  49464. if ( binding.isUniformBuffer ) uniformBuffers ++;
  49465. if ( binding.isSampledTexture ) textures ++;
  49466. }
  49467. }
  49468. }
  49469. this.updateBindings( bindGroup, bindings );
  49470. }
  49471. /**
  49472. * Updates the given bind group definition.
  49473. *
  49474. * @param {BindGroup} bindGroup - The bind group.
  49475. * @param {Array<BindGroup>} bindings - Array of bind groups.
  49476. * @param {number} cacheIndex - The cache index.
  49477. * @param {number} version - The version.
  49478. */
  49479. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  49480. const { gl } = this;
  49481. const bindGroupData = this.get( bindGroup );
  49482. let i = bindGroupData.uniformBuffers;
  49483. let t = bindGroupData.textures;
  49484. for ( const binding of bindGroup.bindings ) {
  49485. const map = this.get( binding );
  49486. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  49487. const array = binding.buffer;
  49488. let { bufferGPU } = this.get( array );
  49489. if ( bufferGPU === undefined ) {
  49490. // create
  49491. bufferGPU = gl.createBuffer();
  49492. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49493. gl.bufferData( gl.UNIFORM_BUFFER, array.byteLength, gl.DYNAMIC_DRAW );
  49494. this.set( array, { bufferGPU } );
  49495. } else {
  49496. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49497. }
  49498. // update
  49499. const updateRanges = binding.updateRanges;
  49500. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49501. if ( updateRanges.length === 0 ) {
  49502. gl.bufferData( gl.UNIFORM_BUFFER, array, gl.DYNAMIC_DRAW );
  49503. } else {
  49504. const isTyped = isTypedArray( array );
  49505. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  49506. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  49507. const range = updateRanges[ i ];
  49508. const dataOffset = range.start * byteOffsetFactor;
  49509. const size = range.count * byteOffsetFactor;
  49510. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  49511. gl.bufferSubData( gl.UNIFORM_BUFFER, bufferOffset, array, dataOffset, size );
  49512. }
  49513. }
  49514. map.index = i ++;
  49515. map.bufferGPU = bufferGPU;
  49516. this.set( binding, map );
  49517. } else if ( binding.isSampledTexture ) {
  49518. const { textureGPU, glTextureType } = this.get( binding.texture );
  49519. map.index = t ++;
  49520. map.textureGPU = textureGPU;
  49521. map.glTextureType = glTextureType;
  49522. this.set( binding, map );
  49523. }
  49524. }
  49525. }
  49526. /**
  49527. * Updates a buffer binding.
  49528. *
  49529. * @param {Buffer} binding - The buffer binding to update.
  49530. */
  49531. updateBinding( binding ) {
  49532. const gl = this.gl;
  49533. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  49534. const bindingData = this.get( binding );
  49535. const bufferGPU = bindingData.bufferGPU;
  49536. const array = binding.buffer;
  49537. const updateRanges = binding.updateRanges;
  49538. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49539. if ( updateRanges.length === 0 ) {
  49540. gl.bufferData( gl.UNIFORM_BUFFER, array, gl.DYNAMIC_DRAW );
  49541. } else {
  49542. const isTyped = isTypedArray( array );
  49543. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  49544. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  49545. const range = updateRanges[ i ];
  49546. const dataOffset = range.start * byteOffsetFactor;
  49547. const size = range.count * byteOffsetFactor;
  49548. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  49549. gl.bufferSubData( gl.UNIFORM_BUFFER, bufferOffset, array, dataOffset, size );
  49550. }
  49551. }
  49552. }
  49553. }
  49554. // attributes
  49555. /**
  49556. * Creates the GPU buffer of an indexed shader attribute.
  49557. *
  49558. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  49559. */
  49560. createIndexAttribute( attribute ) {
  49561. const gl = this.gl;
  49562. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  49563. }
  49564. /**
  49565. * Creates the GPU buffer of a shader attribute.
  49566. *
  49567. * @param {BufferAttribute} attribute - The buffer attribute.
  49568. */
  49569. createAttribute( attribute ) {
  49570. if ( this.has( attribute ) ) return;
  49571. const gl = this.gl;
  49572. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49573. }
  49574. /**
  49575. * Creates the GPU buffer of a storage attribute.
  49576. *
  49577. * @param {BufferAttribute} attribute - The buffer attribute.
  49578. */
  49579. createStorageAttribute( attribute ) {
  49580. if ( this.has( attribute ) ) return;
  49581. const gl = this.gl;
  49582. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49583. }
  49584. /**
  49585. * Updates the GPU buffer of a shader attribute.
  49586. *
  49587. * @param {BufferAttribute} attribute - The buffer attribute to update.
  49588. */
  49589. updateAttribute( attribute ) {
  49590. this.attributeUtils.updateAttribute( attribute );
  49591. }
  49592. /**
  49593. * Destroys the GPU buffer of a shader attribute.
  49594. *
  49595. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  49596. */
  49597. destroyAttribute( attribute ) {
  49598. this.attributeUtils.destroyAttribute( attribute );
  49599. }
  49600. /**
  49601. * Checks if the given feature is supported by the backend.
  49602. *
  49603. * @param {string} name - The feature's name.
  49604. * @return {boolean} Whether the feature is supported or not.
  49605. */
  49606. hasFeature( name ) {
  49607. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  49608. const extensions = this.extensions;
  49609. for ( let i = 0; i < keysMatching.length; i ++ ) {
  49610. if ( extensions.has( keysMatching[ i ] ) ) return true;
  49611. }
  49612. return false;
  49613. }
  49614. /**
  49615. * Returns the maximum anisotropy texture filtering value.
  49616. *
  49617. * @return {number} The maximum anisotropy texture filtering value.
  49618. */
  49619. getMaxAnisotropy() {
  49620. return this.capabilities.getMaxAnisotropy();
  49621. }
  49622. /**
  49623. * Copies data of the given source texture to the given destination texture.
  49624. *
  49625. * @param {Texture} srcTexture - The source texture.
  49626. * @param {Texture} dstTexture - The destination texture.
  49627. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  49628. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  49629. * @param {number} [srcLevel=0] - The source mip level to copy from.
  49630. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  49631. */
  49632. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  49633. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  49634. }
  49635. /**
  49636. * Copies the current bound framebuffer to the given texture.
  49637. *
  49638. * @param {Texture} texture - The destination texture.
  49639. * @param {RenderContext} renderContext - The render context.
  49640. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  49641. */
  49642. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  49643. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  49644. }
  49645. /**
  49646. * Configures the active framebuffer from the given render context.
  49647. *
  49648. * @private
  49649. * @param {RenderContext} descriptor - The render context.
  49650. */
  49651. _setFramebuffer( descriptor ) {
  49652. const { gl, state } = this;
  49653. let currentFrameBuffer = null;
  49654. if ( descriptor.textures !== null ) {
  49655. const renderTarget = descriptor.renderTarget;
  49656. const renderTargetContextData = this.get( renderTarget );
  49657. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  49658. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  49659. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  49660. const isRenderTargetArray = renderTarget.depth > 1;
  49661. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  49662. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  49663. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  49664. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  49665. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  49666. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  49667. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  49668. const cacheKey = getCacheKey( descriptor );
  49669. let fb;
  49670. if ( isCube ) {
  49671. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  49672. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  49673. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  49674. fb = this._xrFramebuffer;
  49675. } else {
  49676. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  49677. fb = renderTargetContextData.framebuffers[ cacheKey ];
  49678. }
  49679. if ( fb === undefined ) {
  49680. fb = gl.createFramebuffer();
  49681. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  49682. const textures = descriptor.textures;
  49683. const depthInvalidationArray = [];
  49684. if ( isCube ) {
  49685. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  49686. const { textureGPU } = this.get( textures[ 0 ] );
  49687. const cubeFace = this.renderer._activeCubeFace;
  49688. const mipLevel = this.renderer._activeMipmapLevel;
  49689. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, mipLevel );
  49690. } else {
  49691. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  49692. for ( let i = 0; i < textures.length; i ++ ) {
  49693. const texture = textures[ i ];
  49694. const textureData = this.get( texture );
  49695. textureData.renderTarget = descriptor.renderTarget;
  49696. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  49697. const attachment = gl.COLOR_ATTACHMENT0 + i;
  49698. if ( renderTarget.multiview ) {
  49699. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  49700. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  49701. const layer = this.renderer._activeCubeFace;
  49702. const mipLevel = this.renderer._activeMipmapLevel;
  49703. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, mipLevel, layer );
  49704. } else {
  49705. if ( useMultisampledRTT ) {
  49706. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  49707. } else {
  49708. const mipLevel = this.renderer._activeMipmapLevel;
  49709. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, mipLevel );
  49710. }
  49711. }
  49712. }
  49713. }
  49714. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  49715. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  49716. const renderbuffer = gl.createRenderbuffer();
  49717. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  49718. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  49719. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  49720. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  49721. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  49722. } else {
  49723. if ( descriptor.depthTexture !== null ) {
  49724. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  49725. const textureData = this.get( descriptor.depthTexture );
  49726. textureData.renderTarget = descriptor.renderTarget;
  49727. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  49728. if ( renderTarget.multiview ) {
  49729. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  49730. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  49731. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  49732. } else {
  49733. if ( descriptor.depthTexture.isArrayTexture ) {
  49734. const layer = this.renderer._activeCubeFace;
  49735. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  49736. } else if ( descriptor.depthTexture.isCubeTexture ) {
  49737. const cubeFace = this.renderer._activeCubeFace;
  49738. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureData.textureGPU, 0 );
  49739. } else {
  49740. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  49741. }
  49742. }
  49743. }
  49744. }
  49745. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  49746. } else {
  49747. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  49748. if ( isRenderCameraDepthArray ) {
  49749. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  49750. const layer = this.renderer._activeCubeFace;
  49751. const depthData = this.get( descriptor.depthTexture );
  49752. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  49753. gl.framebufferTextureLayer(
  49754. gl.FRAMEBUFFER,
  49755. depthStyle,
  49756. depthData.textureGPU,
  49757. 0,
  49758. layer
  49759. );
  49760. }
  49761. // rebind external XR textures
  49762. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  49763. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  49764. // rebind color
  49765. const textureData = this.get( descriptor.textures[ 0 ] );
  49766. if ( renderTarget.multiview ) {
  49767. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  49768. } else if ( useMultisampledRTT ) {
  49769. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  49770. } else {
  49771. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  49772. }
  49773. // rebind depth
  49774. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  49775. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  49776. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  49777. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  49778. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  49779. } else {
  49780. const textureData = this.get( descriptor.depthTexture );
  49781. if ( renderTarget.multiview ) {
  49782. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  49783. } else if ( useMultisampledRTT ) {
  49784. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  49785. } else {
  49786. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  49787. }
  49788. }
  49789. }
  49790. }
  49791. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  49792. if ( msaaFb === undefined ) {
  49793. const invalidationArray = [];
  49794. msaaFb = gl.createFramebuffer();
  49795. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  49796. const msaaRenderbuffers = [];
  49797. const textures = descriptor.textures;
  49798. for ( let i = 0; i < textures.length; i ++ ) {
  49799. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  49800. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  49801. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  49802. const texture = descriptor.textures[ i ];
  49803. const textureData = this.get( texture );
  49804. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  49805. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  49806. }
  49807. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  49808. renderTargetContextData.msaaFrameBuffer = msaaFb;
  49809. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  49810. if ( depthBuffer && depthRenderbuffer === undefined ) {
  49811. depthRenderbuffer = gl.createRenderbuffer();
  49812. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  49813. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  49814. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  49815. invalidationArray.push( depthStyle );
  49816. }
  49817. renderTargetContextData.invalidationArray = invalidationArray;
  49818. }
  49819. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  49820. } else {
  49821. currentFrameBuffer = fb;
  49822. }
  49823. state.drawBuffers( descriptor, fb );
  49824. }
  49825. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  49826. }
  49827. /**
  49828. * Computes the VAO key for the given index and attributes.
  49829. *
  49830. * @private
  49831. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  49832. * @return {string} The VAO key.
  49833. */
  49834. _getVaoKey( attributes ) {
  49835. let key = '';
  49836. for ( let i = 0; i < attributes.length; i ++ ) {
  49837. const attributeData = this.get( attributes[ i ] );
  49838. key += ':' + attributeData.id;
  49839. }
  49840. return key;
  49841. }
  49842. /**
  49843. * Creates a VAO from the index and attributes.
  49844. *
  49845. * @private
  49846. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  49847. * @return {Object} The VAO data.
  49848. */
  49849. _createVao( attributes ) {
  49850. const { gl } = this;
  49851. const vaoGPU = gl.createVertexArray();
  49852. gl.bindVertexArray( vaoGPU );
  49853. for ( let i = 0; i < attributes.length; i ++ ) {
  49854. const attribute = attributes[ i ];
  49855. const attributeData = this.get( attribute );
  49856. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  49857. gl.enableVertexAttribArray( i );
  49858. let stride, offset;
  49859. if ( attribute.isInterleavedBufferAttribute === true ) {
  49860. stride = attribute.data.stride * attributeData.bytesPerElement;
  49861. offset = attribute.offset * attributeData.bytesPerElement;
  49862. } else {
  49863. stride = 0;
  49864. offset = 0;
  49865. }
  49866. if ( attributeData.isInteger ) {
  49867. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  49868. } else {
  49869. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  49870. }
  49871. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  49872. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  49873. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  49874. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  49875. }
  49876. }
  49877. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  49878. return vaoGPU;
  49879. }
  49880. /**
  49881. * Creates a transform feedback from the given transform buffers.
  49882. *
  49883. * @private
  49884. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  49885. * @return {WebGLTransformFeedback} The transform feedback.
  49886. */
  49887. _getTransformFeedback( transformBuffers ) {
  49888. let key = '';
  49889. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  49890. key += ':' + transformBuffers[ i ].id;
  49891. }
  49892. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  49893. if ( transformFeedbackGPU !== undefined ) {
  49894. return transformFeedbackGPU;
  49895. }
  49896. const { gl } = this;
  49897. transformFeedbackGPU = gl.createTransformFeedback();
  49898. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  49899. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  49900. const attributeData = transformBuffers[ i ];
  49901. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  49902. }
  49903. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  49904. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  49905. return transformFeedbackGPU;
  49906. }
  49907. /**
  49908. * Setups the given bindings.
  49909. *
  49910. * @private
  49911. * @param {Array<BindGroup>} bindings - The bindings.
  49912. * @param {WebGLProgram} programGPU - The WebGL program.
  49913. */
  49914. _setupBindings( bindings, programGPU ) {
  49915. const gl = this.gl;
  49916. for ( const bindGroup of bindings ) {
  49917. for ( const binding of bindGroup.bindings ) {
  49918. const bindingData = this.get( binding );
  49919. const index = bindingData.index;
  49920. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  49921. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  49922. gl.uniformBlockBinding( programGPU, location, index );
  49923. } else if ( binding.isSampledTexture ) {
  49924. const location = gl.getUniformLocation( programGPU, binding.name );
  49925. gl.uniform1i( location, index );
  49926. }
  49927. }
  49928. }
  49929. }
  49930. /**
  49931. * Binds the given uniforms.
  49932. *
  49933. * @private
  49934. * @param {Array<BindGroup>} bindings - The bindings.
  49935. */
  49936. _bindUniforms( bindings ) {
  49937. const { gl, state } = this;
  49938. for ( const bindGroup of bindings ) {
  49939. for ( const binding of bindGroup.bindings ) {
  49940. const bindingData = this.get( binding );
  49941. const index = bindingData.index;
  49942. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  49943. // TODO USE bindBufferRange to group multiple uniform buffers
  49944. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  49945. } else if ( binding.isSampledTexture ) {
  49946. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  49947. }
  49948. }
  49949. }
  49950. }
  49951. /**
  49952. * The method ensures multisampled render targets are resolved.
  49953. *
  49954. * @private
  49955. * @param {RenderContext} renderContext - The render context.
  49956. */
  49957. _resolveRenderTarget( renderContext ) {
  49958. const { gl, state } = this;
  49959. const renderTarget = renderContext.renderTarget;
  49960. if ( renderContext.textures !== null && renderTarget ) {
  49961. const renderTargetContextData = this.get( renderTarget );
  49962. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  49963. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  49964. let mask = gl.COLOR_BUFFER_BIT;
  49965. if ( renderTarget.resolveDepthBuffer ) {
  49966. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  49967. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  49968. }
  49969. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  49970. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  49971. const textures = renderContext.textures;
  49972. const isMRT = textures.length > 1;
  49973. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  49974. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  49975. if ( isMRT ) {
  49976. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  49977. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  49978. for ( let i = 0; i < textures.length; i ++ ) {
  49979. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  49980. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  49981. }
  49982. }
  49983. for ( let i = 0; i < textures.length; i ++ ) {
  49984. if ( isMRT ) {
  49985. // configure attachment for resolve
  49986. const { textureGPU } = this.get( textures[ i ] );
  49987. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  49988. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  49989. }
  49990. if ( renderContext.scissor ) {
  49991. const { x, y, width, height } = renderContext.scissorValue;
  49992. const viewY = renderContext.height - height - y;
  49993. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  49994. } else {
  49995. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  49996. }
  49997. }
  49998. if ( isMRT ) {
  49999. // restore attachments
  50000. for ( let i = 0; i < textures.length; i ++ ) {
  50001. const { textureGPU } = this.get( textures[ i ] );
  50002. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  50003. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  50004. }
  50005. }
  50006. if ( this._supportsInvalidateFramebuffer === true ) {
  50007. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  50008. }
  50009. } else if ( renderTarget.resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  50010. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  50011. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  50012. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  50013. }
  50014. }
  50015. }
  50016. /**
  50017. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  50018. * should be used when MSAA is enabled.
  50019. *
  50020. * @private
  50021. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  50022. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  50023. */
  50024. _useMultisampledExtension( renderTarget ) {
  50025. if ( renderTarget.multiview === true ) {
  50026. return true;
  50027. }
  50028. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  50029. }
  50030. /**
  50031. * Frees internal resources.
  50032. */
  50033. dispose() {
  50034. if ( this.textureUtils !== null ) this.textureUtils.dispose();
  50035. const extension = this.extensions.get( 'WEBGL_lose_context' );
  50036. if ( extension ) extension.loseContext();
  50037. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  50038. }
  50039. }
  50040. const GPUPrimitiveTopology = {
  50041. PointList: 'point-list',
  50042. LineList: 'line-list',
  50043. LineStrip: 'line-strip',
  50044. TriangleList: 'triangle-list',
  50045. TriangleStrip: 'triangle-strip',
  50046. };
  50047. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  50048. const GPUCompareFunction = {
  50049. Never: 'never',
  50050. Less: 'less',
  50051. Equal: 'equal',
  50052. LessEqual: 'less-equal',
  50053. Greater: 'greater',
  50054. NotEqual: 'not-equal',
  50055. GreaterEqual: 'greater-equal',
  50056. Always: 'always'
  50057. };
  50058. const GPUStoreOp = {
  50059. Store: 'store'};
  50060. const GPULoadOp = {
  50061. Load: 'load',
  50062. Clear: 'clear'
  50063. };
  50064. const GPUFrontFace = {
  50065. CCW: 'ccw',
  50066. CW: 'cw'
  50067. };
  50068. const GPUCullMode = {
  50069. None: 'none',
  50070. Back: 'back'
  50071. };
  50072. const GPUIndexFormat = {
  50073. Uint16: 'uint16',
  50074. Uint32: 'uint32'
  50075. };
  50076. const GPUTextureFormat = {
  50077. // 8-bit formats
  50078. R8Unorm: 'r8unorm',
  50079. R8Snorm: 'r8snorm',
  50080. R8Uint: 'r8uint',
  50081. R8Sint: 'r8sint',
  50082. // 16-bit formats
  50083. R16Uint: 'r16uint',
  50084. R16Sint: 'r16sint',
  50085. R16Float: 'r16float',
  50086. RG8Unorm: 'rg8unorm',
  50087. RG8Snorm: 'rg8snorm',
  50088. RG8Uint: 'rg8uint',
  50089. RG8Sint: 'rg8sint',
  50090. // 32-bit formats
  50091. R32Uint: 'r32uint',
  50092. R32Sint: 'r32sint',
  50093. R32Float: 'r32float',
  50094. RG16Uint: 'rg16uint',
  50095. RG16Sint: 'rg16sint',
  50096. RG16Float: 'rg16float',
  50097. RGBA8Unorm: 'rgba8unorm',
  50098. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  50099. RGBA8Snorm: 'rgba8snorm',
  50100. RGBA8Uint: 'rgba8uint',
  50101. RGBA8Sint: 'rgba8sint',
  50102. BGRA8Unorm: 'bgra8unorm',
  50103. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  50104. // Packed 32-bit formats
  50105. RGB9E5UFloat: 'rgb9e5ufloat',
  50106. RGB10A2Unorm: 'rgb10a2unorm',
  50107. RG11B10UFloat: 'rg11b10ufloat',
  50108. // 64-bit formats
  50109. RG32Uint: 'rg32uint',
  50110. RG32Sint: 'rg32sint',
  50111. RG32Float: 'rg32float',
  50112. RGBA16Uint: 'rgba16uint',
  50113. RGBA16Sint: 'rgba16sint',
  50114. RGBA16Float: 'rgba16float',
  50115. // 128-bit formats
  50116. RGBA32Uint: 'rgba32uint',
  50117. RGBA32Sint: 'rgba32sint',
  50118. RGBA32Float: 'rgba32float',
  50119. Depth16Unorm: 'depth16unorm',
  50120. Depth24Plus: 'depth24plus',
  50121. Depth24PlusStencil8: 'depth24plus-stencil8',
  50122. Depth32Float: 'depth32float',
  50123. // 'depth32float-stencil8' extension
  50124. Depth32FloatStencil8: 'depth32float-stencil8',
  50125. // BC compressed formats usable if 'texture-compression-bc' is both
  50126. // supported by the device/user agent and enabled in requestDevice.
  50127. BC1RGBAUnorm: 'bc1-rgba-unorm',
  50128. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  50129. BC2RGBAUnorm: 'bc2-rgba-unorm',
  50130. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  50131. BC3RGBAUnorm: 'bc3-rgba-unorm',
  50132. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  50133. BC4RUnorm: 'bc4-r-unorm',
  50134. BC4RSnorm: 'bc4-r-snorm',
  50135. BC5RGUnorm: 'bc5-rg-unorm',
  50136. BC5RGSnorm: 'bc5-rg-snorm',
  50137. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  50138. BC6HRGBFloat: 'bc6h-rgb-float',
  50139. BC7RGBAUnorm: 'bc7-rgba-unorm',
  50140. BC7RGBAUnormSRGB: 'bc7-rgba-unorm-srgb',
  50141. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  50142. // supported by the device/user agent and enabled in requestDevice.
  50143. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  50144. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  50145. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  50146. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  50147. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  50148. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  50149. EACR11Unorm: 'eac-r11unorm',
  50150. EACR11Snorm: 'eac-r11snorm',
  50151. EACRG11Unorm: 'eac-rg11unorm',
  50152. EACRG11Snorm: 'eac-rg11snorm',
  50153. // ASTC compressed formats usable if 'texture-compression-astc' is both
  50154. // supported by the device/user agent and enabled in requestDevice.
  50155. ASTC4x4Unorm: 'astc-4x4-unorm',
  50156. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  50157. ASTC5x4Unorm: 'astc-5x4-unorm',
  50158. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  50159. ASTC5x5Unorm: 'astc-5x5-unorm',
  50160. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  50161. ASTC6x5Unorm: 'astc-6x5-unorm',
  50162. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  50163. ASTC6x6Unorm: 'astc-6x6-unorm',
  50164. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  50165. ASTC8x5Unorm: 'astc-8x5-unorm',
  50166. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  50167. ASTC8x6Unorm: 'astc-8x6-unorm',
  50168. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  50169. ASTC8x8Unorm: 'astc-8x8-unorm',
  50170. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  50171. ASTC10x5Unorm: 'astc-10x5-unorm',
  50172. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  50173. ASTC10x6Unorm: 'astc-10x6-unorm',
  50174. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  50175. ASTC10x8Unorm: 'astc-10x8-unorm',
  50176. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  50177. ASTC10x10Unorm: 'astc-10x10-unorm',
  50178. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  50179. ASTC12x10Unorm: 'astc-12x10-unorm',
  50180. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  50181. ASTC12x12Unorm: 'astc-12x12-unorm',
  50182. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  50183. };
  50184. const GPUAddressMode = {
  50185. ClampToEdge: 'clamp-to-edge',
  50186. Repeat: 'repeat',
  50187. MirrorRepeat: 'mirror-repeat'
  50188. };
  50189. const GPUFilterMode = {
  50190. Linear: 'linear',
  50191. Nearest: 'nearest'
  50192. };
  50193. const GPUBlendFactor = {
  50194. Zero: 'zero',
  50195. One: 'one',
  50196. Src: 'src',
  50197. OneMinusSrc: 'one-minus-src',
  50198. SrcAlpha: 'src-alpha',
  50199. OneMinusSrcAlpha: 'one-minus-src-alpha',
  50200. Dst: 'dst',
  50201. OneMinusDst: 'one-minus-dst',
  50202. DstAlpha: 'dst-alpha',
  50203. OneMinusDstAlpha: 'one-minus-dst-alpha',
  50204. SrcAlphaSaturated: 'src-alpha-saturated',
  50205. Constant: 'constant',
  50206. OneMinusConstant: 'one-minus-constant'
  50207. };
  50208. const GPUBlendOperation = {
  50209. Add: 'add',
  50210. Subtract: 'subtract',
  50211. ReverseSubtract: 'reverse-subtract',
  50212. Min: 'min',
  50213. Max: 'max'
  50214. };
  50215. const GPUColorWriteFlags = {
  50216. None: 0,
  50217. All: 0xF
  50218. };
  50219. const GPUStencilOperation = {
  50220. Keep: 'keep',
  50221. Zero: 'zero',
  50222. Replace: 'replace',
  50223. Invert: 'invert',
  50224. IncrementClamp: 'increment-clamp',
  50225. DecrementClamp: 'decrement-clamp',
  50226. IncrementWrap: 'increment-wrap',
  50227. DecrementWrap: 'decrement-wrap'
  50228. };
  50229. const GPUBufferBindingType = {
  50230. Storage: 'storage',
  50231. ReadOnlyStorage: 'read-only-storage'
  50232. };
  50233. const GPUStorageTextureAccess = {
  50234. WriteOnly: 'write-only',
  50235. ReadOnly: 'read-only',
  50236. ReadWrite: 'read-write',
  50237. };
  50238. const GPUSamplerBindingType = {
  50239. NonFiltering: 'non-filtering',
  50240. Comparison: 'comparison'
  50241. };
  50242. const GPUTextureSampleType = {
  50243. Float: 'float',
  50244. UnfilterableFloat: 'unfilterable-float',
  50245. Depth: 'depth',
  50246. SInt: 'sint',
  50247. UInt: 'uint'
  50248. };
  50249. const GPUTextureDimension = {
  50250. TwoD: '2d',
  50251. ThreeD: '3d'
  50252. };
  50253. const GPUTextureViewDimension = {
  50254. TwoD: '2d',
  50255. TwoDArray: '2d-array',
  50256. Cube: 'cube',
  50257. ThreeD: '3d'
  50258. };
  50259. const GPUTextureAspect = {
  50260. All: 'all'};
  50261. const GPUInputStepMode = {
  50262. Vertex: 'vertex',
  50263. Instance: 'instance'
  50264. };
  50265. const GPUFeatureName = {
  50266. CoreFeaturesAndLimits: 'core-features-and-limits',
  50267. DepthClipControl: 'depth-clip-control',
  50268. Depth32FloatStencil8: 'depth32float-stencil8',
  50269. TextureCompressionBC: 'texture-compression-bc',
  50270. TextureCompressionBCSliced3D: 'texture-compression-bc-sliced-3d',
  50271. TextureCompressionETC2: 'texture-compression-etc2',
  50272. TextureCompressionASTC: 'texture-compression-astc',
  50273. TextureCompressionASTCSliced3D: 'texture-compression-astc-sliced-3d',
  50274. TimestampQuery: 'timestamp-query',
  50275. IndirectFirstInstance: 'indirect-first-instance',
  50276. ShaderF16: 'shader-f16',
  50277. RG11B10UFloat: 'rg11b10ufloat-renderable',
  50278. BGRA8UNormStorage: 'bgra8unorm-storage',
  50279. Float32Filterable: 'float32-filterable',
  50280. Float32Blendable: 'float32-blendable',
  50281. ClipDistances: 'clip-distances',
  50282. DualSourceBlending: 'dual-source-blending',
  50283. Subgroups: 'subgroups',
  50284. TextureFormatsTier1: 'texture-formats-tier1',
  50285. TextureFormatsTier2: 'texture-formats-tier2'
  50286. };
  50287. const GPUFeatureMap = {
  50288. 'texture-compression-s3tc': 'texture-compression-bc',
  50289. 'texture-compression-etc1': 'texture-compression-etc2'
  50290. };
  50291. /**
  50292. * A special form of sampler binding type.
  50293. * It's texture value is managed by a node object.
  50294. *
  50295. * @private
  50296. * @augments Sampler
  50297. */
  50298. class NodeSampler extends Sampler {
  50299. /**
  50300. * Constructs a new node-based sampler.
  50301. *
  50302. * @param {string} name - The samplers's name.
  50303. * @param {TextureNode} textureNode - The texture node.
  50304. * @param {UniformGroupNode} groupNode - The uniform group node.
  50305. */
  50306. constructor( name, textureNode, groupNode ) {
  50307. super( name, textureNode ? textureNode.value : null );
  50308. /**
  50309. * The texture node.
  50310. *
  50311. * @type {TextureNode}
  50312. */
  50313. this.textureNode = textureNode;
  50314. /**
  50315. * The uniform group node.
  50316. *
  50317. * @type {UniformGroupNode}
  50318. */
  50319. this.groupNode = groupNode;
  50320. }
  50321. /**
  50322. * Updates the texture value of this sampler.
  50323. *
  50324. * @return {boolean} Whether the sampler needs an update or not.
  50325. */
  50326. update() {
  50327. const { textureNode } = this;
  50328. if ( this.texture !== textureNode.value ) {
  50329. this.texture = textureNode.value;
  50330. return true;
  50331. }
  50332. return super.update();
  50333. }
  50334. }
  50335. /**
  50336. * Represents a storage buffer binding type.
  50337. *
  50338. * @private
  50339. * @augments Buffer
  50340. */
  50341. class StorageBuffer extends Buffer {
  50342. /**
  50343. * Constructs a new uniform buffer.
  50344. *
  50345. * @param {string} name - The buffer's name.
  50346. * @param {BufferAttribute} attribute - The buffer attribute.
  50347. */
  50348. constructor( name, attribute ) {
  50349. super( name, attribute ? attribute.array : null );
  50350. /**
  50351. * This flag can be used for type testing.
  50352. *
  50353. * @type {BufferAttribute}
  50354. */
  50355. this.attribute = attribute;
  50356. /**
  50357. * This flag can be used for type testing.
  50358. *
  50359. * @type {boolean}
  50360. * @readonly
  50361. * @default true
  50362. */
  50363. this.isStorageBuffer = true;
  50364. }
  50365. }
  50366. let _id = 0;
  50367. /**
  50368. * A special form of storage buffer binding type.
  50369. * It's buffer value is managed by a node object.
  50370. *
  50371. * @private
  50372. * @augments StorageBuffer
  50373. */
  50374. class NodeStorageBuffer extends StorageBuffer {
  50375. /**
  50376. * Constructs a new node-based storage buffer.
  50377. *
  50378. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  50379. * @param {UniformGroupNode} groupNode - The uniform group node.
  50380. */
  50381. constructor( nodeUniform, groupNode ) {
  50382. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  50383. /**
  50384. * The node uniform.
  50385. *
  50386. * @type {StorageBufferNode}
  50387. */
  50388. this.nodeUniform = nodeUniform;
  50389. /**
  50390. * The access type.
  50391. *
  50392. * @type {string}
  50393. */
  50394. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  50395. /**
  50396. * The uniform group node.
  50397. *
  50398. * @type {UniformGroupNode}
  50399. */
  50400. this.groupNode = groupNode;
  50401. }
  50402. /**
  50403. * The storage buffer.
  50404. *
  50405. * @type {BufferAttribute}
  50406. */
  50407. get buffer() {
  50408. return this.nodeUniform.value;
  50409. }
  50410. }
  50411. /**
  50412. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  50413. *
  50414. * @private
  50415. */
  50416. class WebGPUTexturePassUtils extends DataMap {
  50417. /**
  50418. * Constructs a new utility object.
  50419. *
  50420. * @param {GPUDevice} device - The WebGPU device.
  50421. */
  50422. constructor( device ) {
  50423. super();
  50424. /**
  50425. * The WebGPU device.
  50426. *
  50427. * @type {GPUDevice}
  50428. */
  50429. this.device = device;
  50430. const mipmapVertexSource = `
  50431. struct VarysStruct {
  50432. @builtin( position ) Position: vec4<f32>,
  50433. @location( 0 ) vTex : vec2<f32>
  50434. };
  50435. @vertex
  50436. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  50437. var Varys : VarysStruct;
  50438. var pos = array< vec2<f32>, 4 >(
  50439. vec2<f32>( -1.0, 1.0 ),
  50440. vec2<f32>( 1.0, 1.0 ),
  50441. vec2<f32>( -1.0, -1.0 ),
  50442. vec2<f32>( 1.0, -1.0 )
  50443. );
  50444. var tex = array< vec2<f32>, 4 >(
  50445. vec2<f32>( 0.0, 0.0 ),
  50446. vec2<f32>( 1.0, 0.0 ),
  50447. vec2<f32>( 0.0, 1.0 ),
  50448. vec2<f32>( 1.0, 1.0 )
  50449. );
  50450. Varys.vTex = tex[ vertexIndex ];
  50451. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  50452. return Varys;
  50453. }
  50454. `;
  50455. const mipmapFragmentSource = `
  50456. @group( 0 ) @binding( 0 )
  50457. var imgSampler : sampler;
  50458. @group( 0 ) @binding( 1 )
  50459. var img : texture_2d<f32>;
  50460. @fragment
  50461. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  50462. return textureSample( img, imgSampler, vTex );
  50463. }
  50464. `;
  50465. const flipYFragmentSource = `
  50466. @group( 0 ) @binding( 0 )
  50467. var imgSampler : sampler;
  50468. @group( 0 ) @binding( 1 )
  50469. var img : texture_2d<f32>;
  50470. @fragment
  50471. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  50472. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  50473. }
  50474. `;
  50475. /**
  50476. * The mipmap GPU sampler.
  50477. *
  50478. * @type {GPUSampler}
  50479. */
  50480. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  50481. /**
  50482. * The flipY GPU sampler.
  50483. *
  50484. * @type {GPUSampler}
  50485. */
  50486. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  50487. /**
  50488. * A cache for GPU render pipelines used for copy/transfer passes.
  50489. * Every texture format requires a unique pipeline.
  50490. *
  50491. * @type {Object<string,GPURenderPipeline>}
  50492. */
  50493. this.transferPipelines = {};
  50494. /**
  50495. * A cache for GPU render pipelines used for flipY passes.
  50496. * Every texture format requires a unique pipeline.
  50497. *
  50498. * @type {Object<string,GPURenderPipeline>}
  50499. */
  50500. this.flipYPipelines = {};
  50501. /**
  50502. * The mipmap vertex shader module.
  50503. *
  50504. * @type {GPUShaderModule}
  50505. */
  50506. this.mipmapVertexShaderModule = device.createShaderModule( {
  50507. label: 'mipmapVertex',
  50508. code: mipmapVertexSource
  50509. } );
  50510. /**
  50511. * The mipmap fragment shader module.
  50512. *
  50513. * @type {GPUShaderModule}
  50514. */
  50515. this.mipmapFragmentShaderModule = device.createShaderModule( {
  50516. label: 'mipmapFragment',
  50517. code: mipmapFragmentSource
  50518. } );
  50519. /**
  50520. * The flipY fragment shader module.
  50521. *
  50522. * @type {GPUShaderModule}
  50523. */
  50524. this.flipYFragmentShaderModule = device.createShaderModule( {
  50525. label: 'flipYFragment',
  50526. code: flipYFragmentSource
  50527. } );
  50528. }
  50529. /**
  50530. * Returns a render pipeline for the internal copy render pass. The pass
  50531. * requires a unique render pipeline for each texture format.
  50532. *
  50533. * @param {string} format - The GPU texture format
  50534. * @return {GPURenderPipeline} The GPU render pipeline.
  50535. */
  50536. getTransferPipeline( format ) {
  50537. let pipeline = this.transferPipelines[ format ];
  50538. if ( pipeline === undefined ) {
  50539. pipeline = this.device.createRenderPipeline( {
  50540. label: `mipmap-${ format }`,
  50541. vertex: {
  50542. module: this.mipmapVertexShaderModule,
  50543. entryPoint: 'main'
  50544. },
  50545. fragment: {
  50546. module: this.mipmapFragmentShaderModule,
  50547. entryPoint: 'main',
  50548. targets: [ { format } ]
  50549. },
  50550. primitive: {
  50551. topology: GPUPrimitiveTopology.TriangleStrip,
  50552. stripIndexFormat: GPUIndexFormat.Uint32
  50553. },
  50554. layout: 'auto'
  50555. } );
  50556. this.transferPipelines[ format ] = pipeline;
  50557. }
  50558. return pipeline;
  50559. }
  50560. /**
  50561. * Returns a render pipeline for the flipY render pass. The pass
  50562. * requires a unique render pipeline for each texture format.
  50563. *
  50564. * @param {string} format - The GPU texture format
  50565. * @return {GPURenderPipeline} The GPU render pipeline.
  50566. */
  50567. getFlipYPipeline( format ) {
  50568. let pipeline = this.flipYPipelines[ format ];
  50569. if ( pipeline === undefined ) {
  50570. pipeline = this.device.createRenderPipeline( {
  50571. label: `flipY-${ format }`,
  50572. vertex: {
  50573. module: this.mipmapVertexShaderModule,
  50574. entryPoint: 'main'
  50575. },
  50576. fragment: {
  50577. module: this.flipYFragmentShaderModule,
  50578. entryPoint: 'main',
  50579. targets: [ { format } ]
  50580. },
  50581. primitive: {
  50582. topology: GPUPrimitiveTopology.TriangleStrip,
  50583. stripIndexFormat: GPUIndexFormat.Uint32
  50584. },
  50585. layout: 'auto'
  50586. } );
  50587. this.flipYPipelines[ format ] = pipeline;
  50588. }
  50589. return pipeline;
  50590. }
  50591. /**
  50592. * Flip the contents of the given GPU texture along its vertical axis.
  50593. *
  50594. * @param {GPUTexture} textureGPU - The GPU texture object.
  50595. * @param {Object} textureGPUDescriptor - The texture descriptor.
  50596. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  50597. */
  50598. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  50599. const format = textureGPUDescriptor.format;
  50600. const { width, height } = textureGPUDescriptor.size;
  50601. const transferPipeline = this.getTransferPipeline( format );
  50602. const flipYPipeline = this.getFlipYPipeline( format );
  50603. const tempTexture = this.device.createTexture( {
  50604. size: { width, height, depthOrArrayLayers: 1 },
  50605. format,
  50606. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  50607. } );
  50608. const srcView = textureGPU.createView( {
  50609. baseMipLevel: 0,
  50610. mipLevelCount: 1,
  50611. dimension: GPUTextureViewDimension.TwoD,
  50612. baseArrayLayer
  50613. } );
  50614. const dstView = tempTexture.createView( {
  50615. baseMipLevel: 0,
  50616. mipLevelCount: 1,
  50617. dimension: GPUTextureViewDimension.TwoD,
  50618. baseArrayLayer: 0
  50619. } );
  50620. const commandEncoder = this.device.createCommandEncoder( {} );
  50621. const pass = ( pipeline, sourceView, destinationView ) => {
  50622. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  50623. const bindGroup = this.device.createBindGroup( {
  50624. layout: bindGroupLayout,
  50625. entries: [ {
  50626. binding: 0,
  50627. resource: this.flipYSampler
  50628. }, {
  50629. binding: 1,
  50630. resource: sourceView
  50631. } ]
  50632. } );
  50633. const passEncoder = commandEncoder.beginRenderPass( {
  50634. colorAttachments: [ {
  50635. view: destinationView,
  50636. loadOp: GPULoadOp.Clear,
  50637. storeOp: GPUStoreOp.Store,
  50638. clearValue: [ 0, 0, 0, 0 ]
  50639. } ]
  50640. } );
  50641. passEncoder.setPipeline( pipeline );
  50642. passEncoder.setBindGroup( 0, bindGroup );
  50643. passEncoder.draw( 4, 1, 0, 0 );
  50644. passEncoder.end();
  50645. };
  50646. pass( transferPipeline, srcView, dstView );
  50647. pass( flipYPipeline, dstView, srcView );
  50648. this.device.queue.submit( [ commandEncoder.finish() ] );
  50649. tempTexture.destroy();
  50650. }
  50651. /**
  50652. * Generates mipmaps for the given GPU texture.
  50653. *
  50654. * @param {GPUTexture} textureGPU - The GPU texture object.
  50655. * @param {Object} textureGPUDescriptor - The texture descriptor.
  50656. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  50657. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  50658. */
  50659. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0, encoder = null ) {
  50660. const textureData = this.get( textureGPU );
  50661. if ( textureData.layers === undefined ) {
  50662. textureData.layers = [];
  50663. }
  50664. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  50665. const commandEncoder = encoder || this.device.createCommandEncoder( { label: 'mipmapEncoder' } );
  50666. this._mipmapRunBundles( commandEncoder, passes );
  50667. if ( encoder === null ) this.device.queue.submit( [ commandEncoder.finish() ] );
  50668. textureData.layers[ baseArrayLayer ] = passes;
  50669. }
  50670. /**
  50671. * Since multiple copy render passes are required to generate mipmaps, the passes
  50672. * are managed as render bundles to improve performance.
  50673. *
  50674. * @param {GPUTexture} textureGPU - The GPU texture object.
  50675. * @param {Object} textureGPUDescriptor - The texture descriptor.
  50676. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  50677. * @return {Array<Object>} An array of render bundles.
  50678. */
  50679. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  50680. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  50681. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  50682. let srcView = textureGPU.createView( {
  50683. baseMipLevel: 0,
  50684. mipLevelCount: 1,
  50685. dimension: GPUTextureViewDimension.TwoD,
  50686. baseArrayLayer
  50687. } );
  50688. const passes = [];
  50689. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  50690. const bindGroup = this.device.createBindGroup( {
  50691. layout: bindGroupLayout,
  50692. entries: [ {
  50693. binding: 0,
  50694. resource: this.mipmapSampler
  50695. }, {
  50696. binding: 1,
  50697. resource: srcView
  50698. } ]
  50699. } );
  50700. const dstView = textureGPU.createView( {
  50701. baseMipLevel: i,
  50702. mipLevelCount: 1,
  50703. dimension: GPUTextureViewDimension.TwoD,
  50704. baseArrayLayer
  50705. } );
  50706. const passDescriptor = {
  50707. colorAttachments: [ {
  50708. view: dstView,
  50709. loadOp: GPULoadOp.Clear,
  50710. storeOp: GPUStoreOp.Store,
  50711. clearValue: [ 0, 0, 0, 0 ]
  50712. } ]
  50713. };
  50714. const passEncoder = this.device.createRenderBundleEncoder( {
  50715. colorFormats: [ textureGPUDescriptor.format ]
  50716. } );
  50717. passEncoder.setPipeline( pipeline );
  50718. passEncoder.setBindGroup( 0, bindGroup );
  50719. passEncoder.draw( 4, 1, 0, 0 );
  50720. passes.push( {
  50721. renderBundles: [ passEncoder.finish() ],
  50722. passDescriptor
  50723. } );
  50724. srcView = dstView;
  50725. }
  50726. return passes;
  50727. }
  50728. /**
  50729. * Executes the render bundles.
  50730. *
  50731. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  50732. * @param {Array<Object>} passes - An array of render bundles.
  50733. */
  50734. _mipmapRunBundles( commandEncoder, passes ) {
  50735. const levels = passes.length;
  50736. for ( let i = 0; i < levels; i ++ ) {
  50737. const pass = passes[ i ];
  50738. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  50739. passEncoder.executeBundles( pass.renderBundles );
  50740. passEncoder.end();
  50741. }
  50742. }
  50743. }
  50744. const _compareToWebGPU = {
  50745. [ NeverCompare ]: 'never',
  50746. [ LessCompare ]: 'less',
  50747. [ EqualCompare ]: 'equal',
  50748. [ LessEqualCompare ]: 'less-equal',
  50749. [ GreaterCompare ]: 'greater',
  50750. [ GreaterEqualCompare ]: 'greater-equal',
  50751. [ AlwaysCompare ]: 'always',
  50752. [ NotEqualCompare ]: 'not-equal'
  50753. };
  50754. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  50755. /**
  50756. * A WebGPU backend utility module for managing textures.
  50757. *
  50758. * @private
  50759. */
  50760. class WebGPUTextureUtils {
  50761. /**
  50762. * Constructs a new utility object.
  50763. *
  50764. * @param {WebGPUBackend} backend - The WebGPU backend.
  50765. */
  50766. constructor( backend ) {
  50767. /**
  50768. * A reference to the WebGPU backend.
  50769. *
  50770. * @type {WebGPUBackend}
  50771. */
  50772. this.backend = backend;
  50773. /**
  50774. * A reference to the pass utils.
  50775. *
  50776. * @type {?WebGPUTexturePassUtils}
  50777. * @default null
  50778. */
  50779. this._passUtils = null;
  50780. /**
  50781. * A dictionary for managing default textures. The key
  50782. * is the texture format, the value the texture object.
  50783. *
  50784. * @type {Object<string,Texture>}
  50785. */
  50786. this.defaultTexture = {};
  50787. /**
  50788. * A dictionary for managing default cube textures. The key
  50789. * is the texture format, the value the texture object.
  50790. *
  50791. * @type {Object<string,CubeTexture>}
  50792. */
  50793. this.defaultCubeTexture = {};
  50794. /**
  50795. * A default video frame.
  50796. *
  50797. * @type {?VideoFrame}
  50798. * @default null
  50799. */
  50800. this.defaultVideoFrame = null;
  50801. /**
  50802. * A cache of shared texture samplers.
  50803. *
  50804. * @type {Map<string, Object>}
  50805. */
  50806. this._samplerCache = new Map();
  50807. }
  50808. /**
  50809. * Creates a GPU sampler for the given texture.
  50810. *
  50811. * @param {Texture} texture - The texture to create the sampler for.
  50812. * @return {string} The current sampler key.
  50813. */
  50814. updateSampler( texture ) {
  50815. const backend = this.backend;
  50816. const samplerKey = texture.minFilter + '-' + texture.magFilter + '-' +
  50817. texture.wrapS + '-' + texture.wrapT + '-' + ( texture.wrapR || '0' ) + '-' +
  50818. texture.anisotropy + '-' + ( texture.compareFunction || 0 );
  50819. let samplerData = this._samplerCache.get( samplerKey );
  50820. if ( samplerData === undefined ) {
  50821. const samplerDescriptorGPU = {
  50822. addressModeU: this._convertAddressMode( texture.wrapS ),
  50823. addressModeV: this._convertAddressMode( texture.wrapT ),
  50824. addressModeW: this._convertAddressMode( texture.wrapR ),
  50825. magFilter: this._convertFilterMode( texture.magFilter ),
  50826. minFilter: this._convertFilterMode( texture.minFilter ),
  50827. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  50828. maxAnisotropy: 1
  50829. };
  50830. // anisotropy can only be used when all filter modes are set to linear.
  50831. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  50832. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  50833. }
  50834. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  50835. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  50836. }
  50837. const sampler = backend.device.createSampler( samplerDescriptorGPU );
  50838. samplerData = { sampler, usedTimes: 0 };
  50839. this._samplerCache.set( samplerKey, samplerData );
  50840. }
  50841. const textureData = backend.get( texture );
  50842. if ( textureData.sampler !== samplerData.sampler ) {
  50843. // check if previous sampler is unused so it can be deleted
  50844. if ( textureData.sampler !== undefined ) {
  50845. const oldSamplerData = this._samplerCache.get( textureData.samplerKey );
  50846. oldSamplerData.usedTimes --;
  50847. if ( oldSamplerData.usedTimes === 0 ) {
  50848. this._samplerCache.delete( textureData.samplerKey );
  50849. }
  50850. }
  50851. // update to new sampler data
  50852. textureData.samplerKey = samplerKey;
  50853. textureData.sampler = samplerData.sampler;
  50854. samplerData.usedTimes ++;
  50855. }
  50856. return samplerKey;
  50857. }
  50858. /**
  50859. * Creates a default texture for the given texture that can be used
  50860. * as a placeholder until the actual texture is ready for usage.
  50861. *
  50862. * @param {Texture} texture - The texture to create a default texture for.
  50863. */
  50864. createDefaultTexture( texture ) {
  50865. let textureGPU;
  50866. const format = getFormat( texture );
  50867. if ( texture.isCubeTexture ) {
  50868. textureGPU = this._getDefaultCubeTextureGPU( format );
  50869. } else {
  50870. textureGPU = this._getDefaultTextureGPU( format );
  50871. }
  50872. this.backend.get( texture ).texture = textureGPU;
  50873. }
  50874. /**
  50875. * Defines a texture on the GPU for the given texture object.
  50876. *
  50877. * @param {Texture} texture - The texture.
  50878. * @param {Object} [options={}] - Optional configuration parameter.
  50879. */
  50880. createTexture( texture, options = {} ) {
  50881. const backend = this.backend;
  50882. const textureData = backend.get( texture );
  50883. if ( textureData.initialized ) {
  50884. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  50885. }
  50886. if ( texture.isExternalTexture ) {
  50887. textureData.texture = texture.sourceTexture;
  50888. textureData.initialized = true;
  50889. return;
  50890. }
  50891. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  50892. if ( options.levels === undefined ) options.levels = 1;
  50893. if ( options.depth === undefined ) options.depth = 1;
  50894. const { width, height, depth, levels } = options;
  50895. if ( texture.isFramebufferTexture ) {
  50896. if ( options.renderTarget ) {
  50897. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  50898. } else {
  50899. options.format = this.backend.utils.getPreferredCanvasFormat();
  50900. }
  50901. }
  50902. const dimension = this._getDimension( texture );
  50903. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  50904. textureData.format = format;
  50905. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  50906. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  50907. if ( texture.isStorageTexture === true ) {
  50908. usage |= GPUTextureUsage.STORAGE_BINDING;
  50909. }
  50910. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true && format !== GPUTextureFormat.RGB9E5UFloat ) {
  50911. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  50912. }
  50913. const textureDescriptorGPU = {
  50914. label: texture.name,
  50915. size: {
  50916. width: width,
  50917. height: height,
  50918. depthOrArrayLayers: depth,
  50919. },
  50920. mipLevelCount: levels,
  50921. sampleCount: primarySamples,
  50922. dimension: dimension,
  50923. format: format,
  50924. usage: usage
  50925. };
  50926. // texture creation
  50927. if ( format === undefined ) {
  50928. warn( 'WebGPURenderer: Texture format not supported.' );
  50929. this.createDefaultTexture( texture );
  50930. return;
  50931. }
  50932. if ( texture.isCubeTexture ) {
  50933. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  50934. }
  50935. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  50936. if ( isMSAA ) {
  50937. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  50938. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  50939. msaaTextureDescriptorGPU.sampleCount = samples;
  50940. msaaTextureDescriptorGPU.mipLevelCount = 1; // See https://www.w3.org/TR/webgpu/#texture-creation
  50941. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  50942. }
  50943. textureData.initialized = true;
  50944. textureData.textureDescriptorGPU = textureDescriptorGPU;
  50945. }
  50946. /**
  50947. * Destroys the GPU data for the given texture object.
  50948. *
  50949. * @param {Texture} texture - The texture.
  50950. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  50951. */
  50952. destroyTexture( texture, isDefaultTexture = false ) {
  50953. const backend = this.backend;
  50954. const textureData = backend.get( texture );
  50955. if ( textureData.texture !== undefined && isDefaultTexture === false ) textureData.texture.destroy();
  50956. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  50957. backend.delete( texture );
  50958. }
  50959. /**
  50960. * Generates mipmaps for the given texture.
  50961. *
  50962. * @param {Texture} texture - The texture.
  50963. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  50964. */
  50965. generateMipmaps( texture, encoder = null ) {
  50966. const textureData = this.backend.get( texture );
  50967. if ( texture.isCubeTexture ) {
  50968. for ( let i = 0; i < 6; i ++ ) {
  50969. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i, encoder );
  50970. }
  50971. } else {
  50972. const depth = texture.image.depth || 1;
  50973. for ( let i = 0; i < depth; i ++ ) {
  50974. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i, encoder );
  50975. }
  50976. }
  50977. }
  50978. /**
  50979. * Returns the color buffer representing the color
  50980. * attachment of the default framebuffer.
  50981. *
  50982. * @return {GPUTexture} The color buffer.
  50983. */
  50984. getColorBuffer() {
  50985. const backend = this.backend;
  50986. const canvasTarget = backend.renderer.getCanvasTarget();
  50987. const { width, height } = backend.getDrawingBufferSize();
  50988. const samples = backend.renderer.currentSamples;
  50989. const colorTexture = canvasTarget.colorTexture;
  50990. const colorTextureData = backend.get( colorTexture );
  50991. if ( colorTexture.width === width && colorTexture.height === height && colorTexture.samples === samples ) {
  50992. return colorTextureData.texture;
  50993. }
  50994. // recreate
  50995. let colorBuffer = colorTextureData.texture;
  50996. if ( colorBuffer ) colorBuffer.destroy();
  50997. colorBuffer = backend.device.createTexture( {
  50998. label: 'colorBuffer',
  50999. size: {
  51000. width: width,
  51001. height: height,
  51002. depthOrArrayLayers: 1
  51003. },
  51004. sampleCount: backend.utils.getSampleCount( backend.renderer.currentSamples ),
  51005. format: backend.utils.getPreferredCanvasFormat(),
  51006. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  51007. } );
  51008. //
  51009. colorTexture.source.width = width;
  51010. colorTexture.source.height = height;
  51011. colorTexture.samples = samples;
  51012. colorTextureData.texture = colorBuffer;
  51013. return colorBuffer;
  51014. }
  51015. /**
  51016. * Returns the depth buffer representing the depth
  51017. * attachment of the default framebuffer.
  51018. *
  51019. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  51020. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  51021. * @return {GPUTexture} The depth buffer.
  51022. */
  51023. getDepthBuffer( depth = true, stencil = false ) {
  51024. const backend = this.backend;
  51025. const canvasTarget = backend.renderer.getCanvasTarget();
  51026. const { width, height } = backend.getDrawingBufferSize();
  51027. const samples = backend.renderer.currentSamples;
  51028. const depthTexture = canvasTarget.depthTexture;
  51029. if ( depthTexture.width === width &&
  51030. depthTexture.height === height &&
  51031. depthTexture.samples === samples &&
  51032. depthTexture.depth === depth &&
  51033. depthTexture.stencil === stencil ) {
  51034. return backend.get( depthTexture ).texture;
  51035. }
  51036. //
  51037. const depthTextureGPU = backend.get( depthTexture ).texture;
  51038. let format, type;
  51039. if ( stencil ) {
  51040. format = DepthStencilFormat;
  51041. type = UnsignedInt248Type;
  51042. } else if ( depth ) {
  51043. format = DepthFormat;
  51044. type = UnsignedIntType;
  51045. }
  51046. if ( depthTextureGPU !== undefined ) {
  51047. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type && depthTexture.samples === samples ) {
  51048. return depthTextureGPU;
  51049. }
  51050. this.destroyTexture( depthTexture );
  51051. }
  51052. // recreate
  51053. depthTexture.name = 'depthBuffer';
  51054. depthTexture.format = format;
  51055. depthTexture.type = type;
  51056. depthTexture.image.width = width;
  51057. depthTexture.image.height = height;
  51058. depthTexture.samples = samples;
  51059. this.createTexture( depthTexture, { width, height } );
  51060. return backend.get( depthTexture ).texture;
  51061. }
  51062. /**
  51063. * Uploads the updated texture data to the GPU.
  51064. *
  51065. * @param {Texture} texture - The texture.
  51066. * @param {Object} [options={}] - Optional configuration parameter.
  51067. */
  51068. updateTexture( texture, options ) {
  51069. const textureData = this.backend.get( texture );
  51070. const mipmaps = texture.mipmaps;
  51071. const { textureDescriptorGPU } = textureData;
  51072. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  51073. return;
  51074. // transfer texture data
  51075. if ( texture.isDataTexture ) {
  51076. if ( mipmaps.length > 0 ) {
  51077. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  51078. const mipmap = mipmaps[ i ];
  51079. this._copyBufferToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, 0, i );
  51080. }
  51081. } else {
  51082. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  51083. }
  51084. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  51085. for ( let i = 0; i < options.image.depth; i ++ ) {
  51086. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  51087. }
  51088. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  51089. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  51090. } else if ( texture.isCubeTexture ) {
  51091. this._copyCubeMapToTexture( texture, textureData.texture, textureDescriptorGPU );
  51092. } else {
  51093. if ( mipmaps.length > 0 ) {
  51094. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  51095. const mipmap = mipmaps[ i ];
  51096. this._copyImageToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha, i );
  51097. }
  51098. } else {
  51099. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  51100. }
  51101. }
  51102. //
  51103. textureData.version = texture.version;
  51104. }
  51105. /**
  51106. * Returns texture data as a typed array.
  51107. *
  51108. * @async
  51109. * @param {Texture} texture - The texture to copy.
  51110. * @param {number} x - The x coordinate of the copy origin.
  51111. * @param {number} y - The y coordinate of the copy origin.
  51112. * @param {number} width - The width of the copy.
  51113. * @param {number} height - The height of the copy.
  51114. * @param {number} faceIndex - The face index.
  51115. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  51116. */
  51117. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  51118. const device = this.backend.device;
  51119. const textureData = this.backend.get( texture );
  51120. const textureGPU = textureData.texture;
  51121. const format = textureData.textureDescriptorGPU.format;
  51122. const bytesPerTexel = this._getBytesPerTexel( format );
  51123. let bytesPerRow = width * bytesPerTexel;
  51124. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  51125. const readBuffer = device.createBuffer(
  51126. {
  51127. size: ( ( height - 1 ) * bytesPerRow ) + ( width * bytesPerTexel ), // see https://github.com/mrdoob/three.js/issues/31658#issuecomment-3229442010
  51128. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  51129. }
  51130. );
  51131. const encoder = device.createCommandEncoder();
  51132. encoder.copyTextureToBuffer(
  51133. {
  51134. texture: textureGPU,
  51135. origin: { x, y, z: faceIndex },
  51136. },
  51137. {
  51138. buffer: readBuffer,
  51139. bytesPerRow: bytesPerRow
  51140. },
  51141. {
  51142. width: width,
  51143. height: height
  51144. }
  51145. );
  51146. const typedArrayType = this._getTypedArrayType( format );
  51147. device.queue.submit( [ encoder.finish() ] );
  51148. await readBuffer.mapAsync( GPUMapMode.READ );
  51149. const buffer = readBuffer.getMappedRange();
  51150. return new typedArrayType( buffer );
  51151. }
  51152. /**
  51153. * Frees all internal resources.
  51154. */
  51155. dispose() {
  51156. this._samplerCache.clear();
  51157. }
  51158. /**
  51159. * Returns the default GPU texture for the given format.
  51160. *
  51161. * @private
  51162. * @param {string} format - The GPU format.
  51163. * @return {GPUTexture} The GPU texture.
  51164. */
  51165. _getDefaultTextureGPU( format ) {
  51166. let defaultTexture = this.defaultTexture[ format ];
  51167. if ( defaultTexture === undefined ) {
  51168. const texture = new Texture();
  51169. texture.minFilter = NearestFilter;
  51170. texture.magFilter = NearestFilter;
  51171. this.createTexture( texture, { width: 1, height: 1, format } );
  51172. this.defaultTexture[ format ] = defaultTexture = texture;
  51173. }
  51174. return this.backend.get( defaultTexture ).texture;
  51175. }
  51176. /**
  51177. * Returns the default GPU cube texture for the given format.
  51178. *
  51179. * @private
  51180. * @param {string} format - The GPU format.
  51181. * @return {GPUTexture} The GPU texture.
  51182. */
  51183. _getDefaultCubeTextureGPU( format ) {
  51184. let defaultCubeTexture = this.defaultTexture[ format ];
  51185. if ( defaultCubeTexture === undefined ) {
  51186. const texture = new CubeTexture();
  51187. texture.minFilter = NearestFilter;
  51188. texture.magFilter = NearestFilter;
  51189. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  51190. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  51191. }
  51192. return this.backend.get( defaultCubeTexture ).texture;
  51193. }
  51194. /**
  51195. * Uploads cube texture image data to the GPU memory.
  51196. *
  51197. * @private
  51198. * @param {CubeTexture} texture - The cube texture.
  51199. * @param {GPUTexture} textureGPU - The GPU texture.
  51200. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51201. */
  51202. _copyCubeMapToTexture( texture, textureGPU, textureDescriptorGPU ) {
  51203. const images = texture.images;
  51204. const mipmaps = texture.mipmaps;
  51205. for ( let i = 0; i < 6; i ++ ) {
  51206. const image = images[ i ];
  51207. const flipIndex = texture.flipY === true ? _flipMap[ i ] : i;
  51208. if ( image.isDataTexture ) {
  51209. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY );
  51210. } else {
  51211. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha );
  51212. }
  51213. for ( let j = 0; j < mipmaps.length; j ++ ) {
  51214. const mipmap = mipmaps[ j ];
  51215. const image = mipmap.images[ i ];
  51216. if ( image.isDataTexture ) {
  51217. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, 0, j + 1 );
  51218. } else {
  51219. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha, j + 1 );
  51220. }
  51221. }
  51222. }
  51223. }
  51224. /**
  51225. * Uploads texture image data to the GPU memory.
  51226. *
  51227. * @private
  51228. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  51229. * @param {GPUTexture} textureGPU - The GPU texture.
  51230. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51231. * @param {number} originDepth - The origin depth.
  51232. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  51233. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  51234. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  51235. */
  51236. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha, mipLevel = 0 ) {
  51237. const device = this.backend.device;
  51238. const width = ( mipLevel > 0 ) ? image.width : textureDescriptorGPU.size.width;
  51239. const height = ( mipLevel > 0 ) ? image.height : textureDescriptorGPU.size.height;
  51240. device.queue.copyExternalImageToTexture(
  51241. {
  51242. source: image,
  51243. flipY: flipY
  51244. }, {
  51245. texture: textureGPU,
  51246. mipLevel: mipLevel,
  51247. origin: { x: 0, y: 0, z: originDepth },
  51248. premultipliedAlpha: premultiplyAlpha
  51249. }, {
  51250. width: width,
  51251. height: height,
  51252. depthOrArrayLayers: 1
  51253. }
  51254. );
  51255. }
  51256. /**
  51257. * Returns the pass utils singleton.
  51258. *
  51259. * @private
  51260. * @return {WebGPUTexturePassUtils} The utils instance.
  51261. */
  51262. _getPassUtils() {
  51263. let passUtils = this._passUtils;
  51264. if ( passUtils === null ) {
  51265. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  51266. }
  51267. return passUtils;
  51268. }
  51269. /**
  51270. * Generates mipmaps for the given GPU texture.
  51271. *
  51272. * @private
  51273. * @param {GPUTexture} textureGPU - The GPU texture object.
  51274. * @param {Object} textureDescriptorGPU - The texture descriptor.
  51275. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  51276. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  51277. */
  51278. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0, encoder = null ) {
  51279. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer, encoder );
  51280. }
  51281. /**
  51282. * Flip the contents of the given GPU texture along its vertical axis.
  51283. *
  51284. * @private
  51285. * @param {GPUTexture} textureGPU - The GPU texture object.
  51286. * @param {Object} textureDescriptorGPU - The texture descriptor.
  51287. * @param {number} [originDepth=0] - The origin depth.
  51288. */
  51289. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  51290. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  51291. }
  51292. /**
  51293. * Uploads texture buffer data to the GPU memory.
  51294. *
  51295. * @private
  51296. * @param {Object} image - An object defining the image buffer data.
  51297. * @param {GPUTexture} textureGPU - The GPU texture.
  51298. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51299. * @param {number} originDepth - The origin depth.
  51300. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  51301. * @param {number} [depth=0] - The depth offset when copying array or 3D texture data.
  51302. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  51303. */
  51304. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0, mipLevel = 0 ) {
  51305. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  51306. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  51307. const device = this.backend.device;
  51308. const data = image.data;
  51309. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  51310. const bytesPerRow = image.width * bytesPerTexel;
  51311. device.queue.writeTexture(
  51312. {
  51313. texture: textureGPU,
  51314. mipLevel: mipLevel,
  51315. origin: { x: 0, y: 0, z: originDepth }
  51316. },
  51317. data,
  51318. {
  51319. offset: image.width * image.height * bytesPerTexel * depth,
  51320. bytesPerRow
  51321. },
  51322. {
  51323. width: image.width,
  51324. height: image.height,
  51325. depthOrArrayLayers: 1
  51326. } );
  51327. if ( flipY === true ) {
  51328. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  51329. }
  51330. }
  51331. /**
  51332. * Uploads compressed texture data to the GPU memory.
  51333. *
  51334. * @private
  51335. * @param {Array<Object>} mipmaps - An array with mipmap data.
  51336. * @param {GPUTexture} textureGPU - The GPU texture.
  51337. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51338. */
  51339. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  51340. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  51341. const device = this.backend.device;
  51342. const blockData = this._getBlockData( textureDescriptorGPU.format );
  51343. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  51344. for ( let i = 0; i < mipmaps.length; i ++ ) {
  51345. const mipmap = mipmaps[ i ];
  51346. const width = mipmap.width;
  51347. const height = mipmap.height;
  51348. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  51349. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  51350. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  51351. for ( let j = 0; j < depth; j ++ ) {
  51352. device.queue.writeTexture(
  51353. {
  51354. texture: textureGPU,
  51355. mipLevel: i,
  51356. origin: { x: 0, y: 0, z: j }
  51357. },
  51358. mipmap.data,
  51359. {
  51360. offset: j * bytesPerImage,
  51361. bytesPerRow,
  51362. rowsPerImage: Math.ceil( height / blockData.height )
  51363. },
  51364. {
  51365. width: Math.ceil( width / blockData.width ) * blockData.width,
  51366. height: Math.ceil( height / blockData.height ) * blockData.height,
  51367. depthOrArrayLayers: 1
  51368. }
  51369. );
  51370. }
  51371. }
  51372. }
  51373. /**
  51374. * This method is only relevant for compressed texture formats. It returns a block
  51375. * data descriptor for the given GPU compressed texture format.
  51376. *
  51377. * @private
  51378. * @param {string} format - The GPU compressed texture format.
  51379. * @return {Object} The block data descriptor.
  51380. */
  51381. _getBlockData( format ) {
  51382. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  51383. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  51384. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  51385. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  51386. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  51387. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  51388. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  51389. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  51390. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  51391. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  51392. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  51393. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  51394. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  51395. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  51396. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  51397. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  51398. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  51399. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  51400. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  51401. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  51402. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  51403. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  51404. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  51405. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  51406. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  51407. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  51408. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  51409. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  51410. }
  51411. /**
  51412. * Converts the three.js uv wrapping constants to GPU address mode constants.
  51413. *
  51414. * @private
  51415. * @param {number} value - The three.js constant defining a uv wrapping mode.
  51416. * @return {string} The GPU address mode.
  51417. */
  51418. _convertAddressMode( value ) {
  51419. let addressMode = GPUAddressMode.ClampToEdge;
  51420. if ( value === RepeatWrapping ) {
  51421. addressMode = GPUAddressMode.Repeat;
  51422. } else if ( value === MirroredRepeatWrapping ) {
  51423. addressMode = GPUAddressMode.MirrorRepeat;
  51424. }
  51425. return addressMode;
  51426. }
  51427. /**
  51428. * Converts the three.js filter constants to GPU filter constants.
  51429. *
  51430. * @private
  51431. * @param {number} value - The three.js constant defining a filter mode.
  51432. * @return {string} The GPU filter mode.
  51433. */
  51434. _convertFilterMode( value ) {
  51435. let filterMode = GPUFilterMode.Linear;
  51436. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  51437. filterMode = GPUFilterMode.Nearest;
  51438. }
  51439. return filterMode;
  51440. }
  51441. /**
  51442. * Returns the bytes-per-texel value for the given GPU texture format.
  51443. *
  51444. * @private
  51445. * @param {string} format - The GPU texture format.
  51446. * @return {number} The bytes-per-texel.
  51447. */
  51448. _getBytesPerTexel( format ) {
  51449. // 8-bit formats
  51450. if ( format === GPUTextureFormat.R8Unorm ||
  51451. format === GPUTextureFormat.R8Snorm ||
  51452. format === GPUTextureFormat.R8Uint ||
  51453. format === GPUTextureFormat.R8Sint ) return 1;
  51454. // 16-bit formats
  51455. if ( format === GPUTextureFormat.R16Uint ||
  51456. format === GPUTextureFormat.R16Sint ||
  51457. format === GPUTextureFormat.R16Float ||
  51458. format === GPUTextureFormat.RG8Unorm ||
  51459. format === GPUTextureFormat.RG8Snorm ||
  51460. format === GPUTextureFormat.RG8Uint ||
  51461. format === GPUTextureFormat.RG8Sint ) return 2;
  51462. // 32-bit formats
  51463. if ( format === GPUTextureFormat.R32Uint ||
  51464. format === GPUTextureFormat.R32Sint ||
  51465. format === GPUTextureFormat.R32Float ||
  51466. format === GPUTextureFormat.RG16Uint ||
  51467. format === GPUTextureFormat.RG16Sint ||
  51468. format === GPUTextureFormat.RG16Float ||
  51469. format === GPUTextureFormat.RGBA8Unorm ||
  51470. format === GPUTextureFormat.RGBA8UnormSRGB ||
  51471. format === GPUTextureFormat.RGBA8Snorm ||
  51472. format === GPUTextureFormat.RGBA8Uint ||
  51473. format === GPUTextureFormat.RGBA8Sint ||
  51474. format === GPUTextureFormat.BGRA8Unorm ||
  51475. format === GPUTextureFormat.BGRA8UnormSRGB ||
  51476. // Packed 32-bit formats
  51477. format === GPUTextureFormat.RGB9E5UFloat ||
  51478. format === GPUTextureFormat.RGB10A2Unorm ||
  51479. format === GPUTextureFormat.RG11B10UFloat ||
  51480. format === GPUTextureFormat.Depth32Float ||
  51481. format === GPUTextureFormat.Depth24Plus ||
  51482. format === GPUTextureFormat.Depth24PlusStencil8 ||
  51483. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  51484. // 64-bit formats
  51485. if ( format === GPUTextureFormat.RG32Uint ||
  51486. format === GPUTextureFormat.RG32Sint ||
  51487. format === GPUTextureFormat.RG32Float ||
  51488. format === GPUTextureFormat.RGBA16Uint ||
  51489. format === GPUTextureFormat.RGBA16Sint ||
  51490. format === GPUTextureFormat.RGBA16Float ) return 8;
  51491. // 128-bit formats
  51492. if ( format === GPUTextureFormat.RGBA32Uint ||
  51493. format === GPUTextureFormat.RGBA32Sint ||
  51494. format === GPUTextureFormat.RGBA32Float ) return 16;
  51495. }
  51496. /**
  51497. * Returns the corresponding typed array type for the given GPU texture format.
  51498. *
  51499. * @private
  51500. * @param {string} format - The GPU texture format.
  51501. * @return {TypedArray.constructor} The typed array type.
  51502. */
  51503. _getTypedArrayType( format ) {
  51504. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  51505. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  51506. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  51507. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  51508. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  51509. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  51510. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  51511. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  51512. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  51513. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  51514. if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return Uint8Array;
  51515. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  51516. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  51517. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  51518. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  51519. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  51520. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  51521. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  51522. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  51523. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  51524. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  51525. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  51526. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  51527. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  51528. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  51529. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  51530. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  51531. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  51532. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  51533. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  51534. if ( format === GPUTextureFormat.BGRA8Unorm || format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  51535. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  51536. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  51537. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  51538. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  51539. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  51540. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  51541. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  51542. }
  51543. /**
  51544. * Returns the GPU dimensions for the given texture.
  51545. *
  51546. * @private
  51547. * @param {Texture} texture - The texture.
  51548. * @return {string} The GPU dimension.
  51549. */
  51550. _getDimension( texture ) {
  51551. let dimension;
  51552. if ( texture.is3DTexture || texture.isData3DTexture ) {
  51553. dimension = GPUTextureDimension.ThreeD;
  51554. } else {
  51555. dimension = GPUTextureDimension.TwoD;
  51556. }
  51557. return dimension;
  51558. }
  51559. }
  51560. /**
  51561. * Returns the GPU format for the given texture.
  51562. *
  51563. * @param {Texture} texture - The texture.
  51564. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  51565. * It is not necessary to apply the device for most formats.
  51566. * @return {string} The GPU format.
  51567. */
  51568. function getFormat( texture, device = null ) {
  51569. const format = texture.format;
  51570. const type = texture.type;
  51571. const colorSpace = texture.colorSpace;
  51572. const transfer = ColorManagement.getTransfer( colorSpace );
  51573. let formatGPU;
  51574. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  51575. switch ( format ) {
  51576. case RGB_S3TC_DXT1_Format:
  51577. case RGBA_S3TC_DXT1_Format:
  51578. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  51579. break;
  51580. case RGBA_S3TC_DXT3_Format:
  51581. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  51582. break;
  51583. case RGBA_S3TC_DXT5_Format:
  51584. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  51585. break;
  51586. case RED_RGTC1_Format:
  51587. formatGPU = GPUTextureFormat.BC4RUnorm;
  51588. break;
  51589. case SIGNED_RED_RGTC1_Format:
  51590. formatGPU = GPUTextureFormat.BC4RSnorm;
  51591. break;
  51592. case RED_GREEN_RGTC2_Format:
  51593. formatGPU = GPUTextureFormat.BC5RGUnorm;
  51594. break;
  51595. case SIGNED_RED_GREEN_RGTC2_Format:
  51596. formatGPU = GPUTextureFormat.BC5RGSnorm;
  51597. break;
  51598. case RGBA_BPTC_Format:
  51599. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC7RGBAUnormSRGB : GPUTextureFormat.BC7RGBAUnorm;
  51600. break;
  51601. case RGB_ETC2_Format:
  51602. case RGB_ETC1_Format:
  51603. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  51604. break;
  51605. case RGBA_ETC2_EAC_Format:
  51606. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  51607. break;
  51608. case R11_EAC_Format:
  51609. formatGPU = GPUTextureFormat.EACR11Unorm;
  51610. break;
  51611. case SIGNED_R11_EAC_Format:
  51612. formatGPU = GPUTextureFormat.EACR11Snorm;
  51613. break;
  51614. case RG11_EAC_Format:
  51615. formatGPU = GPUTextureFormat.EACRG11Unorm;
  51616. break;
  51617. case SIGNED_RG11_EAC_Format:
  51618. formatGPU = GPUTextureFormat.EACRG11Snorm;
  51619. break;
  51620. case RGBA_ASTC_4x4_Format:
  51621. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  51622. break;
  51623. case RGBA_ASTC_5x4_Format:
  51624. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  51625. break;
  51626. case RGBA_ASTC_5x5_Format:
  51627. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  51628. break;
  51629. case RGBA_ASTC_6x5_Format:
  51630. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  51631. break;
  51632. case RGBA_ASTC_6x6_Format:
  51633. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  51634. break;
  51635. case RGBA_ASTC_8x5_Format:
  51636. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  51637. break;
  51638. case RGBA_ASTC_8x6_Format:
  51639. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  51640. break;
  51641. case RGBA_ASTC_8x8_Format:
  51642. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  51643. break;
  51644. case RGBA_ASTC_10x5_Format:
  51645. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  51646. break;
  51647. case RGBA_ASTC_10x6_Format:
  51648. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  51649. break;
  51650. case RGBA_ASTC_10x8_Format:
  51651. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  51652. break;
  51653. case RGBA_ASTC_10x10_Format:
  51654. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  51655. break;
  51656. case RGBA_ASTC_12x10_Format:
  51657. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  51658. break;
  51659. case RGBA_ASTC_12x12_Format:
  51660. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  51661. break;
  51662. case RGBAFormat:
  51663. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  51664. break;
  51665. default:
  51666. error( 'WebGPURenderer: Unsupported texture format.', format );
  51667. }
  51668. } else {
  51669. switch ( format ) {
  51670. case RGBAFormat:
  51671. switch ( type ) {
  51672. case ByteType:
  51673. formatGPU = GPUTextureFormat.RGBA8Snorm;
  51674. break;
  51675. case ShortType:
  51676. formatGPU = GPUTextureFormat.RGBA16Sint;
  51677. break;
  51678. case UnsignedShortType:
  51679. formatGPU = GPUTextureFormat.RGBA16Uint;
  51680. break;
  51681. case UnsignedIntType:
  51682. formatGPU = GPUTextureFormat.RGBA32Uint;
  51683. break;
  51684. case IntType:
  51685. formatGPU = GPUTextureFormat.RGBA32Sint;
  51686. break;
  51687. case UnsignedByteType:
  51688. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  51689. break;
  51690. case HalfFloatType:
  51691. formatGPU = GPUTextureFormat.RGBA16Float;
  51692. break;
  51693. case FloatType:
  51694. formatGPU = GPUTextureFormat.RGBA32Float;
  51695. break;
  51696. default:
  51697. error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  51698. }
  51699. break;
  51700. case RGBFormat:
  51701. switch ( type ) {
  51702. case UnsignedInt5999Type:
  51703. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  51704. break;
  51705. case UnsignedInt101111Type:
  51706. formatGPU = GPUTextureFormat.RG11B10UFloat;
  51707. break;
  51708. default:
  51709. error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  51710. }
  51711. break;
  51712. case RedFormat:
  51713. switch ( type ) {
  51714. case ByteType:
  51715. formatGPU = GPUTextureFormat.R8Snorm;
  51716. break;
  51717. case ShortType:
  51718. formatGPU = GPUTextureFormat.R16Sint;
  51719. break;
  51720. case UnsignedShortType:
  51721. formatGPU = GPUTextureFormat.R16Uint;
  51722. break;
  51723. case UnsignedIntType:
  51724. formatGPU = GPUTextureFormat.R32Uint;
  51725. break;
  51726. case IntType:
  51727. formatGPU = GPUTextureFormat.R32Sint;
  51728. break;
  51729. case UnsignedByteType:
  51730. formatGPU = GPUTextureFormat.R8Unorm;
  51731. break;
  51732. case HalfFloatType:
  51733. formatGPU = GPUTextureFormat.R16Float;
  51734. break;
  51735. case FloatType:
  51736. formatGPU = GPUTextureFormat.R32Float;
  51737. break;
  51738. default:
  51739. error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  51740. }
  51741. break;
  51742. case RGFormat:
  51743. switch ( type ) {
  51744. case ByteType:
  51745. formatGPU = GPUTextureFormat.RG8Snorm;
  51746. break;
  51747. case ShortType:
  51748. formatGPU = GPUTextureFormat.RG16Sint;
  51749. break;
  51750. case UnsignedShortType:
  51751. formatGPU = GPUTextureFormat.RG16Uint;
  51752. break;
  51753. case UnsignedIntType:
  51754. formatGPU = GPUTextureFormat.RG32Uint;
  51755. break;
  51756. case IntType:
  51757. formatGPU = GPUTextureFormat.RG32Sint;
  51758. break;
  51759. case UnsignedByteType:
  51760. formatGPU = GPUTextureFormat.RG8Unorm;
  51761. break;
  51762. case HalfFloatType:
  51763. formatGPU = GPUTextureFormat.RG16Float;
  51764. break;
  51765. case FloatType:
  51766. formatGPU = GPUTextureFormat.RG32Float;
  51767. break;
  51768. default:
  51769. error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  51770. }
  51771. break;
  51772. case DepthFormat:
  51773. switch ( type ) {
  51774. case UnsignedShortType:
  51775. formatGPU = GPUTextureFormat.Depth16Unorm;
  51776. break;
  51777. case UnsignedIntType:
  51778. formatGPU = GPUTextureFormat.Depth24Plus;
  51779. break;
  51780. case FloatType:
  51781. formatGPU = GPUTextureFormat.Depth32Float;
  51782. break;
  51783. default:
  51784. error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  51785. }
  51786. break;
  51787. case DepthStencilFormat:
  51788. switch ( type ) {
  51789. case UnsignedInt248Type:
  51790. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  51791. break;
  51792. case FloatType:
  51793. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  51794. error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  51795. }
  51796. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  51797. break;
  51798. default:
  51799. error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  51800. }
  51801. break;
  51802. case RedIntegerFormat:
  51803. switch ( type ) {
  51804. case IntType:
  51805. formatGPU = GPUTextureFormat.R32Sint;
  51806. break;
  51807. case UnsignedIntType:
  51808. formatGPU = GPUTextureFormat.R32Uint;
  51809. break;
  51810. default:
  51811. error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  51812. }
  51813. break;
  51814. case RGIntegerFormat:
  51815. switch ( type ) {
  51816. case IntType:
  51817. formatGPU = GPUTextureFormat.RG32Sint;
  51818. break;
  51819. case UnsignedIntType:
  51820. formatGPU = GPUTextureFormat.RG32Uint;
  51821. break;
  51822. default:
  51823. error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  51824. }
  51825. break;
  51826. case RGBAIntegerFormat:
  51827. switch ( type ) {
  51828. case IntType:
  51829. formatGPU = GPUTextureFormat.RGBA32Sint;
  51830. break;
  51831. case UnsignedIntType:
  51832. formatGPU = GPUTextureFormat.RGBA32Uint;
  51833. break;
  51834. default:
  51835. error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  51836. }
  51837. break;
  51838. default:
  51839. error( 'WebGPURenderer: Unsupported texture format.', format );
  51840. }
  51841. }
  51842. return formatGPU;
  51843. }
  51844. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  51845. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  51846. const wgslTypeLib$1 = {
  51847. 'f32': 'float',
  51848. 'i32': 'int',
  51849. 'u32': 'uint',
  51850. 'bool': 'bool',
  51851. 'vec2<f32>': 'vec2',
  51852. 'vec2<i32>': 'ivec2',
  51853. 'vec2<u32>': 'uvec2',
  51854. 'vec2<bool>': 'bvec2',
  51855. 'vec2f': 'vec2',
  51856. 'vec2i': 'ivec2',
  51857. 'vec2u': 'uvec2',
  51858. 'vec2b': 'bvec2',
  51859. 'vec3<f32>': 'vec3',
  51860. 'vec3<i32>': 'ivec3',
  51861. 'vec3<u32>': 'uvec3',
  51862. 'vec3<bool>': 'bvec3',
  51863. 'vec3f': 'vec3',
  51864. 'vec3i': 'ivec3',
  51865. 'vec3u': 'uvec3',
  51866. 'vec3b': 'bvec3',
  51867. 'vec4<f32>': 'vec4',
  51868. 'vec4<i32>': 'ivec4',
  51869. 'vec4<u32>': 'uvec4',
  51870. 'vec4<bool>': 'bvec4',
  51871. 'vec4f': 'vec4',
  51872. 'vec4i': 'ivec4',
  51873. 'vec4u': 'uvec4',
  51874. 'vec4b': 'bvec4',
  51875. 'mat2x2<f32>': 'mat2',
  51876. 'mat2x2f': 'mat2',
  51877. 'mat3x3<f32>': 'mat3',
  51878. 'mat3x3f': 'mat3',
  51879. 'mat4x4<f32>': 'mat4',
  51880. 'mat4x4f': 'mat4',
  51881. 'sampler': 'sampler',
  51882. 'texture_1d': 'texture',
  51883. 'texture_2d': 'texture',
  51884. 'texture_2d_array': 'texture',
  51885. 'texture_multisampled_2d': 'cubeTexture',
  51886. 'texture_depth_2d': 'depthTexture',
  51887. 'texture_depth_2d_array': 'depthTexture',
  51888. 'texture_depth_multisampled_2d': 'depthTexture',
  51889. 'texture_depth_cube': 'depthTexture',
  51890. 'texture_depth_cube_array': 'depthTexture',
  51891. 'texture_3d': 'texture3D',
  51892. 'texture_cube': 'cubeTexture',
  51893. 'texture_cube_array': 'cubeTexture',
  51894. 'texture_storage_1d': 'storageTexture',
  51895. 'texture_storage_2d': 'storageTexture',
  51896. 'texture_storage_2d_array': 'storageTexture',
  51897. 'texture_storage_3d': 'storageTexture'
  51898. };
  51899. const parse = ( source ) => {
  51900. source = source.trim();
  51901. const declaration = source.match( declarationRegexp );
  51902. if ( declaration !== null && declaration.length === 4 ) {
  51903. const inputsCode = declaration[ 2 ];
  51904. const propsMatches = [];
  51905. let match = null;
  51906. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  51907. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  51908. }
  51909. // Process matches to correctly pair names and types
  51910. const inputs = [];
  51911. for ( let i = 0; i < propsMatches.length; i ++ ) {
  51912. const { name, type } = propsMatches[ i ];
  51913. let resolvedType = type;
  51914. if ( resolvedType.startsWith( 'ptr' ) ) {
  51915. resolvedType = 'pointer';
  51916. } else {
  51917. if ( resolvedType.startsWith( 'texture' ) ) {
  51918. resolvedType = type.split( '<' )[ 0 ];
  51919. }
  51920. resolvedType = wgslTypeLib$1[ resolvedType ];
  51921. }
  51922. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  51923. }
  51924. const blockCode = source.substring( declaration[ 0 ].length );
  51925. const outputType = declaration[ 3 ] || 'void';
  51926. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  51927. const type = wgslTypeLib$1[ outputType ] || outputType;
  51928. return {
  51929. type,
  51930. inputs,
  51931. name,
  51932. inputsCode,
  51933. blockCode,
  51934. outputType
  51935. };
  51936. } else {
  51937. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  51938. }
  51939. };
  51940. /**
  51941. * This class represents a WSL node function.
  51942. *
  51943. * @augments NodeFunction
  51944. */
  51945. class WGSLNodeFunction extends NodeFunction {
  51946. /**
  51947. * Constructs a new WGSL node function.
  51948. *
  51949. * @param {string} source - The WGSL source.
  51950. */
  51951. constructor( source ) {
  51952. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  51953. super( type, inputs, name );
  51954. this.inputsCode = inputsCode;
  51955. this.blockCode = blockCode;
  51956. this.outputType = outputType;
  51957. }
  51958. /**
  51959. * This method returns the WGSL code of the node function.
  51960. *
  51961. * @param {string} [name=this.name] - The function's name.
  51962. * @return {string} The shader code.
  51963. */
  51964. getCode( name = this.name ) {
  51965. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  51966. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  51967. }
  51968. }
  51969. /**
  51970. * A WGSL node parser.
  51971. *
  51972. * @augments NodeParser
  51973. */
  51974. class WGSLNodeParser extends NodeParser {
  51975. /**
  51976. * The method parses the given WGSL code an returns a node function.
  51977. *
  51978. * @param {string} source - The WGSL code.
  51979. * @return {WGSLNodeFunction} A node function.
  51980. */
  51981. parseFunction( source ) {
  51982. return new WGSLNodeFunction( source );
  51983. }
  51984. }
  51985. const accessNames = {
  51986. [ NodeAccess.READ_ONLY ]: 'read',
  51987. [ NodeAccess.WRITE_ONLY ]: 'write',
  51988. [ NodeAccess.READ_WRITE ]: 'read_write'
  51989. };
  51990. const wrapNames = {
  51991. [ RepeatWrapping ]: 'repeat',
  51992. [ ClampToEdgeWrapping ]: 'clamp',
  51993. [ MirroredRepeatWrapping ]: 'mirror'
  51994. };
  51995. const gpuShaderStageLib = {
  51996. 'vertex': GPUShaderStage.VERTEX,
  51997. 'fragment': GPUShaderStage.FRAGMENT,
  51998. 'compute': GPUShaderStage.COMPUTE
  51999. };
  52000. const supports = {
  52001. instance: true,
  52002. swizzleAssign: false,
  52003. storageBuffer: true
  52004. };
  52005. const wgslFnOpLib = {
  52006. '^^': 'tsl_xor'
  52007. };
  52008. const wgslTypeLib = {
  52009. float: 'f32',
  52010. int: 'i32',
  52011. uint: 'u32',
  52012. bool: 'bool',
  52013. color: 'vec3<f32>',
  52014. vec2: 'vec2<f32>',
  52015. ivec2: 'vec2<i32>',
  52016. uvec2: 'vec2<u32>',
  52017. bvec2: 'vec2<bool>',
  52018. vec3: 'vec3<f32>',
  52019. ivec3: 'vec3<i32>',
  52020. uvec3: 'vec3<u32>',
  52021. bvec3: 'vec3<bool>',
  52022. vec4: 'vec4<f32>',
  52023. ivec4: 'vec4<i32>',
  52024. uvec4: 'vec4<u32>',
  52025. bvec4: 'vec4<bool>',
  52026. mat2: 'mat2x2<f32>',
  52027. mat3: 'mat3x3<f32>',
  52028. mat4: 'mat4x4<f32>'
  52029. };
  52030. const wgslCodeCache = {};
  52031. const wgslPolyfill = {
  52032. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  52033. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  52034. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  52035. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  52036. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  52037. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  52038. 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 ); }' ),
  52039. 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 ); }' ),
  52040. 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 ); }' ),
  52041. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  52042. 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 ); }' ),
  52043. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  52044. biquadraticTexture: new CodeNode( /* wgsl */`
  52045. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  52046. let res = vec2f( iRes );
  52047. let uvScaled = coord * res;
  52048. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  52049. // https://www.shadertoy.com/view/WtyXRy
  52050. let uv = uvWrapping - 0.5;
  52051. let iuv = floor( uv );
  52052. let f = fract( uv );
  52053. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  52054. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  52055. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  52056. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  52057. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  52058. }
  52059. ` )
  52060. };
  52061. const wgslMethods = {
  52062. dFdx: 'dpdx',
  52063. dFdy: '- dpdy',
  52064. mod_float: 'tsl_mod_float',
  52065. mod_vec2: 'tsl_mod_vec2',
  52066. mod_vec3: 'tsl_mod_vec3',
  52067. mod_vec4: 'tsl_mod_vec4',
  52068. equals_bool: 'tsl_equals_bool',
  52069. equals_bvec2: 'tsl_equals_bvec2',
  52070. equals_bvec3: 'tsl_equals_bvec3',
  52071. equals_bvec4: 'tsl_equals_bvec4',
  52072. inversesqrt: 'inverseSqrt',
  52073. bitcast: 'bitcast<f32>',
  52074. floatpack_snorm_2x16: 'pack2x16snorm',
  52075. floatpack_unorm_2x16: 'pack2x16unorm',
  52076. floatpack_float16_2x16: 'pack2x16float',
  52077. floatunpack_snorm_2x16: 'unpack2x16snorm',
  52078. floatunpack_unorm_2x16: 'unpack2x16unorm',
  52079. floatunpack_float16_2x16: 'unpack2x16float'
  52080. };
  52081. //
  52082. let diagnostics = '';
  52083. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  52084. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  52085. }
  52086. /**
  52087. * A node builder targeting WGSL.
  52088. *
  52089. * This module generates WGSL shader code from node materials and also
  52090. * generates the respective bindings and vertex buffer definitions. These
  52091. * data are later used by the renderer to create render and compute pipelines
  52092. * for render objects.
  52093. *
  52094. * @augments NodeBuilder
  52095. */
  52096. class WGSLNodeBuilder extends NodeBuilder {
  52097. /**
  52098. * Constructs a new WGSL node builder renderer.
  52099. *
  52100. * @param {Object3D} object - The 3D object.
  52101. * @param {Renderer} renderer - The renderer.
  52102. */
  52103. constructor( object, renderer ) {
  52104. super( object, renderer, new WGSLNodeParser() );
  52105. /**
  52106. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  52107. * another dictionary which manages UBOs per group ('render','frame','object').
  52108. *
  52109. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  52110. */
  52111. this.uniformGroups = {};
  52112. /**
  52113. * A dictionary that holds for each shader stage a Map of builtins.
  52114. *
  52115. * @type {Object<string,Map<string,Object>>}
  52116. */
  52117. this.builtins = {};
  52118. /**
  52119. * A dictionary that holds for each shader stage a Set of directives.
  52120. *
  52121. * @type {Object<string,Set<string>>}
  52122. */
  52123. this.directives = {};
  52124. /**
  52125. * A map for managing scope arrays. Only relevant for when using
  52126. * {@link WorkgroupInfoNode} in context of compute shaders.
  52127. *
  52128. * @type {Map<string,Object>}
  52129. */
  52130. this.scopedArrays = new Map();
  52131. }
  52132. /**
  52133. * Generates the WGSL snippet for sampled textures.
  52134. *
  52135. * @private
  52136. * @param {Texture} texture - The texture.
  52137. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52138. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52139. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52140. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52141. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52142. * @return {string} The WGSL snippet.
  52143. */
  52144. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52145. if ( shaderStage === 'fragment' ) {
  52146. if ( depthSnippet ) {
  52147. if ( offsetSnippet ) {
  52148. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ offsetSnippet } )`;
  52149. }
  52150. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  52151. } else {
  52152. if ( offsetSnippet ) {
  52153. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ offsetSnippet } )`;
  52154. }
  52155. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  52156. }
  52157. } else {
  52158. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  52159. }
  52160. }
  52161. /**
  52162. * Generates the WGSL snippet when sampling textures with explicit mip level.
  52163. *
  52164. * @private
  52165. * @param {Texture} texture - The texture.
  52166. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52167. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52168. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52169. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52170. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52171. * @return {string} The WGSL snippet.
  52172. */
  52173. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  52174. if ( this.isUnfilterable( texture ) === false ) {
  52175. if ( offsetSnippet ) {
  52176. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  52177. }
  52178. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  52179. } else if ( this.isFilteredTexture( texture ) ) {
  52180. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  52181. } else {
  52182. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  52183. }
  52184. }
  52185. /**
  52186. * Generates a wrap function used in context of textures.
  52187. *
  52188. * @param {Texture} texture - The texture to generate the function for.
  52189. * @return {string} The name of the generated function.
  52190. */
  52191. generateWrapFunction( texture ) {
  52192. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.is3DTexture || texture.isData3DTexture ? '3d' : '2d' }T`;
  52193. let nodeCode = wgslCodeCache[ functionName ];
  52194. if ( nodeCode === undefined ) {
  52195. const includes = [];
  52196. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  52197. const coordType = texture.is3DTexture || texture.isData3DTexture ? 'vec3f' : 'vec2f';
  52198. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  52199. const addWrapSnippet = ( wrap, axis ) => {
  52200. if ( wrap === RepeatWrapping ) {
  52201. includes.push( wgslPolyfill.repeatWrapping_float );
  52202. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  52203. } else if ( wrap === ClampToEdgeWrapping ) {
  52204. includes.push( wgslPolyfill.clampWrapping_float );
  52205. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  52206. } else if ( wrap === MirroredRepeatWrapping ) {
  52207. includes.push( wgslPolyfill.mirrorWrapping_float );
  52208. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  52209. } else {
  52210. code += `\t\tcoord.${ axis }`;
  52211. warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  52212. }
  52213. };
  52214. addWrapSnippet( texture.wrapS, 'x' );
  52215. code += ',\n';
  52216. addWrapSnippet( texture.wrapT, 'y' );
  52217. if ( texture.is3DTexture || texture.isData3DTexture ) {
  52218. code += ',\n';
  52219. addWrapSnippet( texture.wrapR, 'z' );
  52220. }
  52221. code += '\n\t);\n\n}\n';
  52222. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  52223. }
  52224. nodeCode.build( this );
  52225. return functionName;
  52226. }
  52227. /**
  52228. * Generates the array declaration string.
  52229. *
  52230. * @param {string} type - The type.
  52231. * @param {?number} [count] - The count.
  52232. * @return {string} The generated value as a shader string.
  52233. */
  52234. generateArrayDeclaration( type, count ) {
  52235. return `array< ${ this.getType( type ) }, ${ count } >`;
  52236. }
  52237. /**
  52238. * Generates a WGSL variable that holds the texture dimension of the given texture.
  52239. * It also returns information about the number of layers (elements) of an arrayed
  52240. * texture as well as the cube face count of cube textures.
  52241. *
  52242. * @param {Texture} texture - The texture to generate the function for.
  52243. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  52244. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52245. * @return {string} The name of the dimension variable.
  52246. */
  52247. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  52248. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  52249. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  52250. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  52251. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  52252. let textureDimensionsParams;
  52253. let dimensionType;
  52254. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  52255. const isMultisampled = primarySamples > 1;
  52256. if ( texture.is3DTexture || texture.isData3DTexture ) {
  52257. dimensionType = 'vec3<u32>';
  52258. } else {
  52259. // Regular 2D textures, depth textures, etc.
  52260. dimensionType = 'vec2<u32>';
  52261. }
  52262. // Build parameters string based on texture type and multisampling
  52263. if ( isMultisampled || texture.isStorageTexture ) {
  52264. textureDimensionsParams = textureProperty;
  52265. } else {
  52266. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  52267. }
  52268. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  52269. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  52270. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.is3DTexture || texture.isData3DTexture ) {
  52271. textureData.arrayLayerCount = new VarNode(
  52272. new ExpressionNode(
  52273. `textureNumLayers(${textureProperty})`,
  52274. 'u32'
  52275. )
  52276. );
  52277. }
  52278. // For cube textures, we know it's always 6 faces
  52279. if ( texture.isTextureCube ) {
  52280. textureData.cubeFaceCount = new VarNode(
  52281. new ExpressionNode( '6u', 'u32' )
  52282. );
  52283. }
  52284. }
  52285. return textureDimensionNode.build( this );
  52286. }
  52287. /**
  52288. * Generates the WGSL snippet for a manual filtered texture.
  52289. *
  52290. * @param {Texture} texture - The texture.
  52291. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52292. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52293. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52294. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52295. * @return {string} The WGSL snippet.
  52296. */
  52297. generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet = '0u' ) {
  52298. this._include( 'biquadraticTexture' );
  52299. const wrapFunction = this.generateWrapFunction( texture );
  52300. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  52301. if ( offsetSnippet ) {
  52302. uvSnippet = `${ uvSnippet } + vec2<f32>(${ offsetSnippet }) / ${ textureDimension }`;
  52303. }
  52304. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  52305. }
  52306. /**
  52307. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  52308. * Since it's a lookup, no sampling or filtering is applied.
  52309. *
  52310. * @param {Texture} texture - The texture.
  52311. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52312. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52313. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52314. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52315. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52316. * @return {string} The WGSL snippet.
  52317. */
  52318. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet = '0u' ) {
  52319. const wrapFunction = this.generateWrapFunction( texture );
  52320. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  52321. const vecType = texture.is3DTexture || texture.isData3DTexture ? 'vec3' : 'vec2';
  52322. if ( offsetSnippet ) {
  52323. uvSnippet = `${ uvSnippet } + ${ vecType }<f32>(${ offsetSnippet }) / ${ vecType }<f32>( ${ textureDimension } )`;
  52324. }
  52325. const coordSnippet = `${ vecType }<u32>( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) )`;
  52326. return this.generateTextureLoad( texture, textureProperty, coordSnippet, levelSnippet, depthSnippet, null );
  52327. }
  52328. /**
  52329. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  52330. *
  52331. * @param {Texture} texture - The texture.
  52332. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52333. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52334. * @param {?string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52335. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52336. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52337. * @return {string} The WGSL snippet.
  52338. */
  52339. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  52340. if ( levelSnippet === null ) levelSnippet = '0u';
  52341. if ( offsetSnippet ) {
  52342. uvIndexSnippet = `${ uvIndexSnippet } + ${ offsetSnippet }`;
  52343. }
  52344. let snippet;
  52345. if ( depthSnippet ) {
  52346. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  52347. } else {
  52348. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  52349. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  52350. snippet += '.x';
  52351. }
  52352. }
  52353. return snippet;
  52354. }
  52355. /**
  52356. * Generates the WGSL snippet that writes a single texel to a texture.
  52357. *
  52358. * @param {Texture} texture - The texture.
  52359. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52360. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52361. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52362. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  52363. * @return {string} The WGSL snippet.
  52364. */
  52365. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  52366. let snippet;
  52367. if ( depthSnippet ) {
  52368. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  52369. } else {
  52370. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  52371. }
  52372. return snippet;
  52373. }
  52374. /**
  52375. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  52376. *
  52377. * @param {Texture} texture - The texture.
  52378. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  52379. */
  52380. isSampleCompare( texture ) {
  52381. return texture.isDepthTexture === true && texture.compareFunction !== null;
  52382. }
  52383. /**
  52384. * Returns `true` if the given texture is unfilterable.
  52385. *
  52386. * @param {Texture} texture - The texture.
  52387. * @return {boolean} Whether the given texture is unfilterable or not.
  52388. */
  52389. isUnfilterable( texture ) {
  52390. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  52391. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  52392. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  52393. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  52394. }
  52395. /**
  52396. * Generates the WGSL snippet for sampling/loading the given texture.
  52397. *
  52398. * @param {Texture} texture - The texture.
  52399. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52400. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52401. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52402. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52403. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52404. * @return {string} The WGSL snippet.
  52405. */
  52406. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52407. let snippet = null;
  52408. if ( this.isUnfilterable( texture ) ) {
  52409. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, '0', shaderStage );
  52410. } else {
  52411. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage );
  52412. }
  52413. return snippet;
  52414. }
  52415. /**
  52416. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  52417. *
  52418. * @param {Texture} texture - The texture.
  52419. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52420. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52421. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  52422. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52423. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52424. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52425. * @return {string} The WGSL snippet.
  52426. */
  52427. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52428. if ( shaderStage === 'fragment' ) {
  52429. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  52430. if ( offsetSnippet ) {
  52431. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  52432. }
  52433. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  52434. } else {
  52435. error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  52436. }
  52437. }
  52438. /**
  52439. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  52440. * against a reference value.
  52441. *
  52442. * @param {Texture} texture - The texture.
  52443. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52444. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52445. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  52446. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52447. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52448. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52449. * @return {string} The WGSL snippet.
  52450. */
  52451. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52452. if ( shaderStage === 'fragment' ) {
  52453. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  52454. if ( offsetSnippet ) {
  52455. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  52456. }
  52457. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  52458. }
  52459. if ( offsetSnippet ) {
  52460. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  52461. }
  52462. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  52463. } else {
  52464. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  52465. }
  52466. }
  52467. /**
  52468. * Generates the WGSL snippet when sampling textures with explicit mip level.
  52469. *
  52470. * @param {Texture} texture - The texture.
  52471. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52472. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52473. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  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} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52477. * @return {string} The WGSL snippet.
  52478. */
  52479. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  52480. if ( this.isUnfilterable( texture ) === false ) {
  52481. if ( offsetSnippet ) {
  52482. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  52483. }
  52484. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  52485. } else if ( this.isFilteredTexture( texture ) ) {
  52486. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  52487. } else {
  52488. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  52489. }
  52490. }
  52491. /**
  52492. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  52493. *
  52494. * @param {Texture} texture - The texture.
  52495. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52496. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52497. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  52498. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52499. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52500. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52501. * @return {string} The WGSL snippet.
  52502. */
  52503. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52504. if ( shaderStage === 'fragment' ) {
  52505. if ( offsetSnippet ) {
  52506. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  52507. }
  52508. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  52509. } else {
  52510. error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  52511. }
  52512. }
  52513. /**
  52514. * Returns a WGSL snippet that represents the property name of the given node.
  52515. *
  52516. * @param {Node} node - The node.
  52517. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52518. * @return {string} The property name.
  52519. */
  52520. getPropertyName( node, shaderStage = this.shaderStage ) {
  52521. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  52522. if ( shaderStage === 'vertex' ) {
  52523. return `varyings.${ node.name }`;
  52524. }
  52525. } else if ( node.isNodeUniform === true ) {
  52526. const name = node.name;
  52527. const type = node.type;
  52528. if ( type === 'texture' || type === 'cubeTexture' || type === 'cubeDepthTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  52529. return name;
  52530. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  52531. if ( this.isCustomStruct( node ) ) {
  52532. return name;
  52533. }
  52534. return name + '.value';
  52535. } else {
  52536. return node.groupNode.name + '.' + name;
  52537. }
  52538. }
  52539. return super.getPropertyName( node );
  52540. }
  52541. /**
  52542. * Returns the output struct name.
  52543. *
  52544. * @return {string} The name of the output struct.
  52545. */
  52546. getOutputStructName() {
  52547. return 'output';
  52548. }
  52549. /**
  52550. * Returns the native shader operator name for a given generic name.
  52551. *
  52552. * @param {string} op - The operator name to resolve.
  52553. * @return {?string} The resolved operator name.
  52554. */
  52555. getFunctionOperator( op ) {
  52556. const fnOp = wgslFnOpLib[ op ];
  52557. if ( fnOp !== undefined ) {
  52558. this._include( fnOp );
  52559. return fnOp;
  52560. }
  52561. return null;
  52562. }
  52563. /**
  52564. * Returns the node access for the given node and shader stage.
  52565. *
  52566. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  52567. * @param {string} shaderStage - The shader stage.
  52568. * @return {string} The node access.
  52569. */
  52570. getNodeAccess( node, shaderStage ) {
  52571. if ( shaderStage !== 'compute' ) {
  52572. if ( node.isAtomic === true ) {
  52573. warn( 'WebGPURenderer: Atomic operations are only supported in compute shaders.' );
  52574. return NodeAccess.READ_WRITE;
  52575. }
  52576. return NodeAccess.READ_ONLY;
  52577. }
  52578. return node.access;
  52579. }
  52580. /**
  52581. * Returns A WGSL snippet representing the storage access.
  52582. *
  52583. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  52584. * @param {string} shaderStage - The shader stage.
  52585. * @return {string} The WGSL snippet representing the storage access.
  52586. */
  52587. getStorageAccess( node, shaderStage ) {
  52588. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  52589. }
  52590. /**
  52591. * This method is one of the more important ones since it's responsible
  52592. * for generating a matching binding instance for the given uniform node.
  52593. *
  52594. * These bindings are later used in the renderer to create bind groups
  52595. * and layouts.
  52596. *
  52597. * @param {UniformNode} node - The uniform node.
  52598. * @param {string} type - The node data type.
  52599. * @param {string} shaderStage - The shader stage.
  52600. * @param {?string} [name=null] - An optional uniform name.
  52601. * @return {NodeUniform} The node uniform object.
  52602. */
  52603. getUniformFromNode( node, type, shaderStage, name = null ) {
  52604. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  52605. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  52606. if ( nodeData.uniformGPU === undefined ) {
  52607. let uniformGPU;
  52608. const group = node.groupNode;
  52609. const groupName = group.name;
  52610. const bindings = this.getBindGroupArray( groupName, shaderStage );
  52611. if ( type === 'texture' || type === 'cubeTexture' || type === 'cubeDepthTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  52612. let texture = null;
  52613. const access = this.getNodeAccess( node, shaderStage );
  52614. if ( type === 'texture' || type === 'storageTexture' ) {
  52615. if ( node.value.is3DTexture === true ) {
  52616. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  52617. } else {
  52618. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  52619. }
  52620. } else if ( type === 'cubeTexture' || type === 'cubeDepthTexture' ) {
  52621. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  52622. } else if ( type === 'texture3D' ) {
  52623. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  52624. }
  52625. texture.store = node.isStorageTextureNode === true;
  52626. texture.mipLevel = texture.store ? node.mipLevel : 0;
  52627. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  52628. if ( this.isUnfilterable( node.value ) === false && texture.store === false ) {
  52629. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  52630. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  52631. bindings.push( sampler, texture );
  52632. uniformGPU = [ sampler, texture ];
  52633. } else {
  52634. bindings.push( texture );
  52635. uniformGPU = [ texture ];
  52636. }
  52637. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  52638. const sharedData = this.getSharedDataFromNode( node );
  52639. let buffer = sharedData.buffer;
  52640. if ( buffer === undefined ) {
  52641. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  52642. buffer = new bufferClass( node, group );
  52643. sharedData.buffer = buffer;
  52644. }
  52645. buffer.setVisibility( buffer.getVisibility() | gpuShaderStageLib[ shaderStage ] );
  52646. bindings.push( buffer );
  52647. uniformGPU = buffer;
  52648. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  52649. } else {
  52650. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  52651. let uniformsGroup = uniformsStage[ groupName ];
  52652. if ( uniformsGroup === undefined ) {
  52653. uniformsGroup = new NodeUniformsGroup( groupName, group );
  52654. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  52655. uniformsStage[ groupName ] = uniformsGroup;
  52656. bindings.push( uniformsGroup );
  52657. }
  52658. uniformGPU = this.getNodeUniform( uniformNode, type );
  52659. uniformsGroup.addUniform( uniformGPU );
  52660. }
  52661. nodeData.uniformGPU = uniformGPU;
  52662. }
  52663. return uniformNode;
  52664. }
  52665. /**
  52666. * This method should be used whenever builtins are required in nodes.
  52667. * The internal builtins data structure will make sure builtins are
  52668. * defined in the WGSL source.
  52669. *
  52670. * @param {string} name - The builtin name.
  52671. * @param {string} property - The property name.
  52672. * @param {string} type - The node data type.
  52673. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52674. * @return {string} The property name.
  52675. */
  52676. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  52677. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  52678. if ( map.has( name ) === false ) {
  52679. map.set( name, {
  52680. name,
  52681. property,
  52682. type
  52683. } );
  52684. }
  52685. return property;
  52686. }
  52687. /**
  52688. * Returns `true` if the given builtin is defined in the given shader stage.
  52689. *
  52690. * @param {string} name - The builtin name.
  52691. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52692. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  52693. */
  52694. hasBuiltin( name, shaderStage = this.shaderStage ) {
  52695. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  52696. }
  52697. /**
  52698. * Returns the vertex index builtin.
  52699. *
  52700. * @return {string} The vertex index.
  52701. */
  52702. getVertexIndex() {
  52703. if ( this.shaderStage === 'vertex' ) {
  52704. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  52705. }
  52706. return 'vertexIndex';
  52707. }
  52708. /**
  52709. * Builds the given shader node.
  52710. *
  52711. * @param {ShaderNodeInternal} shaderNode - The shader node.
  52712. * @return {string} The WGSL function code.
  52713. */
  52714. buildFunctionCode( shaderNode ) {
  52715. const layout = shaderNode.layout;
  52716. const flowData = this.flowShaderNode( shaderNode );
  52717. const parameters = [];
  52718. for ( const input of layout.inputs ) {
  52719. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  52720. }
  52721. //
  52722. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  52723. ${ flowData.vars }
  52724. ${ flowData.code }
  52725. `;
  52726. if ( flowData.result ) {
  52727. code += `\treturn ${ flowData.result };\n`;
  52728. }
  52729. code += '\n}\n';
  52730. //
  52731. return code;
  52732. }
  52733. /**
  52734. * Contextually returns either the vertex stage instance index builtin
  52735. * or the linearized index of an compute invocation within a grid of workgroups.
  52736. *
  52737. * @return {string} The instance index.
  52738. */
  52739. getInstanceIndex() {
  52740. if ( this.shaderStage === 'vertex' ) {
  52741. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  52742. }
  52743. return 'instanceIndex';
  52744. }
  52745. /**
  52746. * Returns a builtin representing the index of a compute invocation within the scope of a workgroup load.
  52747. *
  52748. * @return {string} The invocation local index.
  52749. */
  52750. getInvocationLocalIndex() {
  52751. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  52752. }
  52753. /**
  52754. * Returns a builtin representing the size of a subgroup within the current shader.
  52755. *
  52756. * @return {string} The subgroup size.
  52757. */
  52758. getSubgroupSize() {
  52759. this.enableSubGroups();
  52760. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  52761. }
  52762. /**
  52763. * Returns a builtin representing the index of a compute invocation within the scope of a subgroup.
  52764. *
  52765. * @return {string} The invocation subgroup index.
  52766. */
  52767. getInvocationSubgroupIndex() {
  52768. this.enableSubGroups();
  52769. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  52770. }
  52771. /**
  52772. * Returns a builtin representing the index of a compute invocation's subgroup within its workgroup.
  52773. *
  52774. * @return {string} The subgroup index.
  52775. */
  52776. getSubgroupIndex() {
  52777. this.enableSubGroups();
  52778. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  52779. }
  52780. /**
  52781. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  52782. *
  52783. * @return {null} Null.
  52784. */
  52785. getDrawIndex() {
  52786. return null;
  52787. }
  52788. /**
  52789. * Returns the front facing builtin.
  52790. *
  52791. * @return {string} The front facing builtin.
  52792. */
  52793. getFrontFacing() {
  52794. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  52795. }
  52796. /**
  52797. * Returns the frag coord builtin.
  52798. *
  52799. * @return {string} The frag coord builtin.
  52800. */
  52801. getFragCoord() {
  52802. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  52803. }
  52804. /**
  52805. * Returns the frag depth builtin.
  52806. *
  52807. * @return {string} The frag depth builtin.
  52808. */
  52809. getFragDepth() {
  52810. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  52811. }
  52812. /**
  52813. * Returns the clip distances builtin.
  52814. *
  52815. * @return {string} The clip distances builtin.
  52816. */
  52817. getClipDistance() {
  52818. return 'varyings.hw_clip_distances';
  52819. }
  52820. /**
  52821. * Whether to flip texture data along its vertical axis or not.
  52822. *
  52823. * @return {boolean} Returns always `false` in context of WGSL.
  52824. */
  52825. isFlipY() {
  52826. return false;
  52827. }
  52828. /**
  52829. * Enables the given directive for the given shader stage.
  52830. *
  52831. * @param {string} name - The directive name.
  52832. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  52833. */
  52834. enableDirective( name, shaderStage = this.shaderStage ) {
  52835. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  52836. stage.add( name );
  52837. }
  52838. /**
  52839. * Returns the directives of the given shader stage as a WGSL string.
  52840. *
  52841. * @param {string} shaderStage - The shader stage.
  52842. * @return {string} A WGSL snippet that enables the directives of the given stage.
  52843. */
  52844. getDirectives( shaderStage ) {
  52845. const snippets = [];
  52846. const directives = this.directives[ shaderStage ];
  52847. if ( directives !== undefined ) {
  52848. for ( const directive of directives ) {
  52849. snippets.push( `enable ${directive};` );
  52850. }
  52851. }
  52852. return snippets.join( '\n' );
  52853. }
  52854. /**
  52855. * Enables the 'subgroups' directive.
  52856. */
  52857. enableSubGroups() {
  52858. this.enableDirective( 'subgroups' );
  52859. }
  52860. /**
  52861. * Enables the 'subgroups-f16' directive.
  52862. */
  52863. enableSubgroupsF16() {
  52864. this.enableDirective( 'subgroups-f16' );
  52865. }
  52866. /**
  52867. * Enables the 'clip_distances' directive.
  52868. */
  52869. enableClipDistances() {
  52870. this.enableDirective( 'clip_distances' );
  52871. }
  52872. /**
  52873. * Enables the 'f16' directive.
  52874. */
  52875. enableShaderF16() {
  52876. this.enableDirective( 'f16' );
  52877. }
  52878. /**
  52879. * Enables the 'dual_source_blending' directive.
  52880. */
  52881. enableDualSourceBlending() {
  52882. this.enableDirective( 'dual_source_blending' );
  52883. }
  52884. /**
  52885. * Enables hardware clipping.
  52886. *
  52887. * @param {string} planeCount - The clipping plane count.
  52888. */
  52889. enableHardwareClipping( planeCount ) {
  52890. this.enableClipDistances();
  52891. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  52892. }
  52893. /**
  52894. * Returns the builtins of the given shader stage as a WGSL string.
  52895. *
  52896. * @param {string} shaderStage - The shader stage.
  52897. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  52898. */
  52899. getBuiltins( shaderStage ) {
  52900. const snippets = [];
  52901. const builtins = this.builtins[ shaderStage ];
  52902. if ( builtins !== undefined ) {
  52903. for ( const { name, property, type } of builtins.values() ) {
  52904. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  52905. }
  52906. }
  52907. return snippets.join( ',\n\t' );
  52908. }
  52909. /**
  52910. * This method should be used when a new scoped buffer is used in context of
  52911. * compute shaders. It adds the array to the internal data structure which is
  52912. * later used to generate the respective WGSL.
  52913. *
  52914. * @param {string} name - The array name.
  52915. * @param {string} scope - The scope.
  52916. * @param {string} bufferType - The buffer type.
  52917. * @param {string} bufferCount - The buffer count.
  52918. * @return {string} The array name.
  52919. */
  52920. getScopedArray( name, scope, bufferType, bufferCount ) {
  52921. if ( this.scopedArrays.has( name ) === false ) {
  52922. this.scopedArrays.set( name, {
  52923. name,
  52924. scope,
  52925. bufferType,
  52926. bufferCount
  52927. } );
  52928. }
  52929. return name;
  52930. }
  52931. /**
  52932. * Returns the scoped arrays of the given shader stage as a WGSL string.
  52933. *
  52934. * @param {string} shaderStage - The shader stage.
  52935. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  52936. * Returns `undefined` when used in the vertex or fragment stage.
  52937. */
  52938. getScopedArrays( shaderStage ) {
  52939. if ( shaderStage !== 'compute' ) {
  52940. return;
  52941. }
  52942. const snippets = [];
  52943. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  52944. const type = this.getType( bufferType );
  52945. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  52946. }
  52947. return snippets.join( '\n' );
  52948. }
  52949. /**
  52950. * Returns the shader attributes of the given shader stage as a WGSL string.
  52951. *
  52952. * @param {string} shaderStage - The shader stage.
  52953. * @return {string} The WGSL snippet that defines the shader attributes.
  52954. */
  52955. getAttributes( shaderStage ) {
  52956. const snippets = [];
  52957. if ( shaderStage === 'compute' ) {
  52958. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  52959. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  52960. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  52961. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  52962. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  52963. this.enableDirective( 'subgroups', shaderStage );
  52964. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  52965. }
  52966. }
  52967. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  52968. const builtins = this.getBuiltins( 'attribute' );
  52969. if ( builtins ) snippets.push( builtins );
  52970. const attributes = this.getAttributesArray();
  52971. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  52972. const attribute = attributes[ index ];
  52973. const name = attribute.name;
  52974. const type = this.getType( attribute.type );
  52975. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  52976. }
  52977. }
  52978. return snippets.join( ',\n\t' );
  52979. }
  52980. /**
  52981. * Returns the members of the given struct type node as a WGSL string.
  52982. *
  52983. * @param {StructTypeNode} struct - The struct type node.
  52984. * @return {string} The WGSL snippet that defines the struct members.
  52985. */
  52986. getStructMembers( struct ) {
  52987. const snippets = [];
  52988. for ( const member of struct.members ) {
  52989. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  52990. let type = this.getType( member.type );
  52991. if ( member.atomic ) {
  52992. type = 'atomic< ' + type + ' >';
  52993. }
  52994. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  52995. }
  52996. if ( struct.output ) {
  52997. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  52998. }
  52999. return snippets.join( ',\n' );
  53000. }
  53001. /**
  53002. * Returns the structs of the given shader stage as a WGSL string.
  53003. *
  53004. * @param {string} shaderStage - The shader stage.
  53005. * @return {string} The WGSL snippet that defines the structs.
  53006. */
  53007. getStructs( shaderStage ) {
  53008. let result = '';
  53009. const structs = this.structs[ shaderStage ];
  53010. if ( structs.length > 0 ) {
  53011. const snippets = [];
  53012. for ( const struct of structs ) {
  53013. let snippet = `struct ${ struct.name } {\n`;
  53014. snippet += this.getStructMembers( struct );
  53015. snippet += '\n};';
  53016. snippets.push( snippet );
  53017. }
  53018. result = '\n' + snippets.join( '\n\n' ) + '\n';
  53019. }
  53020. return result;
  53021. }
  53022. /**
  53023. * Returns a WGSL string representing a variable.
  53024. *
  53025. * @param {string} type - The variable's type.
  53026. * @param {string} name - The variable's name.
  53027. * @param {?number} [count=null] - The array length.
  53028. * @return {string} The WGSL snippet that defines a variable.
  53029. */
  53030. getVar( type, name, count = null ) {
  53031. let snippet = `var ${ name } : `;
  53032. if ( count !== null ) {
  53033. snippet += this.generateArrayDeclaration( type, count );
  53034. } else {
  53035. snippet += this.getType( type );
  53036. }
  53037. return snippet;
  53038. }
  53039. /**
  53040. * Returns the variables of the given shader stage as a WGSL string.
  53041. *
  53042. * @param {string} shaderStage - The shader stage.
  53043. * @return {string} The WGSL snippet that defines the variables.
  53044. */
  53045. getVars( shaderStage ) {
  53046. const snippets = [];
  53047. const vars = this.vars[ shaderStage ];
  53048. if ( vars !== undefined ) {
  53049. for ( const variable of vars ) {
  53050. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  53051. }
  53052. }
  53053. return `\n${ snippets.join( '\n' ) }\n`;
  53054. }
  53055. /**
  53056. * Returns the varyings of the given shader stage as a WGSL string.
  53057. *
  53058. * @param {string} shaderStage - The shader stage.
  53059. * @return {string} The WGSL snippet that defines the varyings.
  53060. */
  53061. getVaryings( shaderStage ) {
  53062. const snippets = [];
  53063. if ( shaderStage === 'vertex' ) {
  53064. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  53065. }
  53066. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  53067. const varyings = this.varyings;
  53068. const vars = this.vars[ shaderStage ];
  53069. for ( let index = 0; index < varyings.length; index ++ ) {
  53070. const varying = varyings[ index ];
  53071. if ( varying.needsInterpolation ) {
  53072. let attributesSnippet = `@location( ${index} )`;
  53073. if ( varying.interpolationType ) {
  53074. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  53075. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  53076. // Otherwise, optimize interpolation when sensible
  53077. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  53078. attributesSnippet += ` @interpolate( ${ this.renderer.backend.compatibilityMode ? 'flat, either' : 'flat' } )`;
  53079. }
  53080. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  53081. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  53082. vars.push( varying );
  53083. }
  53084. }
  53085. }
  53086. const builtins = this.getBuiltins( shaderStage );
  53087. if ( builtins ) snippets.push( builtins );
  53088. const code = snippets.join( ',\n\t' );
  53089. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  53090. }
  53091. isCustomStruct( nodeUniform ) {
  53092. const attribute = nodeUniform.value;
  53093. const bufferNode = nodeUniform.node;
  53094. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  53095. const isStructArray =
  53096. ( bufferNode.value && bufferNode.value.array ) &&
  53097. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  53098. return isAttributeStructType && ! isStructArray;
  53099. }
  53100. /**
  53101. * Returns the uniforms of the given shader stage as a WGSL string.
  53102. *
  53103. * @param {string} shaderStage - The shader stage.
  53104. * @return {string} The WGSL snippet that defines the uniforms.
  53105. */
  53106. getUniforms( shaderStage ) {
  53107. const uniforms = this.uniforms[ shaderStage ];
  53108. const bindingSnippets = [];
  53109. const bufferSnippets = [];
  53110. const structSnippets = [];
  53111. const uniformGroups = {};
  53112. for ( const uniform of uniforms ) {
  53113. const groupName = uniform.groupNode.name;
  53114. const uniformIndexes = this.bindingsIndexes[ groupName ];
  53115. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'cubeDepthTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  53116. const texture = uniform.node.value;
  53117. if ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  53118. if ( this.isSampleCompare( texture ) ) {
  53119. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  53120. } else {
  53121. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  53122. }
  53123. }
  53124. let textureType;
  53125. let multisampled = '';
  53126. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  53127. if ( primarySamples > 1 ) {
  53128. multisampled = '_multisampled';
  53129. }
  53130. if ( texture.isCubeTexture === true && texture.isDepthTexture === true ) {
  53131. textureType = 'texture_depth_cube';
  53132. } else if ( texture.isCubeTexture === true ) {
  53133. textureType = 'texture_cube<f32>';
  53134. } else if ( texture.isDepthTexture === true ) {
  53135. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  53136. textureType = `texture${ multisampled }_2d<f32>`;
  53137. } else {
  53138. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  53139. }
  53140. } else if ( uniform.node.isStorageTextureNode === true ) {
  53141. const format = getFormat( texture );
  53142. const access = this.getStorageAccess( uniform.node, shaderStage );
  53143. const is3D = uniform.node.value.is3DTexture;
  53144. const isArrayTexture = uniform.node.value.isArrayTexture;
  53145. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  53146. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  53147. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  53148. textureType = 'texture_2d_array<f32>';
  53149. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  53150. textureType = 'texture_3d<f32>';
  53151. } else {
  53152. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  53153. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  53154. }
  53155. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  53156. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  53157. const bufferNode = uniform.node;
  53158. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  53159. const bufferCount = bufferNode.bufferCount;
  53160. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  53161. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  53162. if ( this.isCustomStruct( uniform ) ) {
  53163. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  53164. } else {
  53165. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  53166. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  53167. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  53168. }
  53169. } else {
  53170. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  53171. const groupName = uniform.groupNode.name;
  53172. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  53173. index: uniformIndexes.binding ++,
  53174. id: uniformIndexes.group,
  53175. snippets: []
  53176. } );
  53177. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  53178. }
  53179. }
  53180. for ( const name in uniformGroups ) {
  53181. const group = uniformGroups[ name ];
  53182. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  53183. }
  53184. let code = bindingSnippets.join( '\n' );
  53185. code += bufferSnippets.join( '\n' );
  53186. code += structSnippets.join( '\n' );
  53187. return code;
  53188. }
  53189. /**
  53190. * Controls the code build of the shader stages.
  53191. */
  53192. buildCode() {
  53193. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  53194. this.sortBindingGroups();
  53195. for ( const shaderStage in shadersData ) {
  53196. this.shaderStage = shaderStage;
  53197. const stageData = shadersData[ shaderStage ];
  53198. stageData.uniforms = this.getUniforms( shaderStage );
  53199. stageData.attributes = this.getAttributes( shaderStage );
  53200. stageData.varyings = this.getVaryings( shaderStage );
  53201. stageData.structs = this.getStructs( shaderStage );
  53202. stageData.vars = this.getVars( shaderStage );
  53203. stageData.codes = this.getCodes( shaderStage );
  53204. stageData.directives = this.getDirectives( shaderStage );
  53205. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  53206. //
  53207. let flow = '// code\n\n';
  53208. flow += this.flowCode[ shaderStage ];
  53209. const flowNodes = this.flowNodes[ shaderStage ];
  53210. const mainNode = flowNodes[ flowNodes.length - 1 ];
  53211. const outputNode = mainNode.outputNode;
  53212. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  53213. for ( const node of flowNodes ) {
  53214. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  53215. const slotName = node.name;
  53216. if ( slotName ) {
  53217. if ( flow.length > 0 ) flow += '\n';
  53218. flow += `\t// flow -> ${ slotName }\n`;
  53219. }
  53220. flow += `${ flowSlotData.code }\n\t`;
  53221. if ( node === mainNode && shaderStage !== 'compute' ) {
  53222. flow += '// result\n\n\t';
  53223. if ( shaderStage === 'vertex' ) {
  53224. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  53225. } else if ( shaderStage === 'fragment' ) {
  53226. if ( isOutputStruct ) {
  53227. stageData.returnType = outputNode.getNodeType( this );
  53228. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  53229. flow += `return ${ flowSlotData.result };`;
  53230. } else {
  53231. let structSnippet = '\t@location(0) color: vec4<f32>';
  53232. const builtins = this.getBuiltins( 'output' );
  53233. if ( builtins ) structSnippet += ',\n\t' + builtins;
  53234. stageData.returnType = 'OutputStruct';
  53235. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  53236. stageData.structs += '\nvar<private> output : OutputStruct;';
  53237. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  53238. }
  53239. }
  53240. }
  53241. }
  53242. stageData.flow = flow;
  53243. }
  53244. this.shaderStage = null;
  53245. if ( this.material !== null ) {
  53246. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  53247. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  53248. } else {
  53249. // Early strictly validated in computeNode
  53250. const workgroupSize = this.object.workgroupSize;
  53251. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  53252. }
  53253. }
  53254. /**
  53255. * Returns the native shader method name for a given generic name.
  53256. *
  53257. * @param {string} method - The method name to resolve.
  53258. * @param {?string} [output=null] - An optional output.
  53259. * @return {string} The resolved WGSL method name.
  53260. */
  53261. getMethod( method, output = null ) {
  53262. let wgslMethod;
  53263. if ( output !== null ) {
  53264. wgslMethod = this._getWGSLMethod( method + '_' + output );
  53265. }
  53266. if ( wgslMethod === undefined ) {
  53267. wgslMethod = this._getWGSLMethod( method );
  53268. }
  53269. return wgslMethod || method;
  53270. }
  53271. /**
  53272. * Returns the bitcast method name for a given input and outputType.
  53273. *
  53274. * @param {string} type - The output type to bitcast to.
  53275. * @return {string} The resolved WGSL bitcast invocation.
  53276. */
  53277. getBitcastMethod( type ) {
  53278. const dataType = this.getType( type );
  53279. return `bitcast<${ dataType }>`;
  53280. }
  53281. /**
  53282. * Returns the float packing method name for a given numeric encoding.
  53283. *
  53284. * @param {string} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  53285. * @returns {string} The resolve WGSL float packing method name.
  53286. */
  53287. getFloatPackingMethod( encoding ) {
  53288. return this.getMethod( `floatpack_${ encoding }_2x16` );
  53289. }
  53290. /**
  53291. * Returns the float unpacking method name for a given numeric encoding.
  53292. *
  53293. * @param {string} encoding - The numeric encoding that describes how the integer values are mapped to the float range.
  53294. * @returns {string} The resolve WGSL float unpacking method name.
  53295. */
  53296. getFloatUnpackingMethod( encoding ) {
  53297. return this.getMethod( `floatunpack_${ encoding }_2x16` );
  53298. }
  53299. /**
  53300. * Returns the native snippet for a ternary operation.
  53301. *
  53302. * @param {string} condSnippet - The condition determining which expression gets resolved.
  53303. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  53304. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  53305. * @return {string} The resolved method name.
  53306. */
  53307. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  53308. return `select( ${elseSnippet}, ${ifSnippet}, ${condSnippet} )`;
  53309. }
  53310. /**
  53311. * Returns the WGSL type of the given node data type.
  53312. *
  53313. * @param {string} type - The node data type.
  53314. * @return {string} The WGSL type.
  53315. */
  53316. getType( type ) {
  53317. return wgslTypeLib[ type ] || type;
  53318. }
  53319. /**
  53320. * Whether the requested feature is available or not.
  53321. *
  53322. * @param {string} name - The requested feature.
  53323. * @return {boolean} Whether the requested feature is supported or not.
  53324. */
  53325. isAvailable( name ) {
  53326. let result = supports[ name ];
  53327. if ( result === undefined ) {
  53328. if ( name === 'float32Filterable' ) {
  53329. result = this.renderer.hasFeature( 'float32-filterable' );
  53330. } else if ( name === 'clipDistance' ) {
  53331. result = this.renderer.hasFeature( 'clip-distances' );
  53332. }
  53333. supports[ name ] = result;
  53334. }
  53335. return result;
  53336. }
  53337. /**
  53338. * Returns the native shader method name for a given generic name.
  53339. *
  53340. * @private
  53341. * @param {string} method - The method name to resolve.
  53342. * @return {string} The resolved WGSL method name.
  53343. */
  53344. _getWGSLMethod( method ) {
  53345. if ( wgslPolyfill[ method ] !== undefined ) {
  53346. this._include( method );
  53347. }
  53348. return wgslMethods[ method ];
  53349. }
  53350. /**
  53351. * Includes the given method name into the current
  53352. * function node.
  53353. *
  53354. * @private
  53355. * @param {string} name - The method name to include.
  53356. * @return {CodeNode} The respective code node.
  53357. */
  53358. _include( name ) {
  53359. const codeNode = wgslPolyfill[ name ];
  53360. codeNode.build( this );
  53361. this.addInclude( codeNode );
  53362. return codeNode;
  53363. }
  53364. /**
  53365. * Returns a WGSL vertex shader based on the given shader data.
  53366. *
  53367. * @private
  53368. * @param {Object} shaderData - The shader data.
  53369. * @return {string} The vertex shader.
  53370. */
  53371. _getWGSLVertexCode( shaderData ) {
  53372. return `${ this.getSignature() }
  53373. // directives
  53374. ${shaderData.directives}
  53375. // structs
  53376. ${shaderData.structs}
  53377. // uniforms
  53378. ${shaderData.uniforms}
  53379. // varyings
  53380. ${shaderData.varyings}
  53381. var<private> varyings : VaryingsStruct;
  53382. // codes
  53383. ${shaderData.codes}
  53384. @vertex
  53385. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  53386. // vars
  53387. ${shaderData.vars}
  53388. // flow
  53389. ${shaderData.flow}
  53390. return varyings;
  53391. }
  53392. `;
  53393. }
  53394. /**
  53395. * Returns a WGSL fragment shader based on the given shader data.
  53396. *
  53397. * @private
  53398. * @param {Object} shaderData - The shader data.
  53399. * @return {string} The vertex shader.
  53400. */
  53401. _getWGSLFragmentCode( shaderData ) {
  53402. return `${ this.getSignature() }
  53403. // global
  53404. ${ diagnostics }
  53405. // structs
  53406. ${shaderData.structs}
  53407. // uniforms
  53408. ${shaderData.uniforms}
  53409. // codes
  53410. ${shaderData.codes}
  53411. @fragment
  53412. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  53413. // vars
  53414. ${shaderData.vars}
  53415. // flow
  53416. ${shaderData.flow}
  53417. }
  53418. `;
  53419. }
  53420. /**
  53421. * Returns a WGSL compute shader based on the given shader data.
  53422. *
  53423. * @private
  53424. * @param {Object} shaderData - The shader data.
  53425. * @param {string} workgroupSize - The workgroup size.
  53426. * @return {string} The vertex shader.
  53427. */
  53428. _getWGSLComputeCode( shaderData, workgroupSize ) {
  53429. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  53430. return `${ this.getSignature() }
  53431. // directives
  53432. ${ shaderData.directives }
  53433. // system
  53434. var<private> instanceIndex : u32;
  53435. // locals
  53436. ${ shaderData.scopedArrays }
  53437. // structs
  53438. ${ shaderData.structs }
  53439. // uniforms
  53440. ${ shaderData.uniforms }
  53441. // codes
  53442. ${ shaderData.codes }
  53443. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  53444. fn main( ${ shaderData.attributes } ) {
  53445. // system
  53446. instanceIndex = globalId.x
  53447. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  53448. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  53449. // vars
  53450. ${ shaderData.vars }
  53451. // flow
  53452. ${ shaderData.flow }
  53453. }
  53454. `;
  53455. }
  53456. /**
  53457. * Returns a WGSL struct based on the given name and variables.
  53458. *
  53459. * @private
  53460. * @param {string} name - The struct name.
  53461. * @param {string} vars - The struct variables.
  53462. * @return {string} The WGSL snippet representing a struct.
  53463. */
  53464. _getWGSLStruct( name, vars ) {
  53465. return `
  53466. struct ${name} {
  53467. ${vars}
  53468. };`;
  53469. }
  53470. /**
  53471. * Returns a WGSL struct binding.
  53472. *
  53473. * @private
  53474. * @param {string} name - The struct name.
  53475. * @param {string} vars - The struct variables.
  53476. * @param {string} access - The access.
  53477. * @param {number} [binding=0] - The binding index.
  53478. * @param {number} [group=0] - The group index.
  53479. * @return {string} The WGSL snippet representing a struct binding.
  53480. */
  53481. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  53482. const structName = name + 'Struct';
  53483. const structSnippet = this._getWGSLStruct( structName, vars );
  53484. return `${structSnippet}
  53485. @binding( ${ binding } ) @group( ${ group } )
  53486. var<${access}> ${ name } : ${ structName };`;
  53487. }
  53488. }
  53489. /**
  53490. * A WebGPU backend utility module with common helpers.
  53491. *
  53492. * @private
  53493. */
  53494. class WebGPUUtils {
  53495. /**
  53496. * Constructs a new utility object.
  53497. *
  53498. * @param {WebGPUBackend} backend - The WebGPU backend.
  53499. */
  53500. constructor( backend ) {
  53501. /**
  53502. * A reference to the WebGPU backend.
  53503. *
  53504. * @type {WebGPUBackend}
  53505. */
  53506. this.backend = backend;
  53507. }
  53508. /**
  53509. * Returns the depth/stencil GPU format for the given render context.
  53510. *
  53511. * @param {RenderContext} renderContext - The render context.
  53512. * @return {string} The depth/stencil GPU texture format.
  53513. */
  53514. getCurrentDepthStencilFormat( renderContext ) {
  53515. let format;
  53516. if ( renderContext.depthTexture !== null ) {
  53517. format = this.getTextureFormatGPU( renderContext.depthTexture );
  53518. } else if ( renderContext.depth && renderContext.stencil ) {
  53519. format = GPUTextureFormat.Depth24PlusStencil8;
  53520. } else if ( renderContext.depth ) {
  53521. format = GPUTextureFormat.Depth24Plus;
  53522. }
  53523. return format;
  53524. }
  53525. /**
  53526. * Returns the GPU format for the given texture.
  53527. *
  53528. * @param {Texture} texture - The texture.
  53529. * @return {string} The GPU texture format.
  53530. */
  53531. getTextureFormatGPU( texture ) {
  53532. return this.backend.get( texture ).format;
  53533. }
  53534. /**
  53535. * Returns an object that defines the multi-sampling state of the given texture.
  53536. *
  53537. * @param {Texture} texture - The texture.
  53538. * @return {Object} The multi-sampling state.
  53539. */
  53540. getTextureSampleData( texture ) {
  53541. let samples;
  53542. if ( texture.isFramebufferTexture ) {
  53543. samples = 1;
  53544. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  53545. const renderer = this.backend.renderer;
  53546. const renderTarget = renderer.getRenderTarget();
  53547. samples = renderTarget ? renderTarget.samples : renderer.currentSamples;
  53548. } else if ( texture.renderTarget ) {
  53549. samples = texture.renderTarget.samples;
  53550. }
  53551. samples = samples || 1;
  53552. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  53553. const primarySamples = isMSAA ? 1 : samples;
  53554. return { samples, primarySamples, isMSAA };
  53555. }
  53556. /**
  53557. * Returns the default color attachment's GPU format of the current render context.
  53558. *
  53559. * @param {RenderContext} renderContext - The render context.
  53560. * @return {string} The GPU texture format of the default color attachment.
  53561. */
  53562. getCurrentColorFormat( renderContext ) {
  53563. let format;
  53564. if ( renderContext.textures !== null ) {
  53565. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  53566. } else {
  53567. format = this.getPreferredCanvasFormat(); // default context format
  53568. }
  53569. return format;
  53570. }
  53571. /**
  53572. * Returns the GPU formats of all color attachments of the current render context.
  53573. *
  53574. * @param {RenderContext} renderContext - The render context.
  53575. * @return {Array<string>} The GPU texture formats of all color attachments.
  53576. */
  53577. getCurrentColorFormats( renderContext ) {
  53578. if ( renderContext.textures !== null ) {
  53579. return renderContext.textures.map( t => this.getTextureFormatGPU( t ) );
  53580. } else {
  53581. return [ this.getPreferredCanvasFormat() ]; // default context format
  53582. }
  53583. }
  53584. /**
  53585. * Returns the output color space of the current render context.
  53586. *
  53587. * @param {RenderContext} renderContext - The render context.
  53588. * @return {string} The output color space.
  53589. */
  53590. getCurrentColorSpace( renderContext ) {
  53591. if ( renderContext.textures !== null ) {
  53592. return renderContext.textures[ 0 ].colorSpace;
  53593. }
  53594. return this.backend.renderer.outputColorSpace;
  53595. }
  53596. /**
  53597. * Returns GPU primitive topology for the given object and material.
  53598. *
  53599. * @param {Object3D} object - The 3D object.
  53600. * @param {Material} material - The material.
  53601. * @return {string} The GPU primitive topology.
  53602. */
  53603. getPrimitiveTopology( object, material ) {
  53604. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  53605. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  53606. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  53607. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  53608. }
  53609. /**
  53610. * Returns a modified sample count from the given sample count value.
  53611. *
  53612. * That is required since WebGPU only supports either 1 or 4.
  53613. *
  53614. * @param {number} sampleCount - The input sample count.
  53615. * @return {number} The (potentially updated) output sample count.
  53616. */
  53617. getSampleCount( sampleCount ) {
  53618. return sampleCount >= 4 ? 4 : 1;
  53619. }
  53620. /**
  53621. * Returns the sample count of the given render context.
  53622. *
  53623. * @param {RenderContext} renderContext - The render context.
  53624. * @return {number} The sample count.
  53625. */
  53626. getSampleCountRenderContext( renderContext ) {
  53627. if ( renderContext.textures !== null ) {
  53628. return this.getSampleCount( renderContext.sampleCount );
  53629. }
  53630. return this.getSampleCount( this.backend.renderer.currentSamples );
  53631. }
  53632. /**
  53633. * Returns the preferred canvas format.
  53634. *
  53635. * There is a separate method for this so it's possible to
  53636. * honor edge cases for specific devices.
  53637. *
  53638. * @return {string} The GPU texture format of the canvas.
  53639. */
  53640. getPreferredCanvasFormat() {
  53641. const outputType = this.backend.parameters.outputType;
  53642. if ( outputType === undefined ) {
  53643. return navigator.gpu.getPreferredCanvasFormat();
  53644. } else if ( outputType === UnsignedByteType ) {
  53645. return GPUTextureFormat.BGRA8Unorm;
  53646. } else if ( outputType === HalfFloatType ) {
  53647. return GPUTextureFormat.RGBA16Float;
  53648. } else {
  53649. throw new Error( 'Unsupported outputType' );
  53650. }
  53651. }
  53652. }
  53653. const typedArraysToVertexFormatPrefix = new Map( [
  53654. [ Int8Array, [ 'sint8', 'snorm8' ]],
  53655. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  53656. [ Int16Array, [ 'sint16', 'snorm16' ]],
  53657. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  53658. [ Int32Array, [ 'sint32', 'snorm32' ]],
  53659. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  53660. [ Float32Array, [ 'float32', ]],
  53661. ] );
  53662. if ( typeof Float16Array !== 'undefined' ) {
  53663. typedArraysToVertexFormatPrefix.set( Float16Array, [ 'float16' ] );
  53664. }
  53665. const typedAttributeToVertexFormatPrefix = new Map( [
  53666. [ Float16BufferAttribute, [ 'float16', ]],
  53667. ] );
  53668. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  53669. [ Int32Array, 'sint32' ],
  53670. [ Int16Array, 'sint32' ], // patch for INT16
  53671. [ Uint32Array, 'uint32' ],
  53672. [ Uint16Array, 'uint32' ], // patch for UINT16
  53673. [ Float32Array, 'float32' ]
  53674. ] );
  53675. /**
  53676. * A WebGPU backend utility module for managing shader attributes.
  53677. *
  53678. * @private
  53679. */
  53680. class WebGPUAttributeUtils {
  53681. /**
  53682. * Constructs a new utility object.
  53683. *
  53684. * @param {WebGPUBackend} backend - The WebGPU backend.
  53685. */
  53686. constructor( backend ) {
  53687. /**
  53688. * A reference to the WebGPU backend.
  53689. *
  53690. * @type {WebGPUBackend}
  53691. */
  53692. this.backend = backend;
  53693. }
  53694. /**
  53695. * Creates the GPU buffer for the given buffer attribute.
  53696. *
  53697. * @param {BufferAttribute} attribute - The buffer attribute.
  53698. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  53699. */
  53700. createAttribute( attribute, usage ) {
  53701. const bufferAttribute = this._getBufferAttribute( attribute );
  53702. const backend = this.backend;
  53703. const bufferData = backend.get( bufferAttribute );
  53704. let buffer = bufferData.buffer;
  53705. if ( buffer === undefined ) {
  53706. const device = backend.device;
  53707. let array = bufferAttribute.array;
  53708. // patch for INT16 and UINT16
  53709. if ( attribute.normalized === false ) {
  53710. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  53711. array = new Int32Array( array );
  53712. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  53713. array = new Uint32Array( array );
  53714. if ( usage & GPUBufferUsage.INDEX ) {
  53715. for ( let i = 0; i < array.length; i ++ ) {
  53716. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  53717. }
  53718. }
  53719. }
  53720. }
  53721. bufferAttribute.array = array;
  53722. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  53723. array = new array.constructor( bufferAttribute.count * 4 );
  53724. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  53725. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  53726. }
  53727. // Update BufferAttribute
  53728. bufferAttribute.itemSize = 4;
  53729. bufferAttribute.array = array;
  53730. bufferData._force3to4BytesAlignment = true;
  53731. }
  53732. // ensure 4 byte alignment
  53733. const byteLength = array.byteLength;
  53734. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  53735. buffer = device.createBuffer( {
  53736. label: bufferAttribute.name,
  53737. size: size,
  53738. usage: usage,
  53739. mappedAtCreation: true
  53740. } );
  53741. new array.constructor( buffer.getMappedRange() ).set( array );
  53742. buffer.unmap();
  53743. bufferData.buffer = buffer;
  53744. }
  53745. }
  53746. /**
  53747. * Updates the GPU buffer of the given buffer attribute.
  53748. *
  53749. * @param {BufferAttribute} attribute - The buffer attribute.
  53750. */
  53751. updateAttribute( attribute ) {
  53752. const bufferAttribute = this._getBufferAttribute( attribute );
  53753. const backend = this.backend;
  53754. const device = backend.device;
  53755. const bufferData = backend.get( bufferAttribute );
  53756. const buffer = backend.get( bufferAttribute ).buffer;
  53757. let array = bufferAttribute.array;
  53758. // if storage buffer ensure 4 byte alignment
  53759. if ( bufferData._force3to4BytesAlignment === true ) {
  53760. array = new array.constructor( bufferAttribute.count * 4 );
  53761. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  53762. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  53763. }
  53764. bufferAttribute.array = array;
  53765. }
  53766. const updateRanges = bufferAttribute.updateRanges;
  53767. if ( updateRanges.length === 0 ) {
  53768. // Not using update ranges
  53769. device.queue.writeBuffer(
  53770. buffer,
  53771. 0,
  53772. array,
  53773. 0
  53774. );
  53775. } else {
  53776. const isTyped = isTypedArray( array );
  53777. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  53778. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  53779. const range = updateRanges[ i ];
  53780. let dataOffset, size;
  53781. if ( bufferData._force3to4BytesAlignment === true ) {
  53782. const vertexStart = Math.floor( range.start / 3 );
  53783. const vertexCount = Math.ceil( range.count / 3 );
  53784. dataOffset = vertexStart * 4 * byteOffsetFactor;
  53785. size = vertexCount * 4 * byteOffsetFactor;
  53786. } else {
  53787. dataOffset = range.start * byteOffsetFactor;
  53788. size = range.count * byteOffsetFactor;
  53789. }
  53790. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  53791. device.queue.writeBuffer(
  53792. buffer,
  53793. bufferOffset,
  53794. array,
  53795. dataOffset,
  53796. size
  53797. );
  53798. }
  53799. bufferAttribute.clearUpdateRanges();
  53800. }
  53801. }
  53802. /**
  53803. * This method creates the vertex buffer layout data which are
  53804. * require when creating a render pipeline for the given render object.
  53805. *
  53806. * @param {RenderObject} renderObject - The render object.
  53807. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  53808. */
  53809. createShaderVertexBuffers( renderObject ) {
  53810. const attributes = renderObject.getAttributes();
  53811. const vertexBuffers = new Map();
  53812. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  53813. const geometryAttribute = attributes[ slot ];
  53814. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  53815. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  53816. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  53817. if ( vertexBufferLayout === undefined ) {
  53818. let arrayStride, stepMode;
  53819. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  53820. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  53821. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  53822. } else {
  53823. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  53824. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  53825. }
  53826. // patch for INT16 and UINT16
  53827. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  53828. arrayStride = 4;
  53829. }
  53830. vertexBufferLayout = {
  53831. arrayStride,
  53832. attributes: [],
  53833. stepMode
  53834. };
  53835. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  53836. }
  53837. const format = this._getVertexFormat( geometryAttribute );
  53838. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  53839. vertexBufferLayout.attributes.push( {
  53840. shaderLocation: slot,
  53841. offset,
  53842. format
  53843. } );
  53844. }
  53845. return Array.from( vertexBuffers.values() );
  53846. }
  53847. /**
  53848. * Destroys the GPU buffer of the given buffer attribute.
  53849. *
  53850. * @param {BufferAttribute} attribute - The buffer attribute.
  53851. */
  53852. destroyAttribute( attribute ) {
  53853. const backend = this.backend;
  53854. const data = backend.get( this._getBufferAttribute( attribute ) );
  53855. data.buffer.destroy();
  53856. backend.delete( attribute );
  53857. }
  53858. /**
  53859. * This method performs a readback operation by moving buffer data from
  53860. * a storage buffer attribute from the GPU to the CPU.
  53861. *
  53862. * @async
  53863. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  53864. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  53865. */
  53866. async getArrayBufferAsync( attribute ) {
  53867. const backend = this.backend;
  53868. const device = backend.device;
  53869. const data = backend.get( this._getBufferAttribute( attribute ) );
  53870. const bufferGPU = data.buffer;
  53871. const size = bufferGPU.size;
  53872. const readBufferGPU = device.createBuffer( {
  53873. label: `${ attribute.name }_readback`,
  53874. size,
  53875. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  53876. } );
  53877. const cmdEncoder = device.createCommandEncoder( {
  53878. label: `readback_encoder_${ attribute.name }`
  53879. } );
  53880. cmdEncoder.copyBufferToBuffer(
  53881. bufferGPU,
  53882. 0,
  53883. readBufferGPU,
  53884. 0,
  53885. size
  53886. );
  53887. const gpuCommands = cmdEncoder.finish();
  53888. device.queue.submit( [ gpuCommands ] );
  53889. await readBufferGPU.mapAsync( GPUMapMode.READ );
  53890. const arrayBuffer = readBufferGPU.getMappedRange();
  53891. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  53892. readBufferGPU.unmap();
  53893. return dstBuffer.buffer;
  53894. }
  53895. /**
  53896. * Returns the vertex format of the given buffer attribute.
  53897. *
  53898. * @private
  53899. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  53900. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  53901. */
  53902. _getVertexFormat( geometryAttribute ) {
  53903. const { itemSize, normalized } = geometryAttribute;
  53904. const ArrayType = geometryAttribute.array.constructor;
  53905. const AttributeType = geometryAttribute.constructor;
  53906. let format;
  53907. if ( itemSize === 1 ) {
  53908. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  53909. } else {
  53910. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  53911. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  53912. if ( prefix ) {
  53913. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  53914. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  53915. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  53916. if ( paddedItemSize % 1 ) {
  53917. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  53918. }
  53919. format = `${prefix}x${paddedItemSize}`;
  53920. }
  53921. }
  53922. if ( ! format ) {
  53923. error( 'WebGPUAttributeUtils: Vertex format not supported yet.' );
  53924. }
  53925. return format;
  53926. }
  53927. /**
  53928. * Utility method for handling interleaved buffer attributes correctly.
  53929. * To process them, their `InterleavedBuffer` is returned.
  53930. *
  53931. * @private
  53932. * @param {BufferAttribute} attribute - The attribute.
  53933. * @return {BufferAttribute|InterleavedBuffer}
  53934. */
  53935. _getBufferAttribute( attribute ) {
  53936. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  53937. return attribute;
  53938. }
  53939. }
  53940. /**
  53941. * A WebGPU backend utility module for managing bindings.
  53942. *
  53943. * When reading the documentation it's helpful to keep in mind that
  53944. * all class definitions starting with 'GPU*' are modules from the
  53945. * WebGPU API. So for example `BindGroup` is a class from the engine
  53946. * whereas `GPUBindGroup` is a class from WebGPU.
  53947. *
  53948. * @private
  53949. */
  53950. class WebGPUBindingUtils {
  53951. /**
  53952. * Constructs a new utility object.
  53953. *
  53954. * @param {WebGPUBackend} backend - The WebGPU backend.
  53955. */
  53956. constructor( backend ) {
  53957. /**
  53958. * A reference to the WebGPU backend.
  53959. *
  53960. * @type {WebGPUBackend}
  53961. */
  53962. this.backend = backend;
  53963. /**
  53964. * A cache for managing bind group layouts.
  53965. *
  53966. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  53967. */
  53968. this.bindGroupLayoutCache = new WeakMap();
  53969. }
  53970. /**
  53971. * Creates a GPU bind group layout for the given bind group.
  53972. *
  53973. * @param {BindGroup} bindGroup - The bind group.
  53974. * @return {GPUBindGroupLayout} The GPU bind group layout.
  53975. */
  53976. createBindingsLayout( bindGroup ) {
  53977. const backend = this.backend;
  53978. const device = backend.device;
  53979. const entries = [];
  53980. let index = 0;
  53981. for ( const binding of bindGroup.bindings ) {
  53982. const bindingGPU = {
  53983. binding: index ++,
  53984. visibility: binding.visibility
  53985. };
  53986. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  53987. const buffer = {}; // GPUBufferBindingLayout
  53988. if ( binding.isStorageBuffer ) {
  53989. if ( binding.visibility & GPUShaderStage.COMPUTE ) {
  53990. // compute
  53991. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  53992. buffer.type = GPUBufferBindingType.Storage;
  53993. } else {
  53994. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  53995. }
  53996. } else {
  53997. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  53998. }
  53999. }
  54000. bindingGPU.buffer = buffer;
  54001. } else if ( binding.isSampledTexture && binding.store ) {
  54002. const storageTexture = {}; // GPUStorageTextureBindingLayout
  54003. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  54004. const access = binding.access;
  54005. if ( access === NodeAccess.READ_WRITE ) {
  54006. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  54007. } else if ( access === NodeAccess.WRITE_ONLY ) {
  54008. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  54009. } else {
  54010. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  54011. }
  54012. if ( binding.texture.isArrayTexture ) {
  54013. storageTexture.viewDimension = GPUTextureViewDimension.TwoDArray;
  54014. } else if ( binding.texture.is3DTexture ) {
  54015. storageTexture.viewDimension = GPUTextureViewDimension.ThreeD;
  54016. }
  54017. bindingGPU.storageTexture = storageTexture;
  54018. } else if ( binding.isSampledTexture ) {
  54019. const texture = {}; // GPUTextureBindingLayout
  54020. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  54021. if ( primarySamples > 1 ) {
  54022. texture.multisampled = true;
  54023. if ( ! binding.texture.isDepthTexture ) {
  54024. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  54025. }
  54026. }
  54027. if ( binding.texture.isDepthTexture ) {
  54028. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  54029. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  54030. } else {
  54031. texture.sampleType = GPUTextureSampleType.Depth;
  54032. }
  54033. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  54034. const type = binding.texture.type;
  54035. if ( type === IntType ) {
  54036. texture.sampleType = GPUTextureSampleType.SInt;
  54037. } else if ( type === UnsignedIntType ) {
  54038. texture.sampleType = GPUTextureSampleType.UInt;
  54039. } else if ( type === FloatType ) {
  54040. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  54041. texture.sampleType = GPUTextureSampleType.Float;
  54042. } else {
  54043. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  54044. }
  54045. }
  54046. }
  54047. if ( binding.isSampledCubeTexture ) {
  54048. texture.viewDimension = GPUTextureViewDimension.Cube;
  54049. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  54050. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  54051. } else if ( binding.isSampledTexture3D ) {
  54052. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  54053. }
  54054. bindingGPU.texture = texture;
  54055. } else if ( binding.isSampler ) {
  54056. const sampler = {}; // GPUSamplerBindingLayout
  54057. if ( binding.texture.isDepthTexture ) {
  54058. if ( binding.texture.compareFunction !== null ) {
  54059. sampler.type = GPUSamplerBindingType.Comparison;
  54060. } else if ( backend.compatibilityMode ) {
  54061. sampler.type = GPUSamplerBindingType.NonFiltering;
  54062. }
  54063. }
  54064. bindingGPU.sampler = sampler;
  54065. } else {
  54066. error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  54067. }
  54068. entries.push( bindingGPU );
  54069. }
  54070. return device.createBindGroupLayout( { entries } );
  54071. }
  54072. /**
  54073. * Creates bindings from the given bind group definition.
  54074. *
  54075. * @param {BindGroup} bindGroup - The bind group.
  54076. * @param {Array<BindGroup>} bindings - Array of bind groups.
  54077. * @param {number} cacheIndex - The cache index.
  54078. * @param {number} version - The version.
  54079. */
  54080. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  54081. const { backend, bindGroupLayoutCache } = this;
  54082. const bindingsData = backend.get( bindGroup );
  54083. // setup (static) binding layout and (dynamic) binding group
  54084. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  54085. if ( bindLayoutGPU === undefined ) {
  54086. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  54087. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  54088. }
  54089. let bindGroupGPU;
  54090. if ( cacheIndex > 0 ) {
  54091. if ( bindingsData.groups === undefined ) {
  54092. bindingsData.groups = [];
  54093. bindingsData.versions = [];
  54094. }
  54095. if ( bindingsData.versions[ cacheIndex ] === version ) {
  54096. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  54097. }
  54098. }
  54099. if ( bindGroupGPU === undefined ) {
  54100. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  54101. if ( cacheIndex > 0 ) {
  54102. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  54103. bindingsData.versions[ cacheIndex ] = version;
  54104. }
  54105. }
  54106. bindingsData.group = bindGroupGPU;
  54107. bindingsData.layout = bindLayoutGPU;
  54108. }
  54109. /**
  54110. * Updates a buffer binding.
  54111. *
  54112. * @param {Buffer} binding - The buffer binding to update.
  54113. */
  54114. updateBinding( binding ) {
  54115. const backend = this.backend;
  54116. const device = backend.device;
  54117. const array = binding.buffer; // cpu
  54118. const buffer = backend.get( binding ).buffer; // gpu
  54119. const updateRanges = binding.updateRanges;
  54120. if ( updateRanges.length === 0 ) {
  54121. device.queue.writeBuffer(
  54122. buffer,
  54123. 0,
  54124. array,
  54125. 0
  54126. );
  54127. } else {
  54128. const isTyped = isTypedArray( array );
  54129. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  54130. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  54131. const range = updateRanges[ i ];
  54132. const dataOffset = range.start * byteOffsetFactor;
  54133. const size = range.count * byteOffsetFactor;
  54134. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  54135. device.queue.writeBuffer(
  54136. buffer,
  54137. bufferOffset,
  54138. array,
  54139. dataOffset,
  54140. size
  54141. );
  54142. }
  54143. binding.clearUpdateRanges();
  54144. }
  54145. }
  54146. /**
  54147. * Creates a GPU bind group for the camera index.
  54148. *
  54149. * @param {Uint32Array} data - The index data.
  54150. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  54151. * @return {GPUBindGroup} The GPU bind group.
  54152. */
  54153. createBindGroupIndex( data, layout ) {
  54154. const backend = this.backend;
  54155. const device = backend.device;
  54156. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  54157. const index = data[ 0 ];
  54158. const buffer = device.createBuffer( {
  54159. label: 'bindingCameraIndex_' + index,
  54160. size: 16, // uint(4) * 4
  54161. usage: usage
  54162. } );
  54163. device.queue.writeBuffer( buffer, 0, data, 0 );
  54164. const entries = [ { binding: 0, resource: { buffer } } ];
  54165. return device.createBindGroup( {
  54166. label: 'bindGroupCameraIndex_' + index,
  54167. layout,
  54168. entries
  54169. } );
  54170. }
  54171. /**
  54172. * Creates a GPU bind group for the given bind group and GPU layout.
  54173. *
  54174. * @param {BindGroup} bindGroup - The bind group.
  54175. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  54176. * @return {GPUBindGroup} The GPU bind group.
  54177. */
  54178. createBindGroup( bindGroup, layoutGPU ) {
  54179. const backend = this.backend;
  54180. const device = backend.device;
  54181. let bindingPoint = 0;
  54182. const entriesGPU = [];
  54183. for ( const binding of bindGroup.bindings ) {
  54184. if ( binding.isUniformBuffer ) {
  54185. const bindingData = backend.get( binding );
  54186. if ( bindingData.buffer === undefined ) {
  54187. const byteLength = binding.byteLength;
  54188. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  54189. const visibilities = [];
  54190. if ( binding.visibility & GPUShaderStage.VERTEX ) {
  54191. visibilities.push( 'vertex' );
  54192. }
  54193. if ( binding.visibility & GPUShaderStage.FRAGMENT ) {
  54194. visibilities.push( 'fragment' );
  54195. }
  54196. if ( binding.visibility & GPUShaderStage.COMPUTE ) {
  54197. visibilities.push( 'compute' );
  54198. }
  54199. const bufferVisibility = `(${visibilities.join( ',' )})`;
  54200. const bufferGPU = device.createBuffer( {
  54201. label: `bindingBuffer${binding.id}_${binding.name}_${bufferVisibility}`,
  54202. size: byteLength,
  54203. usage: usage
  54204. } );
  54205. bindingData.buffer = bufferGPU;
  54206. }
  54207. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  54208. } else if ( binding.isStorageBuffer ) {
  54209. const bindingData = backend.get( binding );
  54210. if ( bindingData.buffer === undefined ) {
  54211. const attribute = binding.attribute;
  54212. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  54213. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  54214. bindingData.buffer = backend.get( attribute ).buffer;
  54215. }
  54216. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  54217. } else if ( binding.isSampledTexture ) {
  54218. const textureData = backend.get( binding.texture );
  54219. let resourceGPU;
  54220. if ( textureData.externalTexture !== undefined ) {
  54221. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  54222. } else {
  54223. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  54224. const baseMipLevel = binding.store ? binding.mipLevel : 0;
  54225. let propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }`;
  54226. if ( textureData.texture.depthOrArrayLayers > 1 ) {
  54227. propertyName += `-${ textureData.texture.depthOrArrayLayers }`;
  54228. }
  54229. propertyName += `-${ mipLevelCount }-${ baseMipLevel }`;
  54230. resourceGPU = textureData[ propertyName ];
  54231. if ( resourceGPU === undefined ) {
  54232. const aspectGPU = GPUTextureAspect.All;
  54233. let dimensionViewGPU;
  54234. if ( binding.isSampledCubeTexture ) {
  54235. dimensionViewGPU = GPUTextureViewDimension.Cube;
  54236. } else if ( binding.isSampledTexture3D ) {
  54237. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  54238. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  54239. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  54240. } else {
  54241. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  54242. }
  54243. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount, baseMipLevel } );
  54244. }
  54245. }
  54246. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  54247. } else if ( binding.isSampler ) {
  54248. const textureGPU = backend.get( binding.texture );
  54249. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  54250. }
  54251. bindingPoint ++;
  54252. }
  54253. return device.createBindGroup( {
  54254. label: 'bindGroup_' + bindGroup.name,
  54255. layout: layoutGPU,
  54256. entries: entriesGPU
  54257. } );
  54258. }
  54259. }
  54260. /**
  54261. * A WebGPU backend utility module for managing pipelines.
  54262. *
  54263. * @private
  54264. */
  54265. class WebGPUPipelineUtils {
  54266. /**
  54267. * Constructs a new utility object.
  54268. *
  54269. * @param {WebGPUBackend} backend - The WebGPU backend.
  54270. */
  54271. constructor( backend ) {
  54272. /**
  54273. * A reference to the WebGPU backend.
  54274. *
  54275. * @type {WebGPUBackend}
  54276. */
  54277. this.backend = backend;
  54278. /**
  54279. * A Weak Map that tracks the active pipeline for render or compute passes.
  54280. *
  54281. * @private
  54282. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  54283. */
  54284. this._activePipelines = new WeakMap();
  54285. }
  54286. /**
  54287. * Sets the given pipeline for the given pass. The method makes sure to only set the
  54288. * pipeline when necessary.
  54289. *
  54290. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  54291. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  54292. */
  54293. setPipeline( pass, pipeline ) {
  54294. const currentPipeline = this._activePipelines.get( pass );
  54295. if ( currentPipeline !== pipeline ) {
  54296. pass.setPipeline( pipeline );
  54297. this._activePipelines.set( pass, pipeline );
  54298. }
  54299. }
  54300. /**
  54301. * Returns the sample count derived from the given render context.
  54302. *
  54303. * @private
  54304. * @param {RenderContext} renderContext - The render context.
  54305. * @return {number} The sample count.
  54306. */
  54307. _getSampleCount( renderContext ) {
  54308. return this.backend.utils.getSampleCountRenderContext( renderContext );
  54309. }
  54310. /**
  54311. * Creates a render pipeline for the given render object.
  54312. *
  54313. * @param {RenderObject} renderObject - The render object.
  54314. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  54315. */
  54316. createRenderPipeline( renderObject, promises ) {
  54317. const { object, material, geometry, pipeline } = renderObject;
  54318. const { vertexProgram, fragmentProgram } = pipeline;
  54319. const backend = this.backend;
  54320. const device = backend.device;
  54321. const utils = backend.utils;
  54322. const pipelineData = backend.get( pipeline );
  54323. // bind group layouts
  54324. const bindGroupLayouts = [];
  54325. for ( const bindGroup of renderObject.getBindings() ) {
  54326. const bindingsData = backend.get( bindGroup );
  54327. bindGroupLayouts.push( bindingsData.layout );
  54328. }
  54329. // vertex buffers
  54330. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  54331. // blending
  54332. let blending;
  54333. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  54334. blending = this._getBlending( material );
  54335. }
  54336. // stencil
  54337. let stencilFront = {};
  54338. if ( material.stencilWrite === true ) {
  54339. stencilFront = {
  54340. compare: this._getStencilCompare( material ),
  54341. failOp: this._getStencilOperation( material.stencilFail ),
  54342. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  54343. passOp: this._getStencilOperation( material.stencilZPass )
  54344. };
  54345. }
  54346. const colorWriteMask = this._getColorWriteMask( material );
  54347. const targets = [];
  54348. if ( renderObject.context.textures !== null ) {
  54349. const textures = renderObject.context.textures;
  54350. for ( let i = 0; i < textures.length; i ++ ) {
  54351. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  54352. if ( i === 0 ) {
  54353. targets.push( {
  54354. format: colorFormat,
  54355. blend: blending,
  54356. writeMask: colorWriteMask
  54357. } );
  54358. } else {
  54359. targets.push( {
  54360. format: colorFormat,
  54361. writeMask: colorWriteMask
  54362. } );
  54363. }
  54364. }
  54365. } else {
  54366. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  54367. targets.push( {
  54368. format: colorFormat,
  54369. blend: blending,
  54370. writeMask: colorWriteMask
  54371. } );
  54372. }
  54373. const vertexModule = backend.get( vertexProgram ).module;
  54374. const fragmentModule = backend.get( fragmentProgram ).module;
  54375. const primitiveState = this._getPrimitiveState( object, geometry, material );
  54376. const depthCompare = this._getDepthCompare( material );
  54377. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  54378. const sampleCount = this._getSampleCount( renderObject.context );
  54379. const pipelineDescriptor = {
  54380. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  54381. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  54382. fragment: Object.assign( {}, fragmentModule, { targets } ),
  54383. primitive: primitiveState,
  54384. multisample: {
  54385. count: sampleCount,
  54386. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  54387. },
  54388. layout: device.createPipelineLayout( {
  54389. bindGroupLayouts
  54390. } )
  54391. };
  54392. const depthStencil = {};
  54393. const renderDepth = renderObject.context.depth;
  54394. const renderStencil = renderObject.context.stencil;
  54395. if ( renderDepth === true || renderStencil === true ) {
  54396. if ( renderDepth === true ) {
  54397. depthStencil.format = depthStencilFormat;
  54398. depthStencil.depthWriteEnabled = material.depthWrite;
  54399. depthStencil.depthCompare = depthCompare;
  54400. }
  54401. if ( renderStencil === true ) {
  54402. depthStencil.stencilFront = stencilFront;
  54403. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  54404. depthStencil.stencilReadMask = material.stencilFuncMask;
  54405. depthStencil.stencilWriteMask = material.stencilWriteMask;
  54406. }
  54407. if ( material.polygonOffset === true ) {
  54408. depthStencil.depthBias = material.polygonOffsetUnits;
  54409. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  54410. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  54411. }
  54412. pipelineDescriptor.depthStencil = depthStencil;
  54413. }
  54414. // create pipeline
  54415. device.pushErrorScope( 'validation' );
  54416. if ( promises === null ) {
  54417. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  54418. device.popErrorScope().then( ( err ) => {
  54419. if ( err !== null ) {
  54420. pipelineData.error = true;
  54421. error( err.message );
  54422. }
  54423. } );
  54424. } else {
  54425. const p = new Promise( async ( resolve /*, reject*/ ) => {
  54426. try {
  54427. pipelineData.pipeline = await device.createRenderPipelineAsync( pipelineDescriptor );
  54428. } catch ( err ) { }
  54429. const errorScope = await device.popErrorScope();
  54430. if ( errorScope !== null ) {
  54431. pipelineData.error = true;
  54432. error( errorScope.message );
  54433. }
  54434. resolve();
  54435. } );
  54436. promises.push( p );
  54437. }
  54438. }
  54439. /**
  54440. * Creates GPU render bundle encoder for the given render context.
  54441. *
  54442. * @param {RenderContext} renderContext - The render context.
  54443. * @param {?string} [label='renderBundleEncoder'] - The label.
  54444. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  54445. */
  54446. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  54447. const backend = this.backend;
  54448. const { utils, device } = backend;
  54449. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  54450. const colorFormats = utils.getCurrentColorFormats( renderContext );
  54451. const sampleCount = this._getSampleCount( renderContext );
  54452. const descriptor = {
  54453. label,
  54454. colorFormats,
  54455. depthStencilFormat,
  54456. sampleCount
  54457. };
  54458. return device.createRenderBundleEncoder( descriptor );
  54459. }
  54460. /**
  54461. * Creates a compute pipeline for the given compute node.
  54462. *
  54463. * @param {ComputePipeline} pipeline - The compute pipeline.
  54464. * @param {Array<BindGroup>} bindings - The bindings.
  54465. */
  54466. createComputePipeline( pipeline, bindings ) {
  54467. const backend = this.backend;
  54468. const device = backend.device;
  54469. const computeProgram = backend.get( pipeline.computeProgram ).module;
  54470. const pipelineGPU = backend.get( pipeline );
  54471. // bind group layouts
  54472. const bindGroupLayouts = [];
  54473. for ( const bindingsGroup of bindings ) {
  54474. const bindingsData = backend.get( bindingsGroup );
  54475. bindGroupLayouts.push( bindingsData.layout );
  54476. }
  54477. pipelineGPU.pipeline = device.createComputePipeline( {
  54478. compute: computeProgram,
  54479. layout: device.createPipelineLayout( {
  54480. bindGroupLayouts
  54481. } )
  54482. } );
  54483. }
  54484. /**
  54485. * Returns the blending state as a descriptor object required
  54486. * for the pipeline creation.
  54487. *
  54488. * @private
  54489. * @param {Material} material - The material.
  54490. * @return {Object} The blending state.
  54491. */
  54492. _getBlending( material ) {
  54493. let color, alpha;
  54494. const blending = material.blending;
  54495. const blendSrc = material.blendSrc;
  54496. const blendDst = material.blendDst;
  54497. const blendEquation = material.blendEquation;
  54498. if ( blending === CustomBlending ) {
  54499. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  54500. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  54501. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  54502. color = {
  54503. srcFactor: this._getBlendFactor( blendSrc ),
  54504. dstFactor: this._getBlendFactor( blendDst ),
  54505. operation: this._getBlendOperation( blendEquation )
  54506. };
  54507. alpha = {
  54508. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  54509. dstFactor: this._getBlendFactor( blendDstAlpha ),
  54510. operation: this._getBlendOperation( blendEquationAlpha )
  54511. };
  54512. } else {
  54513. const premultipliedAlpha = material.premultipliedAlpha;
  54514. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  54515. color = {
  54516. srcFactor: srcRGB,
  54517. dstFactor: dstRGB,
  54518. operation: GPUBlendOperation.Add
  54519. };
  54520. alpha = {
  54521. srcFactor: srcAlpha,
  54522. dstFactor: dstAlpha,
  54523. operation: GPUBlendOperation.Add
  54524. };
  54525. };
  54526. if ( premultipliedAlpha ) {
  54527. switch ( blending ) {
  54528. case NormalBlending:
  54529. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  54530. break;
  54531. case AdditiveBlending:
  54532. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  54533. break;
  54534. case SubtractiveBlending:
  54535. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  54536. break;
  54537. case MultiplyBlending:
  54538. setBlend( GPUBlendFactor.Dst, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.Zero, GPUBlendFactor.One );
  54539. break;
  54540. }
  54541. } else {
  54542. switch ( blending ) {
  54543. case NormalBlending:
  54544. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  54545. break;
  54546. case AdditiveBlending:
  54547. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  54548. break;
  54549. case SubtractiveBlending:
  54550. error( 'WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true' );
  54551. break;
  54552. case MultiplyBlending:
  54553. error( 'WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true' );
  54554. break;
  54555. }
  54556. }
  54557. }
  54558. if ( color !== undefined && alpha !== undefined ) {
  54559. return { color, alpha };
  54560. } else {
  54561. error( 'WebGPURenderer: Invalid blending: ', blending );
  54562. }
  54563. }
  54564. /**
  54565. * Returns the GPU blend factor which is required for the pipeline creation.
  54566. *
  54567. * @private
  54568. * @param {number} blend - The blend factor as a three.js constant.
  54569. * @return {string} The GPU blend factor.
  54570. */
  54571. _getBlendFactor( blend ) {
  54572. let blendFactor;
  54573. switch ( blend ) {
  54574. case ZeroFactor:
  54575. blendFactor = GPUBlendFactor.Zero;
  54576. break;
  54577. case OneFactor:
  54578. blendFactor = GPUBlendFactor.One;
  54579. break;
  54580. case SrcColorFactor:
  54581. blendFactor = GPUBlendFactor.Src;
  54582. break;
  54583. case OneMinusSrcColorFactor:
  54584. blendFactor = GPUBlendFactor.OneMinusSrc;
  54585. break;
  54586. case SrcAlphaFactor:
  54587. blendFactor = GPUBlendFactor.SrcAlpha;
  54588. break;
  54589. case OneMinusSrcAlphaFactor:
  54590. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  54591. break;
  54592. case DstColorFactor:
  54593. blendFactor = GPUBlendFactor.Dst;
  54594. break;
  54595. case OneMinusDstColorFactor:
  54596. blendFactor = GPUBlendFactor.OneMinusDst;
  54597. break;
  54598. case DstAlphaFactor:
  54599. blendFactor = GPUBlendFactor.DstAlpha;
  54600. break;
  54601. case OneMinusDstAlphaFactor:
  54602. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  54603. break;
  54604. case SrcAlphaSaturateFactor:
  54605. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  54606. break;
  54607. case BlendColorFactor:
  54608. blendFactor = GPUBlendFactor.Constant;
  54609. break;
  54610. case OneMinusBlendColorFactor:
  54611. blendFactor = GPUBlendFactor.OneMinusConstant;
  54612. break;
  54613. default:
  54614. error( 'WebGPURenderer: Blend factor not supported.', blend );
  54615. }
  54616. return blendFactor;
  54617. }
  54618. /**
  54619. * Returns the GPU stencil compare function which is required for the pipeline creation.
  54620. *
  54621. * @private
  54622. * @param {Material} material - The material.
  54623. * @return {string} The GPU stencil compare function.
  54624. */
  54625. _getStencilCompare( material ) {
  54626. let stencilCompare;
  54627. const stencilFunc = material.stencilFunc;
  54628. switch ( stencilFunc ) {
  54629. case NeverStencilFunc:
  54630. stencilCompare = GPUCompareFunction.Never;
  54631. break;
  54632. case AlwaysStencilFunc:
  54633. stencilCompare = GPUCompareFunction.Always;
  54634. break;
  54635. case LessStencilFunc:
  54636. stencilCompare = GPUCompareFunction.Less;
  54637. break;
  54638. case LessEqualStencilFunc:
  54639. stencilCompare = GPUCompareFunction.LessEqual;
  54640. break;
  54641. case EqualStencilFunc:
  54642. stencilCompare = GPUCompareFunction.Equal;
  54643. break;
  54644. case GreaterEqualStencilFunc:
  54645. stencilCompare = GPUCompareFunction.GreaterEqual;
  54646. break;
  54647. case GreaterStencilFunc:
  54648. stencilCompare = GPUCompareFunction.Greater;
  54649. break;
  54650. case NotEqualStencilFunc:
  54651. stencilCompare = GPUCompareFunction.NotEqual;
  54652. break;
  54653. default:
  54654. error( 'WebGPURenderer: Invalid stencil function.', stencilFunc );
  54655. }
  54656. return stencilCompare;
  54657. }
  54658. /**
  54659. * Returns the GPU stencil operation which is required for the pipeline creation.
  54660. *
  54661. * @private
  54662. * @param {number} op - A three.js constant defining the stencil operation.
  54663. * @return {string} The GPU stencil operation.
  54664. */
  54665. _getStencilOperation( op ) {
  54666. let stencilOperation;
  54667. switch ( op ) {
  54668. case KeepStencilOp:
  54669. stencilOperation = GPUStencilOperation.Keep;
  54670. break;
  54671. case ZeroStencilOp:
  54672. stencilOperation = GPUStencilOperation.Zero;
  54673. break;
  54674. case ReplaceStencilOp:
  54675. stencilOperation = GPUStencilOperation.Replace;
  54676. break;
  54677. case InvertStencilOp:
  54678. stencilOperation = GPUStencilOperation.Invert;
  54679. break;
  54680. case IncrementStencilOp:
  54681. stencilOperation = GPUStencilOperation.IncrementClamp;
  54682. break;
  54683. case DecrementStencilOp:
  54684. stencilOperation = GPUStencilOperation.DecrementClamp;
  54685. break;
  54686. case IncrementWrapStencilOp:
  54687. stencilOperation = GPUStencilOperation.IncrementWrap;
  54688. break;
  54689. case DecrementWrapStencilOp:
  54690. stencilOperation = GPUStencilOperation.DecrementWrap;
  54691. break;
  54692. default:
  54693. error( 'WebGPURenderer: Invalid stencil operation.', stencilOperation );
  54694. }
  54695. return stencilOperation;
  54696. }
  54697. /**
  54698. * Returns the GPU blend operation which is required for the pipeline creation.
  54699. *
  54700. * @private
  54701. * @param {number} blendEquation - A three.js constant defining the blend equation.
  54702. * @return {string} The GPU blend operation.
  54703. */
  54704. _getBlendOperation( blendEquation ) {
  54705. let blendOperation;
  54706. switch ( blendEquation ) {
  54707. case AddEquation:
  54708. blendOperation = GPUBlendOperation.Add;
  54709. break;
  54710. case SubtractEquation:
  54711. blendOperation = GPUBlendOperation.Subtract;
  54712. break;
  54713. case ReverseSubtractEquation:
  54714. blendOperation = GPUBlendOperation.ReverseSubtract;
  54715. break;
  54716. case MinEquation:
  54717. blendOperation = GPUBlendOperation.Min;
  54718. break;
  54719. case MaxEquation:
  54720. blendOperation = GPUBlendOperation.Max;
  54721. break;
  54722. default:
  54723. error( 'WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  54724. }
  54725. return blendOperation;
  54726. }
  54727. /**
  54728. * Returns the primitive state as a descriptor object required
  54729. * for the pipeline creation.
  54730. *
  54731. * @private
  54732. * @param {Object3D} object - The 3D object.
  54733. * @param {BufferGeometry} geometry - The geometry.
  54734. * @param {Material} material - The material.
  54735. * @return {Object} The primitive state.
  54736. */
  54737. _getPrimitiveState( object, geometry, material ) {
  54738. const descriptor = {};
  54739. const utils = this.backend.utils;
  54740. //
  54741. descriptor.topology = utils.getPrimitiveTopology( object, material );
  54742. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  54743. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  54744. }
  54745. //
  54746. let flipSided = ( material.side === BackSide );
  54747. if ( object.isMesh && object.matrixWorld.determinant() < 0 ) flipSided = ! flipSided;
  54748. descriptor.frontFace = ( flipSided === true ) ? GPUFrontFace.CW : GPUFrontFace.CCW;
  54749. //
  54750. descriptor.cullMode = ( material.side === DoubleSide ) ? GPUCullMode.None : GPUCullMode.Back;
  54751. return descriptor;
  54752. }
  54753. /**
  54754. * Returns the GPU color write mask which is required for the pipeline creation.
  54755. *
  54756. * @private
  54757. * @param {Material} material - The material.
  54758. * @return {number} The GPU color write mask.
  54759. */
  54760. _getColorWriteMask( material ) {
  54761. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  54762. }
  54763. /**
  54764. * Returns the GPU depth compare function which is required for the pipeline creation.
  54765. *
  54766. * @private
  54767. * @param {Material} material - The material.
  54768. * @return {string} The GPU depth compare function.
  54769. */
  54770. _getDepthCompare( material ) {
  54771. let depthCompare;
  54772. if ( material.depthTest === false ) {
  54773. depthCompare = GPUCompareFunction.Always;
  54774. } else {
  54775. const depthFunc = material.depthFunc;
  54776. switch ( depthFunc ) {
  54777. case NeverDepth:
  54778. depthCompare = GPUCompareFunction.Never;
  54779. break;
  54780. case AlwaysDepth:
  54781. depthCompare = GPUCompareFunction.Always;
  54782. break;
  54783. case LessDepth:
  54784. depthCompare = GPUCompareFunction.Less;
  54785. break;
  54786. case LessEqualDepth:
  54787. depthCompare = GPUCompareFunction.LessEqual;
  54788. break;
  54789. case EqualDepth:
  54790. depthCompare = GPUCompareFunction.Equal;
  54791. break;
  54792. case GreaterEqualDepth:
  54793. depthCompare = GPUCompareFunction.GreaterEqual;
  54794. break;
  54795. case GreaterDepth:
  54796. depthCompare = GPUCompareFunction.Greater;
  54797. break;
  54798. case NotEqualDepth:
  54799. depthCompare = GPUCompareFunction.NotEqual;
  54800. break;
  54801. default:
  54802. error( 'WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  54803. }
  54804. }
  54805. return depthCompare;
  54806. }
  54807. }
  54808. /**
  54809. * Manages a pool of WebGPU timestamp queries for performance measurement.
  54810. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  54811. *
  54812. * @augments TimestampQueryPool
  54813. */
  54814. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  54815. /**
  54816. * Creates a new WebGPU timestamp query pool.
  54817. *
  54818. * @param {GPUDevice} device - The WebGPU device to create queries on.
  54819. * @param {string} type - The type identifier for this query pool.
  54820. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  54821. */
  54822. constructor( device, type, maxQueries = 2048 ) {
  54823. super( maxQueries );
  54824. this.device = device;
  54825. this.type = type;
  54826. this.querySet = this.device.createQuerySet( {
  54827. type: 'timestamp',
  54828. count: this.maxQueries,
  54829. label: `queryset_global_timestamp_${type}`
  54830. } );
  54831. const bufferSize = this.maxQueries * 8;
  54832. this.resolveBuffer = this.device.createBuffer( {
  54833. label: `buffer_timestamp_resolve_${type}`,
  54834. size: bufferSize,
  54835. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  54836. } );
  54837. this.resultBuffer = this.device.createBuffer( {
  54838. label: `buffer_timestamp_result_${type}`,
  54839. size: bufferSize,
  54840. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  54841. } );
  54842. }
  54843. /**
  54844. * Allocates a pair of queries for a given render context.
  54845. *
  54846. * @param {string} uid - A unique identifier for the render context.
  54847. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  54848. */
  54849. allocateQueriesForContext( uid ) {
  54850. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  54851. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  54852. 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() } ).` );
  54853. return null;
  54854. }
  54855. const baseOffset = this.currentQueryIndex;
  54856. this.currentQueryIndex += 2;
  54857. this.queryOffsets.set( uid, baseOffset );
  54858. return baseOffset;
  54859. }
  54860. /**
  54861. * Asynchronously resolves all pending queries and returns the total duration.
  54862. * If there's already a pending resolve operation, returns that promise instead.
  54863. *
  54864. * @async
  54865. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  54866. */
  54867. async resolveQueriesAsync() {
  54868. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  54869. return this.lastValue;
  54870. }
  54871. if ( this.pendingResolve ) {
  54872. return this.pendingResolve;
  54873. }
  54874. this.pendingResolve = this._resolveQueries();
  54875. try {
  54876. const result = await this.pendingResolve;
  54877. return result;
  54878. } finally {
  54879. this.pendingResolve = null;
  54880. }
  54881. }
  54882. /**
  54883. * Internal method to resolve queries and calculate total duration.
  54884. *
  54885. * @async
  54886. * @private
  54887. * @returns {Promise<number>} The total duration in milliseconds.
  54888. */
  54889. async _resolveQueries() {
  54890. if ( this.isDisposed ) {
  54891. return this.lastValue;
  54892. }
  54893. try {
  54894. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  54895. return this.lastValue;
  54896. }
  54897. const currentOffsets = new Map( this.queryOffsets );
  54898. const queryCount = this.currentQueryIndex;
  54899. const bytesUsed = queryCount * 8;
  54900. // Reset state before GPU work
  54901. this.currentQueryIndex = 0;
  54902. this.queryOffsets.clear();
  54903. const commandEncoder = this.device.createCommandEncoder();
  54904. commandEncoder.resolveQuerySet(
  54905. this.querySet,
  54906. 0,
  54907. queryCount,
  54908. this.resolveBuffer,
  54909. 0
  54910. );
  54911. commandEncoder.copyBufferToBuffer(
  54912. this.resolveBuffer,
  54913. 0,
  54914. this.resultBuffer,
  54915. 0,
  54916. bytesUsed
  54917. );
  54918. const commandBuffer = commandEncoder.finish();
  54919. this.device.queue.submit( [ commandBuffer ] );
  54920. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  54921. return this.lastValue;
  54922. }
  54923. // Create and track the mapping operation
  54924. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  54925. if ( this.isDisposed ) {
  54926. if ( this.resultBuffer.mapState === 'mapped' ) {
  54927. this.resultBuffer.unmap();
  54928. }
  54929. return this.lastValue;
  54930. }
  54931. //
  54932. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  54933. const framesDuration = {};
  54934. const frames = [];
  54935. for ( const [ uid, baseOffset ] of currentOffsets ) {
  54936. const match = uid.match( /^(.*):f(\d+)$/ );
  54937. const frame = parseInt( match[ 2 ] );
  54938. if ( frames.includes( frame ) === false ) {
  54939. frames.push( frame );
  54940. }
  54941. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  54942. const startTime = times[ baseOffset ];
  54943. const endTime = times[ baseOffset + 1 ];
  54944. const duration = Number( endTime - startTime ) / 1e6;
  54945. this.timestamps.set( uid, duration );
  54946. framesDuration[ frame ] += duration;
  54947. }
  54948. // Return the total duration of the last frame
  54949. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  54950. this.resultBuffer.unmap();
  54951. this.lastValue = totalDuration;
  54952. this.frames = frames;
  54953. return totalDuration;
  54954. } catch ( e ) {
  54955. error( 'Error resolving queries:', e );
  54956. if ( this.resultBuffer.mapState === 'mapped' ) {
  54957. this.resultBuffer.unmap();
  54958. }
  54959. return this.lastValue;
  54960. }
  54961. }
  54962. /**
  54963. * Dispose of the query pool.
  54964. *
  54965. * @async
  54966. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  54967. */
  54968. async dispose() {
  54969. if ( this.isDisposed ) {
  54970. return;
  54971. }
  54972. this.isDisposed = true;
  54973. // Wait for pending resolve operation
  54974. if ( this.pendingResolve ) {
  54975. try {
  54976. await this.pendingResolve;
  54977. } catch ( e ) {
  54978. error( 'Error waiting for pending resolve:', e );
  54979. }
  54980. }
  54981. // Ensure buffer is unmapped before destroying
  54982. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  54983. try {
  54984. this.resultBuffer.unmap();
  54985. } catch ( e ) {
  54986. error( 'Error unmapping buffer:', e );
  54987. }
  54988. }
  54989. // Destroy resources
  54990. if ( this.querySet ) {
  54991. this.querySet.destroy();
  54992. this.querySet = null;
  54993. }
  54994. if ( this.resolveBuffer ) {
  54995. this.resolveBuffer.destroy();
  54996. this.resolveBuffer = null;
  54997. }
  54998. if ( this.resultBuffer ) {
  54999. this.resultBuffer.destroy();
  55000. this.resultBuffer = null;
  55001. }
  55002. this.queryOffsets.clear();
  55003. this.pendingResolve = null;
  55004. }
  55005. }
  55006. /*// debugger tools
  55007. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  55008. //*/
  55009. /**
  55010. * A backend implementation targeting WebGPU.
  55011. *
  55012. * @private
  55013. * @augments Backend
  55014. */
  55015. class WebGPUBackend extends Backend {
  55016. /**
  55017. * WebGPUBackend options.
  55018. *
  55019. * @typedef {Object} WebGPUBackend~Options
  55020. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  55021. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  55022. * @property {boolean} [compatibilityMode=false] - Whether the backend should be in compatibility mode or not.
  55023. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  55024. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  55025. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  55026. * @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.
  55027. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  55028. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  55029. * @property {string} [powerPreference=undefined] - The power preference.
  55030. * @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.
  55031. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  55032. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  55033. */
  55034. /**
  55035. * Constructs a new WebGPU backend.
  55036. *
  55037. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  55038. */
  55039. constructor( parameters = {} ) {
  55040. super( parameters );
  55041. /**
  55042. * This flag can be used for type testing.
  55043. *
  55044. * @type {boolean}
  55045. * @readonly
  55046. * @default true
  55047. */
  55048. this.isWebGPUBackend = true;
  55049. // some parameters require default values other than "undefined"
  55050. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  55051. this.parameters.compatibilityMode = ( parameters.compatibilityMode === undefined ) ? false : parameters.compatibilityMode;
  55052. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  55053. /**
  55054. * Indicates whether the backend is in compatibility mode or not.
  55055. * @type {boolean}
  55056. * @default false
  55057. */
  55058. this.compatibilityMode = this.parameters.compatibilityMode;
  55059. /**
  55060. * A reference to the device.
  55061. *
  55062. * @type {?GPUDevice}
  55063. * @default null
  55064. */
  55065. this.device = null;
  55066. /**
  55067. * A reference to the default render pass descriptor.
  55068. *
  55069. * @type {?Object}
  55070. * @default null
  55071. */
  55072. this.defaultRenderPassdescriptor = null;
  55073. /**
  55074. * A reference to a backend module holding common utility functions.
  55075. *
  55076. * @type {WebGPUUtils}
  55077. */
  55078. this.utils = new WebGPUUtils( this );
  55079. /**
  55080. * A reference to a backend module holding shader attribute-related
  55081. * utility functions.
  55082. *
  55083. * @type {WebGPUAttributeUtils}
  55084. */
  55085. this.attributeUtils = new WebGPUAttributeUtils( this );
  55086. /**
  55087. * A reference to a backend module holding shader binding-related
  55088. * utility functions.
  55089. *
  55090. * @type {WebGPUBindingUtils}
  55091. */
  55092. this.bindingUtils = new WebGPUBindingUtils( this );
  55093. /**
  55094. * A reference to a backend module holding shader pipeline-related
  55095. * utility functions.
  55096. *
  55097. * @type {WebGPUPipelineUtils}
  55098. */
  55099. this.pipelineUtils = new WebGPUPipelineUtils( this );
  55100. /**
  55101. * A reference to a backend module holding shader texture-related
  55102. * utility functions.
  55103. *
  55104. * @type {WebGPUTextureUtils}
  55105. */
  55106. this.textureUtils = new WebGPUTextureUtils( this );
  55107. /**
  55108. * A map that manages the resolve buffers for occlusion queries.
  55109. *
  55110. * @type {Map<number,GPUBuffer>}
  55111. */
  55112. this.occludedResolveCache = new Map();
  55113. }
  55114. /**
  55115. * Initializes the backend so it is ready for usage.
  55116. *
  55117. * @async
  55118. * @param {Renderer} renderer - The renderer.
  55119. * @return {Promise} A Promise that resolves when the backend has been initialized.
  55120. */
  55121. async init( renderer ) {
  55122. await super.init( renderer );
  55123. //
  55124. const parameters = this.parameters;
  55125. // create the device if it is not passed with parameters
  55126. let device;
  55127. if ( parameters.device === undefined ) {
  55128. const adapterOptions = {
  55129. powerPreference: parameters.powerPreference,
  55130. featureLevel: parameters.compatibilityMode ? 'compatibility' : undefined
  55131. };
  55132. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  55133. if ( adapter === null ) {
  55134. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  55135. }
  55136. // feature support
  55137. const features = Object.values( GPUFeatureName );
  55138. const supportedFeatures = [];
  55139. for ( const name of features ) {
  55140. if ( adapter.features.has( name ) ) {
  55141. supportedFeatures.push( name );
  55142. }
  55143. }
  55144. const deviceDescriptor = {
  55145. requiredFeatures: supportedFeatures,
  55146. requiredLimits: parameters.requiredLimits
  55147. };
  55148. device = await adapter.requestDevice( deviceDescriptor );
  55149. } else {
  55150. device = parameters.device;
  55151. }
  55152. device.lost.then( ( info ) => {
  55153. const deviceLossInfo = {
  55154. api: 'WebGPU',
  55155. message: info.message || 'Unknown reason',
  55156. reason: info.reason || null,
  55157. originalEvent: info
  55158. };
  55159. renderer.onDeviceLost( deviceLossInfo );
  55160. } );
  55161. this.device = device;
  55162. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  55163. this.updateSize();
  55164. }
  55165. /**
  55166. * A reference to the context.
  55167. *
  55168. * @type {?GPUCanvasContext}
  55169. * @default null
  55170. */
  55171. get context() {
  55172. const canvasTarget = this.renderer.getCanvasTarget();
  55173. const canvasData = this.get( canvasTarget );
  55174. let context = canvasData.context;
  55175. if ( context === undefined ) {
  55176. const parameters = this.parameters;
  55177. if ( canvasTarget.isDefaultCanvasTarget === true && parameters.context !== undefined ) {
  55178. context = parameters.context;
  55179. } else {
  55180. context = canvasTarget.domElement.getContext( 'webgpu' );
  55181. }
  55182. // OffscreenCanvas does not have setAttribute, see #22811
  55183. if ( 'setAttribute' in canvasTarget.domElement ) canvasTarget.domElement.setAttribute( 'data-engine', `three.js r${ REVISION } webgpu` );
  55184. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  55185. const toneMappingMode = parameters.outputType === HalfFloatType ? 'extended' : 'standard';
  55186. context.configure( {
  55187. device: this.device,
  55188. format: this.utils.getPreferredCanvasFormat(),
  55189. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  55190. alphaMode: alphaMode,
  55191. toneMapping: {
  55192. mode: toneMappingMode
  55193. }
  55194. } );
  55195. canvasData.context = context;
  55196. }
  55197. return context;
  55198. }
  55199. /**
  55200. * The coordinate system of the backend.
  55201. *
  55202. * @type {number}
  55203. * @readonly
  55204. */
  55205. get coordinateSystem() {
  55206. return WebGPUCoordinateSystem;
  55207. }
  55208. /**
  55209. * This method performs a readback operation by moving buffer data from
  55210. * a storage buffer attribute from the GPU to the CPU.
  55211. *
  55212. * @async
  55213. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  55214. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  55215. */
  55216. async getArrayBufferAsync( attribute ) {
  55217. return await this.attributeUtils.getArrayBufferAsync( attribute );
  55218. }
  55219. /**
  55220. * Returns the backend's rendering context.
  55221. *
  55222. * @return {GPUCanvasContext} The rendering context.
  55223. */
  55224. getContext() {
  55225. return this.context;
  55226. }
  55227. /**
  55228. * Returns the default render pass descriptor.
  55229. *
  55230. * In WebGPU, the default framebuffer must be configured
  55231. * like custom framebuffers so the backend needs a render
  55232. * pass descriptor even when rendering directly to screen.
  55233. *
  55234. * @private
  55235. * @return {Object} The render pass descriptor.
  55236. */
  55237. _getDefaultRenderPassDescriptor() {
  55238. const renderer = this.renderer;
  55239. const canvasTarget = renderer.getCanvasTarget();
  55240. const canvasData = this.get( canvasTarget );
  55241. const samples = renderer.currentSamples;
  55242. let descriptor = canvasData.descriptor;
  55243. if ( descriptor === undefined || canvasData.samples !== samples ) {
  55244. descriptor = {
  55245. colorAttachments: [ {
  55246. view: null
  55247. } ]
  55248. };
  55249. if ( renderer.depth === true || renderer.stencil === true ) {
  55250. descriptor.depthStencilAttachment = {
  55251. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  55252. };
  55253. }
  55254. const colorAttachment = descriptor.colorAttachments[ 0 ];
  55255. if ( samples > 0 ) {
  55256. colorAttachment.view = this.textureUtils.getColorBuffer().createView();
  55257. } else {
  55258. colorAttachment.resolveTarget = undefined;
  55259. }
  55260. canvasData.descriptor = descriptor;
  55261. canvasData.samples = samples;
  55262. }
  55263. const colorAttachment = descriptor.colorAttachments[ 0 ];
  55264. if ( samples > 0 ) {
  55265. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  55266. } else {
  55267. colorAttachment.view = this.context.getCurrentTexture().createView();
  55268. }
  55269. return descriptor;
  55270. }
  55271. /**
  55272. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  55273. *
  55274. * @param {RenderContext} renderContext - The render context.
  55275. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  55276. *
  55277. * @private
  55278. */
  55279. _isRenderCameraDepthArray( renderContext ) {
  55280. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  55281. }
  55282. /**
  55283. * Returns the render pass descriptor for the given render context.
  55284. *
  55285. * @private
  55286. * @param {RenderContext} renderContext - The render context.
  55287. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  55288. * @return {Object} The render pass descriptor.
  55289. */
  55290. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  55291. const renderTarget = renderContext.renderTarget;
  55292. const renderTargetData = this.get( renderTarget );
  55293. let descriptors = renderTargetData.descriptors;
  55294. if ( descriptors === undefined ||
  55295. renderTargetData.width !== renderTarget.width ||
  55296. renderTargetData.height !== renderTarget.height ||
  55297. renderTargetData.samples !== renderTarget.samples
  55298. ) {
  55299. descriptors = {};
  55300. renderTargetData.descriptors = descriptors;
  55301. }
  55302. const cacheKey = renderContext.getCacheKey();
  55303. let descriptorBase = descriptors[ cacheKey ];
  55304. if ( descriptorBase === undefined ) {
  55305. const textures = renderContext.textures;
  55306. const textureViews = [];
  55307. let sliceIndex;
  55308. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  55309. for ( let i = 0; i < textures.length; i ++ ) {
  55310. const textureData = this.get( textures[ i ] );
  55311. const viewDescriptor = {
  55312. label: `colorAttachment_${ i }`,
  55313. baseMipLevel: renderContext.activeMipmapLevel,
  55314. mipLevelCount: 1,
  55315. baseArrayLayer: renderContext.activeCubeFace,
  55316. arrayLayerCount: 1,
  55317. dimension: GPUTextureViewDimension.TwoD
  55318. };
  55319. if ( renderTarget.isRenderTarget3D ) {
  55320. sliceIndex = renderContext.activeCubeFace;
  55321. viewDescriptor.baseArrayLayer = 0;
  55322. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  55323. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  55324. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  55325. if ( isRenderCameraDepthArray === true ) {
  55326. const cameras = renderContext.camera.cameras;
  55327. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  55328. const layerViewDescriptor = {
  55329. ...viewDescriptor,
  55330. baseArrayLayer: layer,
  55331. arrayLayerCount: 1,
  55332. dimension: GPUTextureViewDimension.TwoD
  55333. };
  55334. const textureView = textureData.texture.createView( layerViewDescriptor );
  55335. textureViews.push( {
  55336. view: textureView,
  55337. resolveTarget: undefined,
  55338. depthSlice: undefined
  55339. } );
  55340. }
  55341. } else {
  55342. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  55343. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  55344. }
  55345. }
  55346. if ( isRenderCameraDepthArray !== true ) {
  55347. const textureView = textureData.texture.createView( viewDescriptor );
  55348. let view, resolveTarget;
  55349. if ( textureData.msaaTexture !== undefined ) {
  55350. view = textureData.msaaTexture.createView();
  55351. resolveTarget = textureView;
  55352. } else {
  55353. view = textureView;
  55354. resolveTarget = undefined;
  55355. }
  55356. textureViews.push( {
  55357. view,
  55358. resolveTarget,
  55359. depthSlice: sliceIndex
  55360. } );
  55361. }
  55362. }
  55363. descriptorBase = { textureViews };
  55364. if ( renderContext.depth ) {
  55365. const depthTextureData = this.get( renderContext.depthTexture );
  55366. const options = {};
  55367. if ( renderContext.depthTexture.isArrayTexture || renderContext.depthTexture.isCubeTexture ) {
  55368. options.dimension = GPUTextureViewDimension.TwoD;
  55369. options.arrayLayerCount = 1;
  55370. options.baseArrayLayer = renderContext.activeCubeFace;
  55371. }
  55372. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  55373. }
  55374. descriptors[ cacheKey ] = descriptorBase;
  55375. renderTargetData.width = renderTarget.width;
  55376. renderTargetData.height = renderTarget.height;
  55377. renderTargetData.samples = renderTarget.samples;
  55378. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  55379. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  55380. }
  55381. const descriptor = {
  55382. colorAttachments: []
  55383. };
  55384. // Apply dynamic properties to cached views
  55385. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  55386. const viewInfo = descriptorBase.textureViews[ i ];
  55387. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  55388. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  55389. clearValue = colorAttachmentsConfig.clearValue;
  55390. }
  55391. descriptor.colorAttachments.push( {
  55392. view: viewInfo.view,
  55393. depthSlice: viewInfo.depthSlice,
  55394. resolveTarget: viewInfo.resolveTarget,
  55395. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  55396. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  55397. clearValue: clearValue
  55398. } );
  55399. }
  55400. if ( descriptorBase.depthStencilView ) {
  55401. descriptor.depthStencilAttachment = {
  55402. view: descriptorBase.depthStencilView
  55403. };
  55404. }
  55405. return descriptor;
  55406. }
  55407. /**
  55408. * This method is executed at the beginning of a render call and prepares
  55409. * the WebGPU state for upcoming render calls
  55410. *
  55411. * @param {RenderContext} renderContext - The render context.
  55412. */
  55413. beginRender( renderContext ) {
  55414. const renderContextData = this.get( renderContext );
  55415. //
  55416. const device = this.device;
  55417. const occlusionQueryCount = renderContext.occlusionQueryCount;
  55418. let occlusionQuerySet;
  55419. if ( occlusionQueryCount > 0 ) {
  55420. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  55421. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  55422. // Get a reference to the array of objects with queries. The renderContextData property
  55423. // can be changed by another render pass before the buffer.mapAsyc() completes.
  55424. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  55425. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  55426. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  55427. //
  55428. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  55429. renderContextData.occlusionQuerySet = occlusionQuerySet;
  55430. renderContextData.occlusionQueryIndex = 0;
  55431. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  55432. renderContextData.lastOcclusionObject = null;
  55433. }
  55434. let descriptor;
  55435. if ( renderContext.textures === null ) {
  55436. descriptor = this._getDefaultRenderPassDescriptor();
  55437. } else {
  55438. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  55439. }
  55440. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ), descriptor );
  55441. descriptor.occlusionQuerySet = occlusionQuerySet;
  55442. const depthStencilAttachment = descriptor.depthStencilAttachment;
  55443. if ( renderContext.textures !== null ) {
  55444. const colorAttachments = descriptor.colorAttachments;
  55445. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  55446. const colorAttachment = colorAttachments[ i ];
  55447. if ( renderContext.clearColor ) {
  55448. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  55449. colorAttachment.loadOp = GPULoadOp.Clear;
  55450. } else {
  55451. colorAttachment.loadOp = GPULoadOp.Load;
  55452. }
  55453. colorAttachment.storeOp = GPUStoreOp.Store;
  55454. }
  55455. } else {
  55456. const colorAttachment = descriptor.colorAttachments[ 0 ];
  55457. if ( renderContext.clearColor ) {
  55458. colorAttachment.clearValue = renderContext.clearColorValue;
  55459. colorAttachment.loadOp = GPULoadOp.Clear;
  55460. } else {
  55461. colorAttachment.loadOp = GPULoadOp.Load;
  55462. }
  55463. colorAttachment.storeOp = GPUStoreOp.Store;
  55464. }
  55465. //
  55466. if ( renderContext.depth ) {
  55467. if ( renderContext.clearDepth ) {
  55468. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  55469. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  55470. } else {
  55471. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  55472. }
  55473. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  55474. }
  55475. if ( renderContext.stencil ) {
  55476. if ( renderContext.clearStencil ) {
  55477. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  55478. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  55479. } else {
  55480. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  55481. }
  55482. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  55483. }
  55484. //
  55485. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  55486. // shadow arrays - prepare bundle encoders for each camera in an array camera
  55487. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  55488. const cameras = renderContext.camera.cameras;
  55489. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  55490. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  55491. } else {
  55492. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  55493. }
  55494. // Create bundle encoders for each layer
  55495. renderContextData.bundleEncoders = [];
  55496. renderContextData.bundleSets = [];
  55497. // Create separate bundle encoders for each camera in the array
  55498. for ( let i = 0; i < cameras.length; i ++ ) {
  55499. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  55500. renderContext,
  55501. 'renderBundleArrayCamera_' + i
  55502. );
  55503. // Initialize state tracking for this bundle
  55504. const bundleSets = {
  55505. attributes: {},
  55506. bindingGroups: [],
  55507. pipeline: null,
  55508. index: null
  55509. };
  55510. renderContextData.bundleEncoders.push( bundleEncoder );
  55511. renderContextData.bundleSets.push( bundleSets );
  55512. }
  55513. // We'll complete the bundles in finishRender
  55514. renderContextData.currentPass = null;
  55515. } else {
  55516. const currentPass = encoder.beginRenderPass( descriptor );
  55517. renderContextData.currentPass = currentPass;
  55518. if ( renderContext.viewport ) {
  55519. this.updateViewport( renderContext );
  55520. }
  55521. if ( renderContext.scissor ) {
  55522. this.updateScissor( renderContext );
  55523. }
  55524. }
  55525. //
  55526. renderContextData.descriptor = descriptor;
  55527. renderContextData.encoder = encoder;
  55528. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  55529. renderContextData.renderBundles = [];
  55530. }
  55531. /**
  55532. * This method creates layer descriptors for each camera in an array camera
  55533. * to prepare for rendering to a depth array texture.
  55534. *
  55535. * @param {RenderContext} renderContext - The render context.
  55536. * @param {Object} renderContextData - The render context data.
  55537. * @param {Object} descriptor - The render pass descriptor.
  55538. * @param {ArrayCamera} cameras - The array camera.
  55539. *
  55540. * @private
  55541. */
  55542. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  55543. const depthStencilAttachment = descriptor.depthStencilAttachment;
  55544. renderContextData.layerDescriptors = [];
  55545. const depthTextureData = this.get( renderContext.depthTexture );
  55546. if ( ! depthTextureData.viewCache ) {
  55547. depthTextureData.viewCache = [];
  55548. }
  55549. for ( let i = 0; i < cameras.length; i ++ ) {
  55550. const layerDescriptor = {
  55551. ...descriptor,
  55552. colorAttachments: [ {
  55553. ...descriptor.colorAttachments[ 0 ],
  55554. view: descriptor.colorAttachments[ i ].view
  55555. } ]
  55556. };
  55557. if ( descriptor.depthStencilAttachment ) {
  55558. const layerIndex = i;
  55559. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  55560. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  55561. dimension: GPUTextureViewDimension.TwoD,
  55562. baseArrayLayer: i,
  55563. arrayLayerCount: 1
  55564. } );
  55565. }
  55566. layerDescriptor.depthStencilAttachment = {
  55567. view: depthTextureData.viewCache[ layerIndex ],
  55568. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  55569. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  55570. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  55571. };
  55572. if ( renderContext.stencil ) {
  55573. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  55574. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  55575. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  55576. }
  55577. } else {
  55578. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  55579. }
  55580. renderContextData.layerDescriptors.push( layerDescriptor );
  55581. }
  55582. }
  55583. /**
  55584. * This method updates the layer descriptors for each camera in an array camera
  55585. * to prepare for rendering to a depth array texture.
  55586. *
  55587. * @param {RenderContext} renderContext - The render context.
  55588. * @param {Object} renderContextData - The render context data.
  55589. * @param {ArrayCamera} cameras - The array camera.
  55590. *
  55591. */
  55592. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  55593. for ( let i = 0; i < cameras.length; i ++ ) {
  55594. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  55595. if ( layerDescriptor.depthStencilAttachment ) {
  55596. const depthAttachment = layerDescriptor.depthStencilAttachment;
  55597. if ( renderContext.depth ) {
  55598. if ( renderContext.clearDepth ) {
  55599. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  55600. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  55601. } else {
  55602. depthAttachment.depthLoadOp = GPULoadOp.Load;
  55603. }
  55604. }
  55605. if ( renderContext.stencil ) {
  55606. if ( renderContext.clearStencil ) {
  55607. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  55608. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  55609. } else {
  55610. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  55611. }
  55612. }
  55613. }
  55614. }
  55615. }
  55616. /**
  55617. * This method is executed at the end of a render call and finalizes work
  55618. * after draw calls.
  55619. *
  55620. * @param {RenderContext} renderContext - The render context.
  55621. */
  55622. finishRender( renderContext ) {
  55623. const renderContextData = this.get( renderContext );
  55624. const occlusionQueryCount = renderContext.occlusionQueryCount;
  55625. if ( renderContextData.renderBundles.length > 0 ) {
  55626. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  55627. }
  55628. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  55629. renderContextData.currentPass.endOcclusionQuery();
  55630. }
  55631. // shadow arrays - Execute bundles for each layer
  55632. const encoder = renderContextData.encoder;
  55633. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  55634. const bundles = [];
  55635. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  55636. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  55637. bundles.push( bundleEncoder.finish() );
  55638. }
  55639. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  55640. if ( i < bundles.length ) {
  55641. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  55642. const renderPass = encoder.beginRenderPass( layerDescriptor );
  55643. if ( renderContext.viewport ) {
  55644. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  55645. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  55646. }
  55647. if ( renderContext.scissor ) {
  55648. const { x, y, width, height } = renderContext.scissorValue;
  55649. renderPass.setScissorRect( x, y, width, height );
  55650. }
  55651. renderPass.executeBundles( [ bundles[ i ] ] );
  55652. renderPass.end();
  55653. }
  55654. }
  55655. } else if ( renderContextData.currentPass ) {
  55656. renderContextData.currentPass.end();
  55657. }
  55658. if ( occlusionQueryCount > 0 ) {
  55659. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  55660. //
  55661. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  55662. if ( queryResolveBuffer === undefined ) {
  55663. queryResolveBuffer = this.device.createBuffer(
  55664. {
  55665. size: bufferSize,
  55666. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  55667. }
  55668. );
  55669. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  55670. }
  55671. //
  55672. const readBuffer = this.device.createBuffer(
  55673. {
  55674. size: bufferSize,
  55675. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  55676. }
  55677. );
  55678. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  55679. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  55680. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  55681. renderContextData.occlusionQueryBuffer = readBuffer;
  55682. //
  55683. this.resolveOccludedAsync( renderContext );
  55684. }
  55685. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  55686. //
  55687. if ( renderContext.textures !== null ) {
  55688. const textures = renderContext.textures;
  55689. for ( let i = 0; i < textures.length; i ++ ) {
  55690. const texture = textures[ i ];
  55691. if ( texture.generateMipmaps === true ) {
  55692. this.textureUtils.generateMipmaps( texture );
  55693. }
  55694. }
  55695. }
  55696. }
  55697. /**
  55698. * Returns `true` if the given 3D object is fully occluded by other
  55699. * 3D objects in the scene.
  55700. *
  55701. * @param {RenderContext} renderContext - The render context.
  55702. * @param {Object3D} object - The 3D object to test.
  55703. * @return {boolean} Whether the 3D object is fully occluded or not.
  55704. */
  55705. isOccluded( renderContext, object ) {
  55706. const renderContextData = this.get( renderContext );
  55707. return renderContextData.occluded && renderContextData.occluded.has( object );
  55708. }
  55709. /**
  55710. * This method processes the result of occlusion queries and writes it
  55711. * into render context data.
  55712. *
  55713. * @async
  55714. * @param {RenderContext} renderContext - The render context.
  55715. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  55716. */
  55717. async resolveOccludedAsync( renderContext ) {
  55718. const renderContextData = this.get( renderContext );
  55719. // handle occlusion query results
  55720. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  55721. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  55722. const occluded = new WeakSet();
  55723. renderContextData.currentOcclusionQueryObjects = null;
  55724. renderContextData.currentOcclusionQueryBuffer = null;
  55725. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  55726. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  55727. const results = new BigUint64Array( buffer );
  55728. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  55729. if ( results[ i ] === BigInt( 0 ) ) {
  55730. occluded.add( currentOcclusionQueryObjects[ i ] );
  55731. }
  55732. }
  55733. currentOcclusionQueryBuffer.destroy();
  55734. renderContextData.occluded = occluded;
  55735. }
  55736. }
  55737. /**
  55738. * Updates the viewport with the values from the given render context.
  55739. *
  55740. * @param {RenderContext} renderContext - The render context.
  55741. */
  55742. updateViewport( renderContext ) {
  55743. const { currentPass } = this.get( renderContext );
  55744. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  55745. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  55746. }
  55747. /**
  55748. * Updates the scissor with the values from the given render context.
  55749. *
  55750. * @param {RenderContext} renderContext - The render context.
  55751. */
  55752. updateScissor( renderContext ) {
  55753. const { currentPass } = this.get( renderContext );
  55754. const { x, y, width, height } = renderContext.scissorValue;
  55755. currentPass.setScissorRect( x, y, width, height );
  55756. }
  55757. /**
  55758. * Returns the clear color and alpha into a single
  55759. * color object.
  55760. *
  55761. * @return {Color4} The clear color.
  55762. */
  55763. getClearColor() {
  55764. const clearColor = super.getClearColor();
  55765. // only premultiply alpha when alphaMode is "premultiplied"
  55766. if ( this.renderer.alpha === true ) {
  55767. clearColor.r *= clearColor.a;
  55768. clearColor.g *= clearColor.a;
  55769. clearColor.b *= clearColor.a;
  55770. }
  55771. return clearColor;
  55772. }
  55773. /**
  55774. * Performs a clear operation.
  55775. *
  55776. * @param {boolean} color - Whether the color buffer should be cleared or not.
  55777. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  55778. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  55779. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  55780. */
  55781. clear( color, depth, stencil, renderTargetContext = null ) {
  55782. const device = this.device;
  55783. const renderer = this.renderer;
  55784. let colorAttachments = [];
  55785. let depthStencilAttachment;
  55786. let clearValue;
  55787. let supportsDepth;
  55788. let supportsStencil;
  55789. if ( color ) {
  55790. const clearColor = this.getClearColor();
  55791. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  55792. }
  55793. if ( renderTargetContext === null ) {
  55794. supportsDepth = renderer.depth;
  55795. supportsStencil = renderer.stencil;
  55796. const descriptor = this._getDefaultRenderPassDescriptor();
  55797. if ( color ) {
  55798. colorAttachments = descriptor.colorAttachments;
  55799. const colorAttachment = colorAttachments[ 0 ];
  55800. colorAttachment.clearValue = clearValue;
  55801. colorAttachment.loadOp = GPULoadOp.Clear;
  55802. colorAttachment.storeOp = GPUStoreOp.Store;
  55803. }
  55804. if ( supportsDepth || supportsStencil ) {
  55805. depthStencilAttachment = descriptor.depthStencilAttachment;
  55806. }
  55807. } else {
  55808. supportsDepth = renderTargetContext.depth;
  55809. supportsStencil = renderTargetContext.stencil;
  55810. const clearConfig = {
  55811. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  55812. clearValue: color ? clearValue : undefined
  55813. };
  55814. if ( supportsDepth ) {
  55815. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  55816. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  55817. clearConfig.depthStoreOp = GPUStoreOp.Store;
  55818. }
  55819. if ( supportsStencil ) {
  55820. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  55821. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  55822. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  55823. }
  55824. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  55825. colorAttachments = descriptor.colorAttachments;
  55826. depthStencilAttachment = descriptor.depthStencilAttachment;
  55827. }
  55828. if ( supportsDepth && depthStencilAttachment ) {
  55829. if ( depth ) {
  55830. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  55831. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  55832. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  55833. } else {
  55834. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  55835. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  55836. }
  55837. }
  55838. //
  55839. if ( supportsStencil && depthStencilAttachment ) {
  55840. if ( stencil ) {
  55841. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  55842. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  55843. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  55844. } else {
  55845. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  55846. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  55847. }
  55848. }
  55849. //
  55850. const encoder = device.createCommandEncoder( { label: 'clear' } );
  55851. const currentPass = encoder.beginRenderPass( {
  55852. colorAttachments,
  55853. depthStencilAttachment
  55854. } );
  55855. currentPass.end();
  55856. device.queue.submit( [ encoder.finish() ] );
  55857. }
  55858. // compute
  55859. /**
  55860. * This method is executed at the beginning of a compute call and
  55861. * prepares the state for upcoming compute tasks.
  55862. *
  55863. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  55864. */
  55865. beginCompute( computeGroup ) {
  55866. const groupGPU = this.get( computeGroup );
  55867. //
  55868. const descriptor = {
  55869. label: 'computeGroup_' + computeGroup.id
  55870. };
  55871. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ), descriptor );
  55872. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  55873. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  55874. }
  55875. /**
  55876. * Executes a compute command for the given compute node.
  55877. *
  55878. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  55879. * @param {Node} computeNode - The compute node.
  55880. * @param {Array<BindGroup>} bindings - The bindings.
  55881. * @param {ComputePipeline} pipeline - The compute pipeline.
  55882. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  55883. * - A single number representing count, or
  55884. * - An array [x, y, z] representing dispatch size, or
  55885. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  55886. */
  55887. compute( computeGroup, computeNode, bindings, pipeline, dispatchSize = null ) {
  55888. const computeNodeData = this.get( computeNode );
  55889. const { passEncoderGPU } = this.get( computeGroup );
  55890. // pipeline
  55891. const pipelineGPU = this.get( pipeline ).pipeline;
  55892. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  55893. // bind groups
  55894. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  55895. const bindGroup = bindings[ i ];
  55896. const bindingsData = this.get( bindGroup );
  55897. passEncoderGPU.setBindGroup( i, bindingsData.group );
  55898. }
  55899. if ( dispatchSize === null ) {
  55900. dispatchSize = computeNode.count;
  55901. }
  55902. // When the dispatchSize is set with a StorageBuffer from the GPU.
  55903. if ( dispatchSize && typeof dispatchSize === 'object' && dispatchSize.isIndirectStorageBufferAttribute ) {
  55904. const dispatchBuffer = this.get( dispatchSize ).buffer;
  55905. passEncoderGPU.dispatchWorkgroupsIndirect( dispatchBuffer, 0 );
  55906. return;
  55907. }
  55908. if ( typeof dispatchSize === 'number' ) {
  55909. // If a single number is given, we calculate the dispatch size based on the workgroup size
  55910. const count = dispatchSize;
  55911. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  55912. // cache dispatch size to avoid recalculating it every time
  55913. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  55914. computeNodeData.count = count;
  55915. const workgroupSize = computeNode.workgroupSize;
  55916. let size = workgroupSize[ 0 ];
  55917. for ( let i = 1; i < workgroupSize.length; i ++ )
  55918. size *= workgroupSize[ i ];
  55919. const dispatchCount = Math.ceil( count / size );
  55920. //
  55921. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  55922. dispatchSize = [ dispatchCount, 1, 1 ];
  55923. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  55924. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  55925. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  55926. }
  55927. computeNodeData.dispatchSize = dispatchSize;
  55928. }
  55929. dispatchSize = computeNodeData.dispatchSize;
  55930. }
  55931. //
  55932. passEncoderGPU.dispatchWorkgroups(
  55933. dispatchSize[ 0 ],
  55934. dispatchSize[ 1 ] || 1,
  55935. dispatchSize[ 2 ] || 1
  55936. );
  55937. }
  55938. /**
  55939. * This method is executed at the end of a compute call and
  55940. * finalizes work after compute tasks.
  55941. *
  55942. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  55943. */
  55944. finishCompute( computeGroup ) {
  55945. const groupData = this.get( computeGroup );
  55946. groupData.passEncoderGPU.end();
  55947. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  55948. }
  55949. // render object
  55950. /**
  55951. * Executes a draw command for the given render object.
  55952. *
  55953. * @param {RenderObject} renderObject - The render object to draw.
  55954. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  55955. */
  55956. draw( renderObject, info ) {
  55957. const { object, material, context, pipeline } = renderObject;
  55958. const bindings = renderObject.getBindings();
  55959. const renderContextData = this.get( context );
  55960. const pipelineData = this.get( pipeline );
  55961. const pipelineGPU = pipelineData.pipeline;
  55962. if ( pipelineData.error === true ) return;
  55963. const index = renderObject.getIndex();
  55964. const hasIndex = ( index !== null );
  55965. const drawParams = renderObject.getDrawParameters();
  55966. if ( drawParams === null ) return;
  55967. // pipeline
  55968. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  55969. // pipeline
  55970. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  55971. currentSets.pipeline = pipelineGPU;
  55972. // bind groups
  55973. const currentBindingGroups = currentSets.bindingGroups;
  55974. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  55975. const bindGroup = bindings[ i ];
  55976. const bindingsData = this.get( bindGroup );
  55977. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  55978. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  55979. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  55980. }
  55981. }
  55982. // attributes
  55983. // index
  55984. if ( hasIndex === true ) {
  55985. if ( currentSets.index !== index ) {
  55986. const buffer = this.get( index ).buffer;
  55987. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  55988. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  55989. currentSets.index = index;
  55990. }
  55991. }
  55992. // vertex buffers
  55993. const vertexBuffers = renderObject.getVertexBuffers();
  55994. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  55995. const vertexBuffer = vertexBuffers[ i ];
  55996. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  55997. const buffer = this.get( vertexBuffer ).buffer;
  55998. passEncoderGPU.setVertexBuffer( i, buffer );
  55999. currentSets.attributes[ i ] = vertexBuffer;
  56000. }
  56001. }
  56002. // stencil
  56003. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  56004. passEncoderGPU.setStencilReference( material.stencilRef );
  56005. renderContextData.currentStencilRef = material.stencilRef;
  56006. }
  56007. };
  56008. // Define draw function
  56009. const draw = ( passEncoderGPU, currentSets ) => {
  56010. setPipelineAndBindings( passEncoderGPU, currentSets );
  56011. if ( object.isBatchedMesh === true ) {
  56012. const starts = object._multiDrawStarts;
  56013. const counts = object._multiDrawCounts;
  56014. const drawCount = object._multiDrawCount;
  56015. const drawInstances = object._multiDrawInstances;
  56016. if ( drawInstances !== null ) {
  56017. // @deprecated, r174
  56018. warnOnce( 'WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  56019. }
  56020. for ( let i = 0; i < drawCount; i ++ ) {
  56021. const count = drawInstances ? drawInstances[ i ] : 1;
  56022. const firstInstance = count > 1 ? 0 : i;
  56023. if ( hasIndex === true ) {
  56024. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  56025. } else {
  56026. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  56027. }
  56028. info.update( object, counts[ i ], count );
  56029. }
  56030. } else if ( hasIndex === true ) {
  56031. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  56032. const indirect = renderObject.getIndirect();
  56033. if ( indirect !== null ) {
  56034. const buffer = this.get( indirect ).buffer;
  56035. const indirectOffset = renderObject.getIndirectOffset();
  56036. passEncoderGPU.drawIndexedIndirect( buffer, indirectOffset );
  56037. } else {
  56038. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  56039. }
  56040. info.update( object, indexCount, instanceCount );
  56041. } else {
  56042. const { vertexCount, instanceCount, firstVertex } = drawParams;
  56043. const indirect = renderObject.getIndirect();
  56044. if ( indirect !== null ) {
  56045. const buffer = this.get( indirect ).buffer;
  56046. const indirectOffset = renderObject.getIndirectOffset();
  56047. passEncoderGPU.drawIndirect( buffer, indirectOffset );
  56048. } else {
  56049. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  56050. }
  56051. info.update( object, vertexCount, instanceCount );
  56052. }
  56053. };
  56054. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  56055. const cameraData = this.get( renderObject.camera );
  56056. const cameras = renderObject.camera.cameras;
  56057. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  56058. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  56059. const bindingsData = this.get( cameraIndex );
  56060. const indexesGPU = [];
  56061. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  56062. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  56063. data[ 0 ] = i;
  56064. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  56065. indexesGPU.push( bindGroupIndex );
  56066. }
  56067. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  56068. }
  56069. const pixelRatio = this.renderer.getPixelRatio();
  56070. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  56071. const subCamera = cameras[ i ];
  56072. if ( object.layers.test( subCamera.layers ) ) {
  56073. const vp = subCamera.viewport;
  56074. let pass = renderContextData.currentPass;
  56075. let sets = renderContextData.currentSets;
  56076. if ( renderContextData.bundleEncoders ) {
  56077. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  56078. const bundleSets = renderContextData.bundleSets[ i ];
  56079. pass = bundleEncoder;
  56080. sets = bundleSets;
  56081. }
  56082. if ( vp ) {
  56083. pass.setViewport(
  56084. Math.floor( vp.x * pixelRatio ),
  56085. Math.floor( vp.y * pixelRatio ),
  56086. Math.floor( vp.width * pixelRatio ),
  56087. Math.floor( vp.height * pixelRatio ),
  56088. context.viewportValue.minDepth,
  56089. context.viewportValue.maxDepth
  56090. );
  56091. }
  56092. // Set camera index binding for this layer
  56093. if ( cameraIndex && cameraData.indexesGPU ) {
  56094. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  56095. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  56096. }
  56097. draw( pass, sets );
  56098. }
  56099. }
  56100. } else {
  56101. // Regular single camera rendering
  56102. if ( renderContextData.currentPass ) {
  56103. // Handle occlusion queries
  56104. if ( renderContextData.occlusionQuerySet !== undefined ) {
  56105. const lastObject = renderContextData.lastOcclusionObject;
  56106. if ( lastObject !== object ) {
  56107. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  56108. renderContextData.currentPass.endOcclusionQuery();
  56109. renderContextData.occlusionQueryIndex ++;
  56110. }
  56111. if ( object.occlusionTest === true ) {
  56112. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  56113. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  56114. }
  56115. renderContextData.lastOcclusionObject = object;
  56116. }
  56117. }
  56118. draw( renderContextData.currentPass, renderContextData.currentSets );
  56119. }
  56120. }
  56121. }
  56122. // cache key
  56123. /**
  56124. * Returns `true` if the render pipeline requires an update.
  56125. *
  56126. * @param {RenderObject} renderObject - The render object.
  56127. * @return {boolean} Whether the render pipeline requires an update or not.
  56128. */
  56129. needsRenderUpdate( renderObject ) {
  56130. const data = this.get( renderObject );
  56131. const { object, material } = renderObject;
  56132. const utils = this.utils;
  56133. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  56134. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  56135. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  56136. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  56137. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  56138. let needsUpdate = false;
  56139. if ( data.material !== material || data.materialVersion !== material.version ||
  56140. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  56141. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  56142. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  56143. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  56144. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  56145. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  56146. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  56147. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  56148. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  56149. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  56150. data.primitiveTopology !== primitiveTopology ||
  56151. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  56152. ) {
  56153. data.material = material; data.materialVersion = material.version;
  56154. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  56155. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  56156. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  56157. data.colorWrite = material.colorWrite;
  56158. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  56159. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  56160. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  56161. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  56162. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  56163. data.sampleCount = sampleCount;
  56164. data.colorSpace = colorSpace;
  56165. data.colorFormat = colorFormat;
  56166. data.depthStencilFormat = depthStencilFormat;
  56167. data.primitiveTopology = primitiveTopology;
  56168. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  56169. needsUpdate = true;
  56170. }
  56171. return needsUpdate;
  56172. }
  56173. /**
  56174. * Returns a cache key that is used to identify render pipelines.
  56175. *
  56176. * @param {RenderObject} renderObject - The render object.
  56177. * @return {string} The cache key.
  56178. */
  56179. getRenderCacheKey( renderObject ) {
  56180. const { object, material } = renderObject;
  56181. const utils = this.utils;
  56182. const renderContext = renderObject.context;
  56183. // meshes with negative scale have a different frontFace render pipeline
  56184. // descriptor value so the following must be honored in the cache key
  56185. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  56186. return [
  56187. material.transparent, material.blending, material.premultipliedAlpha,
  56188. material.blendSrc, material.blendDst, material.blendEquation,
  56189. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  56190. material.colorWrite,
  56191. material.depthWrite, material.depthTest, material.depthFunc,
  56192. material.stencilWrite, material.stencilFunc,
  56193. material.stencilFail, material.stencilZFail, material.stencilZPass,
  56194. material.stencilFuncMask, material.stencilWriteMask,
  56195. material.side,
  56196. frontFaceCW,
  56197. utils.getSampleCountRenderContext( renderContext ),
  56198. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  56199. utils.getPrimitiveTopology( object, material ),
  56200. renderObject.getGeometryCacheKey(),
  56201. renderObject.clippingContextCacheKey
  56202. ].join();
  56203. }
  56204. // textures
  56205. /**
  56206. * Updates a GPU sampler for the given texture.
  56207. *
  56208. * @param {Texture} texture - The texture to update the sampler for.
  56209. * @return {string} The current sampler key.
  56210. */
  56211. updateSampler( texture ) {
  56212. return this.textureUtils.updateSampler( texture );
  56213. }
  56214. /**
  56215. * Creates a default texture for the given texture that can be used
  56216. * as a placeholder until the actual texture is ready for usage.
  56217. *
  56218. * @param {Texture} texture - The texture to create a default texture for.
  56219. * @return {boolean} Whether the sampler has been updated or not.
  56220. */
  56221. createDefaultTexture( texture ) {
  56222. return this.textureUtils.createDefaultTexture( texture );
  56223. }
  56224. /**
  56225. * Defines a texture on the GPU for the given texture object.
  56226. *
  56227. * @param {Texture} texture - The texture.
  56228. * @param {Object} [options={}] - Optional configuration parameter.
  56229. */
  56230. createTexture( texture, options ) {
  56231. this.textureUtils.createTexture( texture, options );
  56232. }
  56233. /**
  56234. * Uploads the updated texture data to the GPU.
  56235. *
  56236. * @param {Texture} texture - The texture.
  56237. * @param {Object} [options={}] - Optional configuration parameter.
  56238. */
  56239. updateTexture( texture, options ) {
  56240. this.textureUtils.updateTexture( texture, options );
  56241. }
  56242. /**
  56243. * Generates mipmaps for the given texture.
  56244. *
  56245. * @param {Texture} texture - The texture.
  56246. */
  56247. generateMipmaps( texture ) {
  56248. this.textureUtils.generateMipmaps( texture );
  56249. }
  56250. /**
  56251. * Destroys the GPU data for the given texture object.
  56252. *
  56253. * @param {Texture} texture - The texture.
  56254. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  56255. */
  56256. destroyTexture( texture, isDefaultTexture = false ) {
  56257. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  56258. }
  56259. /**
  56260. * Returns texture data as a typed array.
  56261. *
  56262. * @async
  56263. * @param {Texture} texture - The texture to copy.
  56264. * @param {number} x - The x coordinate of the copy origin.
  56265. * @param {number} y - The y coordinate of the copy origin.
  56266. * @param {number} width - The width of the copy.
  56267. * @param {number} height - The height of the copy.
  56268. * @param {number} faceIndex - The face index.
  56269. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  56270. */
  56271. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  56272. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  56273. }
  56274. /**
  56275. * Inits a time stamp query for the given render context.
  56276. *
  56277. * @param {string} type - The type of the timestamp query (e.g. 'render', 'compute').
  56278. * @param {number} uid - Unique id for the context (e.g. render context id).
  56279. * @param {Object} descriptor - The query descriptor.
  56280. */
  56281. initTimestampQuery( type, uid, descriptor ) {
  56282. if ( ! this.trackTimestamp ) return;
  56283. if ( ! this.timestampQueryPool[ type ] ) {
  56284. // TODO: Variable maxQueries?
  56285. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  56286. }
  56287. const timestampQueryPool = this.timestampQueryPool[ type ];
  56288. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  56289. descriptor.timestampWrites = {
  56290. querySet: timestampQueryPool.querySet,
  56291. beginningOfPassWriteIndex: baseOffset,
  56292. endOfPassWriteIndex: baseOffset + 1,
  56293. };
  56294. }
  56295. // node builder
  56296. /**
  56297. * Returns a node builder for the given render object.
  56298. *
  56299. * @param {RenderObject} object - The render object.
  56300. * @param {Renderer} renderer - The renderer.
  56301. * @return {WGSLNodeBuilder} The node builder.
  56302. */
  56303. createNodeBuilder( object, renderer ) {
  56304. return new WGSLNodeBuilder( object, renderer );
  56305. }
  56306. // program
  56307. /**
  56308. * Creates a shader program from the given programmable stage.
  56309. *
  56310. * @param {ProgrammableStage} program - The programmable stage.
  56311. */
  56312. createProgram( program ) {
  56313. const programGPU = this.get( program );
  56314. programGPU.module = {
  56315. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  56316. entryPoint: 'main'
  56317. };
  56318. }
  56319. /**
  56320. * Destroys the shader program of the given programmable stage.
  56321. *
  56322. * @param {ProgrammableStage} program - The programmable stage.
  56323. */
  56324. destroyProgram( program ) {
  56325. this.delete( program );
  56326. }
  56327. // pipelines
  56328. /**
  56329. * Creates a render pipeline for the given render object.
  56330. *
  56331. * @param {RenderObject} renderObject - The render object.
  56332. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  56333. */
  56334. createRenderPipeline( renderObject, promises ) {
  56335. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  56336. }
  56337. /**
  56338. * Creates a compute pipeline for the given compute node.
  56339. *
  56340. * @param {ComputePipeline} computePipeline - The compute pipeline.
  56341. * @param {Array<BindGroup>} bindings - The bindings.
  56342. */
  56343. createComputePipeline( computePipeline, bindings ) {
  56344. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  56345. }
  56346. /**
  56347. * Prepares the state for encoding render bundles.
  56348. *
  56349. * @param {RenderContext} renderContext - The render context.
  56350. */
  56351. beginBundle( renderContext ) {
  56352. const renderContextData = this.get( renderContext );
  56353. renderContextData._currentPass = renderContextData.currentPass;
  56354. renderContextData._currentSets = renderContextData.currentSets;
  56355. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  56356. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  56357. }
  56358. /**
  56359. * After processing render bundles this method finalizes related work.
  56360. *
  56361. * @param {RenderContext} renderContext - The render context.
  56362. * @param {RenderBundle} bundle - The render bundle.
  56363. */
  56364. finishBundle( renderContext, bundle ) {
  56365. const renderContextData = this.get( renderContext );
  56366. const bundleEncoder = renderContextData.currentPass;
  56367. const bundleGPU = bundleEncoder.finish();
  56368. this.get( bundle ).bundleGPU = bundleGPU;
  56369. // restore render pass state
  56370. renderContextData.currentSets = renderContextData._currentSets;
  56371. renderContextData.currentPass = renderContextData._currentPass;
  56372. }
  56373. /**
  56374. * Adds a render bundle to the render context data.
  56375. *
  56376. * @param {RenderContext} renderContext - The render context.
  56377. * @param {RenderBundle} bundle - The render bundle to add.
  56378. */
  56379. addBundle( renderContext, bundle ) {
  56380. const renderContextData = this.get( renderContext );
  56381. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  56382. }
  56383. // bindings
  56384. /**
  56385. * Creates bindings from the given bind group definition.
  56386. *
  56387. * @param {BindGroup} bindGroup - The bind group.
  56388. * @param {Array<BindGroup>} bindings - Array of bind groups.
  56389. * @param {number} cacheIndex - The cache index.
  56390. * @param {number} version - The version.
  56391. */
  56392. createBindings( bindGroup, bindings, cacheIndex, version ) {
  56393. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  56394. }
  56395. /**
  56396. * Updates the given bind group definition.
  56397. *
  56398. * @param {BindGroup} bindGroup - The bind group.
  56399. * @param {Array<BindGroup>} bindings - Array of bind groups.
  56400. * @param {number} cacheIndex - The cache index.
  56401. * @param {number} version - The version.
  56402. */
  56403. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  56404. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  56405. }
  56406. /**
  56407. * Updates a buffer binding.
  56408. *
  56409. * @param {Buffer} binding - The buffer binding to update.
  56410. */
  56411. updateBinding( binding ) {
  56412. this.bindingUtils.updateBinding( binding );
  56413. }
  56414. // attributes
  56415. /**
  56416. * Creates the buffer of an indexed shader attribute.
  56417. *
  56418. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  56419. */
  56420. createIndexAttribute( attribute ) {
  56421. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  56422. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  56423. usage |= GPUBufferUsage.STORAGE;
  56424. }
  56425. this.attributeUtils.createAttribute( attribute, usage );
  56426. }
  56427. /**
  56428. * Creates the GPU buffer of a shader attribute.
  56429. *
  56430. * @param {BufferAttribute} attribute - The buffer attribute.
  56431. */
  56432. createAttribute( attribute ) {
  56433. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  56434. }
  56435. /**
  56436. * Creates the GPU buffer of a storage attribute.
  56437. *
  56438. * @param {BufferAttribute} attribute - The buffer attribute.
  56439. */
  56440. createStorageAttribute( attribute ) {
  56441. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  56442. }
  56443. /**
  56444. * Creates the GPU buffer of an indirect storage attribute.
  56445. *
  56446. * @param {BufferAttribute} attribute - The buffer attribute.
  56447. */
  56448. createIndirectStorageAttribute( attribute ) {
  56449. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  56450. }
  56451. /**
  56452. * Updates the GPU buffer of a shader attribute.
  56453. *
  56454. * @param {BufferAttribute} attribute - The buffer attribute to update.
  56455. */
  56456. updateAttribute( attribute ) {
  56457. this.attributeUtils.updateAttribute( attribute );
  56458. }
  56459. /**
  56460. * Destroys the GPU buffer of a shader attribute.
  56461. *
  56462. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  56463. */
  56464. destroyAttribute( attribute ) {
  56465. this.attributeUtils.destroyAttribute( attribute );
  56466. }
  56467. // canvas
  56468. /**
  56469. * Triggers an update of the default render pass descriptor.
  56470. */
  56471. updateSize() {
  56472. this.delete( this.renderer.getCanvasTarget() );
  56473. }
  56474. // utils public
  56475. /**
  56476. * Returns the maximum anisotropy texture filtering value.
  56477. *
  56478. * @return {number} The maximum anisotropy texture filtering value.
  56479. */
  56480. getMaxAnisotropy() {
  56481. return 16;
  56482. }
  56483. /**
  56484. * Checks if the given feature is supported by the backend.
  56485. *
  56486. * @param {string} name - The feature's name.
  56487. * @return {boolean} Whether the feature is supported or not.
  56488. */
  56489. hasFeature( name ) {
  56490. if ( GPUFeatureMap[ name ] !== undefined ) name = GPUFeatureMap[ name ];
  56491. return this.device.features.has( name );
  56492. }
  56493. /**
  56494. * Copies data of the given source texture to the given destination texture.
  56495. *
  56496. * @param {Texture} srcTexture - The source texture.
  56497. * @param {Texture} dstTexture - The destination texture.
  56498. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  56499. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  56500. * @param {number} [srcLevel=0] - The mipmap level to copy.
  56501. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  56502. */
  56503. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  56504. let dstX = 0;
  56505. let dstY = 0;
  56506. let dstZ = 0;
  56507. let srcX = 0;
  56508. let srcY = 0;
  56509. let srcZ = 0;
  56510. let srcWidth = srcTexture.image.width;
  56511. let srcHeight = srcTexture.image.height;
  56512. let srcDepth = 1;
  56513. if ( srcRegion !== null ) {
  56514. if ( srcRegion.isBox3 === true ) {
  56515. srcX = srcRegion.min.x;
  56516. srcY = srcRegion.min.y;
  56517. srcZ = srcRegion.min.z;
  56518. srcWidth = srcRegion.max.x - srcRegion.min.x;
  56519. srcHeight = srcRegion.max.y - srcRegion.min.y;
  56520. srcDepth = srcRegion.max.z - srcRegion.min.z;
  56521. } else {
  56522. // Assume it's a Box2
  56523. srcX = srcRegion.min.x;
  56524. srcY = srcRegion.min.y;
  56525. srcWidth = srcRegion.max.x - srcRegion.min.x;
  56526. srcHeight = srcRegion.max.y - srcRegion.min.y;
  56527. srcDepth = 1;
  56528. }
  56529. }
  56530. if ( dstPosition !== null ) {
  56531. dstX = dstPosition.x;
  56532. dstY = dstPosition.y;
  56533. dstZ = dstPosition.z || 0;
  56534. }
  56535. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  56536. const sourceGPU = this.get( srcTexture ).texture;
  56537. const destinationGPU = this.get( dstTexture ).texture;
  56538. encoder.copyTextureToTexture(
  56539. {
  56540. texture: sourceGPU,
  56541. mipLevel: srcLevel,
  56542. origin: { x: srcX, y: srcY, z: srcZ }
  56543. },
  56544. {
  56545. texture: destinationGPU,
  56546. mipLevel: dstLevel,
  56547. origin: { x: dstX, y: dstY, z: dstZ }
  56548. },
  56549. [
  56550. srcWidth,
  56551. srcHeight,
  56552. srcDepth
  56553. ]
  56554. );
  56555. this.device.queue.submit( [ encoder.finish() ] );
  56556. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  56557. this.textureUtils.generateMipmaps( dstTexture );
  56558. }
  56559. }
  56560. /**
  56561. * Copies the current bound framebuffer to the given texture.
  56562. *
  56563. * @param {Texture} texture - The destination texture.
  56564. * @param {RenderContext} renderContext - The render context.
  56565. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  56566. */
  56567. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  56568. const renderContextData = this.get( renderContext );
  56569. let sourceGPU = null;
  56570. if ( renderContext.renderTarget ) {
  56571. if ( texture.isDepthTexture ) {
  56572. sourceGPU = this.get( renderContext.depthTexture ).texture;
  56573. } else {
  56574. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  56575. }
  56576. } else {
  56577. if ( texture.isDepthTexture ) {
  56578. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  56579. } else {
  56580. sourceGPU = this.context.getCurrentTexture();
  56581. }
  56582. }
  56583. const destinationGPU = this.get( texture ).texture;
  56584. if ( sourceGPU.format !== destinationGPU.format ) {
  56585. error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  56586. return;
  56587. }
  56588. let encoder;
  56589. if ( renderContextData.currentPass ) {
  56590. renderContextData.currentPass.end();
  56591. encoder = renderContextData.encoder;
  56592. } else {
  56593. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  56594. }
  56595. encoder.copyTextureToTexture(
  56596. {
  56597. texture: sourceGPU,
  56598. origin: [ rectangle.x, rectangle.y, 0 ],
  56599. },
  56600. {
  56601. texture: destinationGPU
  56602. },
  56603. [
  56604. rectangle.z,
  56605. rectangle.w
  56606. ]
  56607. );
  56608. // mipmaps must be genereated with the same encoder otherwise the copied texture data
  56609. // might be out-of-sync, see #31768
  56610. if ( texture.generateMipmaps ) {
  56611. this.textureUtils.generateMipmaps( texture, encoder );
  56612. }
  56613. if ( renderContextData.currentPass ) {
  56614. const { descriptor } = renderContextData;
  56615. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  56616. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  56617. }
  56618. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  56619. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  56620. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  56621. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  56622. if ( renderContext.viewport ) {
  56623. this.updateViewport( renderContext );
  56624. }
  56625. if ( renderContext.scissor ) {
  56626. this.updateScissor( renderContext );
  56627. }
  56628. } else {
  56629. this.device.queue.submit( [ encoder.finish() ] );
  56630. }
  56631. }
  56632. dispose() {
  56633. this.textureUtils.dispose();
  56634. }
  56635. }
  56636. /**
  56637. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  56638. *
  56639. * @augments SpotLight
  56640. */
  56641. class IESSpotLight extends SpotLight {
  56642. /**
  56643. * Constructs a new IES spot light.
  56644. *
  56645. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  56646. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  56647. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  56648. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  56649. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  56650. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  56651. */
  56652. constructor( color, intensity, distance, angle, penumbra, decay ) {
  56653. super( color, intensity, distance, angle, penumbra, decay );
  56654. /**
  56655. * TODO
  56656. *
  56657. * @type {?Texture}
  56658. * @default null
  56659. */
  56660. this.iesMap = null;
  56661. }
  56662. copy( source, recursive ) {
  56663. super.copy( source, recursive );
  56664. this.iesMap = source.iesMap;
  56665. return this;
  56666. }
  56667. }
  56668. /**
  56669. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  56670. *
  56671. * @augments SpotLight
  56672. */
  56673. class ProjectorLight extends SpotLight {
  56674. /**
  56675. * Constructs a new projector light.
  56676. *
  56677. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  56678. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  56679. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  56680. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  56681. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  56682. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  56683. */
  56684. constructor( color, intensity, distance, angle, penumbra, decay ) {
  56685. super( color, intensity, distance, angle, penumbra, decay );
  56686. /**
  56687. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  56688. *
  56689. * @type {?number}
  56690. * @default null
  56691. */
  56692. this.aspect = null;
  56693. }
  56694. copy( source, recursive ) {
  56695. super.copy( source, recursive );
  56696. this.aspect = source.aspect;
  56697. return this;
  56698. }
  56699. }
  56700. /**
  56701. * This version of a node library represents the standard version
  56702. * used in {@link WebGPURenderer}. It maps lights, tone mapping
  56703. * techniques and materials to node-based implementations.
  56704. *
  56705. * @private
  56706. * @augments NodeLibrary
  56707. */
  56708. class StandardNodeLibrary extends NodeLibrary {
  56709. /**
  56710. * Constructs a new standard node library.
  56711. */
  56712. constructor() {
  56713. super();
  56714. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  56715. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  56716. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  56717. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  56718. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  56719. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  56720. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  56721. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  56722. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  56723. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  56724. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  56725. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  56726. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  56727. this.addLight( PointLightNode, PointLight );
  56728. this.addLight( DirectionalLightNode, DirectionalLight );
  56729. this.addLight( RectAreaLightNode, RectAreaLight );
  56730. this.addLight( SpotLightNode, SpotLight );
  56731. this.addLight( AmbientLightNode, AmbientLight );
  56732. this.addLight( HemisphereLightNode, HemisphereLight );
  56733. this.addLight( LightProbeNode, LightProbe );
  56734. this.addLight( IESSpotLightNode, IESSpotLight );
  56735. this.addLight( ProjectorLightNode, ProjectorLight );
  56736. this.addToneMapping( linearToneMapping, LinearToneMapping );
  56737. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  56738. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  56739. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  56740. this.addToneMapping( agxToneMapping, AgXToneMapping );
  56741. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  56742. }
  56743. }
  56744. /*
  56745. const debugHandler = {
  56746. get: function ( target, name ) {
  56747. // Add |update
  56748. if ( /^(create|destroy)/.test( name ) ) log( 'WebGPUBackend.' + name );
  56749. return target[ name ];
  56750. }
  56751. };
  56752. */
  56753. /**
  56754. * This renderer is the new alternative of `WebGLRenderer`. `WebGPURenderer` has the ability
  56755. * to target different backends. By default, the renderer tries to use a WebGPU backend if the
  56756. * browser supports WebGPU. If not, `WebGPURenderer` falls backs to a WebGL 2 backend.
  56757. *
  56758. * @augments Renderer
  56759. */
  56760. class WebGPURenderer extends Renderer {
  56761. /**
  56762. * WebGPURenderer options.
  56763. *
  56764. * @typedef {Object} WebGPURenderer~Options
  56765. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  56766. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  56767. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  56768. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  56769. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  56770. * @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.
  56771. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  56772. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  56773. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  56774. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  56775. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  56776. */
  56777. /**
  56778. * Constructs a new WebGPU renderer.
  56779. *
  56780. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  56781. */
  56782. constructor( parameters = {} ) {
  56783. let BackendClass;
  56784. if ( parameters.forceWebGL ) {
  56785. BackendClass = WebGLBackend;
  56786. } else {
  56787. BackendClass = WebGPUBackend;
  56788. parameters.getFallback = () => {
  56789. warn( 'WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  56790. return new WebGLBackend( parameters );
  56791. };
  56792. }
  56793. const backend = new BackendClass( parameters );
  56794. //super( new Proxy( backend, debugHandler ) );
  56795. super( backend, parameters );
  56796. /**
  56797. * The generic default value is overwritten with the
  56798. * standard node library for type mapping.
  56799. *
  56800. * @type {StandardNodeLibrary}
  56801. */
  56802. this.library = new StandardNodeLibrary();
  56803. /**
  56804. * This flag can be used for type testing.
  56805. *
  56806. * @type {boolean}
  56807. * @readonly
  56808. * @default true
  56809. */
  56810. this.isWebGPURenderer = true;
  56811. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  56812. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  56813. }
  56814. }
  56815. }
  56816. /**
  56817. * A specialized group which enables applications access to the
  56818. * Render Bundle API of WebGPU. The group with all its descendant nodes
  56819. * are considered as one render bundle and processed as such by
  56820. * the renderer.
  56821. *
  56822. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  56823. * With a WebGL backend, the group can technically be rendered but without
  56824. * any performance improvements.
  56825. *
  56826. * @augments Group
  56827. */
  56828. class BundleGroup extends Group {
  56829. /**
  56830. * Constructs a new bundle group.
  56831. */
  56832. constructor() {
  56833. super();
  56834. /**
  56835. * This flag can be used for type testing.
  56836. *
  56837. * @type {boolean}
  56838. * @readonly
  56839. * @default true
  56840. */
  56841. this.isBundleGroup = true;
  56842. /**
  56843. * This property is only relevant for detecting types
  56844. * during serialization/deserialization. It should always
  56845. * match the class name.
  56846. *
  56847. * @type {string}
  56848. * @readonly
  56849. * @default 'BundleGroup'
  56850. */
  56851. this.type = 'BundleGroup';
  56852. /**
  56853. * Whether the bundle is static or not. When set to `true`, the structure
  56854. * is assumed to be static and does not change. E.g. no new objects are
  56855. * added to the group
  56856. *
  56857. * If a change is required, an update can still be forced by setting the
  56858. * `needsUpdate` flag to `true`.
  56859. *
  56860. * @type {boolean}
  56861. * @default true
  56862. */
  56863. this.static = true;
  56864. /**
  56865. * The bundle group's version.
  56866. *
  56867. * @type {number}
  56868. * @readonly
  56869. * @default 0
  56870. */
  56871. this.version = 0;
  56872. }
  56873. /**
  56874. * Set this property to `true` when the bundle group has changed.
  56875. *
  56876. * @type {boolean}
  56877. * @default false
  56878. * @param {boolean} value
  56879. */
  56880. set needsUpdate( value ) {
  56881. if ( value === true ) this.version ++;
  56882. }
  56883. }
  56884. /**
  56885. * This module is responsible to manage the post processing setups in apps.
  56886. * You usually create a single instance of this class and use it to define
  56887. * the output of your post processing effect chain.
  56888. * ```js
  56889. * const postProcessing = new PostProcessing( renderer );
  56890. *
  56891. * const scenePass = pass( scene, camera );
  56892. *
  56893. * postProcessing.outputNode = scenePass;
  56894. * ```
  56895. *
  56896. * Note: This module can only be used with `WebGPURenderer`.
  56897. */
  56898. class PostProcessing {
  56899. /**
  56900. * Constructs a new post processing management module.
  56901. *
  56902. * @param {Renderer} renderer - A reference to the renderer.
  56903. * @param {Node<vec4>} outputNode - An optional output node.
  56904. */
  56905. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  56906. /**
  56907. * A reference to the renderer.
  56908. *
  56909. * @type {Renderer}
  56910. */
  56911. this.renderer = renderer;
  56912. /**
  56913. * A node which defines the final output of the post
  56914. * processing. This is usually the last node in a chain
  56915. * of effect nodes.
  56916. *
  56917. * @type {Node<vec4>}
  56918. */
  56919. this.outputNode = outputNode;
  56920. /**
  56921. * Whether the default output tone mapping and color
  56922. * space transformation should be enabled or not.
  56923. *
  56924. * It is enabled by default by it must be disabled when
  56925. * effects must be executed after tone mapping and color
  56926. * space conversion. A typical example is FXAA which
  56927. * requires sRGB input.
  56928. *
  56929. * When set to `false`, the app must control the output
  56930. * transformation with `RenderOutputNode`.
  56931. *
  56932. * ```js
  56933. * const outputPass = renderOutput( scenePass );
  56934. * ```
  56935. *
  56936. * @type {boolean}
  56937. */
  56938. this.outputColorTransform = true;
  56939. /**
  56940. * Must be set to `true` when the output node changes.
  56941. *
  56942. * @type {Node<vec4>}
  56943. */
  56944. this.needsUpdate = true;
  56945. const material = new NodeMaterial();
  56946. material.name = 'PostProcessing';
  56947. /**
  56948. * The full screen quad that is used to render
  56949. * the effects.
  56950. *
  56951. * @private
  56952. * @type {QuadMesh}
  56953. */
  56954. this._quadMesh = new QuadMesh( material );
  56955. this._quadMesh.name = 'Post-Processing';
  56956. /**
  56957. * The context of the post processing stack.
  56958. *
  56959. * @private
  56960. * @type {?Object}
  56961. * @default null
  56962. */
  56963. this._context = null;
  56964. }
  56965. /**
  56966. * When `PostProcessing` is used to apply post processing effects,
  56967. * the application must use this version of `render()` inside
  56968. * its animation loop (not the one from the renderer).
  56969. */
  56970. render() {
  56971. const renderer = this.renderer;
  56972. this._update();
  56973. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  56974. const toneMapping = renderer.toneMapping;
  56975. const outputColorSpace = renderer.outputColorSpace;
  56976. renderer.toneMapping = NoToneMapping;
  56977. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  56978. //
  56979. const currentXR = renderer.xr.enabled;
  56980. renderer.xr.enabled = false;
  56981. this._quadMesh.render( renderer );
  56982. renderer.xr.enabled = currentXR;
  56983. //
  56984. renderer.toneMapping = toneMapping;
  56985. renderer.outputColorSpace = outputColorSpace;
  56986. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  56987. }
  56988. /**
  56989. * Returns the current context of the post processing stack.
  56990. *
  56991. * @readonly
  56992. * @type {?Object}
  56993. */
  56994. get context() {
  56995. return this._context;
  56996. }
  56997. /**
  56998. * Frees internal resources.
  56999. */
  57000. dispose() {
  57001. this._quadMesh.material.dispose();
  57002. }
  57003. /**
  57004. * Updates the state of the module.
  57005. *
  57006. * @private
  57007. */
  57008. _update() {
  57009. if ( this.needsUpdate === true ) {
  57010. const renderer = this.renderer;
  57011. const toneMapping = renderer.toneMapping;
  57012. const outputColorSpace = renderer.outputColorSpace;
  57013. const context = {
  57014. postProcessing: this,
  57015. onBeforePostProcessing: null,
  57016. onAfterPostProcessing: null
  57017. };
  57018. let outputNode = this.outputNode;
  57019. if ( this.outputColorTransform === true ) {
  57020. outputNode = outputNode.context( context );
  57021. outputNode = renderOutput( outputNode, toneMapping, outputColorSpace );
  57022. } else {
  57023. context.toneMapping = toneMapping;
  57024. context.outputColorSpace = outputColorSpace;
  57025. outputNode = outputNode.context( context );
  57026. }
  57027. this._context = context;
  57028. this._quadMesh.material.fragmentNode = outputNode;
  57029. this._quadMesh.material.needsUpdate = true;
  57030. this.needsUpdate = false;
  57031. }
  57032. }
  57033. /**
  57034. * When `PostProcessing` is used to apply post processing effects,
  57035. * the application must use this version of `renderAsync()` inside
  57036. * its animation loop (not the one from the renderer).
  57037. *
  57038. * @async
  57039. * @deprecated
  57040. * @return {Promise} A Promise that resolves when the render has been finished.
  57041. */
  57042. async renderAsync() {
  57043. warnOnce( 'PostProcessing: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  57044. await this.renderer.init();
  57045. this.render();
  57046. }
  57047. }
  57048. /**
  57049. * This special type of texture is intended for compute shaders.
  57050. * It can be used to compute the data of a texture with a compute shader.
  57051. *
  57052. * Note: This type of texture can only be used with `WebGPURenderer`
  57053. * and a WebGPU backend.
  57054. *
  57055. * @augments Texture
  57056. */
  57057. class StorageTexture extends Texture {
  57058. /**
  57059. * Constructs a new storage texture.
  57060. *
  57061. * @param {number} [width=1] - The storage texture's width.
  57062. * @param {number} [height=1] - The storage texture's height.
  57063. */
  57064. constructor( width = 1, height = 1 ) {
  57065. super();
  57066. /**
  57067. * The image object which just represents the texture's dimension.
  57068. *
  57069. * @type {{width: number, height: number}}
  57070. */
  57071. this.image = { width, height };
  57072. /**
  57073. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  57074. *
  57075. * @type {number}
  57076. */
  57077. this.magFilter = LinearFilter;
  57078. /**
  57079. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  57080. *
  57081. * @type {number}
  57082. */
  57083. this.minFilter = LinearFilter;
  57084. /**
  57085. * This flag can be used for type testing.
  57086. *
  57087. * @type {boolean}
  57088. * @readonly
  57089. * @default true
  57090. */
  57091. this.isStorageTexture = true;
  57092. /**
  57093. * When `true`, mipmaps will be auto-generated after compute writes.
  57094. * When `false`, mipmaps must be written manually via compute shaders.
  57095. *
  57096. * @type {boolean}
  57097. * @default true
  57098. */
  57099. this.mipmapsAutoUpdate = true;
  57100. }
  57101. /**
  57102. * Sets the size of the storage texture.
  57103. *
  57104. * @param {number} width - The new width of the storage texture.
  57105. * @param {number} height - The new height of the storage texture.
  57106. */
  57107. setSize( width, height ) {
  57108. if ( this.image.width !== width || this.image.height !== height ) {
  57109. this.image.width = width;
  57110. this.image.height = height;
  57111. this.dispose();
  57112. }
  57113. }
  57114. }
  57115. /**
  57116. * This special type of texture is intended for compute shaders.
  57117. * It can be used to compute the data of a texture with a compute shader.
  57118. *
  57119. * Note: This type of texture can only be used with `WebGPURenderer`
  57120. * and a WebGPU backend.
  57121. *
  57122. * @augments Texture
  57123. */
  57124. class Storage3DTexture extends Texture {
  57125. /**
  57126. * Constructs a new storage texture.
  57127. *
  57128. * @param {number} [width=1] - The storage texture's width.
  57129. * @param {number} [height=1] - The storage texture's height.
  57130. * @param {number} [depth=1] - The storage texture's depth.
  57131. */
  57132. constructor( width = 1, height = 1, depth = 1 ) {
  57133. super();
  57134. //inherited from texture. Must be false for 3DTexture
  57135. this.isArrayTexture = false;
  57136. /**
  57137. * The image object which just represents the texture's dimension.
  57138. *
  57139. * @type {{width: number, height: number, depth: number}}
  57140. */
  57141. this.image = { width, height, depth };
  57142. /**
  57143. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  57144. *
  57145. * @type {number}
  57146. */
  57147. this.magFilter = LinearFilter;
  57148. /**
  57149. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  57150. *
  57151. * @type {number}
  57152. */
  57153. this.minFilter = LinearFilter;
  57154. /**
  57155. * This defines how the texture is wrapped in the depth direction and corresponds to
  57156. * *W* in UVW mapping.
  57157. *
  57158. * @type {number}
  57159. */
  57160. this.wrapR = ClampToEdgeWrapping;
  57161. /**
  57162. * This flag can be used for type testing.
  57163. *
  57164. * @type {boolean}
  57165. * @readonly
  57166. * @default true
  57167. */
  57168. this.isStorageTexture = true;
  57169. /**
  57170. * Indicates whether this texture is a 3D texture.
  57171. *
  57172. * @type {boolean}
  57173. *
  57174. */
  57175. this.is3DTexture = true;
  57176. }
  57177. /**
  57178. * Sets the size of the storage 3d texture.
  57179. *
  57180. * @param {number} width - The new width of the storage texture.
  57181. * @param {number} height - The new height of the storage texture.
  57182. * @param {number} depth - The new depth of the storage texture.
  57183. */
  57184. setSize( width, height, depth ) {
  57185. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  57186. this.image.width = width;
  57187. this.image.height = height;
  57188. this.image.depth = depth;
  57189. this.dispose();
  57190. }
  57191. }
  57192. }
  57193. /**
  57194. * This special type of texture is intended for compute shaders.
  57195. * It can be used to compute the data of a texture with a compute shader.
  57196. *
  57197. * Note: This type of texture can only be used with `WebGPURenderer`
  57198. * and a WebGPU backend.
  57199. *
  57200. * @augments Texture
  57201. */
  57202. class StorageArrayTexture extends Texture {
  57203. /**
  57204. * Constructs a new storage texture.
  57205. *
  57206. * @param {number} [width=1] - The storage texture's width.
  57207. * @param {number} [height=1] - The storage texture's height.
  57208. * @param {number} [depth=1] - The storage texture's depth.
  57209. */
  57210. constructor( width = 1, height = 1, depth = 1 ) {
  57211. super();
  57212. //inherited from texture
  57213. this.isArrayTexture = true;
  57214. /**
  57215. * The image object which just represents the texture's dimension.
  57216. *
  57217. * @type {{width: number, height: number, depth: number}}
  57218. */
  57219. this.image = { width, height, depth };
  57220. /**
  57221. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  57222. *
  57223. * @type {number}
  57224. */
  57225. this.magFilter = LinearFilter;
  57226. /**
  57227. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  57228. *
  57229. * @type {number}
  57230. */
  57231. this.minFilter = LinearFilter;
  57232. /**
  57233. * This flag can be used for type testing.
  57234. *
  57235. * @type {boolean}
  57236. * @readonly
  57237. * @default true
  57238. */
  57239. this.isStorageTexture = true;
  57240. }
  57241. /**
  57242. * Sets the size of the storage array texture.
  57243. *
  57244. * @param {number} width - The new width of the storage texture.
  57245. * @param {number} height - The new height of the storage texture.
  57246. * @param {number} depth - The new depth of the storage texture.
  57247. */
  57248. setSize( width, height, depth ) {
  57249. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  57250. this.image.width = width;
  57251. this.image.height = height;
  57252. this.image.depth = depth;
  57253. this.dispose();
  57254. }
  57255. }
  57256. }
  57257. /**
  57258. * This special type of buffer attribute is intended for compute shaders.
  57259. * It can be used to encode draw parameters for indirect draw calls.
  57260. *
  57261. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  57262. * and a WebGPU backend.
  57263. *
  57264. * @augments StorageBufferAttribute
  57265. */
  57266. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  57267. /**
  57268. * Constructs a new storage buffer attribute.
  57269. *
  57270. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  57271. * The subsequent parameter is then obsolete.
  57272. * @param {number} itemSize - The item size.
  57273. */
  57274. constructor( count, itemSize ) {
  57275. super( count, itemSize, Uint32Array );
  57276. /**
  57277. * This flag can be used for type testing.
  57278. *
  57279. * @type {boolean}
  57280. * @readonly
  57281. * @default true
  57282. */
  57283. this.isIndirectStorageBufferAttribute = true;
  57284. }
  57285. }
  57286. /**
  57287. * A loader for loading node objects in the three.js JSON Object/Scene format.
  57288. *
  57289. * @augments Loader
  57290. */
  57291. class NodeLoader extends Loader {
  57292. /**
  57293. * Constructs a new node loader.
  57294. *
  57295. * @param {LoadingManager} [manager] - A reference to a loading manager.
  57296. */
  57297. constructor( manager ) {
  57298. super( manager );
  57299. /**
  57300. * Represents a dictionary of textures.
  57301. *
  57302. * @type {Object<string,Texture>}
  57303. */
  57304. this.textures = {};
  57305. /**
  57306. * Represents a dictionary of node types.
  57307. *
  57308. * @type {Object<string,Node.constructor>}
  57309. */
  57310. this.nodes = {};
  57311. }
  57312. /**
  57313. * Loads the node definitions from the given URL.
  57314. *
  57315. * @param {string} url - The path/URL of the file to be loaded.
  57316. * @param {Function} onLoad - Will be called when load completes.
  57317. * @param {Function} onProgress - Will be called while load progresses.
  57318. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  57319. */
  57320. load( url, onLoad, onProgress, onError ) {
  57321. const loader = new FileLoader( this.manager );
  57322. loader.setPath( this.path );
  57323. loader.setRequestHeader( this.requestHeader );
  57324. loader.setWithCredentials( this.withCredentials );
  57325. loader.load( url, ( text ) => {
  57326. try {
  57327. onLoad( this.parse( JSON.parse( text ) ) );
  57328. } catch ( e ) {
  57329. if ( onError ) {
  57330. onError( e );
  57331. } else {
  57332. error( e );
  57333. }
  57334. this.manager.itemError( url );
  57335. }
  57336. }, onProgress, onError );
  57337. }
  57338. /**
  57339. * Parse the node dependencies for the loaded node.
  57340. *
  57341. * @param {Array<Object>} [json] - The JSON definition
  57342. * @return {Object<string,Node>} A dictionary with node dependencies.
  57343. */
  57344. parseNodes( json ) {
  57345. const nodes = {};
  57346. if ( json !== undefined ) {
  57347. for ( const nodeJSON of json ) {
  57348. const { uuid, type } = nodeJSON;
  57349. nodes[ uuid ] = this.createNodeFromType( type );
  57350. nodes[ uuid ].uuid = uuid;
  57351. }
  57352. const meta = { nodes, textures: this.textures };
  57353. for ( const nodeJSON of json ) {
  57354. nodeJSON.meta = meta;
  57355. const node = nodes[ nodeJSON.uuid ];
  57356. node.deserialize( nodeJSON );
  57357. delete nodeJSON.meta;
  57358. }
  57359. }
  57360. return nodes;
  57361. }
  57362. /**
  57363. * Parses the node from the given JSON.
  57364. *
  57365. * @param {Object} json - The JSON definition
  57366. * @param {string} json.type - The node type.
  57367. * @param {string} json.uuid - The node UUID.
  57368. * @param {Array<Object>} [json.nodes] - The node dependencies.
  57369. * @param {Object} [json.meta] - The meta data.
  57370. * @return {Node} The parsed node.
  57371. */
  57372. parse( json ) {
  57373. const node = this.createNodeFromType( json.type );
  57374. node.uuid = json.uuid;
  57375. const nodes = this.parseNodes( json.nodes );
  57376. const meta = { nodes, textures: this.textures };
  57377. json.meta = meta;
  57378. node.deserialize( json );
  57379. delete json.meta;
  57380. return node;
  57381. }
  57382. /**
  57383. * Defines the dictionary of textures.
  57384. *
  57385. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  57386. * @return {NodeLoader} A reference to this loader.
  57387. */
  57388. setTextures( value ) {
  57389. this.textures = value;
  57390. return this;
  57391. }
  57392. /**
  57393. * Defines the dictionary of node types.
  57394. *
  57395. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  57396. * @return {NodeLoader} A reference to this loader.
  57397. */
  57398. setNodes( value ) {
  57399. this.nodes = value;
  57400. return this;
  57401. }
  57402. /**
  57403. * Creates a node object from the given type.
  57404. *
  57405. * @param {string} type - The node type.
  57406. * @return {Node} The created node instance.
  57407. */
  57408. createNodeFromType( type ) {
  57409. if ( this.nodes[ type ] === undefined ) {
  57410. error( 'NodeLoader: Node type not found:', type );
  57411. return float();
  57412. }
  57413. return nodeObject( new this.nodes[ type ]() );
  57414. }
  57415. }
  57416. /**
  57417. * A special type of material loader for loading node materials.
  57418. *
  57419. * @augments MaterialLoader
  57420. */
  57421. class NodeMaterialLoader extends MaterialLoader {
  57422. /**
  57423. * Constructs a new node material loader.
  57424. *
  57425. * @param {LoadingManager} [manager] - A reference to a loading manager.
  57426. */
  57427. constructor( manager ) {
  57428. super( manager );
  57429. /**
  57430. * Represents a dictionary of node types.
  57431. *
  57432. * @type {Object<string,Node.constructor>}
  57433. */
  57434. this.nodes = {};
  57435. /**
  57436. * Represents a dictionary of node material types.
  57437. *
  57438. * @type {Object<string,NodeMaterial.constructor>}
  57439. */
  57440. this.nodeMaterials = {};
  57441. }
  57442. /**
  57443. * Parses the node material from the given JSON.
  57444. *
  57445. * @param {Object} json - The JSON definition
  57446. * @return {NodeMaterial}. The parsed material.
  57447. */
  57448. parse( json ) {
  57449. const material = super.parse( json );
  57450. const nodes = this.nodes;
  57451. const inputNodes = json.inputNodes;
  57452. for ( const property in inputNodes ) {
  57453. const uuid = inputNodes[ property ];
  57454. material[ property ] = nodes[ uuid ];
  57455. }
  57456. return material;
  57457. }
  57458. /**
  57459. * Defines the dictionary of node types.
  57460. *
  57461. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  57462. * @return {NodeLoader} A reference to this loader.
  57463. */
  57464. setNodes( value ) {
  57465. this.nodes = value;
  57466. return this;
  57467. }
  57468. /**
  57469. * Defines the dictionary of node material types.
  57470. *
  57471. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  57472. * @return {NodeLoader} A reference to this loader.
  57473. */
  57474. setNodeMaterials( value ) {
  57475. this.nodeMaterials = value;
  57476. return this;
  57477. }
  57478. /**
  57479. * Creates a node material from the given type.
  57480. *
  57481. * @param {string} type - The node material type.
  57482. * @return {Node} The created node material instance.
  57483. */
  57484. createMaterialFromType( type ) {
  57485. const materialClass = this.nodeMaterials[ type ];
  57486. if ( materialClass !== undefined ) {
  57487. return new materialClass();
  57488. }
  57489. return super.createMaterialFromType( type );
  57490. }
  57491. }
  57492. /**
  57493. * A special type of object loader for loading 3D objects using
  57494. * node materials.
  57495. *
  57496. * @augments ObjectLoader
  57497. */
  57498. class NodeObjectLoader extends ObjectLoader {
  57499. /**
  57500. * Constructs a new node object loader.
  57501. *
  57502. * @param {LoadingManager} [manager] - A reference to a loading manager.
  57503. */
  57504. constructor( manager ) {
  57505. super( manager );
  57506. /**
  57507. * Represents a dictionary of node types.
  57508. *
  57509. * @type {Object<string,Node.constructor>}
  57510. */
  57511. this.nodes = {};
  57512. /**
  57513. * Represents a dictionary of node material types.
  57514. *
  57515. * @type {Object<string,NodeMaterial.constructor>}
  57516. */
  57517. this.nodeMaterials = {};
  57518. /**
  57519. * A reference to hold the `nodes` JSON property.
  57520. *
  57521. * @private
  57522. * @type {?Object[]}
  57523. */
  57524. this._nodesJSON = null;
  57525. }
  57526. /**
  57527. * Defines the dictionary of node types.
  57528. *
  57529. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  57530. * @return {NodeObjectLoader} A reference to this loader.
  57531. */
  57532. setNodes( value ) {
  57533. this.nodes = value;
  57534. return this;
  57535. }
  57536. /**
  57537. * Defines the dictionary of node material types.
  57538. *
  57539. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  57540. * @return {NodeObjectLoader} A reference to this loader.
  57541. */
  57542. setNodeMaterials( value ) {
  57543. this.nodeMaterials = value;
  57544. return this;
  57545. }
  57546. /**
  57547. * Parses the node objects from the given JSON.
  57548. *
  57549. * @param {Object} json - The JSON definition
  57550. * @param {Function} onLoad - The onLoad callback function.
  57551. * @return {Object3D}. The parsed 3D object.
  57552. */
  57553. parse( json, onLoad ) {
  57554. this._nodesJSON = json.nodes;
  57555. const data = super.parse( json, onLoad );
  57556. this._nodesJSON = null; // dispose
  57557. return data;
  57558. }
  57559. /**
  57560. * Parses the node objects from the given JSON and textures.
  57561. *
  57562. * @param {Object[]} json - The JSON definition
  57563. * @param {Object<string,Texture>} textures - The texture library.
  57564. * @return {Object<string,Node>}. The parsed nodes.
  57565. */
  57566. parseNodes( json, textures ) {
  57567. if ( json !== undefined ) {
  57568. const loader = new NodeLoader();
  57569. loader.setNodes( this.nodes );
  57570. loader.setTextures( textures );
  57571. return loader.parseNodes( json );
  57572. }
  57573. return {};
  57574. }
  57575. /**
  57576. * Parses the node objects from the given JSON and textures.
  57577. *
  57578. * @param {Object} json - The JSON definition
  57579. * @param {Object<string,Texture>} textures - The texture library.
  57580. * @return {Object<string,NodeMaterial>}. The parsed materials.
  57581. */
  57582. parseMaterials( json, textures ) {
  57583. const materials = {};
  57584. if ( json !== undefined ) {
  57585. const nodes = this.parseNodes( this._nodesJSON, textures );
  57586. const loader = new NodeMaterialLoader();
  57587. loader.setTextures( textures );
  57588. loader.setNodes( nodes );
  57589. loader.setNodeMaterials( this.nodeMaterials );
  57590. for ( let i = 0, l = json.length; i < l; i ++ ) {
  57591. const data = json[ i ];
  57592. materials[ data.uuid ] = loader.parse( data );
  57593. }
  57594. }
  57595. return materials;
  57596. }
  57597. }
  57598. /**
  57599. * In earlier three.js versions, clipping was defined globally
  57600. * on the renderer or on material level. This special version of
  57601. * `THREE.Group` allows to encode the clipping state into the scene
  57602. * graph. Meaning if you create an instance of this group, all
  57603. * descendant 3D objects will be affected by the respective clipping
  57604. * planes.
  57605. *
  57606. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  57607. *
  57608. * @augments Group
  57609. */
  57610. class ClippingGroup extends Group {
  57611. /**
  57612. * Constructs a new clipping group.
  57613. */
  57614. constructor() {
  57615. super();
  57616. /**
  57617. * This flag can be used for type testing.
  57618. *
  57619. * @type {boolean}
  57620. * @readonly
  57621. * @default true
  57622. */
  57623. this.isClippingGroup = true;
  57624. /**
  57625. * An array with clipping planes.
  57626. *
  57627. * @type {Array<Plane>}
  57628. */
  57629. this.clippingPlanes = [];
  57630. /**
  57631. * Whether clipping should be enabled or not.
  57632. *
  57633. * @type {boolean}
  57634. * @default true
  57635. */
  57636. this.enabled = true;
  57637. /**
  57638. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  57639. *
  57640. * @type {boolean}
  57641. * @default false
  57642. */
  57643. this.clipIntersection = false;
  57644. /**
  57645. * Whether shadows should be clipped or not.
  57646. *
  57647. * @type {boolean}
  57648. * @default false
  57649. */
  57650. this.clipShadows = false;
  57651. }
  57652. }
  57653. 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号